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.

62 lines
2.5KB

  1. using System;
  2. using Svelto.DataStructures;
  3. namespace Svelto.ECS
  4. {
  5. /// <summary>
  6. /// I eventually realised that, with the ECS design, no form of communication other than polling entity components can
  7. /// exist.
  8. /// Using groups, you can have always an optimal set of entity components to poll. However EntityStreams
  9. /// can be useful if:
  10. /// - you need to react on seldom entity changes, usually due to user events
  11. /// - you want engines to be able to track entity changes
  12. /// - you want a thread-safe way to read entity states, which includes all the state changes and not the last
  13. /// one only
  14. /// - you want to communicate between EnginesRoots
  15. /// </summary>
  16. struct EntitiesStreams : IDisposable
  17. {
  18. internal Consumer<T> GenerateConsumer<T>(string name, uint capacity)
  19. where T : unmanaged, IEntityComponent
  20. {
  21. if (_streams.ContainsKey(TypeRefWrapper<T>.wrapper) == false)
  22. _streams[TypeRefWrapper<T>.wrapper] = new EntityStream<T>();
  23. return (_streams[TypeRefWrapper<T>.wrapper] as EntityStream<T>).GenerateConsumer(name, capacity);
  24. }
  25. public Consumer<T> GenerateConsumer<T>(ExclusiveGroupStruct group, string name, uint capacity)
  26. where T : unmanaged, IEntityComponent
  27. {
  28. if (_streams.ContainsKey(TypeRefWrapper<T>.wrapper) == false)
  29. _streams[TypeRefWrapper<T>.wrapper] = new EntityStream<T>();
  30. var typeSafeStream = (EntityStream<T>) _streams[TypeRefWrapper<T>.wrapper];
  31. return typeSafeStream.GenerateConsumer(group, name, capacity);
  32. }
  33. internal void PublishEntity<T>(ref T entity, EGID egid) where T : unmanaged, IEntityComponent
  34. {
  35. if (_streams.TryGetValue(TypeRefWrapper<T>.wrapper, out var typeSafeStream))
  36. (typeSafeStream as EntityStream<T>).PublishEntity(ref entity, egid);
  37. else
  38. Console.LogDebug("No Consumers are waiting for this entity to change ", typeof(T));
  39. }
  40. public void Dispose()
  41. {
  42. foreach (var stream in _streams)
  43. stream.Value.Dispose();
  44. }
  45. public static EntitiesStreams Create()
  46. {
  47. var stream = new EntitiesStreams();
  48. stream._streams = FasterDictionary<RefWrapperType, ITypeSafeStream>.Construct();
  49. return stream;
  50. }
  51. FasterDictionary<RefWrapperType, ITypeSafeStream> _streams;
  52. }
  53. }