EnvironmentManagerSerializer.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. namespace COM3D2.MeidoPhotoStudio.Plugin
  6. {
  7. public class EnvironmentManagerSerializer : Serializer<EnvironmentManager>
  8. {
  9. private const short version = 1;
  10. private static SimpleSerializer<TransformDTO> TransformDtoSerializer => Serialization.GetSimple<TransformDTO>();
  11. public override void Serialize(EnvironmentManager manager, BinaryWriter writer)
  12. {
  13. writer.Write(EnvironmentManager.header);
  14. writer.WriteVersion(version);
  15. writer.Write(manager.CurrentBgAsset);
  16. TransformDtoSerializer.Serialize(new TransformDTO(GetBgTransform(manager)), writer);
  17. }
  18. public override void Deserialize(EnvironmentManager manager, BinaryReader reader, SceneMetadata metadata)
  19. {
  20. _ = reader.ReadVersion();
  21. var bg = GetBgTransform(manager);
  22. var bgAsset = reader.ReadString();
  23. var transformDto = TransformDtoSerializer.Deserialize(reader, metadata);
  24. var creativeBg = Utility.IsGuidString(bgAsset);
  25. List<string> bgList = creativeBg
  26. ? Constants.MyRoomCustomBGList.ConvertAll(kvp => kvp.Key)
  27. : Constants.BGList;
  28. var assetIndex = bgList.FindIndex(
  29. asset => asset.Equals(bgAsset, StringComparison.InvariantCultureIgnoreCase)
  30. );
  31. var validBg = assetIndex >= 0;
  32. if (validBg) bgAsset = bgList[assetIndex];
  33. else
  34. {
  35. Utility.LogWarning($"Could not load BG '{bgAsset}'");
  36. creativeBg = false;
  37. bgAsset = EnvironmentManager.defaultBg;
  38. }
  39. manager.ChangeBackground(bgAsset, creativeBg);
  40. if (!validBg) return;
  41. bg.position = transformDto.Position;
  42. bg.rotation = transformDto.Rotation;
  43. bg.localScale = transformDto.LocalScale;
  44. }
  45. private static Transform GetBgTransform(EnvironmentManager manager)
  46. => Utility.GetFieldValue<EnvironmentManager, Transform>(manager, "bg");
  47. }
  48. }