iFactory.Godot/BITKit/Scripts/ECS/Core/GodotEntitiesService.cs

107 lines
3.3 KiB
C#

using System;
using Godot;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using BITKit.Core.Entites;
// ReSharper disable All
namespace BITKit;
/// <summary>
/// 基于Godot.Node的IEntitiesService实现
/// </summary>
public partial class GodotEntitiesService : Node,IEntitiesService
{
public GodotEntitiesService()
{
DI.Register<IEntitiesService>(this);
}
private readonly Dictionary<ulong,IEntity> _entities=new ();
private CancellationTokenSource _cancellationTokenSource;
public event Action<IEntity> OnAdd;
public event Action<IEntity> OnRemove;
public IEntity[] Entities => _entities.Values.ToArray();
public bool Register(IEntity entity)
{
return _entities.TryAdd(entity.Id, entity);
}
public bool UnRegister(IEntity entity)
{
return _entities.TryRemove(entity.Id);
}
public override void _Ready()
{
_cancellationTokenSource = new();
}
protected override void Dispose(bool disposing)
{
if(disposing)_cancellationTokenSource.Cancel();
}
public CancellationToken CancellationToken => _cancellationTokenSource.Token;
public IEntity Get(ulong id)
{
throw new NotImplementedException();
}
public IEntity[] Query<T>() where T : IEntityComponent
{
return _entities.Values.Where(x => x.TryGetComponent<T>(out _)).ToArray();
}
T[] IEntitiesService.QueryComponents<T>()
{
return _entities.Values
.Where(x => x.TryGetComponent<T>(out _))
.Select(x =>
{
var component = x.Components.Single(x => x is T);
return (T)component;
})
.ToArray();
}
public ValueTuple<T>[] QueryComponents<T>() where T : IEntityComponent
{
return _entities.Values
.Where(x => x.TryGetComponent<T>(out _))
.Select(x =>
{
var component = x.Components.Single(x => x is T);
return (T)component;
})
.Select(x => new ValueTuple<T>(x))
.ToArray();
}
public (T, T1)[] QueryComponents<T, T1>() where T : IEntityComponent where T1 : IEntityComponent
{
var entities = _entities.Values.Where(x => x.TryGetComponent<T>(out _) && x.TryGetComponent<T1>(out _));
var result = new List<(T, T1)>();
foreach (var entity in entities)
{
var t = (T)entity.Components.Single(x => x is T);
var t1 = (T1)entity.Components.Single(x => x is T1);
result.Add(new(t,t1));
}
return result.ToArray();
}
public (T, T1, T2)[] QueryComponents<T, T1, T2>() where T : IEntityComponent where T1 : IEntityComponent where T2 : IEntityComponent
{
return _entities.Values
.Where(x => x.TryGetComponent<T>(out _) && x.TryGetComponent<T1>(out _) && x.TryGetComponent<T2>(out _))
.Select(x =>
{
var component = (T)x.Components.Single(x => x is T);
var component1 = (T1)x.Components.Single(x => x is T1);
var component2 = (T2)x.Components.Single(x => x is T2);
(T, T1, T2) value = new(component, component1, component2);
return value;
})
.ToArray();
}
}