EventSystem.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace ET
  6. {
  7. public class EventSystem: Singleton<EventSystem>, ISingletonUpdate, ISingletonLateUpdate
  8. {
  9. private class OneTypeSystems
  10. {
  11. public readonly UnOrderMultiMap<Type, object> Map = new();
  12. // 这里不用hash,数量比较少,直接for循环速度更快
  13. public readonly bool[] QueueFlag = new bool[(int)InstanceQueueIndex.Max];
  14. }
  15. private class TypeSystems
  16. {
  17. private readonly Dictionary<Type, OneTypeSystems> typeSystemsMap = new();
  18. public OneTypeSystems GetOrCreateOneTypeSystems(Type type)
  19. {
  20. OneTypeSystems systems = null;
  21. this.typeSystemsMap.TryGetValue(type, out systems);
  22. if (systems != null)
  23. {
  24. return systems;
  25. }
  26. systems = new OneTypeSystems();
  27. this.typeSystemsMap.Add(type, systems);
  28. return systems;
  29. }
  30. public OneTypeSystems GetOneTypeSystems(Type type)
  31. {
  32. OneTypeSystems systems = null;
  33. this.typeSystemsMap.TryGetValue(type, out systems);
  34. return systems;
  35. }
  36. public List<object> GetSystems(Type type, Type systemType)
  37. {
  38. OneTypeSystems oneTypeSystems = null;
  39. if (!this.typeSystemsMap.TryGetValue(type, out oneTypeSystems))
  40. {
  41. return null;
  42. }
  43. if (!oneTypeSystems.Map.TryGetValue(systemType, out List<object> systems))
  44. {
  45. return null;
  46. }
  47. return systems;
  48. }
  49. }
  50. private class EventInfo
  51. {
  52. public IEvent IEvent { get; }
  53. public SceneType SceneType {get; }
  54. public EventInfo(IEvent iEvent, SceneType sceneType)
  55. {
  56. this.IEvent = iEvent;
  57. this.SceneType = sceneType;
  58. }
  59. }
  60. private readonly Dictionary<string, Type> allTypes = new();
  61. private readonly UnOrderMultiMapSet<Type, Type> types = new();
  62. private readonly Dictionary<Type, List<EventInfo>> allEvents = new();
  63. private Dictionary<Type, Dictionary<int, object>> allInvokes = new();
  64. private TypeSystems typeSystems = new();
  65. private readonly Queue<long>[] queues = new Queue<long>[(int)InstanceQueueIndex.Max];
  66. public EventSystem()
  67. {
  68. for (int i = 0; i < this.queues.Length; i++)
  69. {
  70. this.queues[i] = new Queue<long>();
  71. }
  72. }
  73. public void Add(Dictionary<string, Type> addTypes)
  74. {
  75. this.allTypes.Clear();
  76. this.types.Clear();
  77. foreach ((string fullName, Type type) in addTypes)
  78. {
  79. this.allTypes[fullName] = type;
  80. if (type.IsAbstract)
  81. {
  82. continue;
  83. }
  84. // 记录所有的有BaseAttribute标记的的类型
  85. object[] objects = type.GetCustomAttributes(typeof(BaseAttribute), true);
  86. foreach (object o in objects)
  87. {
  88. this.types.Add(o.GetType(), type);
  89. }
  90. }
  91. this.typeSystems = new TypeSystems();
  92. foreach (Type type in this.GetTypes(typeof (ObjectSystemAttribute)))
  93. {
  94. object obj = Activator.CreateInstance(type);
  95. if (obj is ISystemType iSystemType)
  96. {
  97. OneTypeSystems oneTypeSystems = this.typeSystems.GetOrCreateOneTypeSystems(iSystemType.Type());
  98. oneTypeSystems.Map.Add(iSystemType.SystemType(), obj);
  99. InstanceQueueIndex index = iSystemType.GetInstanceQueueIndex();
  100. if (index > InstanceQueueIndex.None && index < InstanceQueueIndex.Max)
  101. {
  102. oneTypeSystems.QueueFlag[(int)index] = true;
  103. }
  104. }
  105. }
  106. this.allEvents.Clear();
  107. foreach (Type type in types[typeof (EventAttribute)])
  108. {
  109. IEvent obj = Activator.CreateInstance(type) as IEvent;
  110. if (obj == null)
  111. {
  112. throw new Exception($"type not is AEvent: {type.Name}");
  113. }
  114. object[] attrs = type.GetCustomAttributes(typeof(EventAttribute), false);
  115. foreach (object attr in attrs)
  116. {
  117. EventAttribute eventAttribute = attr as EventAttribute;
  118. Type eventType = obj.Type;
  119. EventInfo eventInfo = new(obj, eventAttribute.SceneType);
  120. if (!this.allEvents.ContainsKey(eventType))
  121. {
  122. this.allEvents.Add(eventType, new List<EventInfo>());
  123. }
  124. this.allEvents[eventType].Add(eventInfo);
  125. }
  126. }
  127. this.allInvokes = new Dictionary<Type, Dictionary<int, object>>();
  128. foreach (Type type in types[typeof (InvokeAttribute)])
  129. {
  130. object obj = Activator.CreateInstance(type);
  131. IInvoke iInvoke = obj as IInvoke;
  132. if (iInvoke == null)
  133. {
  134. throw new Exception($"type not is callback: {type.Name}");
  135. }
  136. object[] attrs = type.GetCustomAttributes(typeof(InvokeAttribute), false);
  137. foreach (object attr in attrs)
  138. {
  139. if (!this.allInvokes.TryGetValue(iInvoke.Type, out var dict))
  140. {
  141. dict = new Dictionary<int, object>();
  142. this.allInvokes.Add(iInvoke.Type, dict);
  143. }
  144. InvokeAttribute invokeAttribute = attr as InvokeAttribute;
  145. try
  146. {
  147. dict.Add(invokeAttribute.Type, obj);
  148. }
  149. catch (Exception e)
  150. {
  151. throw new Exception($"action type duplicate: {iInvoke.Type.Name} {invokeAttribute.Type}", e);
  152. }
  153. }
  154. }
  155. }
  156. public HashSet<Type> GetTypes(Type systemAttributeType)
  157. {
  158. if (!this.types.ContainsKey(systemAttributeType))
  159. {
  160. return new HashSet<Type>();
  161. }
  162. return this.types[systemAttributeType];
  163. }
  164. public Dictionary<string, Type> GetTypes()
  165. {
  166. return allTypes;
  167. }
  168. public Type GetType(string typeName)
  169. {
  170. return this.allTypes[typeName];
  171. }
  172. public void RegisterSystem(Entity component)
  173. {
  174. Type type = component.GetType();
  175. OneTypeSystems oneTypeSystems = this.typeSystems.GetOneTypeSystems(type);
  176. if (oneTypeSystems == null)
  177. {
  178. return;
  179. }
  180. for (int i = 0; i < oneTypeSystems.QueueFlag.Length; ++i)
  181. {
  182. if (!oneTypeSystems.QueueFlag[i])
  183. {
  184. continue;
  185. }
  186. this.queues[i].Enqueue(component.InstanceId);
  187. }
  188. }
  189. public void Deserialize(Entity component)
  190. {
  191. List<object> iDeserializeSystems = this.typeSystems.GetSystems(component.GetType(), typeof (IDeserializeSystem));
  192. if (iDeserializeSystems == null)
  193. {
  194. return;
  195. }
  196. foreach (IDeserializeSystem deserializeSystem in iDeserializeSystems)
  197. {
  198. if (deserializeSystem == null)
  199. {
  200. continue;
  201. }
  202. try
  203. {
  204. deserializeSystem.Run(component);
  205. }
  206. catch (Exception e)
  207. {
  208. Log.Error(e);
  209. }
  210. }
  211. }
  212. // GetComponentSystem
  213. public void GetComponent(Entity entity, Entity component)
  214. {
  215. List<object> iGetSystem = this.typeSystems.GetSystems(entity.GetType(), typeof (IGetComponentSystem));
  216. if (iGetSystem == null)
  217. {
  218. return;
  219. }
  220. foreach (IGetComponentSystem getSystem in iGetSystem)
  221. {
  222. if (getSystem == null)
  223. {
  224. continue;
  225. }
  226. try
  227. {
  228. getSystem.Run(entity, component);
  229. }
  230. catch (Exception e)
  231. {
  232. Log.Error(e);
  233. }
  234. }
  235. }
  236. // AddComponentSystem
  237. public void AddComponent(Entity entity, Entity component)
  238. {
  239. List<object> iAddSystem = this.typeSystems.GetSystems(entity.GetType(), typeof (IAddComponentSystem));
  240. if (iAddSystem == null)
  241. {
  242. return;
  243. }
  244. foreach (IAddComponentSystem addComponentSystem in iAddSystem)
  245. {
  246. if (addComponentSystem == null)
  247. {
  248. continue;
  249. }
  250. try
  251. {
  252. addComponentSystem.Run(entity, component);
  253. }
  254. catch (Exception e)
  255. {
  256. Log.Error(e);
  257. }
  258. }
  259. }
  260. public void Awake(Entity component)
  261. {
  262. List<object> iAwakeSystems = this.typeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem));
  263. if (iAwakeSystems == null)
  264. {
  265. return;
  266. }
  267. foreach (IAwakeSystem aAwakeSystem in iAwakeSystems)
  268. {
  269. if (aAwakeSystem == null)
  270. {
  271. continue;
  272. }
  273. try
  274. {
  275. aAwakeSystem.Run(component);
  276. }
  277. catch (Exception e)
  278. {
  279. Log.Error(e);
  280. }
  281. }
  282. }
  283. public void Awake<P1>(Entity component, P1 p1)
  284. {
  285. List<object> iAwakeSystems = this.typeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem<P1>));
  286. if (iAwakeSystems == null)
  287. {
  288. return;
  289. }
  290. foreach (IAwakeSystem<P1> aAwakeSystem in iAwakeSystems)
  291. {
  292. if (aAwakeSystem == null)
  293. {
  294. continue;
  295. }
  296. try
  297. {
  298. aAwakeSystem.Run(component, p1);
  299. }
  300. catch (Exception e)
  301. {
  302. Log.Error(e);
  303. }
  304. }
  305. }
  306. public void Awake<P1, P2>(Entity component, P1 p1, P2 p2)
  307. {
  308. List<object> iAwakeSystems = this.typeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem<P1, P2>));
  309. if (iAwakeSystems == null)
  310. {
  311. return;
  312. }
  313. foreach (IAwakeSystem<P1, P2> aAwakeSystem in iAwakeSystems)
  314. {
  315. if (aAwakeSystem == null)
  316. {
  317. continue;
  318. }
  319. try
  320. {
  321. aAwakeSystem.Run(component, p1, p2);
  322. }
  323. catch (Exception e)
  324. {
  325. Log.Error(e);
  326. }
  327. }
  328. }
  329. public void Awake<P1, P2, P3>(Entity component, P1 p1, P2 p2, P3 p3)
  330. {
  331. List<object> iAwakeSystems = this.typeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem<P1, P2, P3>));
  332. if (iAwakeSystems == null)
  333. {
  334. return;
  335. }
  336. foreach (IAwakeSystem<P1, P2, P3> aAwakeSystem in iAwakeSystems)
  337. {
  338. if (aAwakeSystem == null)
  339. {
  340. continue;
  341. }
  342. try
  343. {
  344. aAwakeSystem.Run(component, p1, p2, p3);
  345. }
  346. catch (Exception e)
  347. {
  348. Log.Error(e);
  349. }
  350. }
  351. }
  352. public void Awake<P1, P2, P3, P4>(Entity component, P1 p1, P2 p2, P3 p3, P4 p4)
  353. {
  354. List<object> iAwakeSystems = this.typeSystems.GetSystems(component.GetType(), typeof (IAwakeSystem<P1, P2, P3, P4>));
  355. if (iAwakeSystems == null)
  356. {
  357. return;
  358. }
  359. foreach (IAwakeSystem<P1, P2, P3, P4> aAwakeSystem in iAwakeSystems)
  360. {
  361. if (aAwakeSystem == null)
  362. {
  363. continue;
  364. }
  365. try
  366. {
  367. aAwakeSystem.Run(component, p1, p2, p3, p4);
  368. }
  369. catch (Exception e)
  370. {
  371. Log.Error(e);
  372. }
  373. }
  374. }
  375. public void Load()
  376. {
  377. Queue<long> queue = this.queues[(int)InstanceQueueIndex.Load];
  378. int count = queue.Count;
  379. while (count-- > 0)
  380. {
  381. long instanceId = queue.Dequeue();
  382. Entity component = Root.Instance.Get(instanceId);
  383. if (component == null)
  384. {
  385. continue;
  386. }
  387. if (component.IsDisposed)
  388. {
  389. continue;
  390. }
  391. List<object> iLoadSystems = this.typeSystems.GetSystems(component.GetType(), typeof (ILoadSystem));
  392. if (iLoadSystems == null)
  393. {
  394. continue;
  395. }
  396. queue.Enqueue(instanceId);
  397. foreach (ILoadSystem iLoadSystem in iLoadSystems)
  398. {
  399. try
  400. {
  401. iLoadSystem.Run(component);
  402. }
  403. catch (Exception e)
  404. {
  405. Log.Error(e);
  406. }
  407. }
  408. }
  409. }
  410. public void Destroy(Entity component)
  411. {
  412. List<object> iDestroySystems = this.typeSystems.GetSystems(component.GetType(), typeof (IDestroySystem));
  413. if (iDestroySystems == null)
  414. {
  415. return;
  416. }
  417. foreach (IDestroySystem iDestroySystem in iDestroySystems)
  418. {
  419. if (iDestroySystem == null)
  420. {
  421. continue;
  422. }
  423. try
  424. {
  425. iDestroySystem.Run(component);
  426. }
  427. catch (Exception e)
  428. {
  429. Log.Error(e);
  430. }
  431. }
  432. }
  433. public void Update(int timeMS)
  434. {
  435. Queue<long> queue = this.queues[(int)InstanceQueueIndex.Update];
  436. int count = queue.Count;
  437. while (count-- > 0)
  438. {
  439. long instanceId = queue.Dequeue();
  440. Entity component = Root.Instance.Get(instanceId);
  441. if (component == null)
  442. {
  443. continue;
  444. }
  445. if (component.IsDisposed)
  446. {
  447. continue;
  448. }
  449. List<object> iUpdateSystems = this.typeSystems.GetSystems(component.GetType(), typeof (IUpdateSystem));
  450. if (iUpdateSystems == null)
  451. {
  452. continue;
  453. }
  454. queue.Enqueue(instanceId);
  455. foreach (IUpdateSystem iUpdateSystem in iUpdateSystems)
  456. {
  457. try
  458. {
  459. iUpdateSystem.Run(component);
  460. }
  461. catch (Exception e)
  462. {
  463. Log.Error(e);
  464. }
  465. }
  466. }
  467. }
  468. public void LateUpdate()
  469. {
  470. Queue<long> queue = this.queues[(int)InstanceQueueIndex.LateUpdate];
  471. int count = queue.Count;
  472. while (count-- > 0)
  473. {
  474. long instanceId = queue.Dequeue();
  475. Entity component = Root.Instance.Get(instanceId);
  476. if (component == null)
  477. {
  478. continue;
  479. }
  480. if (component.IsDisposed)
  481. {
  482. continue;
  483. }
  484. List<object> iLateUpdateSystems = this.typeSystems.GetSystems(component.GetType(), typeof (ILateUpdateSystem));
  485. if (iLateUpdateSystems == null)
  486. {
  487. continue;
  488. }
  489. queue.Enqueue(instanceId);
  490. foreach (ILateUpdateSystem iLateUpdateSystem in iLateUpdateSystems)
  491. {
  492. try
  493. {
  494. iLateUpdateSystem.Run(component);
  495. }
  496. catch (Exception e)
  497. {
  498. Log.Error(e);
  499. }
  500. }
  501. }
  502. }
  503. public async ETTask PublishAsync<T>(Scene scene, T a) where T : struct
  504. {
  505. List<EventInfo> iEvents;
  506. if (!this.allEvents.TryGetValue(typeof(T), out iEvents))
  507. {
  508. return;
  509. }
  510. using ListComponent<ETTask> list = ListComponent<ETTask>.Create();
  511. foreach (EventInfo eventInfo in iEvents)
  512. {
  513. if (scene.SceneType != eventInfo.SceneType && eventInfo.SceneType != SceneType.None)
  514. {
  515. continue;
  516. }
  517. if (!(eventInfo.IEvent is AEvent<T> aEvent))
  518. {
  519. Log.Error($"event error: {eventInfo.IEvent.GetType().Name}");
  520. continue;
  521. }
  522. list.Add(aEvent.Handle(scene, a));
  523. }
  524. try
  525. {
  526. await ETTaskHelper.WaitAll(list);
  527. }
  528. catch (Exception e)
  529. {
  530. Log.Error(e);
  531. }
  532. }
  533. public void Publish<T>(Scene scene, T a) where T : struct
  534. {
  535. List<EventInfo> iEvents;
  536. if (!this.allEvents.TryGetValue(typeof (T), out iEvents))
  537. {
  538. return;
  539. }
  540. SceneType sceneType = scene == null ? SceneType.None: scene.SceneType;
  541. foreach (EventInfo eventInfo in iEvents)
  542. {
  543. if (sceneType != eventInfo.SceneType && eventInfo.SceneType != SceneType.None)
  544. {
  545. continue;
  546. }
  547. if (!(eventInfo.IEvent is AEvent<T> aEvent))
  548. {
  549. Log.Error($"event error: {eventInfo.IEvent.GetType().Name}");
  550. continue;
  551. }
  552. aEvent.Handle(scene, a).Coroutine();
  553. }
  554. }
  555. // Invoke跟Publish的区别(特别注意)
  556. // Invoke类似函数,必须有被调用方,否则异常,调用者跟被调用者属于同一模块,比如MoveComponent中的Timer计时器,调用跟被调用的代码均属于移动模块
  557. // 既然Invoke跟函数一样,那么为什么不使用函数呢? 因为有时候不方便直接调用,比如Config加载,在客户端跟服务端加载方式不一样。比如TimerComponent需要根据Id分发
  558. // 注意,不要把Invoke当函数使用,这样会造成代码可读性降低,能用函数不要用Invoke
  559. // publish是事件,抛出去可以没人订阅,调用者跟被调用者属于两个模块,比如任务系统需要知道道具使用的信息,则订阅道具使用事件
  560. public void Invoke<A>(int type, A args) where A: struct
  561. {
  562. if (!this.allInvokes.TryGetValue(typeof(A), out var invokeHandlers))
  563. {
  564. throw new Exception($"Invoke error: {typeof(A).Name}");
  565. }
  566. if (!invokeHandlers.TryGetValue(type, out var invokeHandler))
  567. {
  568. throw new Exception($"Invoke error: {typeof(A).Name} {type}");
  569. }
  570. var aInvokeHandler = invokeHandler as AInvokeHandler<A>;
  571. if (aInvokeHandler == null)
  572. {
  573. throw new Exception($"Invoke error, not AInvokeHandler: {typeof(A).Name} {type}");
  574. }
  575. aInvokeHandler.Handle(args);
  576. }
  577. public T Invoke<A, T>(int type, A args) where A: struct
  578. {
  579. if (!this.allInvokes.TryGetValue(typeof(A), out var invokeHandlers))
  580. {
  581. throw new Exception($"Invoke error: {typeof(A).Name}");
  582. }
  583. if (!invokeHandlers.TryGetValue(type, out var invokeHandler))
  584. {
  585. throw new Exception($"Invoke error: {typeof(A).Name} {type}");
  586. }
  587. var aInvokeHandler = invokeHandler as AInvokeHandler<A, T>;
  588. if (aInvokeHandler == null)
  589. {
  590. throw new Exception($"Invoke error, not AInvokeHandler: {typeof(T).Name} {type}");
  591. }
  592. return aInvokeHandler.Handle(args);
  593. }
  594. public void Invoke<A>(A args) where A: struct
  595. {
  596. Invoke(0, args);
  597. }
  598. public T Invoke<A, T>(A args) where A: struct
  599. {
  600. return Invoke<A, T>(0, args);
  601. }
  602. }
  603. }