128 lines
3.3 KiB
C#
Raw Normal View History

2024-08-17 14:27:18 +08:00
using System;
2024-08-31 15:35:12 +08:00
using System.Collections.Generic;
2024-08-17 14:27:18 +08:00
using Entitas;
using JNGame.Sync.Entity;
using JNGame.Sync.Frame.Entity.Component.Components;
using JNGame.Sync.Frame.Entity.Components;
using JNGame.Sync.System;
namespace JNGame.Sync.Frame.Entity
{
public abstract class JNContext<T> : Entitas.Context<T>,IJNContext where T : JNEntity, new()
{
public JNSyncService Sync { get; private set; }
public JNEntityLookup CLookup;
2024-08-31 15:35:12 +08:00
//方便查抄的实体Map
public Dictionary<ulong, T> Entities = new ();
2024-08-17 14:27:18 +08:00
public JNContext(): base((new T()).NewCLookup().Count, () => new T())
{
CLookup = (new T()).NewCLookup();
}
public JNContext(int totalComponents, Func<T> entityFactory) : base(totalComponents, entityFactory)
{
}
public JNContext(int totalComponents, int startCreationIndex, ContextInfo contextInfo, Func<IEntity, IAERC> aercFactory, Func<T> entityFactory) : base(totalComponents, startCreationIndex, contextInfo, aercFactory, entityFactory)
{
}
public JNSyncService GetSync()
{
return Sync;
}
public void InitReference(JNSyncService data)
{
Sync = data;
}
2024-08-31 15:35:12 +08:00
public T Query(ulong id)
{
Entities.TryGetValue(id, out var entity);
return entity;
}
public void AddEntity(ulong id, JNEntity entity)
{
Entities.Add(id,entity as T);
}
public void RemoveEntity(ulong id)
{
Entities.Remove(id);
}
2024-08-17 14:27:18 +08:00
public T GetService<T>() where T : SLogicSystem
{
return Sync.GetSystem<T>();
}
protected T NewEntity()
{
T entity = base.CreateEntity();
//绑定组件查询器
entity.CLookup = CLookup;
return entity;
}
protected virtual T BindInitialize(T entity)
{
entity.OnInit(this);
return entity;
}
protected virtual T BindComponent(T entity)
{
entity.AddComponent<JNTransformComponent>();
return entity;
}
protected virtual T BindLifeCycle(T entity)
{
entity.OnSyncStart();
return entity;
}
2024-08-31 21:05:29 +08:00
public override T CreateEntity()
2024-08-17 14:27:18 +08:00
{
var entity = NewEntity();
BindInitialize(entity);
BindComponent(entity);
BindLifeCycle(entity);
return entity;
}
//帧同步 生命周期
public virtual void OnSyncStart(){}
2024-08-31 21:05:29 +08:00
public virtual void OnSyncUpdate(int dt)
2024-08-17 14:27:18 +08:00
{
//给实体推帧
foreach (var entity in GetEntities())
{
if (entity.isEnabled)
{
2024-08-31 21:05:29 +08:00
entity.OnSyncUpdate(dt);
2024-08-17 14:27:18 +08:00
}
}
}
public virtual void OnSyncDestroy()
{}
}
public interface IJNContext : IJNSyncCycle
{
public abstract JNSyncService GetSync();
public abstract void InitReference(JNSyncService data);
2024-08-31 15:35:12 +08:00
public void AddEntity(ulong id,JNEntity entity);
public void RemoveEntity(ulong id);
2024-08-17 14:27:18 +08:00
}
}