Mirror of Svelto.ECS because we're a fan of it
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

432 lines
19KB

  1. #if PROFILE_SVELTO && DEBUG
  2. #warning the global define PROFILE_SVELTO should be used only when it's necessary to profile in order to reduce the overhead of debug code. While debugging remove this define to get insights when errors happen
  3. #endif
  4. using System;
  5. using System.Collections.Generic;
  6. using DBC.ECS;
  7. using Svelto.Common;
  8. using Svelto.DataStructures;
  9. using Svelto.ECS.Internal;
  10. using Svelto.ECS.Schedulers;
  11. namespace Svelto.ECS
  12. {
  13. public partial class EnginesRoot
  14. {
  15. static EnginesRoot()
  16. {
  17. EntityDescriptorsWarmup.WarmUp();
  18. GroupHashMap.WarmUp();
  19. //SharedDictonary.Init();
  20. SerializationDescriptorMap.Init();
  21. _swapEntities = SwapEntities;
  22. _removeEntities = RemoveEntities;
  23. _removeGroup = RemoveGroup;
  24. _swapGroup = SwapGroup;
  25. }
  26. /// <summary>
  27. /// Engines root contextualize your engines and entities. You don't need to limit yourself to one EngineRoot
  28. /// as multiple engines root could promote separation of scopes. The EntitySubmissionScheduler checks
  29. /// periodically if new entity must be submitted to the database and the engines. It's an external
  30. /// dependencies to be independent by the running platform as the user can define it.
  31. /// The EntitySubmissionScheduler cannot hold an EnginesRoot reference, that's why
  32. /// it must receive a weak reference of the EnginesRoot callback.
  33. /// </summary>
  34. public EnginesRoot(EntitiesSubmissionScheduler entitiesComponentScheduler)
  35. {
  36. _entitiesOperations = new EntitiesOperations();
  37. _idChecker = new FasterDictionary<ExclusiveGroupStruct, HashSet<uint>>();
  38. _cachedRangeOfSubmittedIndices = new FasterList<(uint, uint)>();
  39. _transientEntityIDsLeftAndAffectedByRemoval = new FasterList<uint>();
  40. _transientEntityIDsLeftWithoutDuplicates = new FasterDictionary<uint, int>();
  41. _multipleOperationOnSameEGIDChecker = new FasterDictionary<EGID, uint>();
  42. #if UNITY_NATIVE //because of the thread count, ATM this is only for unity
  43. _nativeSwapOperationQueue = new AtomicNativeBags(Allocator.Persistent);
  44. _nativeRemoveOperationQueue = new AtomicNativeBags(Allocator.Persistent);
  45. _nativeAddOperationQueue = new AtomicNativeBags(Allocator.Persistent);
  46. #endif
  47. _serializationDescriptorMap = new SerializationDescriptorMap();
  48. _reactiveEnginesAdd = new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAdd>>>();
  49. _reactiveEnginesAddEx =
  50. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAddEx>>>();
  51. _reactiveEnginesRemove =
  52. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemove>>>();
  53. _reactiveEnginesRemoveEx =
  54. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemoveEx>>>();
  55. _reactiveEnginesSwap =
  56. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwap>>>();
  57. _reactiveEnginesSwapEx =
  58. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwapEx>>>();
  59. _reactiveEnginesDispose =
  60. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDispose>>>();
  61. _reactiveEnginesDisposeEx =
  62. new FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDisposeEx>>>();
  63. _reactiveEnginesSubmission = new FasterList<IReactOnSubmission>();
  64. _reactiveEnginesSubmissionStarted = new FasterList<IReactOnSubmissionStarted>();
  65. _enginesSet = new FasterList<IEngine>();
  66. _enginesTypeSet = new HashSet<Type>();
  67. _disposableEngines = new FasterList<IDisposable>();
  68. _groupEntityComponentsDB =
  69. new FasterDictionary<ExclusiveGroupStruct, FasterDictionary<ComponentID, ITypeSafeDictionary>>();
  70. _groupsPerEntity =
  71. new FasterDictionary<ComponentID, FasterDictionary<ExclusiveGroupStruct, ITypeSafeDictionary>>();
  72. _groupedEntityToAdd = new DoubleBufferedEntitiesToAdd();
  73. _entityStreams = EntitiesStreams.Create();
  74. #if SVELTO_LEGACY_FILTERS
  75. _groupFilters =
  76. new FasterDictionary<ComponentID, FasterDictionary<ExclusiveGroupStruct, LegacyGroupFilters>>();
  77. #endif
  78. _entityLocator.InitEntityReferenceMap();
  79. _entitiesDB = new EntitiesDB(this, _entityLocator);
  80. InitFilters();
  81. scheduler = entitiesComponentScheduler;
  82. scheduler.onTick = new EntitiesSubmitter(this);
  83. #if UNITY_NATIVE
  84. AllocateNativeOperations();
  85. #endif
  86. }
  87. protected EnginesRoot(EntitiesSubmissionScheduler entitiesComponentScheduler,
  88. EnginesReadyOption enginesWaitForReady): this(entitiesComponentScheduler)
  89. {
  90. _enginesWaitForReady = enginesWaitForReady;
  91. }
  92. public EntitiesSubmissionScheduler scheduler { get; }
  93. /// <summary>
  94. /// Dispose an EngineRoot once not used anymore, so that all the
  95. /// engines are notified with the entities removed.
  96. /// It's a clean up process.
  97. /// </summary>
  98. public void Dispose()
  99. {
  100. Dispose(true);
  101. GC.SuppressFinalize(this);
  102. }
  103. public bool IsValid()
  104. {
  105. return _isDisposed == false;
  106. }
  107. public void AddEngine(IEngine engine)
  108. {
  109. var type = engine.GetType();
  110. var refWrapper = new RefWrapperType(type);
  111. Check.Require(engine != null, "Engine to add is invalid or null");
  112. Check.Require(
  113. _enginesTypeSet.Contains(refWrapper) == false ||
  114. type.ContainsCustomAttribute(typeof(AllowMultipleAttribute)),
  115. "The same engine has been added more than once, if intentional, use [AllowMultiple] class attribute "
  116. .FastConcat(engine.ToString()));
  117. try
  118. {
  119. if (engine is IReactOnAdd viewEngineAdd)
  120. #pragma warning disable CS0612
  121. CheckReactEngineComponents(typeof(IReactOnAdd<>), viewEngineAdd, _reactiveEnginesAdd, type.Name);
  122. #pragma warning restore CS0612
  123. if (engine is IReactOnAddEx viewEngineAddEx)
  124. CheckReactEngineComponents(
  125. typeof(IReactOnAddEx<>), viewEngineAddEx, _reactiveEnginesAddEx, type.Name);
  126. if (engine is IReactOnRemove viewEngineRemove)
  127. CheckReactEngineComponents(
  128. #pragma warning disable CS0612
  129. typeof(IReactOnRemove<>), viewEngineRemove, _reactiveEnginesRemove, type.Name);
  130. #pragma warning restore CS0612
  131. if (engine is IReactOnRemoveEx viewEngineRemoveEx)
  132. CheckReactEngineComponents(
  133. typeof(IReactOnRemoveEx<>), viewEngineRemoveEx, _reactiveEnginesRemoveEx, type.Name);
  134. if (engine is IReactOnDispose viewEngineDispose)
  135. CheckReactEngineComponents(
  136. typeof(IReactOnDispose<>), viewEngineDispose, _reactiveEnginesDispose, type.Name);
  137. if (engine is IReactOnDisposeEx viewEngineDisposeEx)
  138. CheckReactEngineComponents(
  139. typeof(IReactOnDisposeEx<>), viewEngineDisposeEx, _reactiveEnginesDisposeEx, type.Name);
  140. if (engine is IReactOnSwap viewEngineSwap)
  141. #pragma warning disable CS0612
  142. CheckReactEngineComponents(typeof(IReactOnSwap<>), viewEngineSwap, _reactiveEnginesSwap, type.Name);
  143. #pragma warning restore CS0612
  144. if (engine is IReactOnSwapEx viewEngineSwapEx)
  145. CheckReactEngineComponents(
  146. typeof(IReactOnSwapEx<>), viewEngineSwapEx, _reactiveEnginesSwapEx, type.Name);
  147. if (engine is IReactOnSubmission submissionEngine)
  148. _reactiveEnginesSubmission.Add(submissionEngine);
  149. if (engine is IReactOnSubmissionStarted submissionEngineStarted)
  150. _reactiveEnginesSubmissionStarted.Add(submissionEngineStarted);
  151. _enginesTypeSet.Add(refWrapper);
  152. _enginesSet.Add(engine);
  153. if (engine is IDisposable)
  154. _disposableEngines.Add(engine as IDisposable);
  155. if (engine is IQueryingEntitiesEngine queryableEntityComponentEngine)
  156. queryableEntityComponentEngine.entitiesDB = _entitiesDB;
  157. if (_enginesWaitForReady == EnginesReadyOption.ReadyAsAdded && engine is IGetReadyEngine getReadyEngine)
  158. getReadyEngine.Ready();
  159. }
  160. catch (Exception e)
  161. {
  162. throw new ECSException(
  163. "Code crashed while adding engine ".FastConcat(engine.GetType().ToString(), " "),
  164. e);
  165. }
  166. }
  167. public void Ready()
  168. {
  169. Check.Require(
  170. _enginesWaitForReady == EnginesReadyOption.WaitForReady,
  171. "The engine has not been initialise to wait for an external ready trigger");
  172. foreach (var engine in _enginesSet)
  173. if (engine is IGetReadyEngine getReadyEngine)
  174. getReadyEngine.Ready();
  175. }
  176. static void AddEngineToList<T>(T engine, Type[] entityComponentTypes,
  177. FasterDictionary<ComponentID, FasterList<ReactEngineContainer<T>>> engines, string typeName)
  178. where T : class, IReactEngine
  179. {
  180. for (var i = 0; i < entityComponentTypes.Length; i++)
  181. {
  182. var type = entityComponentTypes[i];
  183. var componentID = ComponentTypeMap.FetchID(type);
  184. if (engines.TryGetValue(componentID, out var list) == false)
  185. {
  186. list = new FasterList<ReactEngineContainer<T>>();
  187. engines.Add(componentID, list);
  188. }
  189. list.Add(new ReactEngineContainer<T>(engine, typeName));
  190. }
  191. }
  192. void CheckReactEngineComponents<T>(Type genericDefinition, T engine,
  193. FasterDictionary<ComponentID, FasterList<ReactEngineContainer<T>>> engines, string typeName)
  194. where T : class, IReactEngine
  195. {
  196. var interfaces = engine.GetType().GetInterfaces();
  197. foreach (var interf in interfaces)
  198. {
  199. if (interf.IsGenericTypeEx() && interf.GetGenericTypeDefinition() == genericDefinition)
  200. {
  201. Type[] genericArguments = interf.GetGenericArgumentsEx();
  202. AddEngineToList(engine, genericArguments, engines, typeName);
  203. }
  204. }
  205. }
  206. void Dispose(bool disposing)
  207. {
  208. using (var profiler = new PlatformProfiler("Final Dispose"))
  209. {
  210. //Note: The engines are disposed before the the remove callback to give the chance to behave
  211. //differently if a remove happens as a consequence of a dispose
  212. //The pattern is to implement the IDisposable interface and set a flag in the engine. The
  213. //remove callback will then behave differently according the flag.
  214. foreach (var engine in _disposableEngines)
  215. try
  216. {
  217. if (engine is IDisposingEngine dengine)
  218. dengine.isDisposing = true;
  219. engine.Dispose();
  220. }
  221. catch (Exception e)
  222. {
  223. Console.LogException(e);
  224. }
  225. foreach (var groups in _groupEntityComponentsDB)
  226. foreach (var entityList in groups.value)
  227. try
  228. {
  229. ITypeSafeDictionary typeSafeDictionary = entityList.value;
  230. typeSafeDictionary.ExecuteEnginesDisposeCallbacks_Group(
  231. _reactiveEnginesDispose, _reactiveEnginesDisposeEx, groups.key,
  232. profiler);
  233. }
  234. catch (Exception e)
  235. {
  236. Console.LogException(e);
  237. }
  238. foreach (var groups in _groupEntityComponentsDB)
  239. foreach (var entityList in groups.value)
  240. entityList.value.Dispose();
  241. #if SVELTO_LEGACY_FILTERS
  242. foreach (var type in _groupFilters)
  243. foreach (var group in type.value)
  244. group.value.Dispose();
  245. _groupFilters.Clear();
  246. #endif
  247. DisposeFilters();
  248. #if UNITY_NATIVE
  249. _nativeAddOperationQueue.Dispose();
  250. _nativeRemoveOperationQueue.Dispose();
  251. _nativeSwapOperationQueue.Dispose();
  252. #endif
  253. _groupEntityComponentsDB.Clear();
  254. _groupsPerEntity.Clear();
  255. _disposableEngines.Clear();
  256. _enginesSet.Clear();
  257. _enginesTypeSet.Clear();
  258. _reactiveEnginesSwap.Clear();
  259. _reactiveEnginesAdd.Clear();
  260. _reactiveEnginesRemove.Clear();
  261. _reactiveEnginesDispose.Clear();
  262. _reactiveEnginesDisposeEx.Clear();
  263. _reactiveEnginesSubmission.Clear();
  264. _reactiveEnginesSubmissionStarted.Clear();
  265. _groupedEntityToAdd.Dispose();
  266. _entityLocator.DisposeEntityReferenceMap();
  267. _entityStreams.Dispose();
  268. scheduler.Dispose();
  269. }
  270. _isDisposed = true;
  271. }
  272. void NotifyReactiveEnginesOnSubmission()
  273. {
  274. var enginesCount = _reactiveEnginesSubmission.count;
  275. for (var i = 0; i < enginesCount; i++)
  276. _reactiveEnginesSubmission[i].EntitiesSubmitted();
  277. }
  278. void NotifyReactiveEnginesOnSubmissionStarted()
  279. {
  280. var enginesCount = _reactiveEnginesSubmissionStarted.count;
  281. for (var i = 0; i < enginesCount; i++)
  282. _reactiveEnginesSubmissionStarted[i].EntitiesSubmissionStarting();
  283. }
  284. public readonly struct EntitiesSubmitter
  285. {
  286. public EntitiesSubmitter(EnginesRoot enginesRoot): this()
  287. {
  288. _enginesRoot = new DataStructures.WeakReference<EnginesRoot>(enginesRoot);
  289. }
  290. internal void SubmitEntities()
  291. {
  292. Check.Require(_enginesRoot.IsValid, "ticking an GCed engines root?");
  293. var enginesRootTarget = _enginesRoot.Target;
  294. var entitiesSubmissionScheduler = enginesRootTarget.scheduler;
  295. if (entitiesSubmissionScheduler.paused == false)
  296. {
  297. enginesRootTarget.NotifyReactiveEnginesOnSubmissionStarted();
  298. Check.Require(
  299. entitiesSubmissionScheduler.isRunning == false,
  300. "A submission started while the previous one was still flushing");
  301. entitiesSubmissionScheduler.isRunning = true;
  302. using (var profiler = new PlatformProfiler("Svelto.ECS - Entities Submission"))
  303. {
  304. var iterations = 0;
  305. var hasEverSubmitted = false;
  306. // We need to clear transient filters before processing callbacks since the callbacks may add
  307. // new entities to these filters.
  308. enginesRootTarget.ClearTransientFilters();
  309. #if UNITY_NATIVE
  310. enginesRootTarget.FlushNativeOperations(profiler);
  311. #endif
  312. while (enginesRootTarget.HasMadeNewStructuralChangesInThisIteration()
  313. && iterations++ < MAX_SUBMISSION_ITERATIONS)
  314. {
  315. hasEverSubmitted = true;
  316. _enginesRoot.Target.SingleSubmission(profiler);
  317. #if UNITY_NATIVE
  318. enginesRootTarget.FlushNativeOperations(profiler);
  319. #endif
  320. }
  321. #if DEBUG && !PROFILE_SVELTO
  322. if (iterations == MAX_SUBMISSION_ITERATIONS)
  323. throw new ECSException("possible circular submission detected");
  324. #endif
  325. if (hasEverSubmitted)
  326. enginesRootTarget.NotifyReactiveEnginesOnSubmission();
  327. }
  328. entitiesSubmissionScheduler.isRunning = false;
  329. ++entitiesSubmissionScheduler.iteration;
  330. }
  331. }
  332. readonly DataStructures.WeakReference<EnginesRoot> _enginesRoot;
  333. }
  334. ~EnginesRoot()
  335. {
  336. Console.LogWarning("Engines Root has been garbage collected, don't forget to call Dispose()!");
  337. Dispose(false);
  338. }
  339. const int MAX_SUBMISSION_ITERATIONS = 10;
  340. readonly FasterList<IDisposable> _disposableEngines;
  341. readonly FasterList<IEngine> _enginesSet;
  342. readonly HashSet<Type> _enginesTypeSet;
  343. readonly EnginesReadyOption _enginesWaitForReady;
  344. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAdd>>> _reactiveEnginesAdd;
  345. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnAddEx>>> _reactiveEnginesAddEx;
  346. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemove>>> _reactiveEnginesRemove;
  347. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnRemoveEx>>> _reactiveEnginesRemoveEx;
  348. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwap>>> _reactiveEnginesSwap;
  349. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnSwapEx>>> _reactiveEnginesSwapEx;
  350. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDispose>>> _reactiveEnginesDispose;
  351. readonly FasterDictionary<ComponentID, FasterList<ReactEngineContainer<IReactOnDisposeEx>>> _reactiveEnginesDisposeEx;
  352. readonly FasterList<IReactOnSubmission> _reactiveEnginesSubmission;
  353. readonly FasterList<IReactOnSubmissionStarted> _reactiveEnginesSubmissionStarted;
  354. bool _isDisposed;
  355. }
  356. public enum EnginesReadyOption
  357. {
  358. ReadyAsAdded,
  359. WaitForReady
  360. }
  361. }