Skip to content

Commit

Permalink
Finishes implementation of EntitySystem
Browse files Browse the repository at this point in the history
  • Loading branch information
shnakamura committed Sep 20, 2024
1 parent 1f7dfa9 commit 99611b5
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 10 deletions.
5 changes: 4 additions & 1 deletion src/Aurora/Core/EC/Entity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ public struct Entity : IEntity
{
public int Id { get; }

public bool Active { get; set; }
public bool Active {
get => EntitySystem.GetActive(Id);
set => EntitySystem.SetActive(Id, value);
}

internal Entity(int id) {
Id = id;
Expand Down
60 changes: 51 additions & 9 deletions src/Aurora/Core/EC/EntitySystem.cs
Original file line number Diff line number Diff line change
@@ -1,33 +1,75 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;

namespace Aurora.Core.EC;

public sealed class EntitySystem : ModSystem
{
private static readonly List<Entity> Entities = [];
private static readonly List<int> ActiveEntityIds = [];
private static readonly List<int> InactiveEntityIds = [];

private static readonly ConcurrentBag<int> FreeEntityIds = [];

private static int NextEntityId;

/// <summary>
/// Creates a new instance of an entity.
/// </summary>
/// <param name="activate">Whether to activate the entity instance or not.</param>
/// <returns>The created entity instance.</returns>
public static Entity Create(bool activate = true) {
var entity = new Entity();
public static Entity Create(bool activate) {
int id;

if (!FreeEntityIds.TryTake(out id)) {
id = NextEntityId++;
}

if (activate) {
Entities.Add(entity);
ActiveEntityIds.Add(id);
}

return entity;
return new Entity(id);
}

/// <summary>
/// Removes an instance of an entity.
/// Removes an instance of an entity from its unique identifier.
/// </summary>
/// <param name="entity">The entity to remove.</param>
/// <param name="entityId">The identity of the entity to remove.</param>
/// <returns><c>true</c> if the entity was successfully removed; otherwise, <c>false</c>.</returns>
public static bool Remove(Entity entity) {
return Entities.Remove(entity);
public static bool Remove(int id) {
if (id < 0) {
return false;
}

ActiveEntityIds.Remove(id);
InactiveEntityIds.Remove(id);

FreeEntityIds.Add(id);

return true;
}

internal static bool GetActive(int entityId) {
if (entityId < 0) {
return false;
}

return ActiveEntityIds.Contains(entityId);
}

internal static void SetActive(int entityId, bool value) {
if (entityId < 0) {
return;
}

if (value) {
ActiveEntityIds.Add(entityId);
InactiveEntityIds.Remove(entityId);
return;
}

ActiveEntityIds.Remove(entityId);
InactiveEntityIds.Add(entityId);
}
}

0 comments on commit 99611b5

Please sign in to comment.