Create EntitiesService.cs

This commit is contained in:
CortexCore 2024-06-18 10:48:59 +08:00
parent aceed70611
commit 82294e44ee
1 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,82 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace BITKit.Entities
{
public class EntitiesService:IEntitiesService
{
private readonly ConcurrentDictionary<int, IEntity> _entities = new();
private readonly ConcurrentDictionary<Type, IEntity[]> _queryCache = new();
private readonly ConcurrentDictionary<(Type,Type), IEntity[]> _query2ComponentsCache = new();
private readonly ConcurrentDictionary<(Type,Type,Type), IEntity[]> _query3ComponentsCache = new();
public event Action<IEntity> OnAdd;
public event Action<IEntity> OnRemove;
public IEntity[] Entities => _entities.Values.ToArray();
public bool Register(IEntity entity)
{
if (!_entities.TryAdd(entity.Id, entity)) return false;
OnAdd?.Invoke(entity);
return true;
}
public bool UnRegister(IEntity entity)
{
if (!_entities.TryRemove(entity.Id, out _)) return false;
OnRemove?.Invoke(entity);
return true;
}
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
private readonly CancellationTokenSource _cancellationTokenSource = new();
public IEntity Get(int id)
{
return _entities[id];
}
public bool TryGetEntity(int id, out IEntity entity)
{
return _entities.TryGetValue(id, out entity);
}
public IEntity GetOrAdd(int id, Func<int, IEntity> factory)
{
return _entities.GetOrAdd(id, factory);
}
public IEntity[] Query<T>()
{
throw new NotImplementedException();
}
public T[] QueryComponents<T>()
{
return _queryCache.GetOrAdd(typeof(T), type =>
{
return _entities.Values.Where(entity => entity.TryGetComponent(out T component)).ToArray();
}).Cast<T>().ToArray();
}
public (T, T1)[] QueryComponents<T, T1>()
{
List<(T, T1)> list = new();
foreach (var entity in _entities.Values)
{
if (entity.TryGetComponent(out T t) && entity.TryGetComponent(out T1 t1))
list.Add((t, t1));
}
return list.ToArray();
}
public (T, T1, T2)[] QueryComponents<T, T1, T2>()
{
List<(T, T1, T2)> list = new();
foreach (var entity in _entities.Values)
{
if (entity.TryGetComponent(out T t) && entity.TryGetComponent(out T1 t1) && entity.TryGetComponent(out T2 t2))
list.Add((t, t1, t2));
}
return list.ToArray();
}
}
}