ActorSystem.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Threading.Tasks;
  3. using Model;
  4. namespace Hotfix
  5. {
  6. [ObjectEvent]
  7. public class ActorComponentEvent : ObjectEvent<ActorComponent>, IAwake, IAwake<IEntityActorHandler>
  8. {
  9. public void Awake()
  10. {
  11. this.Get().Awake();
  12. }
  13. public void Awake(IEntityActorHandler iEntityActorHandler)
  14. {
  15. this.Get().Awake(iEntityActorHandler);
  16. }
  17. }
  18. /// <summary>
  19. /// 挂上这个组件表示该Entity是一个Actor, 它会将Entity位置注册到Location Server, 接收的消息将会队列处理
  20. /// </summary>
  21. public static class ActorSystem
  22. {
  23. public static void Awake(this ActorComponent self)
  24. {
  25. self.entityActorHandler = new CommonEntityActorHandler();
  26. self.queue = new EQueue<ActorMessageInfo>();
  27. self.actorId = self.Entity.Id;
  28. Game.Scene.GetComponent<ActorManagerComponent>().Add(self.Entity);
  29. self.HandleAsync();
  30. }
  31. public static void Awake(this ActorComponent self, IEntityActorHandler iEntityActorHandler)
  32. {
  33. self.entityActorHandler = iEntityActorHandler;
  34. self.queue = new EQueue<ActorMessageInfo>();
  35. self.actorId = self.Entity.Id;
  36. Game.Scene.GetComponent<ActorManagerComponent>().Add(self.Entity);
  37. self.HandleAsync();
  38. }
  39. public static async Task AddLocation(this ActorComponent self)
  40. {
  41. await Game.Scene.GetComponent<LocationProxyComponent>().Add(self.actorId);
  42. }
  43. public static async Task RemoveLocation(this ActorComponent self)
  44. {
  45. await Game.Scene.GetComponent<LocationProxyComponent>().Remove(self.actorId);
  46. }
  47. public static void Add(this ActorComponent self, ActorMessageInfo info)
  48. {
  49. self.queue.Enqueue(info);
  50. if (self.tcs == null)
  51. {
  52. return;
  53. }
  54. var t = self.tcs;
  55. self.tcs = null;
  56. t.SetResult(self.queue.Dequeue());
  57. }
  58. private static Task<ActorMessageInfo> GetAsync(this ActorComponent self)
  59. {
  60. if (self.queue.Count > 0)
  61. {
  62. return Task.FromResult(self.queue.Dequeue());
  63. }
  64. self.tcs = new TaskCompletionSource<ActorMessageInfo>();
  65. return self.tcs.Task;
  66. }
  67. private static async void HandleAsync(this ActorComponent self)
  68. {
  69. while (true)
  70. {
  71. try
  72. {
  73. ActorMessageInfo info = await self.GetAsync();
  74. await self.entityActorHandler.Handle(info.Session, self.Entity, info.Message);
  75. }
  76. catch (Exception e)
  77. {
  78. Log.Error(e.ToString());
  79. }
  80. }
  81. }
  82. }
  83. }