Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

424 line
18KB

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