MapMigrationSystem.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.IO;
  3. using System.Linq;
  4. using Robust.Server.GameObjects;
  5. using Robust.Shared.ContentPack;
  6. using Robust.Shared.EntitySerialization.Systems;
  7. using Robust.Shared.Map.Events;
  8. using Robust.Shared.Prototypes;
  9. using Robust.Shared.Serialization.Markdown;
  10. using Robust.Shared.Serialization.Markdown.Mapping;
  11. using Robust.Shared.Serialization.Markdown.Value;
  12. using Robust.Shared.Utility;
  13. namespace Content.Server.Maps;
  14. /// <summary>
  15. /// Performs basic map migration operations by listening for engine <see cref="MapLoaderSystem"/> events.
  16. /// </summary>
  17. public sealed class MapMigrationSystem : EntitySystem
  18. {
  19. [Dependency] private readonly IPrototypeManager _protoMan = default!;
  20. [Dependency] private readonly IResourceManager _resMan = default!;
  21. private const string MigrationFile = "/migration.yml";
  22. public override void Initialize()
  23. {
  24. base.Initialize();
  25. SubscribeLocalEvent<BeforeEntityReadEvent>(OnBeforeReadEvent);
  26. #if DEBUG
  27. if (!TryReadFile(out var mappings))
  28. return;
  29. // Verify that all of the entries map to valid entity prototypes.
  30. foreach (var node in mappings.Values)
  31. {
  32. var newId = ((ValueDataNode) node).Value;
  33. if (!string.IsNullOrEmpty(newId) && newId != "null")
  34. DebugTools.Assert(_protoMan.HasIndex<EntityPrototype>(newId), $"{newId} is not an entity prototype.");
  35. }
  36. #endif
  37. }
  38. private bool TryReadFile([NotNullWhen(true)] out MappingDataNode? mappings)
  39. {
  40. mappings = null;
  41. var path = new ResPath(MigrationFile);
  42. if (!_resMan.TryContentFileRead(path, out var stream))
  43. return false;
  44. using var reader = new StreamReader(stream, EncodingHelpers.UTF8);
  45. var documents = DataNodeParser.ParseYamlStream(reader).FirstOrDefault();
  46. if (documents == null)
  47. return false;
  48. mappings = (MappingDataNode) documents.Root;
  49. return true;
  50. }
  51. private void OnBeforeReadEvent(BeforeEntityReadEvent ev)
  52. {
  53. if (!TryReadFile(out var mappings))
  54. return;
  55. foreach (var (key, value) in mappings)
  56. {
  57. if (key is not ValueDataNode keyNode || value is not ValueDataNode valueNode)
  58. continue;
  59. if (string.IsNullOrWhiteSpace(valueNode.Value) || valueNode.Value == "null")
  60. ev.DeletedPrototypes.Add(keyNode.Value);
  61. else
  62. ev.RenamedPrototypes.Add(keyNode.Value, valueNode.Value);
  63. }
  64. }
  65. }