116 Commits
net8 ... tests

Author SHA1 Message Date
22b3a342a8 feat: basic universe object tests 2025-08-05 10:47:19 +03:00
d0aee7fe16 chore: slight improvements on test clarity 2025-08-05 10:46:50 +03:00
be15cba9e1 chore: moved core tests into subdirectory 2025-08-05 10:46:50 +03:00
ac0eac3fbb feat: basic behaviour tests 2025-08-05 10:46:50 +03:00
3c23ac7f1e feat: simple behaviour controller tests added 2025-08-05 10:46:50 +03:00
57807c2a62 chore: added tests project 2025-08-05 10:46:50 +03:00
3452194941 BREAKING CHANGE: removed IUniverseObject.SetParent and made Parent property settable 2025-08-05 10:46:25 +03:00
11612ff0db feat: removed IEnumerable from IUniverseObject for intellisense clarity
Use IUniverseObject.Children to access children
2025-08-05 09:11:46 +03:00
63bc94c7a6 fix: some factories not assigning fields correctly 2025-08-04 22:02:48 +03:00
e00319d7ff fix: active checks on behaviour base and universe object not working properly 2025-08-04 22:01:16 +03:00
11719440dc fix: behaviour controller extensions not null checking in case of uninitialized state 2025-08-04 20:26:45 +03:00
f246d68aa7 fix: remove behaviour not starting the reverse for loop from count - 1 2025-08-04 14:56:43 +03:00
6e87c67096 fix: wrong assert messages are corrected 2025-08-04 14:45:00 +03:00
b8217f2106 feat: last active frame interface 2025-08-03 09:43:18 +03:00
9824980cbf chore!: behaviour collector now removes behaviours on pre unregister 2025-08-03 09:23:30 +03:00
93a79cd075 feat: universe pre register and unregister events 2025-08-03 09:22:22 +03:00
f6e52abcc1 feat: testing universe entrance manager 2025-08-02 23:24:59 +03:00
03232f72e8 fix: LogTrace not having an optional stack trace parameter 2025-07-27 19:01:50 +03:00
37aca44e45 feat: monogame premultiplied color extension method added 2025-07-26 12:03:28 +03:00
9f4d95a57b perf: removed unnecessary operations on hsv colors 2025-07-26 11:59:36 +03:00
65eac57fce fix: color lerp methods fixed 2025-07-26 11:59:04 +03:00
08311acc9a chore!: removed FromTo methods from colors 2025-07-26 11:58:23 +03:00
f8fbae6130 feat: added HSVA 2025-07-26 11:56:58 +03:00
df06e8d134 feat: ticker is decoupled from stopwatch and added timer and stopwatch tickers 2025-07-25 23:24:08 +03:00
ad365dc722 feat: monogame content loader interface added 2025-07-25 21:40:57 +03:00
200e8ae7da feat: ILogger WrapWith extension method added 2025-07-21 10:25:33 +03:00
65cfaf1b4a feat: ILogger.Shared for global access 2025-07-21 10:18:00 +03:00
83b155fc5e feat: trace log level added 2025-07-12 18:31:35 +03:00
7db56e7f3e refactor: moved event log calls to a shared method 2025-07-12 17:34:56 +03:00
42064875a0 chore: added extra line for LoggerExtensions.LogException for better clarity 2025-07-12 17:34:23 +03:00
41245c0c1c refactor: added class restriction to generic type for event senders 2025-07-12 17:05:18 +03:00
0e5cc8f898 feat: added loggers to event classes 2025-07-12 16:53:12 +03:00
c8bb991865 refactor!: removed noise from class names
Renamed classes with names XBehaviour to X
2025-07-09 22:20:42 +03:00
bc1c76d746 feat: added priorities to events 2025-07-06 22:22:57 +03:00
8f03628bd6 fix: invocation loop inversed 2025-07-06 22:21:20 +03:00
a1feb0bad3 docs: added documentation for events 2025-07-06 21:04:22 +03:00
978cba96c8 refactor!: event methods renamed for better clarity 2025-07-06 20:39:45 +03:00
7212094a3d chore: updated misleading comment 2025-06-28 14:15:58 +03:00
14843ddeba refactor: removed unnecessary linq call 2025-06-28 12:50:03 +03:00
5315db0077 refactor!: renamed Math.PI to Math.Pi 2025-06-27 14:44:20 +03:00
026f343d43 docs: removed unnecessary comment lines from math constants 2025-06-27 14:42:45 +03:00
da5f31f9d7 refactor: made equality operators consistent in primitives & added missing ones 2025-06-27 12:00:50 +03:00
fa1614f238 feat: added approximately equals methods to projection 1D and ray 2D 2025-06-27 11:44:52 +03:00
0c096d39db docs: line equation XML comments updated 2025-06-27 11:43:54 +03:00
dae6549bad refactor: Equals methods to use equality operators on primitives 2025-06-27 11:37:20 +03:00
767fc28488 refactor: file logger relative path to full path conversion 2025-06-21 00:27:01 +03:00
c3be8f60b7 feat: added logger wrapper class 2025-06-18 17:39:23 +03:00
33cb44bf36 fix: file logger ensure directory exists 2025-06-18 17:39:11 +03:00
4c1018ddec feat: added logger container behaviour 2025-06-18 17:18:08 +03:00
cf7061fd58 fix: shape2D triangulation order changed 2025-06-15 15:14:06 +03:00
e6b7b9953f feat: ensured all primitives have ToString, GetHashCode & Equals methods 2025-06-15 14:44:50 +03:00
4a3775a0de perf: double copy in shape collider's world shape field 2025-06-15 14:34:52 +03:00
4d353662a1 feat: xna color to engine color rgba extension method 2025-06-15 13:32:13 +03:00
ca0b2de917 docs: fixed typo on Shape2D parameter 2025-06-15 13:29:53 +03:00
2335c3ec62 docs: added ray 2d comments 2025-06-13 22:17:39 +03:00
30ccab1b93 refactor: list pool initial count and capacity parameters added 2025-06-09 20:36:39 +03:00
f56d6a7fc8 chore: standalone physics engine not having pooled lists fixed 2025-06-09 20:27:29 +03:00
29a7f5880f feat: transform up, down, left & right properties added 2025-06-09 18:59:15 +03:00
eee3056614 fix: events not having default parameterless constructor 2025-06-09 18:34:20 +03:00
152b0e93db feat: added list pools 2025-06-09 18:33:47 +03:00
3f914fe46f refactor: extracted interface from pool and added events 2025-06-09 18:19:32 +03:00
62b54ee836 feat: event listener counts as constructor parameters 2025-06-09 18:19:08 +03:00
6a41407005 feat: added raycasting support for physics engine 2D 2025-06-09 18:11:20 +03:00
adfa6c6ba0 feat: Vector2D.Reversed property added 2025-06-09 18:04:41 +03:00
a53766f472 fix: forgotten extension method for Line2D.IntersectionPoint 2025-06-09 17:51:34 +03:00
40735c713a feat: added basic pool helper 2025-06-09 17:51:06 +03:00
2054ae3a35 feat: added Ray2D primitive 2025-06-09 16:55:42 +03:00
9066e11c12 perf: simplified Line2D.ClosestPointTo method 2025-06-08 23:40:00 +03:00
f16a7e55c9 chore: fixed record struct arguments' naming 2025-06-08 21:12:16 +03:00
e3b32b3c4a chore: removed unused variables 2025-06-08 21:11:47 +03:00
a02584f3b6 chore: removed DelegateExtensions.InvokeSafe 2025-06-07 18:19:56 +03:00
45524e474e refactor: updated systems to use the update interfaces 2025-06-06 20:26:19 +03:00
fbdea47dc7 docs: updated physics interface delta parameter comment 2025-06-05 23:28:08 +03:00
f5fbd4e5ef feat: IPhysicsIteration interface added 2025-06-05 23:23:34 +03:00
c7f63dc638 refactor: rewritten MonoGameWindow to take in a universe as a constructor parameter 2025-06-04 20:13:01 +03:00
beecefec1c refactor: switched from universe objects to behaviours on all managers like update, draw & physics etc. 2025-06-03 23:59:40 +03:00
24d1a1d764 feat: ISpriteBatch added for MonoGame integration 2025-06-03 23:38:25 +03:00
9edf3b0aa6 feat: one time listeners for events added 2025-06-03 11:43:46 +03:00
8d49fb467c fix: sprite batcher not collecting drawables 2025-06-01 18:36:20 +03:00
2caa042317 feat: basic MonoGame integration implementations added 2025-06-01 15:02:25 +03:00
fe8bde855d fix: draw and update call orders being reverted 2025-06-01 14:45:28 +03:00
ac620264b1 refactor: removed unnecessary overrides from Behaviour class 2025-06-01 14:31:05 +03:00
f31b84f519 refactor: renamed sort comparer names to be more readable 2025-06-01 14:18:50 +03:00
efb7cc7452 refactor: moved behaviour shortcut properties to base 2025-06-01 14:18:25 +03:00
7a3202a053 chore: simplified type names on physics engine 2D 2025-06-01 10:26:38 +03:00
86c9ed2ba9 feat: parameterless Event type 2025-05-31 20:24:45 +03:00
56321864fb fix: tween manager not returning the cancelled tweens back into the pool 2025-05-31 12:10:57 +03:00
6adc002f1a chore: renamed tween manager queue to pool for better readability 2025-05-31 12:08:44 +03:00
1acc8bdb8f perf!: improved sorted behaviour collector by using binary insertion to reduce performance impact 2025-05-31 12:00:32 +03:00
61e2761580 perf!: events refactored throughout all the project to use Event<> class
All delegate events are refactored to use the Event<TSender> and Event<TSender, TArgument> for performance issues regarding delegate events creating garbage, also this gives us better control on event invocation since C# Delegates did also create unnecessary garbage during Delegate.DynamicInvoke
2025-05-31 00:32:58 +03:00
996e61d0ad perf: tween manager pooling 2025-05-30 23:53:18 +03:00
b1b5af94d3 perf!: behaviour controller memory allocation issues fixed by removing the enumerable interface 2025-05-30 13:04:09 +03:00
b0f8b0dad6 refactor: behaviour collector Count and indexer accessors added 2025-05-29 23:17:11 +03:00
67d7f401b8 refactor: memory leaks caused by behaviour collectors fixed 2025-05-29 22:34:01 +03:00
9bf17cc191 perf: physics engine memory leaks fixed 2025-05-29 22:33:47 +03:00
bf8fbebae3 perf: DelegateExtensions.InvokeSafe marked obsolete for memory allocation reasons, soon to be removed 2025-05-29 21:48:08 +03:00
1b0f25e854 perf: update manager list precache 2025-05-29 10:30:30 +03:00
61a7f685c1 perf: delegate InvokeSafe method allocations are lowered 2025-05-29 00:16:00 +03:00
feb2a05aa3 feat: additive transform tweens added 2025-05-28 16:55:48 +03:00
cd30047e4a feat: GetOrAddBehaviour with fallback type added 2025-05-28 16:55:38 +03:00
a3b03efd47 feat: IPhysicsEngine2D.StepIndividual method for individual object simulation 2025-05-27 15:54:07 +03:00
4213b3f8b5 fix: fixed an issue where when there is an inactive collider in the universe messing up the physics engine 2025-05-27 13:52:53 +03:00
d3fb612904 feat: extension methods for parent & children behaviour list search 2025-05-27 13:36:42 +03:00
8f8558a262 docs: added performance warnings to find methods 2025-05-25 13:56:59 +03:00
2df41e1881 docs: added universe and universe object extension documentation comments 2025-05-25 13:28:36 +03:00
114fa82b9d feat: Find & FindRequired for general type search 2025-05-25 12:59:37 +03:00
bcce427376 feat: added GetUniverseObject/InChildren/InParent to UniverseObjectExtensions 2025-05-25 12:20:37 +03:00
6a750f8ce0 refactor: organized extension methods 2025-05-25 12:05:02 +03:00
3e02ee7b6f refactor: changed concrete list arguments to interface list arguments 2025-05-25 11:43:05 +03:00
6b9020bd24 fix: update manager not calling first frame methods once 2025-05-24 19:56:22 +03:00
832514ba7d docs: added documentation to draw & update interfaces 2025-05-24 13:59:36 +03:00
877a004a13 refactor: added pre, regular & post physics update interfaces 2025-05-24 13:59:07 +03:00
b1970d93f9 refactor: draw & update managers to use active & sorted by priority collector 2025-05-23 22:39:32 +03:00
e7bd924494 refactor: update & draw calls have been refactored into systems 2025-05-22 23:51:08 +03:00
37b87f0f85 feat: added post, regular & post events for Update and Draw 2025-05-22 23:10:47 +03:00
3b6a93d37a refactor: behaviour factory universe object parameter removed 2025-05-18 00:38:49 +03:00
159 changed files with 4979 additions and 1265 deletions

View File

@@ -8,7 +8,7 @@ public interface IAssignable
/// <summary>
/// Event triggered when the <see cref="IAssignable"/>'s fields are unassigned and completely ready to recycle.
/// </summary>
event UnassignEventHandler? OnUnassigned;
Event<IAssignable>? OnUnassigned { get; }
/// <summary>
/// Unassign <see cref="IAssignable"/>'s all fields and make it ready to recycle.
@@ -17,6 +17,4 @@ public interface IAssignable
/// <see cref="true"/>, if the fields are unsigned successfully, <see cref="false"/> if not.
/// </returns>
bool Unassign();
delegate void UnassignEventHandler(IAssignable sender);
}

View File

@@ -8,7 +8,7 @@ public interface IHasBehaviourController : IAssignable
/// <summary>
/// Event triggered when the <see cref="IBehaviourController"/> value has has been assigned a new value.
/// </summary>
event BehaviourControllerAssignedEventHandler? OnBehaviourControllerAssigned;
Event<IHasBehaviourController> OnBehaviourControllerAssigned { get; }
/// <inheritdoc cref="IBehaviourController" />
IBehaviourController BehaviourController { get; }
@@ -21,6 +21,4 @@ public interface IHasBehaviourController : IAssignable
/// <see cref="true"/>, if the value given assigned successfully assigned, <see cref="false"/> if not.
/// </returns>
bool Assign(IBehaviourController behaviourController);
delegate void BehaviourControllerAssignedEventHandler(IHasBehaviourController sender);
}

View File

@@ -8,7 +8,7 @@ public interface IHasEntity : IAssignable
/// <summary>
/// Event triggered when the <see cref="IEntity"/> value has has been assigned a new value.
/// </summary>
event EntityAssignedEventHandler? OnEntityAssigned;
Event<IHasEntity> OnEntityAssigned { get; }
/// <inheritdoc cref="IEntity" />
IEntity Entity { get; }
@@ -21,6 +21,4 @@ public interface IHasEntity : IAssignable
/// <see cref="true"/>, if the value given assigned successfully assigned, <see cref="false"/> if not.
/// </returns>
bool Assign(IEntity entity);
delegate void EntityAssignedEventHandler(IHasEntity sender);
}

View File

@@ -8,7 +8,7 @@ public interface IHasStateEnable : IAssignable
/// <summary>
/// Event triggered when the <see cref="IStateEnable"/> value has has been assigned a new value.
/// </summary>
event StateEnableAssignedEventHandler? OnStateEnableAssigned;
Event<IHasStateEnable> OnStateEnableAssigned { get; }
/// <inheritdoc cref="IStateEnable" />
IStateEnable StateEnable { get; }
@@ -21,6 +21,4 @@ public interface IHasStateEnable : IAssignable
/// <see cref="true"/>, if the value given assigned successfully assigned, <see cref="false"/> if not.
/// </returns>
bool Assign(IStateEnable stateEnable);
delegate void StateEnableAssignedEventHandler(IHasStateEnable sender);
}

View File

@@ -8,7 +8,7 @@ public interface IHasUniverse : IAssignable
/// <summary>
/// Event triggered when the <see cref="IUniverse"/> value has has been assigned a new value.
/// </summary>
event UniverseAssignedEventHandler? OnUniverseAssigned;
Event<IHasUniverse> OnUniverseAssigned { get; }
/// <inheritdoc cref="IUniverse" />
IUniverse Universe { get; }
@@ -21,6 +21,4 @@ public interface IHasUniverse : IAssignable
/// <see cref="true"/>, if the value given assigned successfully assigned, <see cref="false"/> if not.
/// </returns>
bool Assign(IUniverse universe);
delegate void UniverseAssignedEventHandler(IHasUniverse sender);
}

View File

@@ -8,7 +8,7 @@ public interface IHasUniverseObject : IAssignable
/// <summary>
/// Event triggered when the <see cref="IUniverseObject"/> value has has been assigned a new value.
/// </summary>
event UniverseObjectAssignedEventHandler? OnUniverseObjectAssigned;
Event<IHasUniverseObject> OnUniverseObjectAssigned { get; }
/// <inheritdoc cref="IUniverseObject" />
IUniverseObject UniverseObject { get; }
@@ -21,6 +21,4 @@ public interface IHasUniverseObject : IAssignable
/// <see cref="true"/>, if the value given assigned successfully assigned, <see cref="false"/> if not.
/// </returns>
bool Assign(IUniverseObject universeObject);
delegate void UniverseObjectAssignedEventHandler(IHasUniverseObject sender);
}

View File

@@ -8,12 +8,12 @@ public interface IActive
/// <summary>
/// Event triggered when the <see cref="IsActive"/> state of the <see cref="IActive"/> changes.
/// </summary>
event ActiveChangedEventHandler? OnActiveChanged;
Event<IActive, ActiveChangedArguments> OnActiveChanged { get; }
/// <summary>
/// The value indicating whether the <see cref="IActive"/> is enabled.
/// </summary>
bool IsActive { get; }
delegate void ActiveChangedEventHandler(IActive sender, bool previousState);
readonly record struct ActiveChangedArguments(bool PreviousState);
}

View File

@@ -8,12 +8,12 @@ public interface IBehaviour : IEntity, IActive, IHasBehaviourController, IHasSta
/// <summary>
/// Event triggered when the priority of the <see cref="IBehaviour"/> changes.
/// </summary>
event PriorityChangedEventHandler? OnPriorityChanged;
Event<IBehaviour, PriorityChangedArguments> OnPriorityChanged { get; }
/// <summary>
/// The priority of the <see cref="IBehaviour"/>.
/// </summary>
int Priority { get; set; }
delegate void PriorityChangedEventHandler(IBehaviour sender, int previousPriority);
readonly record struct PriorityChangedArguments(int PreviousPriority);
}

View File

@@ -1,5 +1,3 @@
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
/// <summary>
@@ -7,29 +5,38 @@ namespace Syntriax.Engine.Core;
/// Provides mechanisms for tracking additions and removals, and notifies subscribers when such events occur on the assigned <see cref="IUniverse"/>.
/// </summary>
/// <typeparam name="T">The type of objects tracked by the collector.</typeparam>
public interface IBehaviourCollector<T> : IHasUniverse, IEnumerable<T> where T : class
public interface IBehaviourCollector<T> : IHasUniverse where T : class
{
/// <summary>
/// Event triggered when an object of type <typeparamref name="T"/> is added to the collector.
/// </summary>
event CollectedEventHandler? OnCollected;
Event<IBehaviourCollector<T>, BehaviourCollectedArguments> OnCollected { get; }
/// <summary>
/// Event triggered when an object of type <typeparamref name="T"/> is removed from the collector.
/// </summary>
event RemovedEventHandler? OnRemoved;
Event<IBehaviourCollector<T>, BehaviourRemovedArguments> OnRemoved { get; }
/// <summary>
/// Amount of <typeparamref name="T"/> collected.
/// </summary>
int Count { get; }
/// <summary>
/// Get a <typeparamref name="T"/> collected by it's index.
/// </summary>
T this[System.Index index] { get; }
/// <summary>
/// Delegate for handling the <see cref="OnCollected"/> event.
/// </summary>
/// <param name="sender">The instance of the <see cref="IBehaviourCollector{T}"/> that triggered the event.</param>
/// <param name="behaviourCollected">The object of type <typeparamref name="T"/> that was added to the collector.</param>
delegate void CollectedEventHandler(IBehaviourCollector<T> sender, T behaviourCollected);
readonly record struct BehaviourCollectedArguments(T BehaviourCollected);
/// <summary>
/// Delegate for handling the <see cref="OnRemoved"/> event.
/// </summary>
/// <param name="sender">The instance of the <see cref="IBehaviourCollector{T}"/> that triggered the event.</param>
/// <param name="behaviourRemoved">The object of type <typeparamref name="T"/> that was removed from the collector.</param>
delegate void RemovedEventHandler(IBehaviourCollector<T> sender, T behaviourRemoved);
/// <param name="BehaviourRemoved">The object of type <typeparamref name="T"/> that was removed from the collector.</param>
readonly record struct BehaviourRemovedArguments(T BehaviourRemoved);
}

View File

@@ -3,34 +3,29 @@ using System.Collections.Generic;
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a controller for managing <see cref="IBehaviour"/>s and notify them accordingly about the engine's updates. Connected to an <see cref="IUniverseObject"/>.
/// Represents a controller for managing <see cref="IBehaviour"/>s. Connected to an <see cref="IUniverseObject"/>.
/// </summary>
public interface IBehaviourController : IEntity, IHasUniverseObject, IEnumerable<IBehaviour>
public interface IBehaviourController : IEntity, IHasUniverseObject
{
/// <summary>
/// Event triggered before the update of <see cref="IBehaviour"/>s.
/// </summary>
event PreUpdateEventHandler? OnPreUpdate;
/// <summary>
/// Event triggered during the update of <see cref="IBehaviour"/>s.
/// </summary>
event UpdateEventHandler? OnUpdate;
/// <summary>
/// Event triggered before the drawing phase.
/// </summary>
event PreDrawEventHandler? OnPreDraw;
/// <summary>
/// Event triggered when a <see cref="IBehaviour"/> is added to the <see cref="IBehaviourController"/>.
/// </summary>
event BehaviourAddedEventHandler? OnBehaviourAdded;
Event<IBehaviourController, BehaviourAddedArguments> OnBehaviourAdded { get; }
/// <summary>
/// Event triggered when a <see cref="IBehaviour"/> is removed from the <see cref="IBehaviourController"/>.
/// </summary>
event BehaviourRemovedEventHandler? OnBehaviourRemoved;
Event<IBehaviourController, BehaviourRemovedArguments> OnBehaviourRemoved { get; }
/// <summary>
/// Amount of <see cref="IBehaviour"/> collected.
/// </summary>
int Count { get; }
/// <summary>
/// Get a <see cref="IBehaviour"/> collected by it's index.
/// </summary>
IBehaviour this[System.Index index] { get; }
/// <summary>
/// Adds a <see cref="IBehaviour"/> to the <see cref="IBehaviourController"/>.
@@ -83,20 +78,6 @@ public interface IBehaviourController : IEntity, IHasUniverseObject, IEnumerable
/// <param name="behaviour">The <see cref="IBehaviour"/> to remove.</param>
void RemoveBehaviour<T>(T behaviour) where T : class, IBehaviour;
/// <summary>
/// Updates all <see cref="IBehaviour"/>s in the <see cref="IBehaviourController"/>.
/// </summary>
void Update();
/// <summary>
/// Performs pre-draw operations.
/// </summary>
void UpdatePreDraw();
delegate void PreUpdateEventHandler(IBehaviourController sender);
delegate void UpdateEventHandler(IBehaviourController sender);
delegate void PreDrawEventHandler(IBehaviourController sender);
delegate void BehaviourAddedEventHandler(IBehaviourController sender, IBehaviour behaviourAdded);
delegate void BehaviourRemovedEventHandler(IBehaviourController sender, IBehaviour behaviourRemoved);
readonly record struct BehaviourAddedArguments(IBehaviour BehaviourAdded);
readonly record struct BehaviourRemovedArguments(IBehaviour BehaviourRemoved);
}

View File

@@ -9,12 +9,12 @@ public interface IEntity : IInitializable, IHasStateEnable
/// Event triggered when the <see cref="Id"/> of the <see cref="IEntity"/> changes.
/// The string action parameter is the previous <see cref="Id"/> of the <see cref="IEntity"/>.
/// </summary>
event IdChangedEventHandler? OnIdChanged;
Event<IEntity, IdChangedArguments> OnIdChanged { get; }
/// <summary>
/// The ID of the <see cref="IEntity"/>.
/// </summary>
string Id { get; set; }
delegate void IdChangedEventHandler(IEntity sender, string previousId);
readonly record struct IdChangedArguments(string PreviousId);
}

View File

@@ -8,12 +8,12 @@ public interface IInitializable
/// <summary>
/// Event triggered when the <see cref="Initialize"/> method is called successfully.
/// </summary>
event InitializedEventHandler? OnInitialized;
Event<IInitializable> OnInitialized { get; }
/// <summary>
/// Event triggered when the <see cref="IInitializable"/> method is called successfully.
/// </summary>
event FinalizedEventHandler? OnFinalized;
Event<IInitializable> OnFinalized { get; }
/// <summary>
/// The value indicating whether the entity has been initialized.
@@ -31,7 +31,4 @@ public interface IInitializable
/// </summary>
/// <returns><see cref="true"/> if finalization is successful, otherwise <see cref="false"/>.</returns>
bool Finalize();
delegate void InitializedEventHandler(IInitializable sender);
delegate void FinalizedEventHandler(IInitializable sender);
}

View File

@@ -8,12 +8,12 @@ public interface INameable
/// <summary>
/// Event triggered when the name of the entity changes.
/// </summary>
event NameChangedEventHandler? OnNameChanged;
Event<INameable, NameChangedArguments> OnNameChanged { get; }
/// <summary>
/// The name of the entity.
/// </summary>
string Name { get; set; }
delegate void NameChangedEventHandler(INameable sender, string previousName);
readonly record struct NameChangedArguments(string PreviousName);
}

View File

@@ -8,12 +8,12 @@ public interface IStateEnable : IHasEntity
/// <summary>
/// Event triggered when the <see cref="Enabled"/> state of the <see cref="IStateEnable"/> changes.
/// </summary>
event EnabledChangedEventHandler? OnEnabledChanged;
Event<IStateEnable, EnabledChangedArguments> OnEnabledChanged { get; }
/// <summary>
/// The value indicating whether the <see cref="IStateEnable"/> is enabled.
/// </summary>
bool Enabled { get; set; }
delegate void EnabledChangedEventHandler(IStateEnable sender, bool previousState);
readonly record struct EnabledChangedArguments(bool PreviousState);
}

View File

@@ -8,17 +8,37 @@ public interface ITransform2D : IBehaviour
/// <summary>
/// Event triggered when the <see cref="Position"/> of the <see cref="ITransform2D"/> changes.
/// </summary>
event PositionChangedEventHandler? OnPositionChanged;
Event<ITransform2D, PositionChangedArguments> OnPositionChanged { get; }
/// <summary>
/// Event triggered when the <see cref="Scale"/> of the <see cref="ITransform2D"/> changes.
/// </summary>
event ScaleChangedEventHandler? OnScaleChanged;
Event<ITransform2D, ScaleChangedArguments> OnScaleChanged { get; }
/// <summary>
/// Event triggered when the <see cref="Rotation"/> of the <see cref="ITransform"/> changes.
/// </summary>
event RotationChangedEventHandler? OnRotationChanged;
Event<ITransform2D, RotationChangedArguments> OnRotationChanged { get; }
/// <summary>
/// The <see cref="Vector2D"/> pointing upwards in world space.
/// </summary>
Vector2D Up { get; }
/// <summary>
/// The <see cref="Vector2D"/> pointing upwards in world space.
/// </summary>
Vector2D Down { get; }
/// <summary>
/// The <see cref="Vector2D"/> pointing upwards in world space.
/// </summary>
Vector2D Left { get; }
/// <summary>
/// The <see cref="Vector2D"/> pointing upwards in world space.
/// </summary>
Vector2D Right { get; }
/// <summary>
/// The world position of the <see cref="ITransform2D"/> in 2D space.
@@ -51,23 +71,20 @@ public interface ITransform2D : IBehaviour
float LocalRotation { get; set; }
/// <summary>
/// Delegate for the event triggered when the <see cref="ITransform2D"/>'s rotation changes.
/// Arguments for the event triggered when the <see cref="ITransform2D"/>'s rotation changes.
/// </summary>
/// <param name="sender">The <see cref="ITransform2D"/> that the parent has changed.</param>
/// <param name="previousPosition">The previous <see cref="Position"/> of the <see cref="ITransform2D"/>.</param>
delegate void PositionChangedEventHandler(ITransform2D sender, Vector2D previousPosition);
/// <param name="PreviousPosition">The previous <see cref="Position"/> of the <see cref="ITransform2D"/>.</param>
readonly record struct PositionChangedArguments(Vector2D PreviousPosition);
/// <summary>
/// Delegate for the event triggered when the <see cref="ITransform2D"/>'s rotation changes.
/// Arguments for the event triggered when the <see cref="ITransform2D"/>'s rotation changes.
/// </summary>
/// <param name="sender">The <see cref="ITransform2D"/> that the parent has changed.</param>
/// <param name="previousScale">The previous <see cref="Scale"/> of the <see cref="ITransform2D"/>.</param>
delegate void ScaleChangedEventHandler(ITransform2D sender, Vector2D previousScale);
/// <param name="PreviousScale">The previous <see cref="Scale"/> of the <see cref="ITransform2D"/>.</param>
readonly record struct ScaleChangedArguments(Vector2D PreviousScale);
/// <summary>
/// Delegate for the event triggered when the <see cref="ITransform2D"/>'s rotation changes.
/// Arguments for the event triggered when the <see cref="ITransform2D"/>'s rotation changes.
/// </summary>
/// <param name="sender">The <see cref="ITransform2D"/> that the parent has changed.</param>
/// <param name="previousRotation">The previous <see cref="Rotation"/> of the <see cref="ITransform2D"/>.</param>
delegate void RotationChangedEventHandler(ITransform2D sender, float previousRotation);
/// <param name="PreviousRotation">The previous <see cref="Rotation"/> of the <see cref="ITransform2D"/>.</param>
readonly record struct RotationChangedArguments(float PreviousRotation);
}

View File

@@ -10,32 +10,57 @@ public interface IUniverse : IEntity, IEnumerable<IUniverseObject>
/// <summary>
/// Event triggered when <see cref="Update(UniverseTime)"/> is about to be called called on the <see cref="IUniverse"/>.
/// </summary>
event UpdateEventHandler? OnPreUpdate;
Event<IUniverse, UpdateArguments> OnPreUpdate { get; }
/// <summary>
/// Event triggered when <see cref="Update(UniverseTime)"/> is called on the <see cref="IUniverse"/>.
/// </summary>
event UpdateEventHandler? OnUpdate;
Event<IUniverse, UpdateArguments> OnUpdate { get; }
/// <summary>
/// Event triggered when <see cref="PreDraw"/> is called on the <see cref="IUniverse"/>.
/// Event triggered after <see cref="Update(UniverseTime)"/> is called on the <see cref="IUniverse"/>.
/// </summary>
event PreDrawEventHandler? OnPreDraw;
Event<IUniverse, UpdateArguments> OnPostUpdate { get; }
/// <summary>
/// Event triggered when <see cref="Draw"/> is about to be called called on the <see cref="IUniverse"/>.
/// </summary>
Event<IUniverse> OnPreDraw { get; }
/// <summary>
/// Event triggered when <see cref="Draw"/> is called on the <see cref="IUniverse"/>.
/// </summary>
Event<IUniverse> OnDraw { get; }
/// <summary>
/// Event triggered after <see cref="Draw"/> is called on the <see cref="IUniverse"/>.
/// </summary>
Event<IUniverse> OnPostDraw { get; }
/// <summary>
/// Event triggered when a <see cref="IUniverseObject"/> is about to be registered to the <see cref="IUniverse"/>.
/// </summary>
Event<IUniverse, UniverseObjectRegisteredArguments> OnPreUniverseObjectRegistered { get; }
/// <summary>
/// Event triggered when a <see cref="IUniverseObject"/> is registered to the <see cref="IUniverse"/>.
/// </summary>
event UniverseObjectRegisteredEventHandler? OnUniverseObjectRegistered;
Event<IUniverse, UniverseObjectRegisteredArguments> OnUniverseObjectRegistered { get; }
/// <summary>
/// Event triggered when a <see cref="IUniverseObject"/> is about to be unregistered from the <see cref="IUniverse"/>.
/// </summary>
Event<IUniverse, UniverseObjectUnRegisteredArguments> OnPreUniverseObjectUnRegistered { get; }
/// <summary>
/// Event triggered when a <see cref="IUniverseObject"/> is unregistered from the <see cref="IUniverse"/>.
/// </summary>
event UniverseObjectUnRegisteredEventHandler? OnUniverseObjectUnRegistered;
Event<IUniverse, UniverseObjectUnRegisteredArguments> OnUniverseObjectUnRegistered { get; }
/// <summary>
/// Event triggered when <see cref="TimeScale"/> is changed on the <see cref="IUniverse"/>.
/// </summary>
event TimeScaleChangedEventHandler? OnTimeScaleChanged;
Event<IUniverse, TimeScaleChangedArguments> OnTimeScaleChanged { get; }
/// <summary>
/// Current time scale the <see cref="IUniverse"/> operates on.
@@ -84,15 +109,12 @@ public interface IUniverse : IEntity, IEnumerable<IUniverseObject>
void Update(UniverseTime universeTime);
/// <summary>
/// Performs operations that should be done before the draw calls.
/// Performs operations that should be done to the draw.
/// </summary>
void PreDraw();
void Draw();
delegate void TimeScaleChangedEventHandler(IUniverse sender, float previousTimeScale);
delegate void UpdateEventHandler(IUniverse sender, UniverseTime engineTime);
delegate void PreDrawEventHandler(IUniverse sender);
delegate void UniverseObjectRegisteredEventHandler(IUniverse sender, IUniverseObject universeObjectRegistered);
delegate void UniverseObjectUnRegisteredEventHandler(IUniverse sender, IUniverseObject universeObjectUnregistered);
readonly record struct TimeScaleChangedArguments(float PreviousTimeScale);
readonly record struct UpdateArguments(UniverseTime EngineTime);
readonly record struct UniverseObjectRegisteredArguments(IUniverseObject UniverseObjectRegistered);
readonly record struct UniverseObjectUnRegisteredArguments(IUniverseObject UniverseObjectUnregistered);
}

View File

@@ -7,32 +7,32 @@ namespace Syntriax.Engine.Core;
/// This interface allows for tracking the object's presence in the universe and provides events
/// for notifying when the see enters or exits the universe.
/// </summary>
public interface IUniverseObject : IEntity, IActive, INameable, IHasBehaviourController, IEnumerable<IUniverseObject>
public interface IUniverseObject : IEntity, IActive, INameable, IHasBehaviourController
{
/// <summary>
/// Event triggered when the <see cref="IUniverseObject"/> enters the universe.
/// </summary>
event EnteredUniverseEventHandler? OnEnteredUniverse;
Event<IUniverseObject, EnteredUniverseArguments> OnEnteredUniverse { get; }
/// <summary>
/// Event triggered when the <see cref="IUniverseObject"/> exits the universe.
/// </summary>
event ExitedUniverseEventHandler? OnExitedUniverse;
Event<IUniverseObject, ExitedUniverseArguments> OnExitedUniverse { get; }
/// <summary>
/// Event triggered when the <see cref="Parent"/> of the <see cref="IUniverseObject"/> changes. The second parameter is the old <see cref="IUniverseObject"/>.
/// </summary>
event ParentChangedEventHandler? OnParentChanged;
Event<IUniverseObject, ParentChangedArguments> OnParentChanged { get; }
/// <summary>
/// Event triggered when a new <see cref="IUniverseObject"/> is added to the <see cref="Children"/>.
/// </summary>
event ChildrenAddedEventHandler? OnChildrenAdded;
Event<IUniverseObject, ChildrenAddedArguments> OnChildrenAdded { get; }
/// <summary>
/// Event triggered when an <see cref="IUniverseObject"/> is removed from the <see cref="Children"/>.
/// </summary>
event ChildrenRemovedEventHandler? OnChildrenRemoved;
Event<IUniverseObject, ChildrenRemovedArguments> OnChildrenRemoved { get; }
/// <summary>
/// Gets the <see cref="IUniverse"/> this <see cref="IUniverseObject"/> is connected to, if any.
@@ -47,7 +47,7 @@ public interface IUniverseObject : IEntity, IActive, INameable, IHasBehaviourCon
/// <summary>
/// The parent <see cref="IUniverseObject"/> of the <see cref="IUniverseObject"/>.
/// </summary>
IUniverseObject? Parent { get; }
IUniverseObject? Parent { get; set; }
/// <summary>
/// The <see cref="IUniverseObject"/>s that have this <see cref="IUniverseObject"/> as their <see cref="Parent"/>.
@@ -75,12 +75,6 @@ public interface IUniverseObject : IEntity, IActive, INameable, IHasBehaviourCon
/// </returns>
internal bool ExitUniverse();
/// <summary>
/// Sets the parent <see cref="IUniverseObject"/> of this <see cref="IUniverseObject"/>.
/// </summary>
/// <param name="universeObject">The parent <see cref="IUniverseObject"/> to set.</param>
void SetParent(IUniverseObject? universeObject);
/// <summary>
/// Adds a child <see cref="IUniverseObject"/> to this <see cref="IUniverseObject"/>.
/// </summary>
@@ -94,38 +88,38 @@ public interface IUniverseObject : IEntity, IActive, INameable, IHasBehaviourCon
void RemoveChild(IUniverseObject universeObject);
/// <summary>
/// EventHandler delegate for the event triggered when the <see cref="IUniverseObject"/> enters the universe of a <see cref="IUniverse">.
/// Arguments for the event triggered when the <see cref="IUniverseObject"/> enters the universe of a <see cref="IUniverse">.
/// </summary>
/// <param name="sender">The <see cref="IUniverseObject"/> that entered the universe.</param>
/// <param name="universe">The <see cref="IUniverse"/> that the <see cref="IUniverseObject"/> has entered it's universe.</param>
delegate void EnteredUniverseEventHandler(IUniverseObject sender, IUniverse universe);
readonly record struct EnteredUniverseArguments(IUniverse Universe);
/// <summary>
/// EventHandler delegate for the event triggered when the <see cref="IUniverseObject"/> exits the universe of a <see cref="IUniverse">.
/// Arguments for the event triggered when the <see cref="IUniverseObject"/> exits the universe of a <see cref="IUniverse">.
/// </summary>
/// <param name="sender">The <see cref="IUniverseObject"/> that exited the universe.</param>
/// <param name="universe">The <see cref="IUniverse"/> that the <see cref="IUniverseObject"/> has exited it's universe.</param>
delegate void ExitedUniverseEventHandler(IUniverseObject sender, IUniverse universe);
readonly record struct ExitedUniverseArguments(IUniverse Universe);
/// <summary>
/// Delegate for the event triggered when the <see cref="IUniverseObject"/>'s parent changes.
/// Arguments for the event triggered when the <see cref="IUniverseObject"/>'s parent changes.
/// </summary>
/// <param name="sender">The <see cref="IUniverseObject"/> that the parent has changed.</param>
/// <param name="previousParent">The previous <see cref="IUniverseObject"/> the sender was a child of.</param>
/// <param name="newParent">The new and current <see cref="IUniverseObject"/> the sender is a child of.</param>
delegate void ParentChangedEventHandler(IUniverseObject sender, IUniverseObject? previousParent, IUniverseObject? newParent);
readonly record struct ParentChangedArguments(IUniverseObject? PreviousParent, IUniverseObject? CurrentParent);
/// <summary>
/// Delegate for the event triggered when a new <see cref="IUniverseObject"/> added as a child.
/// Arguments for the event triggered when a new <see cref="IUniverseObject"/> added as a child.
/// </summary>
/// <param name="sender">The parent <see cref="IUniverseObject"/> this event is being called from.</param>
/// <param name="childrenAdded">The <see cref="IUniverseObject"/> that got removed as a children of the sender <see cref="IUniverseObject"/>.</param>
delegate void ChildrenAddedEventHandler(IUniverseObject sender, IUniverseObject childrenAdded);
readonly record struct ChildrenAddedArguments(IUniverseObject ChildrenAdded);
/// <summary>
/// Delegate for the event triggered when a new <see cref="IUniverseObject"/> removed from being a child.
/// </summary>
/// <param name="sender">The parent <see cref="IUniverseObject"/> this event is being called from.</param>
/// <param name="childrenAdded">The <see cref="IUniverseObject"/> that got removed as a children of the sender <see cref="IUniverseObject"/>.</param>
delegate void ChildrenRemovedEventHandler(IUniverseObject sender, IUniverseObject childrenRemoved);
readonly record struct ChildrenRemovedArguments(IUniverseObject ChildrenRemoved);
}

View File

@@ -1,89 +1,92 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class ActiveBehaviourCollector<T> : IBehaviourCollector<T> where T : class, IBehaviour
{
public event IAssignable.UnassignEventHandler? OnUnassigned = null;
public event IHasUniverse.UniverseAssignedEventHandler? OnUniverseAssigned = null;
public Event<IBehaviourCollector<T>, IBehaviourCollector<T>.BehaviourCollectedArguments> OnCollected { get; } = new();
public Event<IBehaviourCollector<T>, IBehaviourCollector<T>.BehaviourRemovedArguments> OnRemoved { get; } = new();
public Event<IHasUniverse> OnUniverseAssigned { get; } = new();
public Event<IAssignable>? OnUnassigned { get; } = new();
public event IBehaviourCollector<T>.CollectedEventHandler? OnCollected = null;
public event IBehaviourCollector<T>.RemovedEventHandler? OnRemoved = null;
private readonly Event<IBehaviourController, IBehaviourController.BehaviourAddedArguments>.EventHandler delegateOnBehaviourAdded = null!;
private readonly Event<IBehaviourController, IBehaviourController.BehaviourRemovedArguments>.EventHandler delegateOnBehaviourRemoved = null!;
private readonly Event<IActive, IActive.ActiveChangedArguments>.EventHandler delegateOnBehaviourStateChanged = null!;
private readonly Event<IUniverse, IUniverse.UniverseObjectRegisteredArguments>.EventHandler delegateOnUniverseObjectRegistered = null!;
private readonly Event<IUniverse, IUniverse.UniverseObjectUnRegisteredArguments>.EventHandler delegateOnUniverseObjectUnregistered = null!;
private readonly List<T> monitoringBehaviours = new(32);
protected readonly List<T> activeBehaviours = new(32);
protected readonly Dictionary<IActive, T> monitoringActiveToBehaviour = new(32);
public IReadOnlyList<T> Behaviours => activeBehaviours;
public IUniverse Universe { get; private set; } = null!;
public T this[Index index] => activeBehaviours[index];
public ActiveBehaviourCollector() { }
public ActiveBehaviourCollector(IUniverse universe) => Assign(universe);
private void OnUniverseObjectRegistered(IUniverse manager, IUniverseObject universeObject)
private void OnUniverseObjectRegistered(IUniverse manager, IUniverse.UniverseObjectRegisteredArguments args)
{
universeObject.BehaviourController.OnBehaviourAdded += OnBehaviourAdded;
universeObject.BehaviourController.OnBehaviourRemoved += OnBehaviourRemoved;
IUniverseObject universeObject = args.UniverseObjectRegistered;
foreach (IBehaviour item in universeObject.BehaviourController)
OnBehaviourAdded(universeObject.BehaviourController, item);
universeObject.BehaviourController.OnBehaviourAdded.AddListener(delegateOnBehaviourAdded);
universeObject.BehaviourController.OnBehaviourRemoved.AddListener(delegateOnBehaviourRemoved);
for (int i = 0; i < universeObject.BehaviourController.Count; i++)
OnBehaviourAdded(universeObject.BehaviourController, new(universeObject.BehaviourController[i]));
}
private void OnUniverseObjectUnregistered(IUniverse manager, IUniverseObject universeObject)
private void OnUniverseObjectUnregistered(IUniverse manager, IUniverse.UniverseObjectUnRegisteredArguments args)
{
universeObject.BehaviourController.OnBehaviourAdded -= OnBehaviourAdded;
universeObject.BehaviourController.OnBehaviourRemoved -= OnBehaviourRemoved;
IUniverseObject universeObject = args.UniverseObjectUnregistered;
foreach (IBehaviour item in universeObject.BehaviourController)
OnBehaviourRemoved(universeObject.BehaviourController, item);
universeObject.BehaviourController.OnBehaviourAdded.RemoveListener(delegateOnBehaviourAdded);
universeObject.BehaviourController.OnBehaviourRemoved.RemoveListener(delegateOnBehaviourRemoved);
for (int i = 0; i < universeObject.BehaviourController.Count; i++)
OnBehaviourRemoved(universeObject.BehaviourController, new(universeObject.BehaviourController[i]));
}
protected virtual void OnBehaviourAdd(IBehaviour behaviour) { }
private void OnBehaviourAdded(IBehaviourController controller, IBehaviour behaviour)
private void OnBehaviourAdded(IBehaviourController controller, IBehaviourController.BehaviourAddedArguments args)
{
if (behaviour is not T tBehaviour)
if (args.BehaviourAdded is not T tBehaviour)
return;
monitoringBehaviours.Add(tBehaviour);
monitoringActiveToBehaviour.Add(tBehaviour, tBehaviour);
tBehaviour.OnActiveChanged += OnBehaviourStateChanged;
OnBehaviourStateChanged(tBehaviour, !tBehaviour.IsActive);
tBehaviour.OnActiveChanged.AddListener(delegateOnBehaviourStateChanged);
OnBehaviourStateChanged(tBehaviour, new(!tBehaviour.IsActive));
}
private void OnBehaviourStateChanged(IActive sender, bool previousState)
protected virtual void AddBehaviour(T behaviour) => activeBehaviours.Add(behaviour);
private void OnBehaviourStateChanged(IActive sender, IActive.ActiveChangedArguments args)
{
T behaviour = monitoringActiveToBehaviour[sender];
if (sender.IsActive)
{
activeBehaviours.Add(behaviour);
AddBehaviour(behaviour);
OnBehaviourAdd(behaviour);
OnCollected?.InvokeSafe(this, behaviour);
OnCollected?.Invoke(this, new(behaviour));
}
else if (activeBehaviours.Remove(behaviour))
{
OnBehaviourRemove(behaviour);
OnRemoved?.InvokeSafe(this, behaviour);
OnRemoved?.Invoke(this, new(behaviour));
}
}
protected virtual void OnBehaviourRemove(IBehaviour behaviour) { }
private void OnBehaviourRemoved(IBehaviourController controller, IBehaviour behaviour)
private void OnBehaviourRemoved(IBehaviourController controller, IBehaviourController.BehaviourRemovedArguments args)
{
if (behaviour is not T tBehaviour)
if (args.BehaviourRemoved is not T tBehaviour)
return;
if (!monitoringBehaviours.Remove(tBehaviour) || !monitoringActiveToBehaviour.Remove(tBehaviour))
return;
tBehaviour.OnActiveChanged -= OnBehaviourStateChanged;
tBehaviour.OnActiveChanged.RemoveListener(delegateOnBehaviourStateChanged);
if (activeBehaviours.Remove(tBehaviour))
{
OnBehaviourRemove(tBehaviour);
OnRemoved?.InvokeSafe(this, tBehaviour);
OnRemoved?.Invoke(this, new(tBehaviour));
}
}
@@ -93,13 +96,13 @@ public class ActiveBehaviourCollector<T> : IBehaviourCollector<T> where T : clas
return false;
foreach (IUniverseObject universeObject in universe.UniverseObjects)
OnUniverseObjectRegistered(universe, universeObject);
OnUniverseObjectRegistered(universe, new(universeObject));
universe.OnUniverseObjectRegistered += OnUniverseObjectRegistered;
universe.OnUniverseObjectUnRegistered += OnUniverseObjectUnregistered;
universe.OnUniverseObjectRegistered.AddListener(delegateOnUniverseObjectRegistered);
universe.OnUniverseObjectUnRegistered.AddListener(delegateOnUniverseObjectUnregistered);
Universe = universe;
OnUniverseAssigned?.InvokeSafe(this);
OnUniverseAssigned?.Invoke(this);
return true;
}
@@ -110,16 +113,36 @@ public class ActiveBehaviourCollector<T> : IBehaviourCollector<T> where T : clas
return false;
foreach (IUniverseObject universeObject in Universe.UniverseObjects)
OnUniverseObjectUnregistered(Universe, universeObject);
OnUniverseObjectUnregistered(Universe, new(universeObject));
Universe.OnUniverseObjectRegistered -= OnUniverseObjectRegistered;
Universe.OnUniverseObjectUnRegistered -= OnUniverseObjectUnregistered;
Universe.OnUniverseObjectRegistered.RemoveListener(delegateOnUniverseObjectRegistered);
Universe.OnUniverseObjectUnRegistered.RemoveListener(delegateOnUniverseObjectUnregistered);
Universe = null!;
OnUnassigned?.InvokeSafe(this);
OnUnassigned?.Invoke(this);
return true;
}
public IEnumerator<T> GetEnumerator() => activeBehaviours.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => activeBehaviours.GetEnumerator();
public int Count => activeBehaviours.Count;
public T this[Index index] => activeBehaviours[index];
public ActiveBehaviourCollector()
{
delegateOnBehaviourAdded = OnBehaviourAdded;
delegateOnBehaviourRemoved = OnBehaviourRemoved;
delegateOnBehaviourStateChanged = OnBehaviourStateChanged;
delegateOnUniverseObjectRegistered = OnUniverseObjectRegistered;
delegateOnUniverseObjectUnregistered = OnUniverseObjectUnregistered;
}
public ActiveBehaviourCollector(IUniverse universe)
{
delegateOnBehaviourAdded = OnBehaviourAdded;
delegateOnBehaviourRemoved = OnBehaviourRemoved;
delegateOnBehaviourStateChanged = OnBehaviourStateChanged;
delegateOnUniverseObjectRegistered = OnUniverseObjectRegistered;
delegateOnUniverseObjectUnregistered = OnUniverseObjectUnregistered;
Assign(universe);
}
}

View File

@@ -1,11 +1,14 @@
using System;
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class ActiveBehaviourCollectorSorted<T> : ActiveBehaviourCollector<T> where T : class, IBehaviour
{
private Comparison<T>? _sortBy = null;
public Comparison<T>? SortBy
private readonly Event<IBehaviour, IBehaviour.PriorityChangedArguments>.EventHandler delegateOnPriorityChanged = null!;
private IComparer<T>? _sortBy = null;
public IComparer<T>? SortBy
{
get => _sortBy;
set
@@ -17,12 +20,48 @@ public class ActiveBehaviourCollectorSorted<T> : ActiveBehaviourCollector<T> whe
}
}
protected override void OnBehaviourAdd(IBehaviour behaviour)
protected override void AddBehaviour(T behaviour)
{
if (SortBy is not null)
activeBehaviours.Sort(SortBy);
if (SortBy is null)
{
activeBehaviours.Add(behaviour);
return;
}
int insertionIndex = activeBehaviours.BinarySearch(behaviour, SortBy);
if (insertionIndex < 0)
insertionIndex = ~insertionIndex;
activeBehaviours.Insert(insertionIndex, behaviour);
}
public ActiveBehaviourCollectorSorted() { }
public ActiveBehaviourCollectorSorted(IUniverse universe, Comparison<T> sortBy) : base(universe) => SortBy = sortBy;
protected override void OnBehaviourAdd(IBehaviour behaviour)
{
behaviour.OnPriorityChanged.AddListener(delegateOnPriorityChanged);
}
protected override void OnBehaviourRemove(IBehaviour behaviour)
{
behaviour.OnPriorityChanged.RemoveListener(delegateOnPriorityChanged);
}
private void OnPriorityChanged(IBehaviour sender, IBehaviour.PriorityChangedArguments args)
{
T behaviour = (T)sender;
activeBehaviours.Remove(behaviour);
AddBehaviour(behaviour);
}
public ActiveBehaviourCollectorSorted()
{
delegateOnPriorityChanged = OnPriorityChanged;
}
public ActiveBehaviourCollectorSorted(IUniverse universe, Comparison<T> sortBy) : base(universe)
{
delegateOnPriorityChanged = OnPriorityChanged;
SortBy = Comparer<T>.Create(sortBy);
}
}

View File

@@ -4,13 +4,11 @@ namespace Syntriax.Engine.Core;
public abstract class BaseEntity : IEntity
{
public event IEntity.IdChangedEventHandler? OnIdChanged = null;
public event IInitializable.InitializedEventHandler? OnInitialized = null;
public event IInitializable.FinalizedEventHandler? OnFinalized = null;
public event IHasStateEnable.StateEnableAssignedEventHandler? OnStateEnableAssigned = null;
public event IAssignable.UnassignEventHandler? OnUnassigned = null;
public Event<IEntity, IEntity.IdChangedArguments> OnIdChanged { get; } = new();
public Event<IInitializable> OnInitialized { get; } = new();
public Event<IInitializable> OnFinalized { get; } = new();
public Event<IHasStateEnable> OnStateEnableAssigned { get; } = new();
public Event<IAssignable> OnUnassigned { get; } = new();
private IStateEnable _stateEnable = null!;
@@ -33,7 +31,7 @@ public abstract class BaseEntity : IEntity
string previousId = _id;
_id = value;
OnIdChanged?.InvokeSafe(this, previousId);
OnIdChanged?.Invoke(this, new(previousId));
}
}
@@ -47,9 +45,9 @@ public abstract class BaseEntity : IEntity
_initialized = value;
if (value)
OnInitialized?.InvokeSafe(this);
OnInitialized?.Invoke(this);
else
OnFinalized?.InvokeSafe(this);
OnFinalized?.Invoke(this);
}
}
@@ -62,7 +60,7 @@ public abstract class BaseEntity : IEntity
_stateEnable = stateEnable;
_stateEnable.Assign(this);
OnAssign(stateEnable);
OnStateEnableAssigned?.InvokeSafe(this);
OnStateEnableAssigned?.Invoke(this);
return true;
}
@@ -76,7 +74,7 @@ public abstract class BaseEntity : IEntity
_stateEnable = null!;
_stateEnable.Unassign();
OnUnassigned?.InvokeSafe(this);
OnUnassigned?.Invoke(this);
return true;
}

View File

@@ -2,108 +2,49 @@ namespace Syntriax.Engine.Core;
public abstract class Behaviour : BehaviourBase
{
private bool isInitializedThisFrame = false;
protected IUniverse Universe => BehaviourController.UniverseObject.Universe;
protected IUniverseObject UniverseObject => BehaviourController.UniverseObject;
private readonly Event<IUniverseObject, IUniverseObject.EnteredUniverseArguments>.EventHandler delegateEnteredUniverse = null!;
private readonly Event<IUniverseObject, IUniverseObject.ExitedUniverseArguments>.EventHandler delegateExitedUniverse = null!;
public Behaviour()
{
OnInitialized += OnInitialize;
OnFinalized += OnFinalize;
OnUnassigned += OnUnassign;
OnInitialized.AddListener(OnInitialize);
OnFinalized.AddListener(OnFinalize);
OnUnassigned.AddListener(OnUnassign);
delegateEnteredUniverse = EnteredUniverse;
delegateExitedUniverse = ExitedUniverse;
}
protected virtual void OnUnassign() { }
protected virtual void OnUnassign(IAssignable assignable) => OnUnassign();
protected void OnUnassign(IAssignable assignable) => OnUnassign();
protected virtual void OnInitialize() { }
protected virtual void OnInitialize(IInitializable _)
protected void OnInitialize(IInitializable _)
{
isInitializedThisFrame = true;
BehaviourController.OnPreUpdate += PreUpdate;
BehaviourController.OnPreDraw += PreDraw;
BehaviourController.OnUpdate += Update;
BehaviourController.UniverseObject.OnEnteredUniverse += EnteredUniverse;
BehaviourController.UniverseObject.OnExitedUniverse += ExitedUniverse;
BehaviourController.UniverseObject.OnEnteredUniverse.AddListener(delegateEnteredUniverse);
BehaviourController.UniverseObject.OnExitedUniverse.AddListener(delegateExitedUniverse);
OnInitialize();
if (UniverseObject.IsInUniverse)
EnteredUniverse(UniverseObject, Universe);
EnteredUniverse(UniverseObject, new(Universe));
}
protected virtual void OnFinalize() { }
protected virtual void OnFinalize(IInitializable _)
protected void OnFinalize(IInitializable _)
{
BehaviourController.OnPreUpdate -= PreUpdate;
BehaviourController.OnPreDraw -= PreDraw;
BehaviourController.OnUpdate -= Update;
BehaviourController.UniverseObject.OnEnteredUniverse -= EnteredUniverse;
BehaviourController.UniverseObject.OnExitedUniverse -= ExitedUniverse;
BehaviourController.UniverseObject.OnEnteredUniverse.RemoveListener(delegateEnteredUniverse);
BehaviourController.UniverseObject.OnExitedUniverse.RemoveListener(delegateExitedUniverse);
OnFinalize();
if (UniverseObject.IsInUniverse)
ExitedUniverse(UniverseObject, Universe);
}
protected virtual void OnPreUpdatePreActiveCheck() { }
protected virtual void OnPreUpdate() { }
protected virtual void PreUpdate(IBehaviourController _)
{
Debug.Assert.AssertInitialized(this);
OnPreUpdatePreActiveCheck();
if (!IsActive)
return;
if (isInitializedThisFrame)
FirstActiveFrame();
OnPreUpdate();
}
protected virtual void OnFirstActiveFrame() { }
protected virtual void FirstActiveFrame()
{
OnFirstActiveFrame();
isInitializedThisFrame = false;
}
protected virtual void OnUpdatePreActiveCheck() { }
protected virtual void OnUpdate() { }
protected virtual void Update(IBehaviourController _)
{
Debug.Assert.AssertInitialized(this);
OnUpdatePreActiveCheck();
if (!IsActive)
return;
OnUpdate();
}
protected virtual void OnPreDrawPreActiveCheck() { }
protected virtual void OnPreDraw() { }
protected virtual void PreDraw(IBehaviourController _)
{
Debug.Assert.AssertInitialized(this);
OnPreDrawPreActiveCheck();
if (!StateEnable.Enabled)
return;
OnPreDraw();
ExitedUniverse(UniverseObject, new(Universe));
}
protected virtual void OnEnteredUniverse(IUniverse universe) { }
protected virtual void EnteredUniverse(IUniverseObject sender, IUniverse universe) => OnEnteredUniverse(universe);
protected void EnteredUniverse(IUniverseObject sender, IUniverseObject.EnteredUniverseArguments args) => OnEnteredUniverse(args.Universe);
protected virtual void OnExitedUniverse(IUniverse universe) { }
protected virtual void ExitedUniverse(IUniverseObject sender, IUniverse universe) => OnExitedUniverse(universe);
protected void ExitedUniverse(IUniverseObject sender, IUniverseObject.ExitedUniverseArguments args) => OnExitedUniverse(args.Universe);
}

View File

@@ -4,23 +4,6 @@ public abstract class Behaviour2D : Behaviour, IBehaviour2D
{
public ITransform2D Transform { get; private set; } = null!;
protected sealed override void OnInitialize(IInitializable _)
{
Transform = BehaviourController.GetRequiredBehaviour<ITransform2D>();
base.OnInitialize(_);
}
protected sealed override void OnFinalize(IInitializable _)
{
Transform = null!;
base.OnFinalize(_);
}
protected sealed override void OnUnassign(IAssignable assignable) => base.OnUnassign(assignable);
protected sealed override void PreUpdate(IBehaviourController behaviourController) => base.PreUpdate(behaviourController);
protected sealed override void FirstActiveFrame() => base.FirstActiveFrame();
protected sealed override void Update(IBehaviourController behaviourController) => base.Update(behaviourController);
protected sealed override void PreDraw(IBehaviourController behaviourController) => base.PreDraw(behaviourController);
protected sealed override void EnteredUniverse(IUniverseObject sender, IUniverse universe) => base.EnteredUniverse(sender, universe);
protected sealed override void ExitedUniverse(IUniverseObject sender, IUniverse universe) => base.ExitedUniverse(sender, universe);
protected override void OnInitialize() => Transform = BehaviourController.GetRequiredBehaviour<ITransform2D>();
protected override void OnFinalize() => Transform = null!;
}

View File

@@ -3,9 +3,16 @@ namespace Syntriax.Engine.Core;
[System.Diagnostics.DebuggerDisplay("{GetType().Name, nq}, Priority: {Priority}, Initialized: {Initialized}")]
public abstract class BehaviourBase : BaseEntity, IBehaviour
{
public event IHasBehaviourController.BehaviourControllerAssignedEventHandler? OnBehaviourControllerAssigned = null;
public event IBehaviour.PriorityChangedEventHandler? OnPriorityChanged = null;
public event IActive.ActiveChangedEventHandler? OnActiveChanged = null;
public Event<IBehaviour, IBehaviour.PriorityChangedArguments> OnPriorityChanged { get; } = new();
public Event<IActive, IActive.ActiveChangedArguments> OnActiveChanged { get; } = new();
public Event<IHasBehaviourController> OnBehaviourControllerAssigned { get; } = new();
private readonly Event<IHasUniverseObject>.EventHandler delegateOnUniverseObjectAssigned = null!;
private readonly Event<IActive, IActive.ActiveChangedArguments>.EventHandler delegateOnUniverseObjectActiveChanged = null!;
private readonly Event<IStateEnable, IStateEnable.EnabledChangedArguments>.EventHandler delegateOnStateEnabledChanged = null!;
public IUniverse Universe => BehaviourController.UniverseObject.Universe;
public IUniverseObject UniverseObject => BehaviourController.UniverseObject;
private IBehaviourController _behaviourController = null!;
public IBehaviourController BehaviourController => _behaviourController;
@@ -21,7 +28,7 @@ public abstract class BehaviourBase : BaseEntity, IBehaviour
int previousPriority = _priority;
_priority = value;
OnPriorityChanged?.InvokeSafe(this, previousPriority);
OnPriorityChanged?.Invoke(this, new(previousPriority));
}
}
@@ -36,16 +43,17 @@ public abstract class BehaviourBase : BaseEntity, IBehaviour
_behaviourController = behaviourController;
OnAssign(behaviourController);
behaviourController.OnUniverseObjectAssigned += OnUniverseObjectAssigned;
behaviourController.OnUniverseObjectAssigned.AddListener(delegateOnUniverseObjectAssigned);
behaviourController.StateEnable.OnEnabledChanged.AddListener(delegateOnStateEnabledChanged);
if (behaviourController.UniverseObject is not null)
OnUniverseObjectAssigned(behaviourController);
OnBehaviourControllerAssigned?.InvokeSafe(this);
OnBehaviourControllerAssigned?.Invoke(this);
return true;
}
private void OnUniverseObjectAssigned(IHasUniverseObject sender)
{
sender.UniverseObject.OnActiveChanged += OnUniverseObjectActiveChanged;
sender.UniverseObject.OnActiveChanged.AddListener(delegateOnUniverseObjectActiveChanged);
UpdateActive();
}
@@ -53,13 +61,15 @@ public abstract class BehaviourBase : BaseEntity, IBehaviour
{
base.OnAssign(stateEnable);
stateEnable.OnEnabledChanged += OnStateEnabledChanged;
stateEnable.OnEnabledChanged.AddListener(delegateOnStateEnabledChanged);
}
protected override void UnassignInternal()
{
StateEnable.OnEnabledChanged -= OnStateEnabledChanged;
BehaviourController.OnUniverseObjectAssigned -= OnUniverseObjectAssigned;
BehaviourController.UniverseObject.OnActiveChanged.RemoveListener(delegateOnUniverseObjectActiveChanged);
StateEnable.OnEnabledChanged.RemoveListener(delegateOnStateEnabledChanged);
BehaviourController.OnUniverseObjectAssigned.RemoveListener(delegateOnUniverseObjectAssigned);
BehaviourController.StateEnable.OnEnabledChanged.RemoveListener(delegateOnStateEnabledChanged);
base.UnassignInternal();
_behaviourController = null!;
}
@@ -68,17 +78,26 @@ public abstract class BehaviourBase : BaseEntity, IBehaviour
{
Debug.Assert.AssertBehaviourControllerAssigned(this);
Debug.Assert.AssertStateEnableAssigned(this);
UpdateActive();
}
private void OnStateEnabledChanged(IStateEnable sender, bool previousState) => UpdateActive();
private void OnUniverseObjectActiveChanged(IActive sender, bool previousState) => UpdateActive();
private void OnStateEnabledChanged(IStateEnable sender, IStateEnable.EnabledChangedArguments args) => UpdateActive();
private void OnUniverseObjectActiveChanged(IActive sender, IActive.ActiveChangedArguments args) => UpdateActive();
private void UpdateActive()
{
bool previousActive = IsActive;
_isActive = StateEnable.Enabled && _behaviourController.UniverseObject.IsActive;
_isActive = StateEnable.Enabled && _behaviourController.StateEnable.Enabled && _behaviourController.UniverseObject.IsActive;
if (previousActive != IsActive)
OnActiveChanged?.InvokeSafe(this, previousActive);
OnActiveChanged?.Invoke(this, new(previousActive));
}
protected BehaviourBase()
{
delegateOnUniverseObjectAssigned = OnUniverseObjectAssigned;
delegateOnUniverseObjectActiveChanged = OnUniverseObjectActiveChanged;
delegateOnStateEnabledChanged = OnStateEnabledChanged;
}
}

View File

@@ -1,67 +1,69 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class BehaviourCollector<T> : IBehaviourCollector<T> where T : class
{
public event IAssignable.UnassignEventHandler? OnUnassigned = null;
public event IHasUniverse.UniverseAssignedEventHandler? OnUniverseAssigned = null;
public Event<IBehaviourCollector<T>, IBehaviourCollector<T>.BehaviourCollectedArguments> OnCollected { get; } = new();
public Event<IBehaviourCollector<T>, IBehaviourCollector<T>.BehaviourRemovedArguments> OnRemoved { get; } = new();
public Event<IHasUniverse> OnUniverseAssigned { get; } = new();
public Event<IAssignable>? OnUnassigned { get; } = new();
public event IBehaviourCollector<T>.CollectedEventHandler? OnCollected = null;
public event IBehaviourCollector<T>.RemovedEventHandler? OnRemoved = null;
private readonly Event<IBehaviourController, IBehaviourController.BehaviourAddedArguments>.EventHandler delegateOnBehaviourAdded = null!;
private readonly Event<IBehaviourController, IBehaviourController.BehaviourRemovedArguments>.EventHandler delegateOnBehaviourRemoved = null!;
private readonly Event<IUniverse, IUniverse.UniverseObjectRegisteredArguments>.EventHandler delegateOnUniverseObjectRegistered = null!;
private readonly Event<IUniverse, IUniverse.UniverseObjectUnRegisteredArguments>.EventHandler delegateOnUniverseObjectUnregistered = null!;
protected readonly List<T> behaviours = new(32);
public IReadOnlyList<T> Behaviours => behaviours;
public IUniverse Universe { get; private set; } = null!;
public T this[Index index] => behaviours[index];
public BehaviourCollector() { }
public BehaviourCollector(IUniverse universe) => Assign(universe);
private void OnUniverseObjectRegistered(IUniverse manager, IUniverseObject universeObject)
private void OnUniverseObjectRegistered(IUniverse manager, IUniverse.UniverseObjectRegisteredArguments args)
{
universeObject.BehaviourController.OnBehaviourAdded += OnBehaviourAdded;
universeObject.BehaviourController.OnBehaviourRemoved += OnBehaviourRemoved;
IUniverseObject universeObject = args.UniverseObjectRegistered;
foreach (IBehaviour item in universeObject.BehaviourController)
OnBehaviourAdded(universeObject.BehaviourController, item);
universeObject.BehaviourController.OnBehaviourAdded.AddListener(delegateOnBehaviourAdded);
universeObject.BehaviourController.OnBehaviourRemoved.AddListener(delegateOnBehaviourRemoved);
for (int i = 0; i < universeObject.BehaviourController.Count; i++)
OnBehaviourAdded(universeObject.BehaviourController, new(universeObject.BehaviourController[i]));
}
private void OnUniverseObjectUnregistered(IUniverse manager, IUniverseObject universeObject)
private void OnUniverseObjectUnregistered(IUniverse manager, IUniverse.UniverseObjectUnRegisteredArguments args)
{
universeObject.BehaviourController.OnBehaviourAdded -= OnBehaviourAdded;
universeObject.BehaviourController.OnBehaviourRemoved -= OnBehaviourRemoved;
IUniverseObject universeObject = args.UniverseObjectUnregistered;
foreach (IBehaviour item in universeObject.BehaviourController)
OnBehaviourRemoved(universeObject.BehaviourController, item);
universeObject.BehaviourController.OnBehaviourAdded.RemoveListener(delegateOnBehaviourAdded);
universeObject.BehaviourController.OnBehaviourRemoved.RemoveListener(delegateOnBehaviourRemoved);
for (int i = 0; i < universeObject.BehaviourController.Count; i++)
OnBehaviourRemoved(universeObject.BehaviourController, new(universeObject.BehaviourController[i]));
}
protected virtual void AddBehaviour(T behaviour) => behaviours.Add(behaviour);
protected virtual void OnBehaviourAdd(IBehaviour behaviour) { }
private void OnBehaviourAdded(IBehaviourController controller, IBehaviour behaviour)
private void OnBehaviourAdded(IBehaviourController controller, IBehaviourController.BehaviourAddedArguments args)
{
if (behaviour is not T tBehaviour)
if (args.BehaviourAdded is not T tBehaviour)
return;
behaviours.Add(tBehaviour);
OnBehaviourAdd(behaviour);
OnCollected?.InvokeSafe(this, tBehaviour);
AddBehaviour(tBehaviour);
OnBehaviourAdd(args.BehaviourAdded);
OnCollected?.Invoke(this, new(tBehaviour));
}
protected virtual void OnBehaviourRemove(IBehaviour behaviour) { }
private void OnBehaviourRemoved(IBehaviourController controller, IBehaviour behaviour)
private void OnBehaviourRemoved(IBehaviourController controller, IBehaviourController.BehaviourRemovedArguments args)
{
if (behaviour is not T tBehaviour)
if (args.BehaviourRemoved is not T tBehaviour)
return;
if (!behaviours.Remove(tBehaviour))
return;
OnBehaviourRemove(behaviour);
OnRemoved?.InvokeSafe(this, tBehaviour);
OnBehaviourRemove(args.BehaviourRemoved);
OnRemoved?.Invoke(this, new(tBehaviour));
}
protected virtual void OnAssign(IUniverse universe) { }
@@ -71,14 +73,14 @@ public class BehaviourCollector<T> : IBehaviourCollector<T> where T : class
return false;
foreach (IUniverseObject universeObject in universe.UniverseObjects)
OnUniverseObjectRegistered(universe, universeObject);
OnUniverseObjectRegistered(universe, new(universeObject));
universe.OnUniverseObjectRegistered += OnUniverseObjectRegistered;
universe.OnUniverseObjectUnRegistered += OnUniverseObjectUnregistered;
universe.OnUniverseObjectRegistered.AddListener(delegateOnUniverseObjectRegistered);
universe.OnPreUniverseObjectUnRegistered.AddListener(delegateOnUniverseObjectUnregistered);
Universe = universe;
OnAssign(universe);
OnUniverseAssigned?.InvokeSafe(this);
OnUniverseAssigned?.Invoke(this);
return true;
}
@@ -89,16 +91,34 @@ public class BehaviourCollector<T> : IBehaviourCollector<T> where T : class
return false;
foreach (IUniverseObject universeObject in Universe.UniverseObjects)
OnUniverseObjectUnregistered(Universe, universeObject);
OnUniverseObjectUnregistered(Universe, new(universeObject));
Universe.OnUniverseObjectRegistered -= OnUniverseObjectRegistered;
Universe.OnUniverseObjectUnRegistered -= OnUniverseObjectUnregistered;
Universe.OnUniverseObjectRegistered.RemoveListener(delegateOnUniverseObjectRegistered);
Universe.OnPreUniverseObjectUnRegistered.RemoveListener(delegateOnUniverseObjectUnregistered);
Universe = null!;
OnUnassigned?.InvokeSafe(this);
OnUnassigned?.Invoke(this);
return true;
}
public IEnumerator<T> GetEnumerator() => behaviours.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => behaviours.GetEnumerator();
public int Count => behaviours.Count;
public T this[Index index] => behaviours[index];
public BehaviourCollector()
{
delegateOnBehaviourAdded = OnBehaviourAdded;
delegateOnBehaviourRemoved = OnBehaviourRemoved;
delegateOnUniverseObjectRegistered = OnUniverseObjectRegistered;
delegateOnUniverseObjectUnregistered = OnUniverseObjectUnregistered;
}
public BehaviourCollector(IUniverse universe)
{
delegateOnBehaviourAdded = OnBehaviourAdded;
delegateOnBehaviourRemoved = OnBehaviourRemoved;
delegateOnUniverseObjectRegistered = OnUniverseObjectRegistered;
delegateOnUniverseObjectUnregistered = OnUniverseObjectUnregistered;
Assign(universe);
}
}

View File

@@ -1,11 +1,14 @@
using System;
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class BehaviourCollectorSorted<T> : BehaviourCollector<T> where T : class
{
private Comparison<T>? _sortBy = null;
public Comparison<T>? SortBy
private readonly Event<IBehaviour, IBehaviour.PriorityChangedArguments>.EventHandler delegateOnPriorityChanged = null!;
private IComparer<T>? _sortBy = null;
public IComparer<T>? SortBy
{
get => _sortBy;
set
@@ -17,12 +20,48 @@ public class BehaviourCollectorSorted<T> : BehaviourCollector<T> where T : class
}
}
protected override void OnBehaviourAdd(IBehaviour behaviour)
protected override void AddBehaviour(T behaviour)
{
if (SortBy is not null)
behaviours.Sort(SortBy);
if (SortBy is null)
{
behaviours.Add(behaviour);
return;
}
int insertionIndex = behaviours.BinarySearch(behaviour, SortBy);
if (insertionIndex < 0)
insertionIndex = ~insertionIndex;
behaviours.Insert(insertionIndex, behaviour);
}
public BehaviourCollectorSorted() { }
public BehaviourCollectorSorted(IUniverse universe, Comparison<T> sortBy) : base(universe) => SortBy = sortBy;
protected override void OnBehaviourAdd(IBehaviour behaviour)
{
behaviour.OnPriorityChanged.AddListener(delegateOnPriorityChanged);
}
protected override void OnBehaviourRemove(IBehaviour behaviour)
{
behaviour.OnPriorityChanged.RemoveListener(delegateOnPriorityChanged);
}
private void OnPriorityChanged(IBehaviour sender, IBehaviour.PriorityChangedArguments args)
{
T behaviour = (T)sender;
behaviours.Remove(behaviour);
AddBehaviour(behaviour);
}
public BehaviourCollectorSorted()
{
delegateOnPriorityChanged = OnPriorityChanged;
}
public BehaviourCollectorSorted(IUniverse universe, Comparison<T> sortBy) : base(universe)
{
delegateOnPriorityChanged = OnPriorityChanged;
SortBy = Comparer<T>.Create(sortBy);
}
}

View File

@@ -1,26 +1,22 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Syntriax.Engine.Core;
[System.Diagnostics.DebuggerDisplay("Behaviour Count: {behaviours.Count}")]
public class BehaviourController : BaseEntity, IBehaviourController
{
public event IBehaviourController.PreUpdateEventHandler? OnPreUpdate = null;
public event IBehaviourController.UpdateEventHandler? OnUpdate = null;
public event IBehaviourController.PreDrawEventHandler? OnPreDraw = null;
public Event<IBehaviourController, IBehaviourController.BehaviourAddedArguments> OnBehaviourAdded { get; } = new();
public Event<IBehaviourController, IBehaviourController.BehaviourRemovedArguments> OnBehaviourRemoved { get; } = new();
public Event<IHasUniverseObject> OnUniverseObjectAssigned { get; } = new();
public event IBehaviourController.BehaviourAddedEventHandler? OnBehaviourAdded = null;
public event IBehaviourController.BehaviourRemovedEventHandler? OnBehaviourRemoved = null;
public event IHasUniverseObject.UniverseObjectAssignedEventHandler? OnUniverseObjectAssigned = null;
private readonly IList<IBehaviour> behaviours = new List<IBehaviour>(Constants.BEHAVIOURS_SIZE_INITIAL);
private readonly List<IBehaviour> behaviours = new(Constants.BEHAVIOURS_SIZE_INITIAL);
private IUniverseObject _universeObject = null!;
public IUniverseObject UniverseObject => _universeObject;
public int Count => behaviours.Count;
public IBehaviour this[Index index] => behaviours[index];
public T AddBehaviour<T>(T behaviour) where T : class, IBehaviour
{
@@ -30,13 +26,17 @@ public class BehaviourController : BaseEntity, IBehaviourController
if (IsInitialized)
behaviour.Initialize();
behaviour.OnPriorityChanged += OnPriorityChange;
OnBehaviourAdded?.InvokeSafe(this, behaviour);
behaviour.OnPriorityChanged.AddListener(OnPriorityChange);
OnBehaviourAdded?.Invoke(this, new(behaviour));
return behaviour;
}
public T AddBehaviour<T>(params object?[]? args) where T : class, IBehaviour
=> AddBehaviour(Factory.BehaviourFactory.Instantiate<T>(_universeObject, args));
{
T behaviour = Factory.BehaviourFactory.Instantiate<T>(args);
return AddBehaviour(behaviour);
}
public T? GetBehaviour<T>()
{
@@ -49,17 +49,13 @@ public class BehaviourController : BaseEntity, IBehaviourController
public IReadOnlyList<T> GetBehaviours<T>()
{
List<T>? behaviours = null;
List<T> behaviours = [];
foreach (IBehaviour behaviourItem in this.behaviours)
{
if (behaviourItem is not T behaviour)
continue;
if (behaviourItem is T behaviour)
behaviours.Add(behaviour);
behaviours ??= [];
behaviours.Add(behaviour);
}
return behaviours ?? Enumerable.Empty<T>().ToList();
return behaviours;
}
public void GetBehaviours<T>(IList<T> results)
@@ -76,7 +72,7 @@ public class BehaviourController : BaseEntity, IBehaviourController
public void RemoveBehaviour<T>(bool removeAll = false) where T : class, IBehaviour
{
for (int i = behaviours.Count; i >= 0; i--)
for (int i = behaviours.Count - 1; i >= 0; i--)
{
if (behaviours[i] is not T behaviour)
continue;
@@ -93,10 +89,10 @@ public class BehaviourController : BaseEntity, IBehaviourController
if (!behaviours.Contains(behaviour))
throw new Exception($"{behaviour.GetType().Name} does not exist in {UniverseObject.Name}'s {nameof(IBehaviourController)}.");
behaviour.OnPriorityChanged -= OnPriorityChange;
behaviour.OnPriorityChanged.RemoveListener(OnPriorityChange);
behaviour.Finalize();
behaviours.Remove(behaviour);
OnBehaviourRemoved?.InvokeSafe(this, behaviour);
OnBehaviourRemoved?.Invoke(this, new(behaviour));
}
protected virtual void OnAssign(IUniverseObject universeObject) { }
@@ -107,7 +103,7 @@ public class BehaviourController : BaseEntity, IBehaviourController
_universeObject = universeObject;
OnAssign(universeObject);
OnUniverseObjectAssigned?.InvokeSafe(this);
OnUniverseObjectAssigned?.Invoke(this);
return true;
}
@@ -125,27 +121,6 @@ public class BehaviourController : BaseEntity, IBehaviourController
behaviour.Finalize();
}
public void Update()
{
Debug.Assert.AssertInitialized(this);
if (!UniverseObject.StateEnable.Enabled || !StateEnable.Enabled)
return;
OnPreUpdate?.InvokeSafe(this);
OnUpdate?.InvokeSafe(this);
}
public void UpdatePreDraw()
{
Debug.Assert.AssertInitialized(this);
if (!UniverseObject.StateEnable.Enabled || !StateEnable.Enabled)
return;
OnPreDraw?.InvokeSafe(this);
}
public BehaviourController() { }
public BehaviourController(IUniverseObject universeObject) => Assign(universeObject);
@@ -166,12 +141,9 @@ public class BehaviourController : BaseEntity, IBehaviourController
behaviours.Add(behaviour);
}
private void OnPriorityChange(IBehaviour sender, int previousPriority)
private void OnPriorityChange(IBehaviour sender, IBehaviour.PriorityChangedArguments args)
{
behaviours.Remove(sender);
InsertBehaviourByPriority(sender);
}
public IEnumerator<IBehaviour> GetEnumerator() => behaviours.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => behaviours.GetEnumerator();
}

View File

@@ -3,7 +3,7 @@ using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class CoroutineManager : UniverseObject
public class CoroutineManager : Behaviour, IUpdate
{
private readonly List<IEnumerator> enumerators = [];
@@ -18,17 +18,7 @@ public class CoroutineManager : UniverseObject
enumerators.Remove(enumerator);
}
protected override void OnEnteringUniverse(IUniverse universe)
{
universe.OnUpdate += OnUpdate;
}
protected override void OnExitingUniverse(IUniverse universe)
{
universe.OnUpdate -= OnUpdate;
}
private void OnUpdate(IUniverse sender, UniverseTime time)
void IUpdate.Update()
{
for (int i = enumerators.Count - 1; i >= 0; i--)
{
@@ -39,4 +29,6 @@ public class CoroutineManager : UniverseObject
enumerators.RemoveAt(i);
}
}
public CoroutineManager() => Priority = int.MinValue;
}

View File

@@ -10,21 +10,21 @@ public static class Assert
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AssertBehaviourControllerAssigned(IHasBehaviourController assignable)
=> System.Diagnostics.Debug.Assert(assignable.BehaviourController is not null, $"{assignable.GetType().Name} must be initialized");
=> System.Diagnostics.Debug.Assert(assignable.BehaviourController is not null, $"{assignable.GetType().Name} must be assigned an {nameof(IBehaviourController)}");
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AssertEntityAssigned(IHasEntity assignable)
=> System.Diagnostics.Debug.Assert(assignable.Entity is not null, $"{assignable.GetType().Name} must be initialized");
=> System.Diagnostics.Debug.Assert(assignable.Entity is not null, $"{assignable.GetType().Name} must be assigned an {nameof(IEntity)}");
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AssertUniverseAssigned(IHasUniverse assignable)
=> System.Diagnostics.Debug.Assert(assignable.Universe is not null, $"{assignable.GetType().Name} must be initialized");
=> System.Diagnostics.Debug.Assert(assignable.Universe is not null, $"{assignable.GetType().Name} must be assigned an {nameof(IUniverse)}");
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AssertUniverseObjectAssigned(IHasUniverseObject assignable)
=> System.Diagnostics.Debug.Assert(assignable.UniverseObject is not null, $"{assignable.GetType().Name} must be initialized");
=> System.Diagnostics.Debug.Assert(assignable.UniverseObject is not null, $"{assignable.GetType().Name} must be assigned an {nameof(IUniverseObject)}");
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AssertStateEnableAssigned(IHasStateEnable assignable)
=> System.Diagnostics.Debug.Assert(assignable.StateEnable is not null, $"{assignable.GetType().Name} must be initialized");
=> System.Diagnostics.Debug.Assert(assignable.StateEnable is not null, $"{assignable.GetType().Name} must be assigned an {nameof(IStateEnable)}");
}

View File

@@ -7,14 +7,23 @@ public class FileLogger : LoggerBase
{
public readonly string FilePath;
public FileLogger(string filePath)
{
FilePath = filePath;
File.Open(filePath, FileMode.Create).Close();
}
protected override void Write(string message)
{
File.AppendAllTextAsync(FilePath, $"{message}{Environment.NewLine}");
}
public FileLogger(string filePath)
{
FilePath = filePath;
bool isRelativePath = Path.GetFullPath(filePath).CompareTo(filePath) != 0;
if (isRelativePath)
FilePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filePath));
if (Path.GetDirectoryName(FilePath) is string directoryPath)
Directory.CreateDirectory(directoryPath);
File.Open(FilePath, FileMode.Create).Close();
}
}

View File

@@ -2,12 +2,15 @@ namespace Syntriax.Engine.Core.Debug;
public interface ILogger
{
static ILogger Shared { get; set; } = new ConsoleLogger();
Level FilterLevel { get; set; }
void Log(string message, Level level = Level.Info, bool force = false);
enum Level
{
Trace,
Info,
Warning,
Error,

View File

@@ -4,7 +4,7 @@ namespace Syntriax.Engine.Core.Debug;
public abstract class LoggerBase : ILogger
{
public ILogger.Level FilterLevel { get; set; } = ILogger.Level.Info;
public ILogger.Level FilterLevel { get; set; } = ILogger.Level.Trace;
public void Log(string message, ILogger.Level level = ILogger.Level.Info, bool force = false)
{

View File

@@ -0,0 +1,9 @@
namespace Syntriax.Engine.Core.Debug;
public class LoggerContainer : Behaviour, ILogger
{
public ILogger Logger { get; set; } = ILogger.Shared;
public ILogger.Level FilterLevel { get => Logger.FilterLevel; set => Logger.FilterLevel = value; }
public void Log(string message, ILogger.Level level = ILogger.Level.Info, bool force = false) => Logger.Log(message, level, force);
}

View File

@@ -16,13 +16,21 @@ public static class LoggerExtensions
public static void LogError<T>(this ILogger logger, T caller, string message, bool force = false)
{
Log(logger, caller, message, ILogger.Level.Error, force);
Log(logger, caller, $"{nameof(StackTrace)}:{Environment.NewLine}{new StackTrace()}");
LogTrace(logger, caller, new StackTrace(), force);
}
public static void LogException<T>(this ILogger logger, T caller, Exception exception, bool force = false)
{
Log(logger, caller, $"Exception of type {exception.GetType().Name} occured", ILogger.Level.Error, force);
Log(logger, caller, $"Message: {exception.Message}", ILogger.Level.Error, force);
Log(logger, caller, $"InnerException: {exception.InnerException}", ILogger.Level.Error, force);
Log(logger, caller, $"{nameof(StackTrace)}:{Environment.NewLine}{exception.StackTrace}");
// Not using LogTrace because exception.StackTrace is a type of string
Log(logger, caller, $"{nameof(StackTrace)}:{Environment.NewLine}{exception.StackTrace}", ILogger.Level.Trace);
}
public static void LogTrace<T>(this ILogger logger, T caller, StackTrace? stackTrace = null, bool force = false)
{
Log(logger, caller, $"{nameof(StackTrace)}:{Environment.NewLine}{stackTrace ?? new()}", ILogger.Level.Trace, force);
}
}

View File

@@ -0,0 +1,23 @@
namespace Syntriax.Engine.Core.Debug;
public class LoggerWrapper(ILogger firstLogger, ILogger secondLogger) : ILogger
{
private readonly ILogger firstLogger = firstLogger;
private readonly ILogger secondLogger = secondLogger;
public ILogger.Level FilterLevel
{
get => firstLogger.FilterLevel;
set
{
firstLogger.FilterLevel = value;
secondLogger.FilterLevel = value;
}
}
public void Log(string message, ILogger.Level level = ILogger.Level.Info, bool force = false)
{
firstLogger.Log(message, level, force);
secondLogger.Log(message, level, force);
}
}

View File

@@ -0,0 +1,6 @@
namespace Syntriax.Engine.Core.Debug;
public static class LoggerWrapperExtensions
{
public static ILogger WrapWith(this ILogger thisLogger, ILogger logger) => new LoggerWrapper(thisLogger, logger);
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>false</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Syntriax.Engine.Core</RootNamespace>

View File

@@ -1,9 +1,3 @@
using System;
namespace Syntriax.Engine.Core.Exceptions;
public class BehaviourNotFoundException(string? message) : Exception(message)
{
public static NotAssignedException FromType<TBehaviour>()
=> new($"{typeof(TBehaviour).FullName} was not found");
}
public class BehaviourNotFoundException(string? message) : NotFoundException(message);

View File

@@ -0,0 +1,9 @@
using System;
namespace Syntriax.Engine.Core.Exceptions;
public class NotFoundException(string? message) : Exception(message)
{
public static NotAssignedException FromType<T>()
=> new($"{typeof(T).FullName} was not found");
}

View File

@@ -1,9 +1,3 @@
using System;
namespace Syntriax.Engine.Core.Exceptions;
public class UniverseObjectNotFoundException(string? message) : Exception(message)
{
public static NotAssignedException FromType<TUniverseObject>()
=> new($"{typeof(TUniverseObject).FullName} was not found");
}
public class UniverseObjectNotFoundException(string? message) : NotFoundException(message);

View File

@@ -1,3 +1,4 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Syntriax.Engine.Core.Exceptions;
@@ -26,7 +27,7 @@ public static class BehaviourControllerExtensions
/// <param name="behaviourController">The <see cref="IBehaviourController"/> to start searching from.</param>
/// <returns>The <see cref="IBehaviour"/> of the specified type if found; otherwise, throws <see cref="BehaviourNotFoundException"/>.</returns>
public static T GetRequiredBehaviour<T>(this IBehaviourController behaviourController) where T : class
=> behaviourController.GetBehaviour<T>() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject.Name}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName}");
=> behaviourController.GetBehaviour<T>() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject?.Name ?? "NULL"}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName}");
/// <summary>
/// Gets an existing <see cref="IBehaviour"/> of the specified type, or adds and returns a new one if it doesn't exist.
@@ -38,6 +39,19 @@ public static class BehaviourControllerExtensions
public static T GetOrAddBehaviour<T>(this IBehaviourController behaviourController, params object?[]? args) where T : class, IBehaviour
=> behaviourController.GetBehaviour<T>() ?? behaviourController.AddBehaviour<T>(args);
/// <summary>
/// Gets an existing <see cref="IBehaviour"/> of the specified type, or adds and returns the fallback type if it doesn't exist.
/// </summary>
/// <typeparam name="TOriginal">The type of <see cref="IBehaviour"/> to get.</typeparam>
/// <typeparam name="TFallback">The type of <see cref="IBehaviour"/> to add. It must be assignable from <typeparamref name="TOriginal"/></typeparam>
/// <param name="behaviourController">The <see cref="IBehaviourController"/> to search in.</param>
/// <param name="args">Optional arguments to pass to the constructor of the <see cref="IBehaviour"/> if a new one is added.</param>
/// <returns>The existing or newly added <see cref="IBehaviour"/> of the specified type.</returns>
public static TOriginal GetOrAddBehaviour<TOriginal, TFallback>(this IBehaviourController behaviourController, params object?[]? args)
where TOriginal : class
where TFallback : class, IBehaviour, TOriginal
=> behaviourController.GetBehaviour<TOriginal>() ?? behaviourController.AddBehaviour<TFallback>(args);
/// <summary>
/// Tries to get a <see cref="IBehaviour"/> of the specified type in it's <see cref="IUniverseObject"/>'s parents recursively.
/// </summary>
@@ -79,7 +93,28 @@ public static class BehaviourControllerExtensions
/// <param name="behaviourController">The <see cref="IBehaviourController"/> to start searching from.</param>
/// <returns>The <see cref="IBehaviour"/> of the specified type if found; otherwise, throws <see cref="BehaviourNotFoundException"/>.</returns>
public static T GetRequiredBehaviourInParent<T>(this IBehaviourController behaviourController) where T : class
=> behaviourController.GetBehaviourInParent<T>() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject.Name}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName} on any parent");
=> behaviourController.GetBehaviourInParent<T>() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject?.Name ?? "NULL"}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName} on any parent");
/// <summary>
/// Gets all <see cref="IBehaviour"/>s of the specified type in it's <see cref="IUniverseObject"/>'s parents recursively and stores them in the provided list.
/// </summary>
/// <typeparam name="T">The type of <see cref="IBehaviour"/>s to get.</typeparam>
/// <param name="behavioursInParent">The list to store the <see cref="IBehaviour"/>s.</param>
public static void GetBehavioursInParent<T>(this IBehaviourController behaviourController, IList<T> behavioursInParent) where T : class
{
IBehaviourController? controller = behaviourController;
List<T> cache = [];
behavioursInParent.Clear();
while (controller is not null)
{
controller.GetBehaviours(cache);
foreach (T behaviour in cache)
behavioursInParent.Add(behaviour);
controller = controller.UniverseObject.Parent?.BehaviourController;
}
}
/// <summary>
/// Tries to get a <see cref="IBehaviour"/> of the specified type in it's <see cref="IUniverseObject"/>'s children recursively.
@@ -105,7 +140,7 @@ public static class BehaviourControllerExtensions
if (behaviourController.GetBehaviour<T>() is T localBehaviour)
return localBehaviour;
foreach (IUniverseObject child in behaviourController.UniverseObject)
foreach (IUniverseObject child in behaviourController.UniverseObject.Children)
if (GetBehaviourInChildren<T>(child.BehaviourController) is T behaviour)
return behaviour;
@@ -119,5 +154,29 @@ public static class BehaviourControllerExtensions
/// <param name="behaviourController">The <see cref="IBehaviourController"/> to start searching from.</param>
/// <returns>The <see cref="IBehaviour"/> of the specified type if found; otherwise, throws <see cref="BehaviourNotFoundException"/>.</returns>
public static T GetRequiredBehaviourInChildren<T>(this IBehaviourController behaviourController) where T : class
=> behaviourController.GetBehaviourInChildren<T>() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject.Name}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName} on any children ");
=> behaviourController.GetBehaviourInChildren<T>() ?? throw new BehaviourNotFoundException($"{behaviourController.UniverseObject?.Name ?? "NULL"}'s {nameof(IBehaviourController)} does not contain any {typeof(T).FullName} on any children ");
/// <summary>
/// Gets all <see cref="IBehaviour"/>s of the specified type in it's <see cref="IUniverseObject"/>'s children recursively and stores them in the provided list.
/// </summary>
/// <typeparam name="T">The type of <see cref="IBehaviour"/>s to get.</typeparam>
/// <param name="behavioursInChildren">The list to store the <see cref="IBehaviour"/>s.</param>
public static void GetBehavioursInChildren<T>(this IBehaviourController behaviourController, IList<T> behavioursInChildren) where T : class
{
List<T> cache = [];
behavioursInChildren.Clear();
TraverseChildrenForBehaviour(behaviourController.UniverseObject, behavioursInChildren, cache);
}
private static void TraverseChildrenForBehaviour<T>(IUniverseObject universeObject, IList<T> behaviours, IList<T> cache) where T : class
{
universeObject.BehaviourController.GetBehaviours(cache);
foreach (T behaviour in cache)
behaviours.Add(behaviour);
foreach (IUniverseObject child in universeObject.Children)
TraverseChildrenForBehaviour(child, behaviours, cache);
}
}

View File

@@ -1,34 +0,0 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Syntriax.Engine.Core;
public static class BehaviourExtensions
{
public static T? FindBehaviour<T>(this IEnumerable<IUniverseObject> universeObjects) where T : class
{
foreach (IUniverseObject universeObject in universeObjects)
if (universeObject.BehaviourController.GetBehaviour<T>() is T behaviour)
return behaviour;
return default;
}
public static bool TryFindBehaviour<T>(this IEnumerable<IUniverseObject> universeObjects, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class
{
behaviour = FindBehaviour<T>(universeObjects);
return behaviour is not null;
}
public static void FindBehaviours<T>(this IEnumerable<IUniverseObject> universeObjects, List<T> behaviours) where T : class
{
behaviours.Clear();
List<T> cache = [];
foreach (IUniverseObject universeObject in universeObjects)
{
universeObject.BehaviourController.GetBehaviours(cache);
behaviours.AddRange(cache);
}
}
}

View File

@@ -7,9 +7,30 @@ public static class UniverseExtensions
public static IUniverseObject InstantiateUniverseObject(this IUniverse universe, params object?[]? args)
=> universe.InstantiateUniverseObject<UniverseObject>(args);
/// <summary>
/// Searches through all <see cref="IUniverseObject"/>s to find the specified instance of the type.
/// </summary>
/// <typeparam name="T">Type to be searched through the <see cref="IUniverse"/>.</typeparam>
/// <returns>The specified type if found; otherwise, throws <see cref="UniverseObjectNotFoundException"/>.</returns>
public static T GetRequiredUniverseObject<T>(this IUniverse universe) where T : class
=> universe.GetUniverseObject<T>() ?? throw new UniverseObjectNotFoundException($"{universe.GetType().FullName}({universe.Id}) does not contain any {nameof(IUniverseObject)} object of type {typeof(T).FullName}");
/// <summary>
/// Searches through all <see cref="IBehaviours"/>s to find the specified instance of the type.
/// </summary>
/// <typeparam name="T">Type to be searched through the <see cref="IUniverse"/>.</typeparam>
/// <returns>The specified type if found; otherwise, throws <see cref="BehaviourNotFoundException"/>.</returns>
public static T FindRequiredBehaviour<T>(this IUniverse universe) where T : class
=> universe.FindBehaviour<T>() ?? throw new BehaviourNotFoundException($"{universe.GetType().FullName}({universe.Id}) does not contain any {nameof(IUniverseObject)} with {nameof(IBehaviour)} of type {typeof(T).FullName}");
/// <summary>
/// Searches through all <see cref="IUniverseObject"/>s and <see cref="IBehaviours"/>s to find the specified instance of the type.
/// </summary>
/// <remarks>
/// WARNING: This is more expensive compared to <see cref="GetRequiredUniverseObject{T}(IUniverse)"/> or <see cref="FindRequiredBehaviour{T}(IUniverse)"/> as it combines the two. If you know whether the type is either a type that gets implemented on an <see cref="IBehaviour"/> or <see cref="IUniverseObject"/> use the method appropriate for it for performance.
/// </remarks>
/// <typeparam name="T">Type to be searched through the <see cref="IUniverse"/>.</typeparam>
/// <returns>The specified type if found; otherwise, throws <see cref="NotFoundException"/>.</returns>
public static T FindRequired<T>(this IUniverse universe) where T : class
=> universe.Find<T>() ?? throw new NotFoundException($"{universe.GetType().FullName}({universe.Id}) does not contain any {nameof(IUniverseObject)} or {nameof(IBehaviour)} of type {typeof(T).FullName}");
}

View File

@@ -1,6 +1,8 @@
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Syntriax.Engine.Core.Exceptions;
namespace Syntriax.Engine.Core;
public static class UniverseObjectExtensions
@@ -10,10 +12,17 @@ public static class UniverseObjectExtensions
if (!string.IsNullOrWhiteSpace(name))
universeObject.Name = name;
if (parent is not null)
universeObject.SetParent(parent);
universeObject.Parent = parent;
return universeObject;
}
#region Universe Object Search
/// <summary>
/// Gets a <see cref="IUniverseObject"/> of the specified type.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="universeObjects">The <see cref="IUniverseObject"/>s to search.</param>
/// <returns>The first found <see cref="IUniverseObject"/> of the specified type; otherwise, null.</returns>
public static T? GetUniverseObject<T>(this IEnumerable<IUniverseObject> universeObjects) where T : class
{
foreach (IUniverseObject universeObject in universeObjects)
@@ -23,17 +32,224 @@ public static class UniverseObjectExtensions
return default;
}
public static bool TryGetUniverseObject<T>(this IEnumerable<IUniverseObject> universeObjects, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class
/// <summary>
/// Tries to get a <see cref="IUniverseObject"/> of the specified type.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="universeObjects">The <see cref="IUniverseObject"/>s to search.</param>
/// <returns><see cref="true"/> if a <see cref="IUniverseObject"/> of the specified type was found in the universe objects; otherwise, <see cref="false"/>.</returns>
public static bool TryGetUniverseObject<T>(this IEnumerable<IUniverseObject> universeObjects, [NotNullWhen(returnValue: true)] out T? universeObject) where T : class
{
behaviour = GetUniverseObject<T>(universeObjects);
universeObject = GetUniverseObject<T>(universeObjects);
return universeObject is not null;
}
/// <summary>
/// Searches through the provided <see cref="IUniverseObject"/>s to collect a list of <see cref="IUniverseObject"/>s of the specified type.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="universeObject">The <see cref="IUniverseObject"/> to search.</param>
/// <returns>The found <see cref="IUniverseObject"/>s of the specified types</returns>
public static void GetUniverseObjects<T>(this IEnumerable<IUniverseObject> universeObjects, IList<T> foundUniverseObjects) where T : class
{
foundUniverseObjects.Clear();
foreach (IUniverseObject universeObject in universeObjects)
if (universeObject is T @object)
foundUniverseObjects.Add(@object);
}
#endregion
#region Universe Object Search In Parent
/// <summary>
/// Tries to get a <see cref="IUniverseObject"/> of the specified type in it's parents recursively.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="behaviour">When this method returns, contains the <see cref="IUniverseObject"/> of the specified type, if found; otherwise, null.</param>
/// <returns><see cref="true"/> if a <see cref="IUniverseObject"/> of the specified type was found in the parent universe objects; otherwise, <see cref="false"/>.</returns>
public static bool TryGetUniverseObjectInParent<T>(this IUniverseObject universeObject, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class
{
behaviour = GetUniverseObjectInParent<T>(universeObject);
return behaviour is not null;
}
public static void GetUniverseObjects<T>(this IEnumerable<IUniverseObject> universeObjects, List<T> behaviours) where T : class
/// <summary>
/// Gets a <see cref="IUniverseObject"/> of the specified type in it's parents recursively.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="universeObject">The <see cref="IUniverseObject"/> to start searching from.</param>
/// <returns>The <see cref="IUniverseObject"/> of the specified type if found; otherwise, null.</returns>
public static T? GetUniverseObjectInParent<T>(this IUniverseObject universeObject) where T : class
{
if (universeObject.Children.GetUniverseObject<T>() is T localUniverseObject)
return localUniverseObject;
IUniverseObject? parent = universeObject;
while (parent is not null)
{
if (parent is T behaviour)
return behaviour;
parent = universeObject.Parent;
}
return default;
}
/// <summary>
/// Gets a <see cref="IUniverseObject"/> of the specified type in the parents recursively. Throws an error if not found.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="universeObject">The <see cref="IUniverseObject"/> to start searching from.</param>
/// <returns>The <see cref="IUniverseObject"/> of the specified type if found; otherwise, throws <see cref="UniverseObjectNotFoundException"/>.</returns>
public static T GetRequiredUniverseObjectInParent<T>(this IUniverseObject universeObject) where T : class
=> universeObject.GetUniverseObjectInParent<T>() ?? throw new UniverseObjectNotFoundException($"{universeObject.Name}'s {nameof(IUniverseObject)} does not contain any {typeof(T).FullName} on any parent ");
#endregion
#region Universe Object Search In Children
/// <summary>
/// Tries to get a <see cref="IUniverseObject"/> of the specified type in it's children recursively.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="behaviour">When this method returns, contains the <see cref="IUniverseObject"/> of the specified type, if found; otherwise, null.</param>
/// <returns><see cref="true"/> if a <see cref="IUniverseObject"/> of the specified type was found in the child universe objects; otherwise, <see cref="false"/>.</returns>
public static bool TryGetUniverseObjectInChildren<T>(this IUniverseObject universeObject, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class
{
behaviour = GetUniverseObjectInChildren<T>(universeObject);
return behaviour is not null;
}
/// <summary>
/// Gets a <see cref="IUniverseObject"/> of the specified type in it's children recursively.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="universeObject">The <see cref="IUniverseObject"/> to start searching from.</param>
/// <returns>The <see cref="IUniverseObject"/> of the specified type if found; otherwise, null.</returns>
public static T? GetUniverseObjectInChildren<T>(this IUniverseObject universeObject) where T : class
{
if (universeObject.Children.GetUniverseObject<T>() is T localUniverseObject)
return localUniverseObject;
foreach (IUniverseObject child in universeObject.Children)
if (GetUniverseObjectInChildren<T>(child) is T behaviour)
return behaviour;
return default;
}
/// <summary>
/// Gets a <see cref="IUniverseObject"/> of the specified type in the children recursively. Throws an error if not found.
/// </summary>
/// <typeparam name="T">The type of <see cref="IUniverseObject"/> to get.</typeparam>
/// <param name="universeObject">The <see cref="IUniverseObject"/> to start searching from.</param>
/// <returns>The <see cref="IUniverseObject"/> of the specified type if found; otherwise, throws <see cref="UniverseObjectNotFoundException"/>.</returns>
public static T GetRequiredUniverseObjectInChildren<T>(this IUniverseObject universeObject) where T : class
=> universeObject.GetUniverseObjectInChildren<T>() ?? throw new UniverseObjectNotFoundException($"{universeObject.Name}'s {nameof(IUniverseObject)} does not contain any {typeof(T).FullName} on any children ");
#endregion
#region Behaviour Search
/// <summary>
/// Finds a <see cref="IBehaviour"/> of the specified type in the provided <see cref="IUniverseObject"/>s.
/// </summary>
/// <typeparam name="T">The type of <see cref="IBehaviour"/> to find.</typeparam>
/// <returns>The first found <see cref="IBehaviour"/> of the specified type; otherwise, null.</returns>
public static T? FindBehaviour<T>(this IEnumerable<IUniverseObject> universeObjects) where T : class
{
foreach (IUniverseObject universeObject in universeObjects)
if (universeObject.BehaviourController.GetBehaviour<T>() is T behaviour)
return behaviour;
return default;
}
/// <summary>
/// Tries to find a <see cref="IBehaviour"/> of the specified type in the provided <see cref="IUniverseObject"/>s.
/// </summary>
/// <typeparam name="T">The type of <see cref="IBehaviour"/> to find.</typeparam>
/// <param name="behaviour">When this method returns, contains the <see cref="IUniverseObject"/> of the specified type, if found; otherwise, null.</param>
/// <returns><see cref="true"/> if a <see cref="IBehaviour"/> of the specified type was found in the provided <see cref="IUniverseObject"/>s; otherwise, <see cref="false"/>.</returns>
public static bool TryFindBehaviour<T>(this IEnumerable<IUniverseObject> universeObjects, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class
{
behaviour = FindBehaviour<T>(universeObjects);
return behaviour is not null;
}
/// <summary>
/// Searches through the provided <see cref="IUniverseObject"/>s to collect a list of <see cref="IBehaviour"/>s of the specified type.
/// </summary>
/// <typeparam name="T">The type of <see cref="IBehaviour"/> to get.</typeparam>
/// <param name="universeObjects">The <see cref="IUniverseObject"/>s to search.</param>
public static void FindBehaviours<T>(this IEnumerable<IUniverseObject> universeObjects, IList<T> behaviours) where T : class
{
behaviours.Clear();
List<T> cache = [];
foreach (IUniverseObject universeObject in universeObjects)
if (universeObject is T @object)
behaviours.Add(@object);
{
universeObject.BehaviourController.GetBehaviours(cache);
foreach (T behaviour in cache)
behaviours.Add(behaviour);
}
}
#endregion
#region General Search
/// <summary>
/// Finds an object of the specified type in the provided <see cref="IUniverseObject"/>s and their <see cref="IBehaviour"/>s.
/// </summary>
/// <remarks>
/// WARNING: This is more expensive compared to <see cref="GetUniverseObject{T}(IEnumerable{IUniverseObject})"/> or <see cref="FindBehaviour{T}(IEnumerable{IUniverseObject})"/> as it combines the two. If you know whether the type is either a type that gets implemented on an <see cref="IBehaviour"/> or <see cref="IUniverseObject"/> use the method appropriate for it for performance.
/// </remarks>
/// <typeparam name="T">The type of <see cref="IBehaviour"/> to find.</typeparam>
/// <returns>The first found instance of the specified type; otherwise, null.</returns>
public static T? Find<T>(this IEnumerable<IUniverseObject> universeObjects) where T : class
{
if (universeObjects.GetUniverseObject<T>() is T foundUniverseObject)
return foundUniverseObject;
if (universeObjects.FindBehaviour<T>() is T foundBehaviour)
return foundBehaviour;
return null;
}
/// <summary>
/// Tries to find an object of the specified type in the provided <see cref="IUniverseObject"/>s and their <see cref="IBehaviour"/>s.
/// </summary>
/// <remarks>
/// WARNING: This is more expensive compared to <see cref="TryGetUniverseObject{T}(IEnumerable{IUniverseObject}, out T?)"/> or <see cref="TryFindBehaviour{T}(IEnumerable{IUniverseObject}, out T?)"/> as it combines the two. If you know whether the type is either a type that gets implemented on an <see cref="IBehaviour"/> or <see cref="IUniverseObject"/> use the method appropriate for it for performance.
/// </remarks>
/// <typeparam name="T">The type of <see cref="IBehaviour"/> to find.</typeparam>
/// <param name="behaviour">When this method returns, contains the <see cref="IUniverseObject"/> of the specified type, if found; otherwise, null.</param>
/// <returns><see cref="true"/> if an object of the specified type was found in the provided <see cref="IUniverseObject"/>s; otherwise, <see cref="false"/>.</returns>
public static bool TryFind<T>(this IEnumerable<IUniverseObject> universeObjects, [NotNullWhen(returnValue: true)] out T? behaviour) where T : class
{
behaviour = Find<T>(universeObjects);
return behaviour is not null;
}
/// <summary>
/// Searches through the provided <see cref="IUniverseObject"/>s and their <see cref="IBehaviour"/>s to collect a list of the specified type.
/// </summary>
/// <remarks>
/// WARNING: This is more expensive compared to <see cref="GetUniverseObjects{T}(IEnumerable{IUniverseObject}, IList{T})"/> or <see cref="FindBehaviours{T}(IEnumerable{IUniverseObject}, IList{T})"/> as it combines the two. If you know whether the type is either a type that gets implemented on an <see cref="IBehaviour"/> or <see cref="IUniverseObject"/> use the method appropriate for it for performance.
/// </remarks>
/// <typeparam name="T">The type of <see cref="IBehaviour"/> to get.</typeparam>
/// <param name="instances">List of objects found wit the specified type.</param>
/// <param name="universeObjects">The <see cref="IUniverseObject"/>s to search.</param>
public static void Find<T>(this IEnumerable<IUniverseObject> universeObjects, IList<T> instances) where T : class
{
instances.Clear();
List<T> cache = [];
foreach (IUniverseObject universeObject in universeObjects)
{
universeObject.Children.Find(cache);
foreach (T behaviour in cache)
instances.Add(behaviour);
}
}
#endregion
}

View File

@@ -4,10 +4,10 @@ namespace Syntriax.Engine.Core.Factory;
public class BehaviourControllerFactory
{
public static IBehaviourController Instantiate(IUniverseObject universeObject)
=> Instantiate<BehaviourController>(universeObject);
public static IBehaviourController Instantiate(IUniverseObject universeObject, IStateEnable? stateEnable = null)
=> Instantiate<BehaviourController>(universeObject, stateEnable);
public static T Instantiate<T>(IUniverseObject universeObject, params object?[]? args)
public static T Instantiate<T>(IUniverseObject universeObject, IStateEnable? stateEnable = null, params object?[]? args)
where T : class, IBehaviourController
{
T behaviourController = TypeFactory.Get<T>(args);
@@ -18,6 +18,17 @@ public class BehaviourControllerFactory
if (!behaviourController.Assign(universeObject))
throw AssignFailedException.From(behaviourController, universeObject);
if (stateEnable is not null)
{
if (!stateEnable.Assign(behaviourController))
throw AssignFailedException.From(stateEnable, behaviourController);
if (!behaviourController.Assign(stateEnable))
throw AssignFailedException.From(behaviourController, stateEnable);
}
else
StateEnableFactory.Instantiate(behaviourController);
return behaviourController;
}
}

View File

@@ -4,22 +4,23 @@ namespace Syntriax.Engine.Core.Factory;
public class BehaviourFactory
{
public static T Instantiate<T>(IUniverseObject universeObject, params object?[]? args) where T : class, IBehaviour
=> Instantiate<T>(universeObject, stateEnable: null, args);
public static T Instantiate<T>(params object?[]? args) where T : class, IBehaviour
=> Instantiate<T>(stateEnable: null, args);
public static T Instantiate<T>(IUniverseObject universeObject, IStateEnable? stateEnable, params object?[]? args)
public static T Instantiate<T>(IStateEnable? stateEnable, params object?[]? args)
where T : class, IBehaviour
{
T behaviour = TypeFactory.Get<T>(args);
stateEnable ??= TypeFactory.Get<StateEnable>();
if (!stateEnable.Assign(behaviour))
throw AssignFailedException.From(stateEnable, behaviour);
if (!behaviour.Assign(stateEnable))
throw AssignFailedException.From(behaviour, stateEnable);
if (!behaviour.Assign(universeObject.BehaviourController))
throw AssignFailedException.From(behaviour, universeObject.BehaviourController);
if (stateEnable is not null)
{
if (!stateEnable.Assign(behaviour))
throw AssignFailedException.From(stateEnable, behaviour);
if (!behaviour.Assign(stateEnable))
throw AssignFailedException.From(behaviour, stateEnable);
}
else
StateEnableFactory.Instantiate(behaviour);
return behaviour;
}

View File

@@ -18,18 +18,25 @@ public class UniverseObjectFactory
{
T universeObject = TypeFactory.Get<T>(args);
behaviourController ??= TypeFactory.Get<BehaviourController>();
stateEnable ??= TypeFactory.Get<StateEnable>();
if (behaviourController is not null)
{
if (!behaviourController.Assign(universeObject))
throw AssignFailedException.From(behaviourController, universeObject);
if (!universeObject.Assign(behaviourController))
throw AssignFailedException.From(universeObject, behaviourController);
}
else
BehaviourControllerFactory.Instantiate(universeObject);
if (!behaviourController.Assign(universeObject))
throw AssignFailedException.From(behaviourController, universeObject);
if (!stateEnable.Assign(universeObject))
throw AssignFailedException.From(stateEnable, universeObject);
if (!universeObject.Assign(behaviourController))
throw AssignFailedException.From(universeObject, behaviourController);
if (!universeObject.Assign(stateEnable))
throw AssignFailedException.From(universeObject, stateEnable);
if (stateEnable is not null)
{
if (!stateEnable.Assign(universeObject))
throw AssignFailedException.From(stateEnable, universeObject);
if (!universeObject.Assign(stateEnable))
throw AssignFailedException.From(universeObject, stateEnable);
}
else
StateEnableFactory.Instantiate(universeObject);
return universeObject;
}

View File

@@ -1,17 +0,0 @@
using System;
namespace Syntriax.Engine.Core;
public static class DelegateExtensions
{
public static void InvokeSafe(this Delegate @delegate, params object?[] args)
{
foreach (Delegate invocation in @delegate.GetInvocationList())
try { invocation.DynamicInvoke(args); }
catch (Exception exception)
{
string methodCallRepresentation = $"{invocation.Method.DeclaringType?.FullName}.{invocation.Method.Name}({string.Join(", ", args)})";
Console.WriteLine($"Unexpected exception on invocation of method {methodCallRepresentation}:{Environment.NewLine}{exception.InnerException}");
}
}
}

View File

@@ -0,0 +1,500 @@
using System;
using System.Collections.Generic;
using Syntriax.Engine.Core.Debug;
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a simple event with no parameters.
/// <para>Example usage:</para>
/// <code>
/// public class MyBehaviour : Behaviour, IUpdate
/// {
/// public readonly Event MyEvent = new();
///
/// public MyBehaviour()
/// {
/// MyEvent.AddListener(OnEventTriggered);
/// MyEvent.AddOneTimeListener(OnEventTriggeredOneTime);
/// }
///
/// public void Update()
/// {
/// MyEvent.Invoke();
/// }
///
/// private void OnEventTriggered()
/// {
/// Console.WriteLine($"Event occurred!");
/// }
///
/// private static void OnEventTriggeredOneTime()
/// {
/// Console.WriteLine($"Event called once!");
/// }
/// }
/// </code>
/// The output of the example code above would be:
/// <code>
/// Event occurred!
/// Event called once!
/// Event occurred!
/// Event occurred!
/// Event occurred!
/// ...
/// </code>
/// </summary>
public class Event
{
// We use Ascending order because draw calls are running from last to first
private static readonly Comparer<ListenerData> SortByAscendingPriority = Comparer<ListenerData>.Create((x, y) => x.Priority.CompareTo(y.Priority));
private ILogger _logger = ILogger.Shared;
public ILogger Logger { get => _logger; set => _logger = value ?? ILogger.Shared; }
private readonly List<ListenerData> listeners = null!;
private readonly List<ListenerData> onceListeners = null!;
/// <summary>
/// Subscribes the callback to be invoked whenever the event is triggered.
/// </summary>
/// <param name="listener">The callback to be called when the event is triggered.</param>
/// <param name="priority">Priority of the callback.</param>
public void AddListener(EventHandler listener, int priority = 0)
{
ListenerData listenerData = new(listener, priority);
int insertIndex = listeners.BinarySearch(listenerData, SortByAscendingPriority);
if (insertIndex < 0)
insertIndex = ~insertIndex;
listeners.Insert(insertIndex, listenerData);
}
/// <summary>
/// Subscribes the callback to be invoked the next time the event is triggered. The callback will be called only once.
/// </summary>
/// <param name="listener">The callback to be called the next time the event is triggered.</param>
/// <param name="priority">Priority of the callback.</param>
public void AddOneTimeListener(EventHandler listener, int priority = 0)
{
ListenerData listenerData = new(listener, priority);
int insertIndex = onceListeners.BinarySearch(listenerData, SortByAscendingPriority);
if (insertIndex < 0)
insertIndex = ~insertIndex;
onceListeners.Insert(insertIndex, listenerData);
}
/// <summary>
/// Unsubscribes the callback that was previously registered by <see cref="AddListener(EventHandler)"/>.
/// </summary>
/// <param name="listener">The callback that was previously registered by <see cref="AddListener(EventHandler)"/></param>
public void RemoveListener(EventHandler listener)
{
for (int i = listeners.Count - 1; i >= 0; i--)
if (listeners[i].Callback == listener)
{
listeners.RemoveAt(i);
return;
}
}
/// <summary>
/// Unsubscribes the callback that was previously registered by <see cref="AddOneTimeListener(EventHandler)"/>.
/// </summary>
/// <param name="listener">The callback that was previously registered by <see cref="AddOneTimeListener(EventHandler)"/></param>
public void RemoveOneTimeListener(EventHandler listener)
{
for (int i = 0; i < onceListeners.Count; i++)
if (onceListeners[i].Callback == listener)
{
onceListeners.RemoveAt(i);
return;
}
}
/// <summary>
/// Unsubscribes all listeners that was previously registered by either <see cref="AddListener(EventHandler)"/> or <see cref="AddOneTimeListener(EventHandler)"/>.
/// </summary>
public void Clear() { listeners.Clear(); onceListeners.Clear(); }
/// <summary>
/// Triggers the event.
/// </summary>
public void Invoke()
{
for (int i = listeners.Count - 1; i >= 0; i--)
try { listeners[i].Callback.Invoke(); }
catch (Exception exception)
{
string methodCallRepresentation = $"{listeners[i].Callback.Method.DeclaringType?.FullName}.{listeners[i].Callback.Method.Name}()";
EventHelpers.LogInvocationException(listeners[i].Callback.Target ?? this, Logger, exception, methodCallRepresentation);
}
for (int i = onceListeners.Count - 1; i >= 0; i--)
{
try { onceListeners[i].Callback.Invoke(); }
catch (Exception exception)
{
string methodCallRepresentation = $"{onceListeners[i].Callback.Method.DeclaringType?.FullName}.{onceListeners[i].Callback.Method.Name}()";
EventHelpers.LogInvocationException(onceListeners[i].Callback.Target ?? this, Logger, exception, methodCallRepresentation);
}
onceListeners.RemoveAt(i);
}
}
public Event(int initialListenerCount = 4, int initialOnceListenerCount = 2)
{
listeners = new(initialListenerCount);
onceListeners = new(initialOnceListenerCount);
}
public Event()
{
listeners = new(4);
onceListeners = new(2);
}
public delegate void EventHandler();
private record struct ListenerData(EventHandler Callback, int Priority);
}
/// <summary>
/// Represents an event with only sender parameters.
/// <para>Example usage:</para>
/// <code>
/// public class MyBehaviour : Behaviour, IUpdate
/// {
/// public readonly Event&lt;MyBehaviour&gt; MyEvent = new();
///
/// public MyBehaviour()
/// {
/// MyEvent.AddListener(OnEventTriggered);
/// MyEvent.AddOneTimeListener(OnEventTriggeredOneTime);
/// }
///
/// public void Update()
/// {
/// MyEvent.Invoke(this);
/// }
///
/// private void OnEventTriggered(MyBehaviour sender)
/// {
/// Console.WriteLine($"{sender.Id}'s event occurred!");
/// }
///
/// private static void OnEventTriggeredOneTime(MyBehaviour sender)
/// {
/// Console.WriteLine($"{sender.Id}'s event called once!");
/// }
/// }
/// </code>
/// The output of the example code above would be:
/// <code>
/// [Id]'s event occurred!
/// [Id]'s event called once!
/// [Id]'s event occurred!
/// [Id]'s event occurred!
/// [Id]'s event occurred!
/// ...
/// </code>
///
/// </summary>
/// <typeparam name="TSender">Sender type</typeparam>
public class Event<TSender> where TSender : class
{
// We use Ascending order because draw calls are running from last to first
private static readonly Comparer<ListenerData> SortByAscendingPriority = Comparer<ListenerData>.Create((x, y) => x.Priority.CompareTo(y.Priority));
private ILogger _logger = ILogger.Shared;
public ILogger Logger { get => _logger; set => _logger = value ?? ILogger.Shared; }
private readonly List<ListenerData> listeners = null!;
private readonly List<ListenerData> onceListeners = null!;
/// <summary>
/// Subscribes the callback to be invoked whenever the event is triggered.
/// </summary>
/// <param name="listener">The callback to be called when the event is triggered.</param>
/// <param name="priority">Priority of the callback.</param>
public void AddListener(EventHandler listener, int priority = 0)
{
ListenerData listenerData = new(listener, priority);
int insertIndex = listeners.BinarySearch(listenerData, SortByAscendingPriority);
if (insertIndex < 0)
insertIndex = ~insertIndex;
listeners.Insert(insertIndex, listenerData);
}
/// <summary>
/// Subscribes the callback to be invoked the next time the event is triggered. The callback will be called only once.
/// </summary>
/// <param name="listener">The callback to be called the next time the event is triggered.</param>
/// <param name="priority">Priority of the callback.</param>
public void AddOneTimeListener(EventHandler listener, int priority = 0)
{
ListenerData listenerData = new(listener, priority);
int insertIndex = onceListeners.BinarySearch(listenerData, SortByAscendingPriority);
if (insertIndex < 0)
insertIndex = ~insertIndex;
onceListeners.Insert(insertIndex, listenerData);
}
/// <summary>
/// Unsubscribes the callback that was previously registered by <see cref="AddListener(EventHandler)"/>.
/// </summary>
/// <param name="listener">The callback that was previously registered by <see cref="AddListener(EventHandler)"/></param>
public void RemoveListener(EventHandler listener)
{
for (int i = listeners.Count - 1; i >= 0; i--)
if (listeners[i].Callback == listener)
{
listeners.RemoveAt(i);
return;
}
}
/// <summary>
/// Unsubscribes the callback that was previously registered by <see cref="AddOneTimeListener(EventHandler)"/>.
/// </summary>
/// <param name="listener">The callback that was previously registered by <see cref="AddOneTimeListener(EventHandler)"/></param>
public void RemoveOneTimeListener(EventHandler listener)
{
for (int i = 0; i < onceListeners.Count; i++)
if (onceListeners[i].Callback == listener)
{
onceListeners.RemoveAt(i);
return;
}
}
/// <summary>
/// Unsubscribes all listeners that was previously registered by either <see cref="AddListener(EventHandler)"/> or <see cref="AddOneTimeListener(EventHandler)"/>.
/// </summary>
public void Clear() { listeners.Clear(); onceListeners.Clear(); }
/// <summary>
/// Triggers the event.
/// </summary>
/// <param name="sender">The caller that's triggering this event.</param>
public void Invoke(TSender sender)
{
for (int i = listeners.Count - 1; i >= 0; i--)
try { listeners[i].Callback.Invoke(sender); }
catch (Exception exception)
{
string methodCallRepresentation = $"{listeners[i].Callback.Method.DeclaringType?.FullName}.{listeners[i].Callback.Method.Name}({sender})";
EventHelpers.LogInvocationException(listeners[i].Callback.Target ?? sender, Logger, exception, methodCallRepresentation);
}
for (int i = onceListeners.Count - 1; i >= 0; i--)
{
try { onceListeners[i].Callback.Invoke(sender); }
catch (Exception exception)
{
string methodCallRepresentation = $"{onceListeners[i].Callback.Method.DeclaringType?.FullName}.{onceListeners[i].Callback.Method.Name}({sender})";
EventHelpers.LogInvocationException(onceListeners[i].Callback.Target ?? sender, Logger, exception, methodCallRepresentation);
}
onceListeners.RemoveAt(i);
}
}
public Event(int initialListenerCount = 4, int initialOnceListenerCount = 2)
{
listeners = new(initialListenerCount);
onceListeners = new(initialOnceListenerCount);
}
public Event()
{
listeners = new(4);
onceListeners = new(2);
}
public delegate void EventHandler(TSender sender);
private record struct ListenerData(EventHandler Callback, int Priority);
}
/// <summary>
/// Represents an event with sender and argument parameters.
/// <para>Example usage:</para>
/// <code>
/// public class MyBehaviour : Behaviour, IUpdate
/// {
/// public readonly Event&lt;MyBehaviour, MyArguments&gt; MyEvent = new();
///
/// private int myInt = 0;
/// private bool myBool = false;
///
/// public MyBehaviour()
/// {
/// MyEvent.AddOneTimeListener(OnEventTriggeredOneTime);
/// MyEvent.AddListener(OnEventTriggered);
/// }
///
/// public void Update()
/// {
/// MyEvent.Invoke(this, new MyArguments(myInt, myBool));
/// myInt++;
/// myBool = !myBool;
/// }
///
/// private void OnEventTriggered(MyBehaviour sender, MyArguments args)
/// {
/// Console.WriteLine($"{sender.Id}'s event occurred with MyInt: {args.MyInt} and MyBool {args.MyBool}!");
/// }
///
/// private static void OnEventTriggeredOneTime(MyBehaviour sender, MyArguments args)
/// {
/// Console.WriteLine($"{sender.Id}'s event called once with MyInt: {args.MyInt} and MyBool {args.MyBool}!");
/// }
///
/// public readonly record struct MyArguments(int MyInt, bool MyBool);
/// }
/// </code>
/// The output of the example code above would be:
/// <code>
/// [Id]'s event occurred with MyInt: 0 and MyBool False!
/// [Id]'s event called once with MyInt: 0 and MyBool False!
/// [Id]'s event occurred with MyInt: 1 and MyBool True!
/// [Id]'s event occurred with MyInt: 2 and MyBool False!
/// [Id]'s event occurred with MyInt: 3 and MyBool True!
/// ...
/// </code>
///
/// </summary>
/// <typeparam name="TSender">Sender type</typeparam>
public class Event<TSender, TArguments> where TSender : class
{
// We use Ascending order because draw calls are running from last to first
private static readonly Comparer<ListenerData> SortByAscendingPriority = Comparer<ListenerData>.Create((x, y) => x.Priority.CompareTo(y.Priority));
private ILogger _logger = ILogger.Shared;
public ILogger Logger { get => _logger; set => _logger = value ?? ILogger.Shared; }
private readonly List<ListenerData> listeners = null!;
private readonly List<ListenerData> onceListeners = null!;
/// <summary>
/// Subscribes the callback to be invoked whenever the event is triggered.
/// </summary>
/// <param name="listener">The callback to be called when the event is triggered.</param>
/// <param name="priority">Priority of the callback.</param>
public void AddListener(EventHandler listener, int priority = 0)
{
ListenerData listenerData = new(listener, priority);
int insertIndex = listeners.BinarySearch(listenerData, SortByAscendingPriority);
if (insertIndex < 0)
insertIndex = ~insertIndex;
listeners.Insert(insertIndex, listenerData);
}
/// <summary>
/// Subscribes the callback to be invoked the next time the event is triggered. The callback will be called only once.
/// </summary>
/// <param name="listener">The callback to be called the next time the event is triggered.</param>
/// <param name="priority">Priority of the callback.</param>
public void AddOneTimeListener(EventHandler listener, int priority = 0)
{
ListenerData listenerData = new(listener, priority);
int insertIndex = onceListeners.BinarySearch(listenerData, SortByAscendingPriority);
if (insertIndex < 0)
insertIndex = ~insertIndex;
onceListeners.Insert(insertIndex, listenerData);
}
/// <summary>
/// Unsubscribes the callback that was previously registered by <see cref="AddListener(EventHandler)"/>.
/// </summary>
/// <param name="listener">The callback that was previously registered by <see cref="AddListener(EventHandler)"/></param>
public void RemoveListener(EventHandler listener)
{
for (int i = listeners.Count - 1; i >= 0; i--)
if (listeners[i].Callback == listener)
{
listeners.RemoveAt(i);
return;
}
}
/// <summary>
/// Unsubscribes the callback that was previously registered by <see cref="AddOneTimeListener(EventHandler)"/>.
/// </summary>
/// <param name="listener">The callback that was previously registered by <see cref="AddOneTimeListener(EventHandler)"/></param>
public void RemoveOneTimeListener(EventHandler listener)
{
for (int i = 0; i < onceListeners.Count; i++)
if (onceListeners[i].Callback == listener)
{
onceListeners.RemoveAt(i);
return;
}
}
/// <summary>
/// Unsubscribes all listeners that was previously registered by either <see cref="AddListener(EventHandler)"/> or <see cref="AddOneTimeListener(EventHandler)"/>.
/// </summary>
public void Clear() { listeners.Clear(); onceListeners.Clear(); }
/// <summary>
/// Triggers the event.
/// </summary>
/// <param name="sender">The caller that's triggering this event.</param>
/// <param name="args">The arguments provided for this event.</param>
public void Invoke(TSender sender, TArguments args)
{
for (int i = listeners.Count - 1; i >= 0; i--)
try { listeners[i].Callback.Invoke(sender, args); }
catch (Exception exception)
{
string methodCallRepresentation = $"{listeners[i].Callback.Method.DeclaringType?.FullName}.{listeners[i].Callback.Method.Name}({sender}, {args})";
EventHelpers.LogInvocationException(listeners[i].Callback.Target ?? sender, Logger, exception, methodCallRepresentation);
}
for (int i = onceListeners.Count - 1; i >= 0; i--)
{
try { onceListeners[i].Callback.Invoke(sender, args); }
catch (Exception exception)
{
string methodCallRepresentation = $"{onceListeners[i].Callback.Method.DeclaringType?.FullName}.{onceListeners[i].Callback.Method.Name}({sender}, {args})";
EventHelpers.LogInvocationException(onceListeners[i].Callback.Target ?? sender, Logger, exception, methodCallRepresentation);
}
onceListeners.RemoveAt(i);
}
}
public Event(int initialListenerCount = 4, int initialOnceListenerCount = 2)
{
listeners = new(initialListenerCount);
onceListeners = new(initialOnceListenerCount);
}
public Event()
{
listeners = new(4);
onceListeners = new(2);
}
public delegate void EventHandler(TSender sender, TArguments args);
private record struct ListenerData(EventHandler Callback, int Priority);
}
internal static class EventHelpers
{
public static void LogInvocationException(object sender, ILogger logger, Exception exception, string methodCallRepresentation)
{
logger.LogException(sender, exception);
logger.LogError(sender, $"Unexpected exception on invocation of method {methodCallRepresentation}");
}
}

View File

@@ -0,0 +1,10 @@
namespace Syntriax.Engine.Core;
public interface IPool<T>
{
Event<IPool<T>, T> OnRemoved { get; }
Event<IPool<T>, T> OnReturned { get; }
T Get();
void Return(T item);
}

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class ListPool<T> : IPool<List<T>>
{
public Event<IPool<List<T>>, List<T>> OnReturned { get; } = new();
public Event<IPool<List<T>>, List<T>> OnRemoved { get; } = new();
private readonly Func<List<T>> generator = null!;
private readonly Queue<List<T>> queue = new();
public List<T> Get()
{
if (!queue.TryDequeue(out List<T>? result))
result = generator();
result.Clear();
OnRemoved?.Invoke(this, result);
return result;
}
public void Return(List<T> list)
{
if (queue.Contains(list))
return;
list.Clear();
queue.Enqueue(list);
OnReturned?.Invoke(this, list);
}
public ListPool(int initialListCount = 1, int initialListCapacity = 32)
{
generator = () => new(initialListCapacity);
for (int i = 0; i < initialListCount; i++)
queue.Enqueue(generator());
}
}

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class Pool<T> : IPool<T>
{
public Event<IPool<T>, T> OnRemoved { get; } = new();
public Event<IPool<T>, T> OnReturned { get; } = new();
private readonly Func<T> generator = null!;
private readonly Queue<T> queue = new();
public T Get()
{
if (!queue.TryDequeue(out T? result))
result = generator();
OnRemoved?.Invoke(this, result);
return result;
}
public void Return(T item)
{
if (queue.Contains(item))
return;
queue.Enqueue(item);
OnReturned?.Invoke(this, item);
}
public Pool(Func<T> generator, int initialCapacity = 1)
{
this.generator = generator;
for (int i = 0; i < initialCapacity; i++)
queue.Enqueue(generator());
}
}

View File

@@ -2,12 +2,11 @@ namespace Syntriax.Engine.Core;
public interface IReadOnlyProgressionTracker
{
event ProgressionUpdatedEventHandler? OnUpdated;
event ProgressionEndedEventHandler? OnEnded;
Event<IReadOnlyProgressionTracker, ProgressionUpdatedArguments> OnUpdated { get; }
Event<IReadOnlyProgressionTracker> OnEnded { get; }
float Progression { get; }
string Status { get; }
delegate void ProgressionUpdatedEventHandler(IReadOnlyProgressionTracker sender, float previousProgression, string previousStatus);
delegate void ProgressionEndedEventHandler(IReadOnlyProgressionTracker sender);
readonly record struct ProgressionUpdatedArguments(float PreviousProgression, string PreviousStatus);
}

View File

@@ -2,8 +2,8 @@ namespace Syntriax.Engine.Core;
public class ProgressionTracker : IProgressionTracker
{
public event IReadOnlyProgressionTracker.ProgressionUpdatedEventHandler? OnUpdated = null;
public event IReadOnlyProgressionTracker.ProgressionEndedEventHandler? OnEnded = null;
public Event<IReadOnlyProgressionTracker, IReadOnlyProgressionTracker.ProgressionUpdatedArguments> OnUpdated { get; } = new();
public Event<IReadOnlyProgressionTracker> OnEnded { get; } = new();
public float Progression { get; private set; } = 0f;
public string Status { get; private set; } = "Default";
@@ -19,10 +19,10 @@ public class ProgressionTracker : IProgressionTracker
Progression = progression.Clamp(Progression, 1f);
Status = status;
OnUpdated?.InvokeSafe(this, previousProgression, previousStatus);
OnUpdated?.Invoke(this, new(previousProgression, previousStatus));
if (progression >= 1f)
OnEnded?.InvokeSafe(this);
OnEnded?.Invoke(this);
}
void IProgressionTracker.Reset()
@@ -30,7 +30,7 @@ public class ProgressionTracker : IProgressionTracker
Progression = 0f;
Status = "Default";
OnUpdated = null;
OnEnded = null;
OnUpdated.Clear();
OnEnded.Clear();
}
}

View File

@@ -6,29 +6,29 @@ namespace Syntriax.Engine.Core;
public static class Math
{
/// <summary>
/// The value of Pi (π), a mathematical constant approximately equal to 3.14159.
/// The value of Pi (π).
/// </summary>
public const float PI = 3.1415926535897932f;
public const float Pi = 3.1415926535897932f;
/// <summary>
/// The value of Tau (τ), a mathematical constant equal to 2π, approximately equal to 6.28319.
/// The value of Tau (τ), mathematical constant equal to 2π.
/// </summary>
public const float Tau = 2f * PI;
public const float Tau = 2f * Pi;
/// <summary>
/// The base of the natural logarithm, approximately equal to 2.71828.
/// The base of the natural logarithm.
/// </summary>
public const float E = 2.718281828459045f;
/// <summary>
/// The conversion factor from radians to degrees.
/// </summary>
public const float RadianToDegree = 180f / PI;
public const float RadianToDegree = 180f / Pi;
/// <summary>
/// The conversion factor from degrees to radians.
/// </summary>
public const float DegreeToRadian = PI / 180f;
public const float DegreeToRadian = Pi / 180f;
/// <summary>
/// Gets one minus of given <see cref="T"/>.

View File

@@ -38,6 +38,9 @@ public readonly struct AABB(Vector2D lowerBoundary, Vector2D upperBoundary)
/// </summary>
public readonly Vector2D SizeHalf => Size * .5f;
public static bool operator ==(AABB left, AABB right) => left.UpperBoundary == right.UpperBoundary && left.LowerBoundary == right.LowerBoundary;
public static bool operator !=(AABB left, AABB right) => left.UpperBoundary != right.UpperBoundary || left.LowerBoundary != right.LowerBoundary;
/// <summary>
/// Creates an <see cref="AABB"/> from a collection of <see cref="Vector2D"/>s.
/// </summary>
@@ -63,12 +66,6 @@ public readonly struct AABB(Vector2D lowerBoundary, Vector2D upperBoundary)
return new(lowerBoundary, upperBoundary);
}
/// <summary>
/// Converts the <see cref="AABB"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="AABB"/>.</returns>
public override string ToString() => $"{nameof(AABB)}({LowerBoundary}, {UpperBoundary})";
/// <summary>
/// Checks if two <see cref="AABB"/>s are approximately equal.
/// </summary>
@@ -78,6 +75,25 @@ public readonly struct AABB(Vector2D lowerBoundary, Vector2D upperBoundary)
/// <returns><see cref="true"/> if the <see cref="AABB"/>s are approximately equal; otherwise, <see cref="false"/>.</returns>
public static bool ApproximatelyEquals(AABB left, AABB right, float epsilon = float.Epsilon)
=> left.LowerBoundary.ApproximatelyEquals(right.LowerBoundary, epsilon) && left.UpperBoundary.ApproximatelyEquals(right.UpperBoundary, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="AABB"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="AABB"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="AABB"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is AABB aabb && this == aabb;
/// <summary>
/// Generates a hash code for the <see cref="AABB"/>.
/// </summary>
/// <returns>A hash code for the <see cref="AABB"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(LowerBoundary, UpperBoundary);
/// <summary>
/// Converts the <see cref="AABB"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="AABB"/>.</returns>
public override string ToString() => $"{nameof(AABB)}({LowerBoundary}, {UpperBoundary})";
}
/// <summary>

View File

@@ -38,6 +38,9 @@ public readonly struct Circle(Vector2D center, float radius)
/// </summary>
public static readonly Circle UnitCircle = new(Vector2D.Zero, 1f);
public static bool operator ==(Circle left, Circle right) => left.Center == right.Center && left.Radius == right.Radius;
public static bool operator !=(Circle left, Circle right) => left.Center != right.Center || left.Radius != right.Radius;
/// <summary>
/// Sets the center of the <see cref="Circle"/>.
/// </summary>
@@ -77,6 +80,25 @@ public readonly struct Circle(Vector2D center, float radius)
/// <returns><see cref="true"/> if the <see cref="Circle"/>s are approximately equal; otherwise, <see cref="false"/>.</returns>
public static bool ApproximatelyEquals(Circle left, Circle right, float epsilon = float.Epsilon)
=> left.Center.ApproximatelyEquals(right.Center, epsilon) && left.Radius.ApproximatelyEquals(right.Radius, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Circle"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Circle"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Circle"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Circle circle && this == circle;
/// <summary>
/// Generates a hash code for the <see cref="Circle"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Circle"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(Center, Radius);
/// <summary>
/// Converts the <see cref="Circle"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Circle"/>.</returns>
public override string ToString() => $"{nameof(Circle)}({Center}, {Radius})";
}
/// <summary>

View File

@@ -27,49 +27,19 @@ public readonly struct ColorHSV(float hue, float saturation, float value)
/// </summary>
public readonly float Value = value.Clamp(0f, 1f);
public static ColorHSV operator -(ColorHSV color) => new(color.Hue.OneMinus().Clamp(0f, 1f), color.Saturation.OneMinus().Clamp(0f, 1f), color.Value.OneMinus().Clamp(0f, 1f));
public static ColorHSV operator +(ColorHSV left, ColorHSV right) => new((left.Hue + right.Hue).Clamp(0f, 1f), (left.Saturation + right.Saturation).Clamp(0f, 1f), (left.Value + right.Value).Clamp(0f, 1f));
public static ColorHSV operator -(ColorHSV left, ColorHSV right) => new((left.Hue - right.Hue).Clamp(0f, 1f), (left.Saturation - right.Saturation).Clamp(0f, 1f), (left.Value - right.Value).Clamp(0f, 1f));
public static ColorHSV operator *(ColorHSV left, ColorHSV right) => new((left.Hue * right.Hue).Clamp(0f, 1f), (left.Saturation * right.Saturation).Clamp(0f, 1f), (left.Value * right.Value).Clamp(0f, 1f));
public static ColorHSV operator *(ColorHSV color, float value) => new((color.Hue * value).Clamp(0f, 1f), (color.Saturation * value).Clamp(0f, 1f), (color.Value * value).Clamp(0f, 1f));
public static ColorHSV operator *(float value, ColorHSV color) => new((color.Hue * value).Clamp(0f, 1f), (color.Saturation * value).Clamp(0f, 1f), (color.Value * value).Clamp(0f, 1f));
public static ColorHSV operator /(ColorHSV color, float value) => new((color.Hue / value).Clamp(0f, 1f), (color.Saturation / value).Clamp(0f, 1f), (color.Value / value).Clamp(0f, 1f));
public static bool operator ==(ColorHSV left, ColorHSV right) => left.Hue.ApproximatelyEquals(right.Hue) && left.Saturation.ApproximatelyEquals(right.Saturation) && left.Value.ApproximatelyEquals(right.Value);
public static bool operator !=(ColorHSV left, ColorHSV right) => !left.Hue.ApproximatelyEquals(right.Hue) || !left.Saturation.ApproximatelyEquals(right.Saturation) || !left.Value.ApproximatelyEquals(right.Value);
public static ColorHSV operator -(ColorHSV color) => new(color.Hue.OneMinus(), color.Saturation.OneMinus(), color.Value.OneMinus());
public static ColorHSV operator +(ColorHSV left, ColorHSV right) => new(left.Hue + right.Hue, left.Saturation + right.Saturation, left.Value + right.Value);
public static ColorHSV operator -(ColorHSV left, ColorHSV right) => new(left.Hue - right.Hue, left.Saturation - right.Saturation, left.Value - right.Value);
public static ColorHSV operator *(ColorHSV left, ColorHSV right) => new(left.Hue * right.Hue, left.Saturation * right.Saturation, left.Value * right.Value);
public static ColorHSV operator *(ColorHSV color, float value) => new(color.Hue * value, color.Saturation * value, color.Value * value);
public static ColorHSV operator *(float value, ColorHSV color) => new(color.Hue * value, color.Saturation * value, color.Value * value);
public static ColorHSV operator /(ColorHSV color, float value) => new(color.Hue / value, color.Saturation / value, color.Value / value);
public static bool operator ==(ColorHSV left, ColorHSV right) => left.Hue == right.Hue && left.Saturation == right.Saturation && left.Value == right.Value;
public static bool operator !=(ColorHSV left, ColorHSV right) => left.Hue != right.Hue || left.Saturation != right.Saturation || left.Value != right.Value;
public static implicit operator ColorHSV(ColorRGBA rgba) => (ColorRGB)rgba;
public static implicit operator ColorHSV(ColorRGB rgb)
{
float hue;
float saturation;
float value;
float rd = rgb.R / 255f;
float gd = rgb.G / 255f;
float bd = rgb.B / 255f;
float max = Math.Max(rd, Math.Max(gd, bd));
float min = Math.Min(rd, Math.Min(gd, bd));
float delta = max - min;
if (delta.ApproximatelyEquals(0))
hue = 0f;
else if (max.ApproximatelyEquals(rd))
hue = 60f * ((gd - bd) / delta % 6f);
else if (max.ApproximatelyEquals(gd))
hue = 60f * (((bd - rd) / delta) + 2f);
else
hue = 60f * (((rd - gd) / delta) + 4f);
if (hue < 0f)
hue += 360f;
hue /= 360f;
saturation = max.ApproximatelyEquals(0f) ? 0f : delta / max;
value = max;
return new(hue, saturation, value);
}
public static implicit operator ColorHSV(ColorHSVA hsva) => new(hsva.Hue, hsva.Saturation, hsva.Value);
public static implicit operator ColorHSV(ColorRGBA rgba) => (ColorHSVA)rgba;
public static implicit operator ColorHSV(ColorRGB rgb) => (ColorHSVA)rgb;
/// <summary>
/// Inverts the given <see cref="ColorHSV"/>.
@@ -110,14 +80,6 @@ public readonly struct ColorHSV(float hue, float saturation, float value)
/// <returns>The result of dividing the <see cref="ColorHSV"/> by the scalar value.</returns>
public static ColorHSV Divide(ColorHSV color, float value) => color / value;
/// <summary>
/// Calculates the <see cref="ColorHSV"/> from one point to another.
/// </summary>
/// <param name="from">The starting point.</param>
/// <param name="to">The ending point.</param>
/// <returns>The <see cref="ColorHSV"/> from the starting point to the ending point.</returns>
public static ColorHSV FromTo(ColorHSV from, ColorHSV to) => to - from;
/// <summary>
/// Performs linear interpolation between two <see cref="ColorHSV"/>s.
/// </summary>
@@ -125,13 +87,14 @@ public readonly struct ColorHSV(float hue, float saturation, float value)
/// <param name="to">The ending <see cref="ColorHSV"/> (t = 1).</param>
/// <param name="t">The interpolation parameter.</param>
/// <returns>The interpolated <see cref="ColorHSV"/>.</returns>
public static ColorHSV Lerp(ColorHSV from, ColorHSV to, float t) => from + FromTo(from, to) * t;
public static ColorHSV Lerp(ColorHSV from, ColorHSV to, float t)
{
float hueDiff = to.Hue - from.Hue;
float saturationDiff = to.Saturation - from.Saturation;
float valueDiff = to.Value - from.Value;
/// <summary>
/// Converts the <see cref="ColorHSV"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="ColorHSV"/>.</returns>
public override string ToString() => $"{nameof(ColorHSV)}({Hue}, {Saturation}, {Value})";
return from + new ColorHSV(hueDiff * t, saturationDiff * t, valueDiff * t);
}
/// <summary>
/// Checks if two <see cref="ColorHSV"/>s are approximately equal within a specified epsilon range.
@@ -148,13 +111,19 @@ public readonly struct ColorHSV(float hue, float saturation, float value)
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="ColorHSV"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="ColorHSV"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is ColorHSV objVec && Hue.Equals(objVec.Hue) && Saturation.Equals(objVec.Saturation) && Value.Equals(objVec.Value);
public override bool Equals(object? obj) => obj is ColorHSV colorHSV && this == colorHSV;
/// <summary>
/// Generates a hash code for the <see cref="ColorHSV"/>.
/// </summary>
/// <returns>A hash code for the <see cref="ColorHSV"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(Hue, Saturation, Value);
/// <summary>
/// Converts the <see cref="ColorHSV"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="ColorHSV"/>.</returns>
public override string ToString() => $"{nameof(ColorHSV)}({Hue}, {Saturation}, {Value})";
}
/// <summary>
@@ -174,9 +143,6 @@ public static class ColorHSVExtensions
/// <inheritdoc cref="ColorHSV.Divide(ColorHSV, ColorHSV)" />
public static ColorHSV Divide(this ColorHSV color, float value) => ColorHSV.Divide(color, value);
/// <inheritdoc cref="ColorHSV.FromTo(ColorHSV, ColorHSV)" />
public static ColorHSV FromTo(this ColorHSV from, ColorHSV to) => ColorHSV.FromTo(from, to);
/// <inheritdoc cref="ColorHSV.Lerp(ColorHSV, ColorHSV, float)" />
public static ColorHSV Lerp(this ColorHSV from, ColorHSV to, float t) => ColorHSV.Lerp(from, to, t);

View File

@@ -0,0 +1,189 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents an HSV color.
/// </summary>
/// <param name="hue">Hue of the <see cref="ColorHSVA"/>.</param>
/// <param name="saturation">Saturation of the <see cref="ColorHSVA"/>.</param>
/// <param name="value">Value of the <see cref="ColorHSVA"/>.</param>
/// <param name="alpha">Alpha of the <see cref="ColorHSVA"/>.</param>
/// <remarks>
/// Initializes a new instance of the <see cref="ColorHSVA"/> struct with the specified values.
/// </remarks>
[System.Diagnostics.DebuggerDisplay("{ToString(),nq}")]
public readonly struct ColorHSVA(float hue, float saturation, float value, float alpha = 1)
{
/// <summary>
/// The Hue value of the <see cref="ColorHSVA"/>.
/// </summary>
public readonly float Hue = hue.Clamp(0f, 1f);
/// <summary>
/// The Saturation value of the <see cref="ColorHSVA"/>.
/// </summary>
public readonly float Saturation = saturation.Clamp(0f, 1f);
/// <summary>
/// The Value value of the <see cref="ColorHSVA"/>.
/// </summary>
public readonly float Value = value.Clamp(0f, 1f);
/// <summary>
/// The Alpha value of the <see cref="ColorHSVA"/>.
/// </summary>
public readonly float Alpha = alpha;
public static ColorHSVA operator -(ColorHSVA color) => new(color.Hue.OneMinus(), color.Saturation.OneMinus(), color.Value.OneMinus(), color.Alpha);
public static ColorHSVA operator +(ColorHSVA left, ColorHSVA right) => new(left.Hue + right.Hue, left.Saturation + right.Saturation, left.Value + right.Value, left.Alpha + right.Alpha);
public static ColorHSVA operator -(ColorHSVA left, ColorHSVA right) => new(left.Hue - right.Hue, left.Saturation - right.Saturation, left.Value - right.Value, left.Alpha - right.Alpha);
public static ColorHSVA operator *(ColorHSVA left, ColorHSVA right) => new(left.Hue * right.Hue, left.Saturation * right.Saturation, left.Value * right.Value, left.Alpha * right.Alpha);
public static ColorHSVA operator *(ColorHSVA color, float value) => new(color.Hue * value, color.Saturation * value, color.Value * value, color.Alpha * value);
public static ColorHSVA operator *(float value, ColorHSVA color) => new(color.Hue * value, color.Saturation * value, color.Value * value, color.Alpha * value);
public static ColorHSVA operator /(ColorHSVA color, float value) => new(color.Hue / value, color.Saturation / value, color.Value / value, color.Alpha / value);
public static bool operator ==(ColorHSVA left, ColorHSVA right) => left.Hue == right.Hue && left.Saturation == right.Saturation && left.Value == right.Value;
public static bool operator !=(ColorHSVA left, ColorHSVA right) => left.Hue != right.Hue || left.Saturation != right.Saturation || left.Value != right.Value;
public static implicit operator ColorHSVA(ColorHSV hsv) => new(hsv.Hue, hsv.Saturation, hsv.Value, 1f);
public static implicit operator ColorHSVA(ColorRGB rgb) => (ColorRGBA)rgb;
public static implicit operator ColorHSVA(ColorRGBA rgba)
{
float hue;
float saturation;
float value;
float rd = rgba.R / 255f;
float gd = rgba.G / 255f;
float bd = rgba.B / 255f;
float max = Math.Max(rd, Math.Max(gd, bd));
float min = Math.Min(rd, Math.Min(gd, bd));
float delta = max - min;
if (delta.ApproximatelyEquals(0))
hue = 0f;
else if (max.ApproximatelyEquals(rd))
hue = 60f * ((gd - bd) / delta % 6f);
else if (max.ApproximatelyEquals(gd))
hue = 60f * (((bd - rd) / delta) + 2f);
else
hue = 60f * (((rd - gd) / delta) + 4f);
if (hue < 0f)
hue += 360f;
hue /= 360f;
saturation = max.ApproximatelyEquals(0f) ? 0f : delta / max;
value = max;
return new(hue, saturation, value, rgba.A / 255f);
}
/// <summary>
/// Inverts the given <see cref="ColorHSVA"/>.
/// </summary>
/// <param name="color">The <see cref="ColorHSVA"/>.</param>
/// <returns>The inverted <see cref="ColorHSVA"/>.</returns>
public static ColorHSVA Invert(ColorHSVA color) => -color;
/// <summary>
/// Adds two <see cref="ColorHSVA"/>s.
/// </summary>
/// <param name="left">The first <see cref="ColorHSVA"/>.</param>
/// <param name="right">The second <see cref="ColorHSVA"/>.</param>
/// <returns>The sum of the two <see cref="ColorHSVA"/>s.</returns>
public static ColorHSVA Add(ColorHSVA left, ColorHSVA right) => left + right;
/// <summary>
/// Subtracts one <see cref="ColorHSVA"/> from another.
/// </summary>
/// <param name="left">The <see cref="ColorHSVA"/> to subtract from.</param>
/// <param name="right">The <see cref="ColorHSVA"/> to subtract.</param>
/// <returns>The result of subtracting the second <see cref="ColorHSVA"/> from the first.</returns>
public static ColorHSVA Subtract(ColorHSVA left, ColorHSVA right) => left - right;
/// <summary>
/// Multiplies a <see cref="ColorHSVA"/> by a scalar value.
/// </summary>
/// <param name="color">The <see cref="ColorHSVA"/>.</param>
/// <param name="value">The scalar value.</param>
/// <returns>The result of multiplying the <see cref="ColorHSVA"/> by the scalar value.</returns>
public static ColorHSVA Multiply(ColorHSVA color, float value) => color * value;
/// <summary>
/// Divides a <see cref="ColorHSVA"/> by a scalar value.
/// </summary>
/// <param name="color">The <see cref="ColorHSVA"/>.</param>
/// <param name="value">The scalar value.</param>
/// <returns>The result of dividing the <see cref="ColorHSVA"/> by the scalar value.</returns>
public static ColorHSVA Divide(ColorHSVA color, float value) => color / value;
/// <summary>
/// Performs linear interpolation between two <see cref="ColorHSVA"/>s.
/// </summary>
/// <param name="from">The starting <see cref="ColorHSVA"/> (t = 0).</param>
/// <param name="to">The ending <see cref="ColorHSVA"/> (t = 1).</param>
/// <param name="t">The interpolation parameter.</param>
/// <returns>The interpolated <see cref="ColorHSVA"/>.</returns>
public static ColorHSVA Lerp(ColorHSVA from, ColorHSVA to, float t)
{
float hueDiff = to.Hue - from.Hue;
float saturationDiff = to.Saturation - from.Saturation;
float valueDiff = to.Value - from.Value;
float alphaDiff = to.Alpha - from.Alpha;
return from + new ColorHSVA(hueDiff * t, saturationDiff * t, valueDiff * t, alphaDiff * t);
}
/// <summary>
/// Checks if two <see cref="ColorHSVA"/>s are approximately equal within a specified epsilon range.
/// </summary>
/// <param name="left">The first <see cref="ColorHSVA"/>.</param>
/// <param name="right">The second <see cref="ColorHSVA"/>.</param>
/// <param name="epsilon">The epsilon range.</param>
/// <returns><see cref="true"/> if the <see cref="ColorHSVA"/>s are approximately equal; otherwise, <see cref="false"/>.</returns>
public static bool ApproximatelyEquals(ColorHSVA left, ColorHSVA right, float epsilon = float.Epsilon)
=> left.Hue.ApproximatelyEquals(right.Hue, epsilon) && left.Saturation.ApproximatelyEquals(right.Saturation, epsilon) && left.Value.ApproximatelyEquals(right.Value, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="ColorHSVA"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="ColorHSVA"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="ColorHSVA"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is ColorHSVA colorHSVA && this == colorHSVA;
/// <summary>
/// Generates a hash code for the <see cref="ColorHSVA"/>.
/// </summary>
/// <returns>A hash code for the <see cref="ColorHSVA"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(Hue, Saturation, Value);
/// <summary>
/// Converts the <see cref="ColorHSVA"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="ColorHSVA"/>.</returns>
public override string ToString() => $"{nameof(ColorHSVA)}({Hue}, {Saturation}, {Value})";
}
/// <summary>
/// Provides extension methods for <see cref="ColorHSVA"/> type.
/// </summary>
public static class ColorHSVAExtensions
{
/// <inheritdoc cref="ColorHSVA.Add(ColorHSVA, ColorHSVA)" />
public static ColorHSVA Add(this ColorHSVA color, ColorHSVA value) => ColorHSVA.Add(color, value);
/// <inheritdoc cref="ColorHSVA.Subtract(ColorHSVA, ColorHSVA)" />
public static ColorHSVA Subtract(this ColorHSVA color, ColorHSVA value) => ColorHSVA.Subtract(color, value);
/// <inheritdoc cref="ColorHSVA.Multiply(ColorHSVA, ColorHSVA)" />
public static ColorHSVA Multiply(this ColorHSVA color, float value) => ColorHSVA.Multiply(color, value);
/// <inheritdoc cref="ColorHSVA.Divide(ColorHSVA, ColorHSVA)" />
public static ColorHSVA Divide(this ColorHSVA color, float value) => ColorHSVA.Divide(color, value);
/// <inheritdoc cref="ColorHSVA.Lerp(ColorHSVA, ColorHSVA, float)" />
public static ColorHSVA Lerp(this ColorHSVA from, ColorHSVA to, float t) => ColorHSVA.Lerp(from, to, t);
/// <inheritdoc cref="ColorHSVA.ApproximatelyEquals(ColorHSVA, ColorHSVA, float) " />
public static bool ApproximatelyEquals(this ColorHSVA left, ColorHSVA right, float epsilon = float.Epsilon) => ColorHSVA.ApproximatelyEquals(left, right, epsilon);
}

View File

@@ -38,30 +38,8 @@ public readonly struct ColorRGB(byte r, byte g, byte b)
public static bool operator !=(ColorRGB left, ColorRGB right) => left.R != right.R || left.G != right.G || left.B != right.B;
public static implicit operator ColorRGB(ColorRGBA rgba) => new(rgba.R, rgba.G, rgba.B);
public static implicit operator ColorRGB(ColorHSV hsv)
{
float hue = hsv.Hue * 360f;
float chroma = hsv.Value * hsv.Saturation;
float x = chroma * (1f - Math.Abs(hue / 60f % 2f - 1f));
float m = hsv.Value - chroma;
float r1 = 0f;
float g1 = 0f;
float b1 = 0f;
if (hue < 60) { r1 = chroma; g1 = x; b1 = 0; }
else if (hue < 120) { r1 = x; g1 = chroma; b1 = 0; }
else if (hue < 180) { r1 = 0; g1 = chroma; b1 = x; }
else if (hue < 240) { r1 = 0; g1 = x; b1 = chroma; }
else if (hue < 300) { r1 = x; g1 = 0; b1 = chroma; }
else if (hue <= 360) { r1 = chroma; g1 = 0; b1 = x; }
byte r = (byte)Math.RoundToInt((r1 + m) * 255);
byte g = (byte)Math.RoundToInt((g1 + m) * 255);
byte b = (byte)Math.RoundToInt((b1 + m) * 255);
return new(r, g, b);
}
public static implicit operator ColorRGB(ColorHSVA hsva) => (ColorRGBA)hsva;
public static implicit operator ColorRGB(ColorHSV hsv) => (ColorRGBA)hsv;
/// <summary>
/// Inverts the given <see cref="ColorRGB"/>.
@@ -102,14 +80,6 @@ public readonly struct ColorRGB(byte r, byte g, byte b)
/// <returns>The result of dividing the <see cref="ColorRGB"/> by the scalar value.</returns>
public static ColorRGB Divide(ColorRGB color, float value) => color / value;
/// <summary>
/// Calculates the <see cref="ColorRGB"/> from one point to another.
/// </summary>
/// <param name="from">The starting point.</param>
/// <param name="to">The ending point.</param>
/// <returns>The <see cref="ColorRGB"/> from the starting point to the ending point.</returns>
public static ColorRGB FromTo(ColorRGB from, ColorRGB to) => to - from;
/// <summary>
/// Performs linear interpolation between two <see cref="ColorRGB"/>s.
/// </summary>
@@ -117,26 +87,33 @@ public readonly struct ColorRGB(byte r, byte g, byte b)
/// <param name="to">The ending <see cref="ColorRGB"/> (t = 1).</param>
/// <param name="t">The interpolation parameter.</param>
/// <returns>The interpolated <see cref="ColorRGB"/>.</returns>
public static ColorRGB Lerp(ColorRGB from, ColorRGB to, float t) => from + FromTo(from, to) * t;
public static ColorRGB Lerp(ColorRGB from, ColorRGB to, float t)
{
int redDiff = to.R - from.R;
int greenDiff = to.G - from.G;
int blueDiff = to.B - from.B;
/// <summary>
/// Converts the <see cref="ColorRGB"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="ColorRGB"/>.</returns>
public override string ToString() => $"{nameof(ColorRGB)}({R}, {G}, {B})";
return from + new ColorRGB((byte)(redDiff * t), (byte)(greenDiff * t), (byte)(blueDiff * t));
}
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="ColorRGB"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="ColorRGB"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="ColorRGB"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is ColorRGB objVec && R.Equals(objVec.R) && G.Equals(objVec.G) && B.Equals(objVec.B);
public override bool Equals(object? obj) => obj is ColorRGB colorRGB && this == colorRGB;
/// <summary>
/// Generates a hash code for the <see cref="ColorRGB"/>.
/// </summary>
/// <returns>A hash code for the <see cref="ColorRGB"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(R, G, B);
/// <summary>
/// Converts the <see cref="ColorRGB"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="ColorRGB"/>.</returns>
public override string ToString() => $"{nameof(ColorRGB)}({R}, {G}, {B})";
}
/// <summary>
@@ -156,9 +133,6 @@ public static class ColorRGBExtensions
/// <inheritdoc cref="ColorRGB.Divide(ColorRGB, ColorRGB)" />
public static ColorRGB Divide(this ColorRGB color, float value) => ColorRGB.Divide(color, value);
/// <inheritdoc cref="ColorRGB.FromTo(ColorRGB, ColorRGB)" />
public static ColorRGB FromTo(this ColorRGB from, ColorRGB to) => ColorRGB.FromTo(from, to);
/// <inheritdoc cref="ColorRGB.Lerp(ColorRGB, ColorRGB, float)" />
public static ColorRGB Lerp(this ColorRGB from, ColorRGB to, float t) => ColorRGB.Lerp(from, to, t);
}

View File

@@ -44,7 +44,31 @@ public readonly struct ColorRGBA(byte r, byte g, byte b, byte a = 255)
public static bool operator !=(ColorRGBA left, ColorRGBA right) => left.R != right.R || left.G != right.G || left.B != right.B || left.A != right.A;
public static implicit operator ColorRGBA(ColorRGB rgb) => new(rgb.R, rgb.G, rgb.B, 255);
public static implicit operator ColorRGBA(ColorHSV hsv) => (ColorRGB)hsv;
public static implicit operator ColorRGBA(ColorHSV hsv) => (ColorHSVA)hsv;
public static implicit operator ColorRGBA(ColorHSVA hsva)
{
float hue = hsva.Hue * 360f;
float chroma = hsva.Value * hsva.Saturation;
float x = chroma * (1f - Math.Abs(hue / 60f % 2f - 1f));
float m = hsva.Value - chroma;
float r1 = 0f;
float g1 = 0f;
float b1 = 0f;
if (hue < 60) { r1 = chroma; g1 = x; b1 = 0; }
else if (hue < 120) { r1 = x; g1 = chroma; b1 = 0; }
else if (hue < 180) { r1 = 0; g1 = chroma; b1 = x; }
else if (hue < 240) { r1 = 0; g1 = x; b1 = chroma; }
else if (hue < 300) { r1 = x; g1 = 0; b1 = chroma; }
else if (hue <= 360) { r1 = chroma; g1 = 0; b1 = x; }
byte r = (byte)Math.RoundToInt((r1 + m) * 255);
byte g = (byte)Math.RoundToInt((g1 + m) * 255);
byte b = (byte)Math.RoundToInt((b1 + m) * 255);
return new(r, g, b, (byte)(hsva.Alpha * 255));
}
/// <summary>
/// Inverts the given <see cref="ColorRGBA"/>.
@@ -85,14 +109,6 @@ public readonly struct ColorRGBA(byte r, byte g, byte b, byte a = 255)
/// <returns>The result of dividing the <see cref="ColorRGBA"/> by the scalar value.</returns>
public static ColorRGBA Divide(ColorRGBA color, float value) => color / value;
/// <summary>
/// Calculates the <see cref="ColorRGBA"/> from one point to another.
/// </summary>
/// <param name="from">The starting point.</param>
/// <param name="to">The ending point.</param>
/// <returns>The <see cref="ColorRGBA"/> from the starting point to the ending point.</returns>
public static ColorRGBA FromTo(ColorRGBA from, ColorRGBA to) => to - from;
/// <summary>
/// Performs linear interpolation between two <see cref="ColorRGBA"/>s.
/// </summary>
@@ -100,26 +116,34 @@ public readonly struct ColorRGBA(byte r, byte g, byte b, byte a = 255)
/// <param name="to">The ending <see cref="ColorRGBA"/> (t = 1).</param>
/// <param name="t">The interpolation parameter.</param>
/// <returns>The interpolated <see cref="ColorRGBA"/>.</returns>
public static ColorRGBA Lerp(ColorRGBA from, ColorRGBA to, float t) => from + FromTo(from, to) * t;
public static ColorRGBA Lerp(ColorRGBA from, ColorRGBA to, float t)
{
int redDiff = to.R - from.R;
int greenDiff = to.G - from.G;
int blueDiff = to.B - from.B;
int alphaDiff = to.A - from.A;
/// <summary>
/// Converts the <see cref="ColorRGBA"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="ColorRGBA"/>.</returns>
public override string ToString() => $"{nameof(ColorRGBA)}({R}, {G}, {B}, {A})";
return from + new ColorRGBA((byte)(redDiff * t), (byte)(greenDiff * t), (byte)(blueDiff * t), (byte)(alphaDiff * t));
}
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="ColorRGBA"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="ColorRGBA"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="ColorRGBA"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is ColorRGBA objVec && R.Equals(objVec.R) && G.Equals(objVec.G) && B.Equals(objVec.B) && A.Equals(objVec.A);
public override bool Equals(object? obj) => obj is ColorRGBA colorRGBA && this == colorRGBA;
/// <summary>
/// Generates a hash code for the <see cref="ColorRGBA"/>.
/// </summary>
/// <returns>A hash code for the <see cref="ColorRGBA"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(R, G, B, A);
/// <summary>
/// Converts the <see cref="ColorRGBA"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="ColorRGBA"/>.</returns>
public override string ToString() => $"{nameof(ColorRGBA)}({R}, {G}, {B}, {A})";
}
/// <summary>
@@ -139,9 +163,6 @@ public static class ColorRGBAExtensions
/// <inheritdoc cref="ColorRGBA.Divide(ColorRGBA, ColorRGBA)" />
public static ColorRGBA Divide(this ColorRGBA color, float value) => ColorRGBA.Divide(color, value);
/// <inheritdoc cref="ColorRGBA.FromTo(ColorRGBA, ColorRGBA)" />
public static ColorRGBA FromTo(this ColorRGBA from, ColorRGBA to) => ColorRGBA.FromTo(from, to);
/// <inheritdoc cref="ColorRGBA.Lerp(ColorRGBA, ColorRGBA, float)" />
public static ColorRGBA Lerp(this ColorRGBA from, ColorRGBA to, float t) => ColorRGBA.Lerp(from, to, t);
}

View File

@@ -43,6 +43,9 @@ public readonly struct Line2D(Vector2D from, Vector2D to)
/// </summary>
public readonly float LengthSquared => From.FromTo(To).LengthSquared();
public static bool operator ==(Line2D left, Line2D right) => left.From == right.From && left.To == right.To;
public static bool operator !=(Line2D left, Line2D right) => left.From != right.From || left.To != right.To;
/// <summary>
/// The equation of the <see cref="Line2D"/> defined by this <see cref="Line2D"/> segment.
/// </summary>
@@ -167,17 +170,14 @@ public readonly struct Line2D(Vector2D from, Vector2D to)
/// </summary>
public static Vector2D ClosestPointTo(Line2D line, Vector2D point)
{
Vector2D edgeVector = line.From.FromTo(line.To);
Vector2D pointVector = point - line.From;
Vector2D lineRelativeVector = line.From.FromTo(line.To);
float t = (pointVector.X * edgeVector.X + pointVector.Y * edgeVector.Y) / (edgeVector.X * edgeVector.X + edgeVector.Y * edgeVector.Y);
Vector2D lineDirection = lineRelativeVector.Normalized;
Vector2D pointVector = line.From.FromTo(point);
t = Math.Max(0, Math.Min(1, t));
float dot = lineDirection.Dot(pointVector).Clamp(0f, lineRelativeVector.Magnitude);
float closestX = line.From.X + t * edgeVector.X;
float closestY = line.From.Y + t * edgeVector.Y;
return new Vector2D((float)closestX, (float)closestY);
return lineDirection * dot;
}
/// <summary>
@@ -189,6 +189,25 @@ public readonly struct Line2D(Vector2D from, Vector2D to)
/// <returns><see cref="true"/> if the <see cref="Line2D"/>s are approximately equal; otherwise, <see cref="false"/>.</returns>
public static bool ApproximatelyEquals(Line2D left, Line2D right, float epsilon = float.Epsilon)
=> left.From.ApproximatelyEquals(right.From, epsilon) && left.To.ApproximatelyEquals(right.To, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Line2D"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Line2D"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Line2D"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Line2D line2D && this == line2D;
/// <summary>
/// Generates a hash code for the <see cref="Line2D"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Line2D"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(From, To);
/// <summary>
/// Converts the <see cref="Line2D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Line2D"/>.</returns>
public override string ToString() => $"{nameof(Line2D)}({From}, {To})";
}
/// <summary>
@@ -205,6 +224,9 @@ public static class Line2DExtensions
/// <inheritdoc cref="Line2D.Intersects(Line2D, Vector2D)" />
public static bool Intersects(this Line2D line, Vector2D point) => Line2D.Intersects(line, point);
/// <inheritdoc cref="Line2D.IntersectionPoint(Line2D, Line2D)" />
public static Vector2D IntersectionPoint(this Line2D left, Line2D right) => Line2D.IntersectionPoint(left, right);
/// <inheritdoc cref="Line2D.GetT(Line2D, Vector2D)" />
public static float GetT(this Line2D line, Vector2D point) => Line2D.GetT(line, point);
@@ -214,6 +236,9 @@ public static class Line2DExtensions
/// <inheritdoc cref="Line2D.Intersects(Line2D, Line2D, out Vector2D?)" />
public static bool Intersects(this Line2D left, Line2D right, [NotNullWhen(returnValue: true)] out Vector2D? point) => Line2D.Intersects(left, right, out point);
/// <inheritdoc cref="Line2D.ClosestPointTo(Line2D, Vector2D)" />
public static Vector2D ClosestPointTo(this Line2D line, Vector2D point) => Line2D.ClosestPointTo(line, point);
/// <inheritdoc cref="Line2D.ApproximatelyEquals(Line2D, Line2D, float)" />
public static bool ApproximatelyEquals(this Line2D left, Line2D right, float epsilon = float.Epsilon) => Line2D.ApproximatelyEquals(left, right, epsilon);
}

View File

@@ -1,47 +1,69 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a line equation in the form y = mx + b.
/// Represents a <see cref="Line2DEquation"/> in the form y = mx + b.
/// </summary>
/// <param name="slope">The slope of the line.</param>
/// <param name="offsetY">The y-intercept of the line.</param>
/// <param name="offsetY">The Y intercept of the line.</param>
/// <remarks>
/// Initializes a new instance of the <see cref="Line2DEquation"/> struct with the specified slope and y-intercept.
/// Initializes a new instance of the <see cref="Line2DEquation"/> struct with the specified slope and Y intercept.
/// </remarks>
[System.Diagnostics.DebuggerDisplay("y = {Slope}x + {OffsetY}")]
public readonly struct Line2DEquation(float slope, float offsetY)
{
/// <summary>
/// The slope of the line equation.
/// The slope of the <see cref="Line2DEquation"/>.
/// </summary>
public readonly float Slope = slope;
/// <summary>
/// The y-intercept of the line equation.
/// The Y intercept of the <see cref="Line2DEquation"/>.
/// </summary>
public readonly float OffsetY = offsetY;
public static bool operator ==(Line2DEquation left, Line2DEquation right) => left.Slope == right.Slope && left.OffsetY == right.OffsetY;
public static bool operator !=(Line2DEquation left, Line2DEquation right) => left.Slope != right.Slope || left.OffsetY != right.OffsetY;
/// <summary>
/// Resolves the y-coordinate for a given x-coordinate using the line equation.
/// Resolves the Y coordinate for a given X coordinate using the <see cref="Line2DEquation"/>.
/// </summary>
/// <param name="lineEquation">The line equation to resolve.</param>
/// <param name="x">The x-coordinate for which to resolve the y-coordinate.</param>
/// <returns>The y-coordinate resolved using the line equation.</returns>
/// <param name="lineEquation">The <see cref="Line2DEquation"/> to resolve.</param>
/// <param name="x">The X coordinate for which to resolve the Y coordinate.</param>
/// <returns>The Y coordinate resolved using the <see cref="Line2DEquation"/>.</returns>
public static float Resolve(Line2DEquation lineEquation, float x) => lineEquation.Slope * x + lineEquation.OffsetY; // y = mx + b
/// <summary>
/// Checks if two line equations are approximately equal.
/// Checks if two <see cref="Line2DEquation"/> are approximately equal.
/// </summary>
/// <param name="left">The first line equation to compare.</param>
/// <param name="right">The second line equation to compare.</param>
/// <param name="left">The first <see cref="Line2DEquation"/> to compare.</param>
/// <param name="right">The second <see cref="Line2DEquation"/> to compare.</param>
/// <param name="epsilon">The epsilon range.</param>
/// <returns>True if the line equations are approximately equal; otherwise, false.</returns>
/// <returns>True if the <see cref="Line2DEquation"/> are approximately equal; otherwise, false.</returns>
public static bool ApproximatelyEquals(Line2DEquation left, Line2DEquation right, float epsilon = float.Epsilon)
=> left.Slope.ApproximatelyEquals(right.Slope, epsilon) && left.OffsetY.ApproximatelyEquals(right.OffsetY, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Line2DEquation"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Line2DEquation"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Line2DEquation"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Line2DEquation lineEquation && this == lineEquation;
/// <summary>
/// Generates a hash code for the <see cref="Line2DEquation"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Line2DEquation"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(Slope, OffsetY);
/// <summary>
/// Converts the <see cref="Line2DEquation"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Line2DEquation"/>.</returns>
public override string ToString() => $"{nameof(Line2DEquation)}({Slope}, {OffsetY})";
}
/// <summary>
/// Provides extension methods for the LineEquation struct.
/// Provides extension methods for the <see cref="Line2DEquation"/> struct.
/// </summary>
public static class Line2DEquationExtensions
{

View File

@@ -21,6 +21,9 @@ public readonly struct Projection1D(float min, float max)
/// </summary>
public readonly float Max = max;
public static bool operator ==(Projection1D left, Projection1D right) => left.Min == right.Min && left.Max == right.Max;
public static bool operator !=(Projection1D left, Projection1D right) => left.Min != right.Min || left.Max != right.Max;
/// <summary>
/// Checks if two projections overlap.
/// </summary>
@@ -70,6 +73,35 @@ public readonly struct Projection1D(float min, float max)
depth = 0f;
return false;
}
/// <summary>
/// Checks if two <see cref="Projection1D"/>s are approximately equal within a specified epsilon range.
/// </summary>
/// <param name="left">The first <see cref="Projection1D"/>.</param>
/// <param name="right">The second <see cref="Projection1D"/>.</param>
/// <param name="epsilon">The epsilon range.</param>
/// <returns><see cref="true"/> if the <see cref="Projection1D"/>s are approximately equal; otherwise, <see cref="false"/>.</returns>
public static bool ApproximatelyEquals(Projection1D left, Projection1D right, float epsilon = float.Epsilon)
=> left.Min.ApproximatelyEquals(right.Min, epsilon) && left.Max.ApproximatelyEquals(right.Max, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Projection1D"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Projection1D"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Projection1D"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Projection1D projection1D && this == projection1D;
/// <summary>
/// Generates a hash code for the <see cref="Projection1D"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Projection1D"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(Min, Max);
/// <summary>
/// Converts the <see cref="Projection1D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Projection1D"/>.</returns>
public override string ToString() => $"{nameof(Projection1D)}({Min}, {Max})";
}
/// <summary>
@@ -82,4 +114,7 @@ public static class Projection1DExtensions
/// <inheritdoc cref="Projection1D.Overlaps(Projection1D, Projection1D, out float)" />
public static bool Overlaps(this Projection1D left, Projection1D right, out float depth) => Projection1D.Overlaps(left, right, out depth);
/// <inheritdoc cref="Projection1D.ApproximatelyEquals(Projection1D, Projection1D, float)" />
public static bool ApproximatelyEquals(this Projection1D left, Projection1D right, float epsilon = float.Epsilon) => Projection1D.ApproximatelyEquals(left, right, epsilon);
}

View File

@@ -282,24 +282,24 @@ public readonly struct Quaternion(float x, float y, float z, float w)
public static bool ApproximatelyEquals(Quaternion left, Quaternion right, float epsilon = float.Epsilon)
=> left.X.ApproximatelyEquals(right.X, epsilon) && left.Y.ApproximatelyEquals(right.Y, epsilon) && left.Z.ApproximatelyEquals(right.Z, epsilon) && left.W.ApproximatelyEquals(right.W, epsilon);
/// <summary>
/// Converts the <see cref="Quaternion"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Quaternion"/>.</returns>
public override string ToString() => $"{nameof(Quaternion)}({W}, {X}, {Y}, {Z})";
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Quaternion"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Quaternion"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Quaternion"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Quaternion objVec && X.Equals(objVec.X) && Y.Equals(objVec.Y) && Z.Equals(objVec.Z) && W.Equals(objVec.W);
public override bool Equals(object? obj) => obj is Quaternion quaternion && this == quaternion;
/// <summary>
/// Generates a hash code for the <see cref="Quaternion"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Quaternion"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(X, Y, Z);
public override int GetHashCode() => System.HashCode.Combine(W, X, Y, Z);
/// <summary>
/// Converts the <see cref="Quaternion"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Quaternion"/>.</returns>
public override string ToString() => $"{nameof(Quaternion)}({W}, {X}, {Y}, {Z})";
}
/// <summary>

View File

@@ -0,0 +1,105 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents an infinite ray in 2D space.
/// </summary>
/// <param name="Origin">The <see cref="Vector2D"/> in 2D space where the ray starts from.</param>
/// <param name="Direction">Normalized <see cref="Vector2D"/> indicating the ray's is direction.</param>
public readonly struct Ray2D(Vector2D Origin, Vector2D Direction)
{
/// <summary>
/// The starting point of the <see cref="Ray2D"/>.
/// </summary>
public readonly Vector2D Origin = Origin;
/// <summary>
/// The direction in which the <see cref="Ray2D"/> points. Should be a normalized vector.
/// </summary>
public readonly Vector2D Direction = Direction;
/// <summary>
/// Gets a <see cref="Ray2D"/> with the same origin but with the direction reversed.
/// </summary>
public readonly Ray2D Reversed => new(Origin, -Direction);
public static bool operator ==(Ray2D left, Ray2D right) => left.Origin == right.Origin && left.Direction == right.Direction;
public static bool operator !=(Ray2D left, Ray2D right) => left.Origin != right.Origin || left.Direction != right.Direction;
public static implicit operator Ray2D(Line2D line) => new(line.From, line.From.FromTo(line.To).Normalized);
/// <summary>
/// Constructs a <see cref="Line2D"/> from a <see cref="Ray2D"/>, extending from its origin in the <see cref="Ray2D"/>'s direction for a given distance.
/// </summary>
/// <param name="ray">The source <see cref="Ray2D"/>.</param>
/// <param name="distance">The length of the line segment to create from the <see cref="Ray2D"/>.</param>
/// <returns>A <see cref="Line2D"/> representing the segment of the <see cref="Ray2D"/>.</returns>
public static Line2D GetLine(Ray2D ray, float distance)
=> new(ray.Origin, ray.Origin + ray.Direction * distance);
/// <summary>
/// Evaluates the point on the <see cref="Ray2D"/> at a specified distance from its origin.
/// </summary>
/// <param name="ray">The <see cref="Ray2D"/> to evaluate.</param>
/// <param name="distanceFromOrigin">The distance from the origin along the <see cref="Ray2D"/>'s direction.</param>
/// <returns>A <see cref="Vector2D"/> representing the point at the given distance on the <see cref="Ray2D"/>.</returns>
public static Vector2D Evaluate(Ray2D ray, float distanceFromOrigin)
=> ray.Origin + ray.Direction * distanceFromOrigin;
/// <summary>
/// Calculates the closest point on the <see cref="Ray2D"/> to the specified point.
/// </summary>
public static Vector2D ClosestPointTo(Ray2D ray, Vector2D point)
{
Vector2D originToPoint = ray.Origin.FromTo(point);
float dot = ray.Direction.Dot(originToPoint);
return ray.Origin + ray.Direction * dot;
}
/// <summary>
/// Checks if two <see cref="Ray2D"/>s are approximately equal within a specified epsilon range.
/// </summary>
/// <param name="left">The first <see cref="Ray2D"/>.</param>
/// <param name="right">The second <see cref="Ray2D"/>.</param>
/// <param name="epsilon">The epsilon range.</param>
/// <returns><see cref="true"/> if the <see cref="Ray2D"/>s are approximately equal; otherwise, <see cref="false"/>.</returns>
public static bool ApproximatelyEquals(Ray2D left, Ray2D right, float epsilon = float.Epsilon)
=> left.Origin.ApproximatelyEquals(right.Origin, epsilon) && left.Direction.ApproximatelyEquals(right.Direction, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Ray2D"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Ray2D"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Ray2D"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Ray2D ray2D && this == ray2D;
/// <summary>
/// Generates a hash code for the <see cref="Ray2D"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Ray2D"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(Origin, Direction);
/// <summary>
/// Converts the <see cref="Ray2D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Ray2D"/>.</returns>
public override string ToString() => $"{nameof(Ray2D)}({Origin}, {Direction})";
}
/// <summary>
/// Provides extension methods for the <see cref="Ray2D"/> struct.
/// </summary>
public static class Ray2DExtensions
{
/// <inheritdoc cref="Ray2D.GetLine(Ray2D, float) />
public static Line2D ToLine(this Ray2D ray, float distance) => Ray2D.GetLine(ray, distance);
/// <inheritdoc cref="Ray2D.Evaluate(Ray2D, float) />
public static Vector2D Evaluate(this Ray2D ray, float distanceFromOrigin) => Ray2D.Evaluate(ray, distanceFromOrigin);
/// <inheritdoc cref="Ray2D.ClosestPointTo(Ray2D, Vector2D) />
public static Vector2D ClosestPointTo(this Ray2D ray, Vector2D point) => Ray2D.ClosestPointTo(ray, point);
/// <inheritdoc cref="Ray2D.ApproximatelyEquals(Ray2D, Ray2D, float)" />
public static bool ApproximatelyEquals(this Ray2D left, Ray2D right, float epsilon = float.Epsilon) => Ray2D.ApproximatelyEquals(left, right, epsilon);
}

View File

@@ -18,7 +18,7 @@ public class Shape2D(List<Vector2D> vertices) : IEnumerable<Vector2D>
public static Shape2D Pentagon => CreateNgon(5, Vector2D.Up);
public static Shape2D Hexagon => CreateNgon(6, Vector2D.Right);
public event ShapeUpdatedEventHandler? OnShapeUpdated = null;
public Event<Shape2D> OnShapeUpdated { get; } = new();
private List<Vector2D> _vertices = vertices;
@@ -35,7 +35,7 @@ public class Shape2D(List<Vector2D> vertices) : IEnumerable<Vector2D>
foreach (Vector2D vertex in value)
_vertices.Add(vertex);
OnShapeUpdated?.InvokeSafe(this);
OnShapeUpdated?.Invoke(this);
}
}
@@ -122,7 +122,7 @@ public class Shape2D(List<Vector2D> vertices) : IEnumerable<Vector2D>
triangles.Clear();
for (int i = 2; i < shape.Vertices.Count; i++)
triangles.Add(new Triangle(shape[0], shape[i - 1], shape[i]));
triangles.Add(new Triangle(shape[0], shape[i], shape[i - 1]));
}
/// <summary>
@@ -229,7 +229,7 @@ public class Shape2D(List<Vector2D> vertices) : IEnumerable<Vector2D>
for (int i = 0; i < count; i++)
to._vertices.Add(transform.Transform(from[i]));
to.OnShapeUpdated?.InvokeSafe(to);
to.OnShapeUpdated?.Invoke(to);
}
/// <summary>
@@ -251,13 +251,39 @@ public class Shape2D(List<Vector2D> vertices) : IEnumerable<Vector2D>
return true;
}
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Shape2D"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Shape2D"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Shape2D"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Shape2D shape2D && _vertices.Equals(shape2D._vertices);
/// <summary>
/// Generates a hash code for the <see cref="Shape2D"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Shape2D"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(Vertices);
/// <summary>
/// Converts the <see cref="Shape2D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Shape2D"/>.</returns>
public override string ToString()
{
System.Text.StringBuilder stringBuilder = new(Vertices[0].ToString());
for (int i = 1; i < Vertices.Count; i++)
{
stringBuilder.Append(", ");
stringBuilder.Append(Vertices[i].ToString());
}
return $"{nameof(Shape2D)}({stringBuilder})";
}
/// <inheritdoc/>
public IEnumerator<Vector2D> GetEnumerator() => Vertices.GetEnumerator();
/// <inheritdoc/>
IEnumerator IEnumerable.GetEnumerator() => Vertices.GetEnumerator();
public delegate void ShapeUpdatedEventHandler(Shape2D shape2D);
}
/// <summary>
@@ -272,7 +298,7 @@ public static class Shape2DExtensions
public static Triangle ToSuperTriangle(this Shape2D shape) => Shape2D.GetSuperTriangle(shape);
/// <inheritdoc cref="Shape2D.TriangulateConvex(Shape2D, IList{Triangle})" />
public static void ToTrianglesConvex(this Shape2D shape, IList<Triangle> lines) => Shape2D.TriangulateConvex(shape, lines);
public static void ToTrianglesConvex(this Shape2D shape, IList<Triangle> triangles) => Shape2D.TriangulateConvex(shape, triangles);
/// <inheritdoc cref="Shape2D.TriangulateConvex(Shape2D)" />
public static List<Triangle> ToTrianglesConvex(this Shape2D shape) => Shape2D.TriangulateConvex(shape);

View File

@@ -7,6 +7,9 @@ public readonly struct Triangle(Vector2D A, Vector2D B, Vector2D C)
public readonly Vector2D B { get; init; } = B;
public readonly Vector2D C { get; init; } = C;
public static bool operator ==(Triangle left, Triangle right) => left.A == right.A && left.B == right.B && left.C == right.C;
public static bool operator !=(Triangle left, Triangle right) => left.A != right.A || left.B != right.B || left.C != right.C;
public readonly float Area
=> .5f * Math.Abs(
A.X * (B.Y - C.Y) +
@@ -44,6 +47,25 @@ public readonly struct Triangle(Vector2D A, Vector2D B, Vector2D C)
/// <returns><c>true</c> if the <see cref="Triangle"/>s are approximately equal; otherwise, <c>false</c>.</returns>
public static bool ApproximatelyEquals(Triangle left, Triangle right, float epsilon = float.Epsilon)
=> left.A.ApproximatelyEquals(right.A, epsilon) && left.B.ApproximatelyEquals(right.B, epsilon) && left.C.ApproximatelyEquals(right.C, epsilon);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Triangle"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Triangle"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Triangle"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Triangle triangle && this == triangle;
/// <summary>
/// Generates a hash code for the <see cref="Triangle"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Triangle"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(A, B, C);
/// <summary>
/// Converts the <see cref="Triangle"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Triangle"/>.</returns>
public override string ToString() => $"{nameof(Triangle)}({A}, {B}, {C})";
}
public static class TriangleExtensions

View File

@@ -31,6 +31,11 @@ public readonly struct Vector2D(float x, float y)
/// </summary>
public float MagnitudeSquared => LengthSquared(this);
/// <summary>
/// Gets a <see cref="Vector2D"/> with the direction reversed.
/// </summary>
public readonly Vector2D Reversed => -this;
/// <summary>
/// The normalized form of the <see cref="Vector2D"/> (a <see cref="Vector2D"/> with the same direction and a magnitude of 1).
/// </summary>
@@ -297,24 +302,24 @@ public readonly struct Vector2D(float x, float y)
public static bool ApproximatelyEquals(Vector2D left, Vector2D right, float epsilon = float.Epsilon)
=> left.X.ApproximatelyEquals(right.X, epsilon) && left.Y.ApproximatelyEquals(right.Y, epsilon);
/// <summary>
/// Converts the <see cref="Vector2D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Vector2D"/>.</returns>
public override string ToString() => $"{nameof(Vector2D)}({X}, {Y})";
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Vector2D"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Vector2D"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Vector2D"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Vector2D objVec && X.Equals(objVec.X) && Y.Equals(objVec.Y);
public override bool Equals(object? obj) => obj is Vector2D vector2D && this == vector2D;
/// <summary>
/// Generates a hash code for the <see cref="Vector2D"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Vector2D"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(X, Y);
/// <summary>
/// Converts the <see cref="Vector2D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Vector2D"/>.</returns>
public override string ToString() => $"{nameof(Vector2D)}({X}, {Y})";
}
/// <summary>

View File

@@ -271,24 +271,24 @@ public readonly struct Vector3D(float x, float y, float z)
public static bool ApproximatelyEquals(Vector3D left, Vector3D right, float epsilon = float.Epsilon)
=> left.X.ApproximatelyEquals(right.X, epsilon) && left.Y.ApproximatelyEquals(right.Y, epsilon) && left.Z.ApproximatelyEquals(right.Z, epsilon);
/// <summary>
/// Converts the <see cref="Vector3D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Vector3D"/>.</returns>
public override string ToString() => $"{nameof(Vector3D)}({X}, {Y}, {Z})";
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="Vector3D"/>.
/// </summary>
/// <param name="obj">The object to compare with the current <see cref="Vector3D"/>.</param>
/// <returns><see cref="true"/> if the specified object is equal to the current <see cref="Vector3D"/>; otherwise, <see cref="false"/>.</returns>
public override bool Equals(object? obj) => obj is Vector3D objVec && X.Equals(objVec.X) && Y.Equals(objVec.Y) && Z.Equals(objVec.Z);
public override bool Equals(object? obj) => obj is Vector3D vector3D && this == vector3D;
/// <summary>
/// Generates a hash code for the <see cref="Vector3D"/>.
/// </summary>
/// <returns>A hash code for the <see cref="Vector3D"/>.</returns>
public override int GetHashCode() => System.HashCode.Combine(X, Y, Z);
/// <summary>
/// Converts the <see cref="Vector3D"/> to its string representation.
/// </summary>
/// <returns>A string representation of the <see cref="Vector3D"/>.</returns>
public override string ToString() => $"{nameof(Vector3D)}({X}, {Y}, {Z})";
}
/// <summary>

View File

@@ -5,7 +5,7 @@ namespace Syntriax.Engine.Core.Serialization;
public class EntityRegistry
{
public event EntityRegisteredEventHandler? OnEntityRegistered = null!;
public Event<EntityRegistry, EntityRegisteredArguments> OnEntityRegistered = null!;
private readonly Dictionary<string, Action<IEntity>?> assignCallbacks = [];
private readonly Dictionary<string, IEntity> registeredEntities = [];
@@ -14,7 +14,7 @@ public class EntityRegistry
public void Add(IEntity entity)
{
if (registeredEntities.TryAdd(entity.Id, entity))
OnEntityRegistered?.InvokeSafe(this, entity);
OnEntityRegistered?.Invoke(this, new(entity));
}
public void QueueAssign(string id, Action<IEntity> setMethod)
@@ -26,7 +26,7 @@ public class EntityRegistry
public void AssignAll()
{
foreach ((string id, Action<IEntity>? action) in assignCallbacks)
action?.InvokeSafe(registeredEntities[id]);
action?.Invoke(registeredEntities[id]);
}
public void Reset()
@@ -35,5 +35,5 @@ public class EntityRegistry
registeredEntities.Clear();
}
public delegate void EntityRegisteredEventHandler(EntityRegistry sender, IEntity entity);
public readonly record struct EntityRegisteredArguments(IEntity Entity);
}

View File

@@ -2,9 +2,9 @@ namespace Syntriax.Engine.Core;
public class StateEnable : IStateEnable
{
public event IAssignable.UnassignEventHandler? OnUnassigned = null;
public event IHasEntity.EntityAssignedEventHandler? OnEntityAssigned = null;
public event IStateEnable.EnabledChangedEventHandler? OnEnabledChanged = null;
public Event<IStateEnable, IStateEnable.EnabledChangedArguments> OnEnabledChanged { get; } = new();
public Event<IHasEntity> OnEntityAssigned { get; } = new();
public Event<IAssignable>? OnUnassigned { get; } = new();
private bool _enabled = true;
private IEntity _entity = null!;
@@ -21,7 +21,7 @@ public class StateEnable : IStateEnable
bool previousState = _enabled;
_enabled = value;
OnEnabledChanged?.InvokeSafe(this, previousState);
OnEnabledChanged?.Invoke(this, new(previousState));
}
}
@@ -33,7 +33,7 @@ public class StateEnable : IStateEnable
_entity = entity;
OnAssign(entity);
OnEntityAssigned?.InvokeSafe(this);
OnEntityAssigned?.Invoke(this);
return true;
}
@@ -43,7 +43,7 @@ public class StateEnable : IStateEnable
return false;
_entity = null!;
OnUnassigned?.InvokeSafe(this);
OnUnassigned?.Invoke(this);
return true;
}
}

View File

@@ -0,0 +1,12 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a <see cref="IBehaviour"/> to be notified when the draw phase of the <see cref="IUniverse"/> occurs.
/// </summary>
public interface IDraw : IBehaviour
{
/// <summary>
/// Calls draw logic for the <see cref="IBehaviour"/> to be displayed visually.
/// </summary>
void Draw();
}

View File

@@ -0,0 +1,6 @@
namespace Syntriax.Engine.Core;
public interface IEnterUniverse : IBehaviour
{
void EnterUniverse(IUniverse universe);
}

View File

@@ -0,0 +1,6 @@
namespace Syntriax.Engine.Core;
public interface IExitUniverse : IBehaviour
{
void ExitUniverse(IUniverse universe);
}

View File

@@ -0,0 +1,6 @@
namespace Syntriax.Engine.Core;
public interface IFirstFrameUpdate : IBehaviour
{
void FirstActiveFrame();
}

View File

@@ -0,0 +1,6 @@
namespace Syntriax.Engine.Core;
public interface ILastFrameUpdate : IBehaviour
{
void LastActiveFrame();
}

View File

@@ -0,0 +1,12 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a <see cref="IBehaviour"/> to be notified after the draw phase of the <see cref="IUniverse"/> occurs.
/// </summary>
public interface IPostDraw : IBehaviour
{
/// <summary>
/// Updates the state of the <see cref="IBehaviour"/> after the main draw phase happens.
/// </summary>
void PostDraw();
}

View File

@@ -0,0 +1,12 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a <see cref="IBehaviour"/> to be notified after the update phase of the <see cref="IUniverse"/> occurs.
/// </summary>
public interface IPostUpdate : IBehaviour
{
/// <summary>
/// Updates the state of the <see cref="IBehaviour"/> after the main update phase happens.
/// </summary>
void PostUpdate();
}

View File

@@ -0,0 +1,12 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a <see cref="IBehaviour"/> to be notified before the draw phase of the <see cref="IUniverse"/> occurs.
/// </summary>
public interface IPreDraw : IBehaviour
{
/// <summary>
/// Updates the state of the <see cref="IBehaviour"/> before the main draw phase happens.
/// </summary>
void PreDraw();
}

View File

@@ -0,0 +1,12 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a <see cref="IBehaviour"/> to be notified before the update phase of the <see cref="IUniverse"/> occurs.
/// </summary>
public interface IPreUpdate : IBehaviour
{
/// <summary>
/// Updates the state of the <see cref="IBehaviour"/> before the main update phase happens.
/// </summary>
void PreUpdate();
}

View File

@@ -0,0 +1,12 @@
namespace Syntriax.Engine.Core;
/// <summary>
/// Represents a <see cref="IBehaviour"/> to be notified when the update phase of the <see cref="IUniverse"/> occurs.
/// </summary>
public interface IUpdate : IBehaviour
{
/// <summary>
/// Updates the state of the <see cref="IBehaviour"/>.
/// </summary>
void Update();
}

View File

@@ -0,0 +1,53 @@
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class DrawManager : Behaviour
{
// We use Descending order because draw calls are running from last to first
private static Comparer<IBehaviour> SortByDescendingPriority() => Comparer<IBehaviour>.Create((x, y) => y.Priority.CompareTo(x.Priority));
private readonly ActiveBehaviourCollectorSorted<IPreDraw> preDrawEntities = new() { SortBy = SortByDescendingPriority() };
private readonly ActiveBehaviourCollectorSorted<IDraw> drawEntities = new() { SortBy = SortByDescendingPriority() };
private readonly ActiveBehaviourCollectorSorted<IPostDraw> postDrawEntities = new() { SortBy = SortByDescendingPriority() };
private void OnPreDraw(IUniverse sender)
{
for (int i = preDrawEntities.Count - 1; i >= 0; i--)
preDrawEntities[i].PreDraw();
}
private void OnDraw(IUniverse sender)
{
for (int i = drawEntities.Count - 1; i >= 0; i--)
drawEntities[i].Draw();
}
private void OnPostDraw(IUniverse sender)
{
for (int i = postDrawEntities.Count - 1; i >= 0; i--)
postDrawEntities[i].PostDraw();
}
protected override void OnEnteredUniverse(IUniverse universe)
{
preDrawEntities.Assign(universe);
drawEntities.Assign(universe);
postDrawEntities.Assign(universe);
universe.OnPreDraw.AddListener(OnPreDraw);
universe.OnDraw.AddListener(OnDraw);
universe.OnPostDraw.AddListener(OnPostDraw);
}
protected override void OnExitedUniverse(IUniverse universe)
{
preDrawEntities.Unassign();
drawEntities.Unassign();
postDrawEntities.Unassign();
universe.OnPreDraw.RemoveListener(OnPreDraw);
universe.OnDraw.RemoveListener(OnDraw);
universe.OnPostDraw.RemoveListener(OnPostDraw);
}
}

View File

@@ -0,0 +1,71 @@
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class UniverseEntranceManager : Behaviour
{
// We use Ascending order because we are using reverse for loop to call them
private static Comparer<IBehaviour> SortByAscendingPriority() => Comparer<IBehaviour>.Create((x, y) => x.Priority.CompareTo(y.Priority));
private readonly ActiveBehaviourCollectorSorted<IEnterUniverse> enterUniverses = new() { SortBy = SortByAscendingPriority() };
private readonly ActiveBehaviourCollectorSorted<IExitUniverse> exitUniverses = new() { SortBy = SortByAscendingPriority() };
private readonly List<IEnterUniverse> toCallEnterUniverses = new(32);
private readonly List<IExitUniverse> toCallExitUniverses = new(32);
protected override void OnEnteredUniverse(IUniverse universe)
{
enterUniverses.Assign(universe);
foreach (IUniverseObject universeObject in Universe.UniverseObjects)
OnUniverseObjectRegistered(Universe, new(universeObject));
universe.OnUniverseObjectRegistered.AddListener(OnUniverseObjectRegistered);
universe.OnUniverseObjectUnRegistered.AddListener(OnUniverseObjectUnRegistered);
}
protected override void OnExitedUniverse(IUniverse universe)
{
enterUniverses.Unassign();
foreach (IUniverseObject universeObject in Universe.UniverseObjects)
OnUniverseObjectUnRegistered(Universe, new(universeObject));
universe.OnUniverseObjectRegistered.RemoveListener(OnUniverseObjectRegistered);
universe.OnUniverseObjectUnRegistered.RemoveListener(OnUniverseObjectUnRegistered);
}
private void OnUniverseObjectUnRegistered(IUniverse sender, IUniverse.UniverseObjectUnRegisteredArguments args)
{
for (int i = toCallExitUniverses.Count - 1; i >= 0; i--)
{
toCallExitUniverses[i].ExitUniverse(Universe);
toCallExitUniverses.RemoveAt(i);
}
}
private void OnUniverseObjectRegistered(IUniverse sender, IUniverse.UniverseObjectRegisteredArguments args)
{
for (int i = toCallEnterUniverses.Count - 1; i >= 0; i--)
{
toCallEnterUniverses[i].EnterUniverse(Universe);
toCallEnterUniverses.RemoveAt(i);
}
}
private void OnEnterUniverseCollected(IBehaviourCollector<IEnterUniverse> sender, IBehaviourCollector<IEnterUniverse>.BehaviourCollectedArguments args)
{
toCallEnterUniverses.Add(args.BehaviourCollected);
}
private void OnExitUniverseCollected(IBehaviourCollector<IExitUniverse> sender, IBehaviourCollector<IExitUniverse>.BehaviourCollectedArguments args)
{
toCallExitUniverses.Add(args.BehaviourCollected);
}
public UniverseEntranceManager()
{
enterUniverses.OnCollected.AddListener(OnEnterUniverseCollected);
exitUniverses.OnCollected.AddListener(OnExitUniverseCollected);
}
}

View File

@@ -0,0 +1,83 @@
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
public class UpdateManager : Behaviour
{
// We use Ascending order because we are using reverse for loop to call them
private static Comparer<IBehaviour> SortByAscendingPriority() => Comparer<IBehaviour>.Create((x, y) => x.Priority.CompareTo(y.Priority));
private readonly ActiveBehaviourCollectorSorted<IFirstFrameUpdate> firstFrameUpdates = new() { SortBy = SortByAscendingPriority() };
private readonly ActiveBehaviourCollector<ILastFrameUpdate> lastFrameUpdates = new();
private readonly ActiveBehaviourCollectorSorted<IPreUpdate> preUpdateEntities = new() { SortBy = SortByAscendingPriority() };
private readonly ActiveBehaviourCollectorSorted<IUpdate> updateEntities = new() { SortBy = SortByAscendingPriority() };
private readonly ActiveBehaviourCollectorSorted<IPostUpdate> postUpdateEntities = new() { SortBy = SortByAscendingPriority() };
private readonly List<IFirstFrameUpdate> toCallFirstFrameUpdates = new(32);
protected override void OnEnteredUniverse(IUniverse universe)
{
firstFrameUpdates.Assign(universe);
lastFrameUpdates.Assign(universe);
preUpdateEntities.Assign(universe);
updateEntities.Assign(universe);
postUpdateEntities.Assign(universe);
universe.OnPreUpdate.AddListener(OnPreUpdate);
universe.OnUpdate.AddListener(OnUpdate);
universe.OnPostUpdate.AddListener(OnPostUpdate);
}
protected override void OnExitedUniverse(IUniverse universe)
{
firstFrameUpdates.Unassign();
lastFrameUpdates.Unassign();
preUpdateEntities.Unassign();
updateEntities.Unassign();
postUpdateEntities.Unassign();
universe.OnPreUpdate.RemoveListener(OnPreUpdate);
universe.OnUpdate.RemoveListener(OnUpdate);
universe.OnPostUpdate.RemoveListener(OnPostUpdate);
}
private void OnPreUpdate(IUniverse sender, IUniverse.UpdateArguments args)
{
for (int i = toCallFirstFrameUpdates.Count - 1; i >= 0; i--)
{
toCallFirstFrameUpdates[i].FirstActiveFrame();
toCallFirstFrameUpdates.RemoveAt(i);
}
for (int i = preUpdateEntities.Count - 1; i >= 0; i--)
preUpdateEntities[i].PreUpdate();
}
private void OnUpdate(IUniverse sender, IUniverse.UpdateArguments args)
{
for (int i = updateEntities.Count - 1; i >= 0; i--)
updateEntities[i].Update();
}
private void OnPostUpdate(IUniverse sender, IUniverse.UpdateArguments args)
{
for (int i = postUpdateEntities.Count - 1; i >= 0; i--)
postUpdateEntities[i].PostUpdate();
}
private void OnFirstFrameCollected(IBehaviourCollector<IFirstFrameUpdate> sender, IBehaviourCollector<IFirstFrameUpdate>.BehaviourCollectedArguments args)
{
toCallFirstFrameUpdates.Add(args.BehaviourCollected);
}
private void OnLastFrameRemoved(IBehaviourCollector<ILastFrameUpdate> sender, IBehaviourCollector<ILastFrameUpdate>.BehaviourRemovedArguments args)
{
args.BehaviourRemoved.LastActiveFrame();
}
public UpdateManager()
{
firstFrameUpdates.OnCollected.AddListener(OnFirstFrameCollected);
lastFrameUpdates.OnRemoved.AddListener(OnLastFrameRemoved);
}
}

View File

@@ -5,9 +5,9 @@ namespace Syntriax.Engine.Core;
[System.Diagnostics.DebuggerDisplay("Name: {UniverseObject.Name, nq} Position: {Position.ToString(), nq}, Scale: {Scale.ToString(), nq}, Rotation: {Rotation}")]
public class Transform2D : Behaviour, ITransform2D
{
public event ITransform2D.PositionChangedEventHandler? OnPositionChanged = null;
public event ITransform2D.ScaleChangedEventHandler? OnScaleChanged = null;
public event ITransform2D.RotationChangedEventHandler? OnRotationChanged = null;
public Event<ITransform2D, ITransform2D.PositionChangedArguments> OnPositionChanged { get; } = new();
public Event<ITransform2D, ITransform2D.ScaleChangedArguments> OnScaleChanged { get; } = new();
public Event<ITransform2D, ITransform2D.RotationChangedArguments> OnRotationChanged { get; } = new();
private Vector2D _position = Vector2D.Zero;
private Vector2D _scale = Vector2D.One;
@@ -19,6 +19,11 @@ public class Transform2D : Behaviour, ITransform2D
private ITransform2D? parentTransform = null;
public Vector2D Up => Vector2D.Up.Rotate(Rotation * Math.DegreeToRadian);
public Vector2D Down => Vector2D.Down.Rotate(Rotation * Math.DegreeToRadian);
public Vector2D Left => Vector2D.Left.Rotate(Rotation * Math.DegreeToRadian);
public Vector2D Right => Vector2D.Right.Rotate(Rotation * Math.DegreeToRadian);
public Vector2D Position
{
get => _position;
@@ -31,7 +36,7 @@ public class Transform2D : Behaviour, ITransform2D
_position = value;
UpdateLocalPosition();
OnPositionChanged?.InvokeSafe(this, previousPosition);
OnPositionChanged?.Invoke(this, new(previousPosition));
}
}
@@ -47,7 +52,7 @@ public class Transform2D : Behaviour, ITransform2D
_scale = value;
UpdateLocalScale();
OnScaleChanged?.InvokeSafe(this, previousScale);
OnScaleChanged?.Invoke(this, new(previousScale));
}
}
@@ -63,7 +68,7 @@ public class Transform2D : Behaviour, ITransform2D
_rotation = value;
UpdateLocalRotation();
OnRotationChanged?.InvokeSafe(this, previousRotation);
OnRotationChanged?.Invoke(this, new(previousRotation));
}
}
@@ -79,7 +84,7 @@ public class Transform2D : Behaviour, ITransform2D
_localPosition = value;
UpdatePosition();
OnPositionChanged?.InvokeSafe(this, previousPosition);
OnPositionChanged?.Invoke(this, new(previousPosition));
}
}
@@ -97,8 +102,8 @@ public class Transform2D : Behaviour, ITransform2D
UpdateScale();
UpdatePosition();
OnScaleChanged?.InvokeSafe(this, previousScale);
OnPositionChanged?.InvokeSafe(this, previousPosition);
OnScaleChanged?.Invoke(this, new(previousScale));
OnPositionChanged?.Invoke(this, new(previousPosition));
}
}
@@ -114,21 +119,21 @@ public class Transform2D : Behaviour, ITransform2D
_localRotation = value;
UpdateRotation();
OnRotationChanged?.InvokeSafe(this, previousRotation);
OnRotationChanged?.Invoke(this, new(previousRotation));
}
}
private void RecalculatePosition(ITransform2D _, Vector2D previousPosition)
private void RecalculatePosition(ITransform2D _, ITransform2D.PositionChangedArguments args)
{
if (parentTransform is null)
return;
UpdatePosition();
OnPositionChanged?.InvokeSafe(this, previousPosition);
OnPositionChanged?.Invoke(this, args);
}
private void RecalculateScale(ITransform2D _, Vector2D previousScale)
private void RecalculateScale(ITransform2D _, ITransform2D.ScaleChangedArguments args)
{
if (parentTransform is null)
return;
@@ -138,11 +143,11 @@ public class Transform2D : Behaviour, ITransform2D
UpdateScale();
UpdatePosition();
OnScaleChanged?.InvokeSafe(this, previousScale);
OnPositionChanged?.InvokeSafe(this, previousPosition);
OnScaleChanged?.Invoke(this, args);
OnPositionChanged?.Invoke(this, new(previousPosition));
}
private void RecalculateRotation(ITransform2D _, float previousRotation)
private void RecalculateRotation(ITransform2D _, ITransform2D.RotationChangedArguments args)
{
if (parentTransform is null)
return;
@@ -152,8 +157,8 @@ public class Transform2D : Behaviour, ITransform2D
UpdateRotation();
UpdatePosition();
OnRotationChanged?.InvokeSafe(this, previousRotation);
OnPositionChanged?.InvokeSafe(this, previousPosition);
OnRotationChanged?.Invoke(this, args);
OnPositionChanged?.Invoke(this, new(previousPosition));
}
private void UpdateLocalPosition()
@@ -207,12 +212,12 @@ public class Transform2D : Behaviour, ITransform2D
protected override void InitializeInternal()
{
UpdateReferences(UniverseObject.Parent);
UniverseObject.OnParentChanged += OnParentChanged;
UniverseObject.OnParentChanged.AddListener(OnParentChanged);
}
protected override void FinalizeInternal()
{
UniverseObject.OnParentChanged -= OnParentChanged;
UniverseObject.OnParentChanged.RemoveListener(OnParentChanged);
}
private void UpdateReferences(IUniverseObject? parent)
@@ -220,48 +225,48 @@ public class Transform2D : Behaviour, ITransform2D
ITransform2D? previousParent = parentTransform;
if (previousParent is not null)
{
previousParent.OnPositionChanged -= RecalculatePosition;
previousParent.OnScaleChanged -= RecalculateScale;
previousParent.OnRotationChanged -= RecalculateRotation;
previousParent.BehaviourController.UniverseObject.OnParentChanged -= OnParentChanged;
previousParent.BehaviourController.OnBehaviourAdded -= LookForTransform2D;
previousParent.OnPositionChanged.RemoveListener(RecalculatePosition);
previousParent.OnScaleChanged.RemoveListener(RecalculateScale);
previousParent.OnRotationChanged.RemoveListener(RecalculateRotation);
previousParent.BehaviourController.UniverseObject.OnParentChanged.RemoveListener(OnParentChanged);
previousParent.BehaviourController.OnBehaviourAdded.RemoveListener(LookForTransform2D);
}
parentTransform = parent?.BehaviourController.GetBehaviour<ITransform2D>();
if (parentTransform is not null)
{
parentTransform.OnPositionChanged += RecalculatePosition;
parentTransform.OnScaleChanged += RecalculateScale;
parentTransform.OnRotationChanged += RecalculateRotation;
parentTransform.BehaviourController.UniverseObject.OnParentChanged += OnParentChanged;
parentTransform.OnPositionChanged.AddListener(RecalculatePosition);
parentTransform.OnScaleChanged.AddListener(RecalculateScale);
parentTransform.OnRotationChanged.AddListener(RecalculateRotation);
parentTransform.BehaviourController.UniverseObject.OnParentChanged.AddListener(OnParentChanged);
UpdatePosition();
UpdateScale();
UpdateRotation();
}
else if (UniverseObject.Parent is not null)
UniverseObject.Parent.BehaviourController.OnBehaviourAdded += LookForTransform2D;
UniverseObject.Parent.BehaviourController.OnBehaviourAdded.AddListener(LookForTransform2D);
UpdateLocalPosition();
UpdateLocalScale();
UpdateLocalRotation();
OnPositionChanged?.InvokeSafe(this, Position);
OnScaleChanged?.InvokeSafe(this, Scale);
OnRotationChanged?.InvokeSafe(this, Rotation);
OnPositionChanged?.Invoke(this, new(Position));
OnScaleChanged?.Invoke(this, new(Scale));
OnRotationChanged?.Invoke(this, new(Rotation));
}
private void LookForTransform2D(IBehaviourController sender, IBehaviour behaviourAdded)
private void LookForTransform2D(IBehaviourController sender, IBehaviourController.BehaviourAddedArguments args)
{
if (behaviourAdded is not ITransform2D transform2D)
if (args.BehaviourAdded is not ITransform2D)
return;
UpdateReferences(UniverseObject.Parent);
}
private void OnParentChanged(IUniverseObject sender, IUniverseObject? previousParent, IUniverseObject? newParent)
private void OnParentChanged(IUniverseObject sender, IUniverseObject.ParentChangedArguments args)
{
UpdateReferences(newParent);
UpdateReferences(args.CurrentParent);
}
}

View File

@@ -7,18 +7,30 @@ namespace Syntriax.Engine.Core;
[System.Diagnostics.DebuggerDisplay("UniverseObject Count: {_universeObjects.Count}")]
public class Universe : BaseEntity, IUniverse
{
public event IUniverse.UpdateEventHandler? OnPreUpdate = null;
public event IUniverse.UpdateEventHandler? OnUpdate = null;
public event IUniverse.PreDrawEventHandler? OnPreDraw = null;
public Event<IUniverse, IUniverse.UpdateArguments> OnPreUpdate { get; } = new();
public Event<IUniverse, IUniverse.UpdateArguments> OnUpdate { get; } = new();
public Event<IUniverse, IUniverse.UpdateArguments> OnPostUpdate { get; } = new();
public Event<IUniverse> OnPreDraw { get; } = new();
public Event<IUniverse> OnDraw { get; } = new();
public Event<IUniverse> OnPostDraw { get; } = new();
public Event<IUniverse, IUniverse.UniverseObjectRegisteredArguments> OnPreUniverseObjectRegistered { get; } = new();
public Event<IUniverse, IUniverse.UniverseObjectRegisteredArguments> OnUniverseObjectRegistered { get; } = new();
public Event<IUniverse, IUniverse.UniverseObjectUnRegisteredArguments> OnPreUniverseObjectUnRegistered { get; } = new();
public Event<IUniverse, IUniverse.UniverseObjectUnRegisteredArguments> OnUniverseObjectUnRegistered { get; } = new();
public Event<IUniverse, IUniverse.TimeScaleChangedArguments> OnTimeScaleChanged { get; } = new();
public event IUniverse.UniverseObjectRegisteredEventHandler? OnUniverseObjectRegistered = null;
public event IUniverse.UniverseObjectUnRegisteredEventHandler? OnUniverseObjectUnRegistered = null;
public event IUniverse.TimeScaleChangedEventHandler? OnTimeScaleChanged = null;
private readonly Event<IInitializable>.EventHandler delegateOnUniverseObjectFinalize = null!;
private readonly Event<IUniverseObject, IUniverseObject.ExitedUniverseArguments>.EventHandler delegateOnUniverseObjectExitedUniverse = null!;
private readonly List<IUniverseObject> _universeObjects = new(Constants.UNIVERSE_OBJECTS_SIZE_INITIAL);
private float _timeScale = 1f;
public Universe()
{
delegateOnUniverseObjectFinalize = OnUniverseObjectFinalize;
delegateOnUniverseObjectExitedUniverse = OnUniverseObjectExitedUniverse;
}
public IReadOnlyList<IUniverseObject> UniverseObjects => _universeObjects;
public UniverseTime Time { get; private set; } = new();
@@ -34,7 +46,7 @@ public class Universe : BaseEntity, IUniverse
float previousTimeScale = _timeScale;
_timeScale = value;
OnTimeScaleChanged?.InvokeSafe(this, previousTimeScale);
OnTimeScaleChanged?.Invoke(this, new(previousTimeScale));
}
}
@@ -43,8 +55,10 @@ public class Universe : BaseEntity, IUniverse
if (_universeObjects.Contains(universeObject))
throw new Exception($"{nameof(IUniverseObject)} named {universeObject.Name} is already registered to the {nameof(Universe)}.");
universeObject.OnFinalized += OnUniverseObjectFinalize;
universeObject.OnExitedUniverse += OnUniverseObjectExitedUniverse;
OnPreUniverseObjectRegistered?.Invoke(this, new(universeObject));
universeObject.OnFinalized.AddListener(delegateOnUniverseObjectFinalize);
universeObject.OnExitedUniverse.AddListener(delegateOnUniverseObjectExitedUniverse);
if (!universeObject.Initialize())
throw new Exception($"{universeObject.Name} can't be initialized");
@@ -57,7 +71,7 @@ public class Universe : BaseEntity, IUniverse
if (!universeObject.EnterUniverse(this))
throw new Exception($"{universeObject.Name} can't enter the universe");
OnUniverseObjectRegistered?.InvokeSafe(this, universeObject);
OnUniverseObjectRegistered?.Invoke(this, new(universeObject));
}
public T InstantiateUniverseObject<T>(params object?[]? args) where T : class, IUniverseObject
@@ -69,7 +83,7 @@ public class Universe : BaseEntity, IUniverse
public void Remove(IUniverseObject universeObject)
{
universeObject.SetParent(null);
universeObject.Parent = null;
RemoveIncursive(universeObject);
}
@@ -78,8 +92,10 @@ public class Universe : BaseEntity, IUniverse
if (!_universeObjects.Contains(universeObject))
throw new Exception($"{nameof(IUniverseObject)} named {universeObject.Name} is not registered to the {nameof(Universe)}.");
universeObject.OnFinalized -= OnUniverseObjectFinalize;
universeObject.OnExitedUniverse -= OnUniverseObjectExitedUniverse;
OnPreUniverseObjectUnRegistered?.Invoke(this, new(universeObject));
universeObject.OnFinalized.RemoveListener(delegateOnUniverseObjectFinalize);
universeObject.OnExitedUniverse.RemoveListener(delegateOnUniverseObjectExitedUniverse);
for (int i = universeObject.Children.Count - 1; i >= 0; i--)
Remove(universeObject.Children[i]);
@@ -92,7 +108,7 @@ public class Universe : BaseEntity, IUniverse
if (!universeObject.Finalize())
throw new Exception($"{universeObject.Name} can't be finalized");
OnUniverseObjectUnRegistered?.InvokeSafe(this, universeObject);
OnUniverseObjectUnRegistered?.Invoke(this, new(universeObject));
}
protected override void InitializeInternal()
@@ -115,22 +131,18 @@ public class Universe : BaseEntity, IUniverse
UnscaledTime = engineTime;
Time = new(TimeSpan.FromTicks((long)(Time.TimeSinceStart.Ticks + engineTime.DeltaSpan.Ticks * TimeScale)), TimeSpan.FromTicks((long)(engineTime.DeltaSpan.Ticks * TimeScale)));
OnPreUpdate?.InvokeSafe(this, Time);
for (int i = 0; i < UniverseObjects.Count; i++)
UniverseObjects[i].BehaviourController.Update();
OnUpdate?.InvokeSafe(this, Time);
OnPreUpdate?.Invoke(this, new(Time));
OnUpdate?.Invoke(this, new(Time));
OnPostUpdate?.Invoke(this, new(Time));
}
public void PreDraw()
public void Draw()
{
Debug.Assert.AssertInitialized(this);
for (int i = 0; i < UniverseObjects.Count; i++)
UniverseObjects[i].BehaviourController.UpdatePreDraw();
OnPreDraw?.InvokeSafe(this);
OnPreDraw?.Invoke(this);
OnDraw?.Invoke(this);
OnPostDraw?.Invoke(this);
}
private void OnUniverseObjectFinalize(IInitializable initializable)
@@ -139,7 +151,7 @@ public class Universe : BaseEntity, IUniverse
Remove(universeObject);
}
private void OnUniverseObjectExitedUniverse(IUniverseObject sender, IUniverse universe)
private void OnUniverseObjectExitedUniverse(IUniverseObject sender, IUniverseObject.ExitedUniverseArguments args)
{
if (sender is IUniverseObject universeObject)
Remove(universeObject);

View File

@@ -1,4 +1,3 @@
using System.Collections;
using System.Collections.Generic;
namespace Syntriax.Engine.Core;
@@ -6,22 +5,23 @@ namespace Syntriax.Engine.Core;
[System.Diagnostics.DebuggerDisplay("Name: {Name}, Initialized: {Initialized}")]
public class UniverseObject : BaseEntity, IUniverseObject
{
public event IUniverseObject.EnteredUniverseEventHandler? OnEnteredUniverse = null;
public event IUniverseObject.ExitedUniverseEventHandler? OnExitedUniverse = null;
public event IUniverseObject.ParentChangedEventHandler? OnParentChanged = null;
public event IUniverseObject.ChildrenAddedEventHandler? OnChildrenAdded = null;
public event IUniverseObject.ChildrenRemovedEventHandler? OnChildrenRemoved = null;
public event IHasBehaviourController.BehaviourControllerAssignedEventHandler? OnBehaviourControllerAssigned = null;
public event INameable.NameChangedEventHandler? OnNameChanged = null;
public event IActive.ActiveChangedEventHandler? OnActiveChanged = null;
public Event<IUniverseObject, IUniverseObject.EnteredUniverseArguments> OnEnteredUniverse { get; } = new();
public Event<IUniverseObject, IUniverseObject.ExitedUniverseArguments> OnExitedUniverse { get; } = new();
public Event<IUniverseObject, IUniverseObject.ParentChangedArguments> OnParentChanged { get; } = new();
public Event<IUniverseObject, IUniverseObject.ChildrenAddedArguments> OnChildrenAdded { get; } = new();
public Event<IUniverseObject, IUniverseObject.ChildrenRemovedArguments> OnChildrenRemoved { get; } = new();
public Event<IActive, IActive.ActiveChangedArguments> OnActiveChanged { get; } = new();
public Event<INameable, INameable.NameChangedArguments> OnNameChanged { get; } = new();
public Event<IHasBehaviourController> OnBehaviourControllerAssigned { get; } = new();
private string _name = nameof(UniverseObject);
private IUniverse _universe = null!;
private IBehaviourController _behaviourController = null!;
private bool _isActive = false;
private readonly List<IUniverseObject> _children = [];
private IUniverseObject? _parent = null;
public IUniverseObject? Parent { get; private set; } = null;
public IReadOnlyList<IUniverseObject> Children => _children;
public IBehaviourController BehaviourController => _behaviourController;
public IUniverse Universe => _universe;
@@ -37,7 +37,41 @@ public class UniverseObject : BaseEntity, IUniverseObject
string previousName = _name;
_name = value;
OnNameChanged?.InvokeSafe(this, previousName);
OnNameChanged?.Invoke(this, new(previousName));
}
}
public IUniverseObject? Parent
{
get => _parent;
set
{
if (value == this)
throw new Exceptions.AssignFailedException($"{Name} can not parent itself");
if (_parent == value)
return;
IUniverseObject? previousParent = Parent;
if (previousParent is not null)
{
previousParent.RemoveChild(this);
previousParent.OnActiveChanged.RemoveListener(OnParentActiveChanged);
}
_parent = value;
if (value is not null)
{
if (value.IsInUniverse && !IsInUniverse)
value.Universe.Register(this);
value.AddChild(this);
value.OnActiveChanged.AddListener(OnParentActiveChanged);
}
UpdateActive();
OnParentChanged?.Invoke(this, new(previousParent, value));
}
}
@@ -50,7 +84,7 @@ public class UniverseObject : BaseEntity, IUniverseObject
_universe = universe;
UpdateActive();
OnEnteringUniverse(universe);
OnEnteredUniverse?.InvokeSafe(this, universe);
OnEnteredUniverse?.Invoke(this, new(universe));
return true;
}
@@ -62,48 +96,18 @@ public class UniverseObject : BaseEntity, IUniverseObject
OnExitingUniverse(universe);
_universe = null!;
OnExitedUniverse?.InvokeSafe(this, universe);
OnExitedUniverse?.Invoke(this, new(universe));
return true;
}
public void SetParent(IUniverseObject? parent)
{
if (parent == this)
throw new Exceptions.AssignFailedException($"{Name} can not parent itself");
if (Parent == parent)
return;
IUniverseObject? previousParent = Parent;
if (previousParent is not null)
{
previousParent.RemoveChild(this);
previousParent.OnActiveChanged -= OnParentActiveChanged;
}
Parent = parent;
if (parent is not null)
{
if (parent.IsInUniverse && !IsInUniverse)
parent.Universe.Register(this);
parent.AddChild(this);
parent.OnActiveChanged += OnParentActiveChanged;
}
UpdateActive();
OnParentChanged?.InvokeSafe(this, previousParent, parent);
}
public void AddChild(IUniverseObject parent)
{
if (_children.Contains(parent))
return;
_children.Add(parent);
parent.SetParent(this);
OnChildrenAdded?.InvokeSafe(this, parent);
parent.Parent = this;
OnChildrenAdded?.Invoke(this, new(parent));
}
public void RemoveChild(IUniverseObject child)
@@ -111,8 +115,8 @@ public class UniverseObject : BaseEntity, IUniverseObject
if (!_children.Remove(child))
return;
child.SetParent(null);
OnChildrenRemoved?.InvokeSafe(this, child);
child.Parent = null;
OnChildrenRemoved?.Invoke(this, new(child));
}
protected virtual void OnAssign(IBehaviourController behaviourController) { }
@@ -123,7 +127,7 @@ public class UniverseObject : BaseEntity, IUniverseObject
_behaviourController = behaviourController;
OnAssign(behaviourController);
OnBehaviourControllerAssigned?.InvokeSafe(this);
OnBehaviourControllerAssigned?.Invoke(this);
return true;
}
@@ -131,11 +135,12 @@ public class UniverseObject : BaseEntity, IUniverseObject
{
base.OnAssign(stateEnable);
stateEnable.OnEnabledChanged += OnStateEnabledChanged;
stateEnable.OnEnabledChanged.AddListener(OnStateEnabledChanged);
UpdateActive();
}
private void OnParentActiveChanged(IActive sender, bool previousState) => UpdateActive();
private void OnStateEnabledChanged(IStateEnable sender, bool previousState) => UpdateActive();
private void OnParentActiveChanged(IActive sender, IActive.ActiveChangedArguments args) => UpdateActive();
private void OnStateEnabledChanged(IStateEnable sender, IStateEnable.EnabledChangedArguments args) => UpdateActive();
private void UpdateActive()
{
@@ -143,13 +148,13 @@ public class UniverseObject : BaseEntity, IUniverseObject
_isActive = StateEnable.Enabled && (Parent?.IsActive ?? true);
if (previousActive != IsActive)
OnActiveChanged?.InvokeSafe(this, previousActive);
OnActiveChanged?.Invoke(this, new(previousActive));
}
protected override void UnassignInternal()
{
base.UnassignInternal();
StateEnable.OnEnabledChanged -= OnStateEnabledChanged;
StateEnable.OnEnabledChanged.RemoveListener(OnStateEnabledChanged);
}
protected override void InitializeInternal()
@@ -163,7 +168,4 @@ public class UniverseObject : BaseEntity, IUniverseObject
{
_name = GetType().Name;
}
public IEnumerator<IUniverseObject> GetEnumerator() => _children.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _children.GetEnumerator();
}

View File

@@ -0,0 +1,8 @@
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public interface IDrawableSprite : IBehaviour
{
void Draw(ISpriteBatch spriteBatch);
}

View File

@@ -0,0 +1,8 @@
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public interface IDrawableTriangle : IBehaviour
{
void Draw(ITriangleBatch triangleBatch);
}

View File

@@ -0,0 +1,10 @@
using Microsoft.Xna.Framework.Content;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public interface ILoadContent : IBehaviour
{
void LoadContent(ContentManager content);
}

View File

@@ -0,0 +1,29 @@
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public interface ISpriteBatch
{
void Begin(SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendState? blendState = null, SamplerState? samplerState = null, DepthStencilState? depthStencilState = null, RasterizerState? rasterizerState = null, Effect? effect = null, Matrix? transformMatrix = null);
void Draw(Texture2D texture, Vector2D position, AABB? sourceAABB, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth);
void Draw(Texture2D texture, Vector2D position, AABB? sourceAABB, Color color, float rotation, Vector2D origin, float scale, SpriteEffects effects, float layerDepth);
void Draw(Texture2D texture, AABB destinationAABB, AABB? sourceAABB, Color color, float rotation, Vector2D origin, SpriteEffects effects, float layerDepth);
void Draw(Texture2D texture, Vector2D position, AABB? sourceAABB, Color color);
void Draw(Texture2D texture, AABB destinationAABB, AABB? sourceAABB, Color color);
void Draw(Texture2D texture, Vector2D position, Color color);
void Draw(Texture2D texture, AABB destinationAABB, Color color);
void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color);
void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color, float rotation, Vector2D origin, float scale, SpriteEffects effects, float layerDepth);
void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth);
void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth, bool rtl);
void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color);
void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color, float rotation, Vector2D origin, float scale, SpriteEffects effects, float layerDepth);
void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth);
void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth, bool rtl);
void End();
}

View File

@@ -0,0 +1,12 @@
using Microsoft.Xna.Framework;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public interface ITriangleBatch
{
void Begin(Matrix? view = null, Matrix? projection = null);
void Draw(Triangle triangle, ColorRGBA colorRGBA);
void End();
}

View File

@@ -0,0 +1,29 @@
using System.Collections.Generic;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public class DrawableShape : Behaviour2D, IDrawableTriangle, IPreDraw
{
private readonly Shape2D shape = new([]);
private readonly List<Triangle> worldTriangles = [];
private readonly Shape2D worldShape = new([]);
protected ColorRGB color = new(255, 255, 255);
public void PreDraw() => UpdateWorldShape();
public void Draw(ITriangleBatch triangleBatch)
{
worldShape.ToTrianglesConvex(worldTriangles);
foreach (Triangle triangle in worldTriangles)
triangleBatch.Draw(new(triangle.C, triangle.B, triangle.A), color);
}
protected void UpdateWorldShape() => shape.Transform(Transform, worldShape);
public DrawableShape() => shape = Shape2D.Triangle;
public DrawableShape(Shape2D shape) => this.shape = shape;
public DrawableShape(Shape2D shape, ColorRGB color) { this.shape = shape; this.color = color; }
}

View File

@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;
using Syntriax.Engine.Core;
using Syntriax.Engine.Systems.Input;
namespace Syntriax.Engine.Integration.MonoGame;
public class KeyboardInputs : Behaviour, IButtonInputs<Keys>, IUpdate
{
public Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments> OnAnyButtonPressed { get; } = new();
public Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments> OnAnyButtonReleased { get; } = new();
private readonly Dictionary<Keys, Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>> OnPressed = new(256);
private readonly Dictionary<Keys, Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>> OnReleased = new(256);
private int cachePressedCurrentlyCount = 0;
private readonly Keys[] cachePressedCurrently = new Keys[256];
private int cachePressedPreviouslyCount = 0;
private readonly Keys[] cachePressedPreviously = new Keys[256];
public void RegisterOnPress(Keys key, Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>.EventHandler callback)
{
if (!OnPressed.TryGetValue(key, out Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>? delegateCallback))
{
delegateCallback = new();
OnPressed.Add(key, delegateCallback);
}
delegateCallback.AddListener(callback);
}
public void UnregisterOnPress(Keys key, Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>.EventHandler callback)
{
if (OnPressed.TryGetValue(key, out Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>? delegateCallback))
delegateCallback.RemoveListener(callback);
}
public void RegisterOnRelease(Keys key, Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>.EventHandler callback)
{
if (!OnReleased.TryGetValue(key, out Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>? delegateCallback))
{
delegateCallback = new();
OnReleased.Add(key, delegateCallback);
}
delegateCallback.AddListener(callback);
}
public void UnregisterOnRelease(Keys key, Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>.EventHandler callback)
{
if (OnReleased.TryGetValue(key, out Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>? delegateCallback))
delegateCallback.RemoveListener(callback);
}
public void Update()
{
KeyboardState keyboardState = Keyboard.GetState();
keyboardState.GetPressedKeys(cachePressedCurrently);
cachePressedCurrentlyCount = keyboardState.GetPressedKeyCount();
for (int i = 0; i < cachePressedCurrentlyCount; i++)
{
Keys currentlyPressedKey = cachePressedCurrently[i];
if (WasPressed(currentlyPressedKey))
continue;
if (OnPressed.TryGetValue(currentlyPressedKey, out Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>? callback))
callback?.Invoke(this, new(currentlyPressedKey));
OnAnyButtonPressed?.Invoke(this, new(currentlyPressedKey));
}
for (int i = 0; i < cachePressedPreviouslyCount; i++)
{
Keys previouslyPressedKey = cachePressedPreviously[i];
if (IsPressed(previouslyPressedKey))
continue;
if (OnReleased.TryGetValue(previouslyPressedKey, out Event<IButtonInputs<Keys>, IButtonInputs<Keys>.ButtonCallbackArguments>? callback))
callback?.Invoke(this, new(previouslyPressedKey));
OnAnyButtonReleased?.Invoke(this, new(previouslyPressedKey));
}
Array.Copy(cachePressedCurrently, cachePressedPreviously, cachePressedCurrentlyCount);
cachePressedPreviouslyCount = cachePressedCurrentlyCount;
}
public bool IsPressed(Keys key)
{
for (int i = 0; i < cachePressedCurrentlyCount; i++)
if (cachePressedCurrently[i] == key)
return true;
return false;
}
private bool WasPressed(Keys key)
{
for (int i = 0; i < cachePressedPreviouslyCount; i++)
if (cachePressedPreviously[i] == key)
return true;
return false;
}
}

View File

@@ -0,0 +1,53 @@
using System.Collections.Generic;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public class LoadContentManager : Behaviour, IFirstFrameUpdate
{
// We use Ascending order because we are using reverse for loop to call them
private static Comparer<IBehaviour> SortByAscendingPriority() => Comparer<IBehaviour>.Create((x, y) => x.Priority.CompareTo(y.Priority));
private readonly ActiveBehaviourCollectorSorted<ILoadContent> loadContents = new() { SortBy = SortByAscendingPriority() };
private readonly List<ILoadContent> toCallLoadContents = new(32);
private MonoGameWindowContainer monoGameWindowContainer = null!;
public void FirstActiveFrame()
{
monoGameWindowContainer = Universe.FindRequiredBehaviour<MonoGameWindowContainer>();
}
protected override void OnEnteredUniverse(IUniverse universe)
{
loadContents.Assign(universe);
universe.OnPreUpdate.AddListener(OnPreUpdate);
}
protected override void OnExitedUniverse(IUniverse universe)
{
loadContents.Unassign();
universe.OnPreUpdate.RemoveListener(OnPreUpdate);
}
private void OnPreUpdate(IUniverse sender, IUniverse.UpdateArguments args)
{
for (int i = toCallLoadContents.Count - 1; i >= 0; i--)
{
toCallLoadContents[i].LoadContent(monoGameWindowContainer.Window.Content);
toCallLoadContents.RemoveAt(i);
}
}
private void OnFirstFrameCollected(IBehaviourCollector<ILoadContent> sender, IBehaviourCollector<ILoadContent>.BehaviourCollectedArguments args)
{
toCallLoadContents.Add(args.BehaviourCollected);
}
public LoadContentManager()
{
loadContents.OnCollected.AddListener(OnFirstFrameCollected);
}
}

View File

@@ -0,0 +1,109 @@
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public class MonoGameCamera2D : BehaviourBase, ICamera2D, IFirstFrameUpdate, IPreDraw
{
public event MatrixTransformChangedArguments? OnMatrixTransformChanged = null;
public event ViewportChangedArguments? OnViewportChanged = null;
public event ZoomChangedArguments? OnZoomChanged = null;
private Matrix _matrixTransform = Matrix.Identity;
private Viewport _viewport = default;
private float _zoom = 1f;
public GraphicsDeviceManager Graphics { get; private set; } = null!;
public ITransform2D Transform { get; private set; } = null!;
public Matrix MatrixTransform
{
get => _matrixTransform;
set
{
if (_matrixTransform == value)
return;
_matrixTransform = value;
OnMatrixTransformChanged?.Invoke(this);
}
}
public Vector2D Position
{
get => Transform.Position;
set => Transform.Position = value;
}
public Viewport Viewport
{
get => _viewport;
set
{
if (_viewport.Equals(value))
return;
_viewport = value;
OnViewportChanged?.Invoke(this);
}
}
public float Zoom
{
get => _zoom;
set
{
float newValue = Syntriax.Engine.Core.Math.Max(0.1f, value);
if (_zoom == newValue)
return;
_zoom = newValue;
OnZoomChanged?.Invoke(this);
}
}
public float Rotation
{
get => Transform.Rotation;
set => Transform.Rotation = value;
}
// TODO This causes delay since OnPreDraw calls assuming this is called in in Update
public Vector2D ScreenToWorldPosition(Vector2D screenPosition)
{
Vector2D worldPosition = Vector2.Transform(screenPosition.ToVector2(), Matrix.Invert(MatrixTransform)).ToVector2D();
return worldPosition.Scale(EngineConverterExtensions.screenScale);
}
public Vector2D WorldToScreenPosition(Vector2D worldPosition)
{
Vector2D screenPosition = Vector2.Transform(worldPosition.ToVector2(), MatrixTransform).ToVector2D();
return screenPosition.Scale(EngineConverterExtensions.screenScale);
}
public void FirstActiveFrame()
{
Graphics = BehaviourController.UniverseObject.Universe.FindRequiredBehaviour<MonoGameWindowContainer>().Window.Graphics;
Viewport = Graphics.GraphicsDevice.Viewport;
}
public void PreDraw()
{
MatrixTransform =
Matrix.CreateTranslation(new Vector3(-Position.X, Position.Y, 0f)) *
Matrix.CreateRotationZ(Rotation * Syntriax.Engine.Core.Math.DegreeToRadian) *
Matrix.CreateScale(Transform.Scale.X.Max(Transform.Scale.Y)) *
Matrix.CreateScale(Zoom) *
Matrix.CreateTranslation(new Vector3(_viewport.Width * .5f, _viewport.Height * .5f, 0f));
}
protected sealed override void InitializeInternal() => Transform = BehaviourController.GetRequiredBehaviour<ITransform2D>();
protected sealed override void FinalizeInternal() => Transform = null!;
public delegate void MatrixTransformChangedArguments(MonoGameCamera2D sender);
public delegate void ViewportChangedArguments(MonoGameCamera2D sender);
public delegate void ZoomChangedArguments(MonoGameCamera2D sender);
}

View File

@@ -0,0 +1,64 @@
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public class SpriteBatchWrapper(GraphicsDevice graphicsDevice) : ISpriteBatch
{
private readonly SpriteBatch spriteBatch = new(graphicsDevice);
public void Begin(SpriteSortMode sortMode = SpriteSortMode.Deferred, BlendState? blendState = null, SamplerState? samplerState = null, DepthStencilState? depthStencilState = null, RasterizerState? rasterizerState = null, Effect? effect = null, Matrix? transformMatrix = null)
=> spriteBatch.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix);
public void Draw(Texture2D texture, Vector2D position, AABB? sourceAABB, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth)
=> spriteBatch.Draw(texture, position.ToDisplayVector2(), sourceAABB?.ToRectangle(), color, rotation, origin.ToDisplayVector2(), scale.ToDisplayVector2(), effects, layerDepth);
public void Draw(Texture2D texture, Vector2D position, AABB? sourceAABB, Color color, float rotation, Vector2D origin, float scale, SpriteEffects effects, float layerDepth)
=> spriteBatch.Draw(texture, position.ToDisplayVector2(), sourceAABB?.ToRectangle(), color, rotation, origin.ToDisplayVector2(), scale, effects, layerDepth);
public void Draw(Texture2D texture, AABB destinationAABB, AABB? sourceAABB, Color color, float rotation, Vector2D origin, SpriteEffects effects, float layerDepth)
=> spriteBatch.Draw(texture, destinationAABB.ToRectangle(), sourceAABB?.ToRectangle(), color, rotation, origin.ToDisplayVector2(), effects, layerDepth);
public void Draw(Texture2D texture, Vector2D position, AABB? sourceAABB, Color color)
=> spriteBatch.Draw(texture, position.ToDisplayVector2(), sourceAABB?.ToRectangle(), color);
public void Draw(Texture2D texture, AABB destinationAABB, AABB? sourceAABB, Color color)
=> spriteBatch.Draw(texture, destinationAABB.ToRectangle(), sourceAABB?.ToRectangle(), color);
public void Draw(Texture2D texture, Vector2D position, Color color)
=> spriteBatch.Draw(texture, position.ToDisplayVector2(), color);
public void Draw(Texture2D texture, AABB destinationAABB, Color color)
=> spriteBatch.Draw(texture, destinationAABB.ToRectangle(), color);
public void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color);
public void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color, float rotation, Vector2D origin, float scale, SpriteEffects effects, float layerDepth)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color, rotation, origin.ToDisplayVector2(), scale, effects, layerDepth);
public void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color, rotation, origin.ToDisplayVector2(), scale.ToDisplayVector2(), effects, layerDepth);
public void DrawString(SpriteFont spriteFont, string text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth, bool rtl)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color, rotation, origin.ToDisplayVector2(), scale.ToDisplayVector2(), effects, layerDepth, rtl);
public void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color);
public void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color, float rotation, Vector2D origin, float scale, SpriteEffects effects, float layerDepth)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color, rotation, origin.ToDisplayVector2(), scale, effects, layerDepth);
public void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color, rotation, origin.ToDisplayVector2(), scale.ToDisplayVector2(), effects, layerDepth);
public void DrawString(SpriteFont spriteFont, StringBuilder text, Vector2D position, Color color, float rotation, Vector2D origin, Vector2D scale, SpriteEffects effects, float layerDepth, bool rtl)
=> spriteBatch.DrawString(spriteFont, text, position.ToDisplayVector2(), color, rotation, origin.ToDisplayVector2(), scale.ToDisplayVector2(), effects, layerDepth, rtl);
public void End()
=> spriteBatch.End();
}

View File

@@ -0,0 +1,33 @@
using System.Collections.Generic;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public class SpriteBatcher : BehaviourBase, IFirstFrameUpdate, IDraw
{
private static Comparer<IBehaviour> SortByPriority() => Comparer<IBehaviour>.Create((x, y) => y.Priority.CompareTo(x.Priority));
private ISpriteBatch spriteBatch = null!;
private MonoGameCamera2D camera2D = null!;
private readonly ActiveBehaviourCollectorSorted<IDrawableSprite> drawableSprites = new() { SortBy = SortByPriority() };
public void FirstActiveFrame()
{
MonoGameWindowContainer windowContainer = Universe.FindRequiredBehaviour<MonoGameWindowContainer>();
camera2D = Universe.FindRequiredBehaviour<MonoGameCamera2D>();
spriteBatch = new SpriteBatchWrapper(windowContainer.Window.GraphicsDevice);
drawableSprites.Unassign();
drawableSprites.Assign(Universe);
}
public void Draw()
{
spriteBatch.Begin(transformMatrix: camera2D.MatrixTransform);
for (int i = 0; i < drawableSprites.Count; i++)
drawableSprites[i].Draw(spriteBatch);
spriteBatch.End();
}
}

View File

@@ -0,0 +1,38 @@
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Syntriax.Engine.Core;
namespace Syntriax.Engine.Integration.MonoGame;
public class TriangleBatcher : BehaviourBase, ITriangleBatch, IFirstFrameUpdate, IDraw
{
private static Comparer<IBehaviour> SortByAscendingPriority() => Comparer<IBehaviour>.Create((x, y) => x.Priority.CompareTo(y.Priority));
private TriangleBatch triangleBatch = null!;
private MonoGameCamera2D camera2D = null!;
private readonly ActiveBehaviourCollectorSorted<IDrawableTriangle> drawableShapes = new() { SortBy = SortByAscendingPriority() };
public void FirstActiveFrame()
{
MonoGameWindowContainer windowContainer = BehaviourController.UniverseObject.Universe.FindRequiredBehaviour<MonoGameWindowContainer>();
camera2D = BehaviourController.UniverseObject.Universe.FindRequiredBehaviour<MonoGameCamera2D>();
triangleBatch = new(windowContainer.Window.GraphicsDevice);
drawableShapes.Unassign();
drawableShapes.Assign(BehaviourController.UniverseObject.Universe);
}
public void Draw()
{
triangleBatch.Begin(camera2D.MatrixTransform);
for (int i = 0; i < drawableShapes.Count; i++)
drawableShapes[i].Draw(triangleBatch);
triangleBatch.End();
}
public void Begin(Matrix? view = null, Matrix? projection = null) => triangleBatch.Begin(view, projection);
public void Draw(Triangle triangle, ColorRGBA colorRGBA) => triangleBatch.Draw(triangle, colorRGBA);
public void End() => triangleBatch.End();
}

View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>Syntriax.Engine.Integration.MonoGame</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MonoGame.Framework.DesktopGL" Version="3.8.2.1105">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Engine\Engine.csproj" />
</ItemGroup>
</Project>

Some files were not shown because too many files have changed in this diff Show More