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.

65 lines
2.5KB

  1. using System;
  2. using Svelto.DataStructures;
  3. using Svelto.ECS.Internal;
  4. namespace Svelto.ECS
  5. {
  6. /// <summary>
  7. /// I eventually realised that, with the ECS design, no form of engines (systems) communication other
  8. /// than polling entity components is effective.
  9. /// The only purpose of this publisher/consumer model is to let two enginesroots communicate with each other
  10. /// through a thread safe ring buffer.
  11. /// The engines root A publishes entities.
  12. /// The engines root B can consume those entities at any time, as they will be a copy of the original
  13. /// entities and won't point directly to the database of the engines root A
  14. /// </summary>
  15. struct EntitiesStreams : IDisposable
  16. {
  17. internal Consumer<T> GenerateConsumer<T>(string name, uint capacity)
  18. where T : unmanaged, _IInternalEntityComponent
  19. {
  20. var componentId = ComponentTypeID<T>.id;
  21. if (_streams.ContainsKey(componentId) == false)
  22. _streams[componentId] = new EntityStream<T>();
  23. return (_streams[componentId] as EntityStream<T>).GenerateConsumer(name, capacity);
  24. }
  25. public Consumer<T> GenerateConsumer<T>(ExclusiveGroupStruct group, string name, uint capacity)
  26. where T : unmanaged, _IInternalEntityComponent
  27. {
  28. var componentId = ComponentTypeID<T>.id;
  29. if (_streams.ContainsKey(componentId) == false)
  30. _streams[componentId] = new EntityStream<T>();
  31. var typeSafeStream = (EntityStream<T>) _streams[componentId];
  32. return typeSafeStream.GenerateConsumer(group, name, capacity);
  33. }
  34. internal void PublishEntity<T>(ref T entity, EGID egid) where T : unmanaged, _IInternalEntityComponent
  35. {
  36. if (_streams.TryGetValue(ComponentTypeID<T>.id, out var typeSafeStream))
  37. (typeSafeStream as EntityStream<T>).PublishEntity(ref entity, egid);
  38. else
  39. Console.LogDebug($"No Consumers are waiting for this entity to change {typeof(T)}");
  40. }
  41. public void Dispose()
  42. {
  43. foreach (var stream in _streams)
  44. stream.value.Dispose();
  45. }
  46. public static EntitiesStreams Create()
  47. {
  48. var stream = new EntitiesStreams();
  49. stream._streams = FasterDictionary<ComponentID, ITypeSafeStream>.Construct();
  50. return stream;
  51. }
  52. FasterDictionary<ComponentID, ITypeSafeStream> _streams;
  53. }
  54. }