using System; using System.Collections.Generic; using System.Linq; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; namespace Syntriax.Engine.Core.Serialization; public class UniverseObjectSerializer : IEngineTypeYamlSerializer { private const string SERIALIZED_SCALAR_NAME = "Properties"; public bool Accepts(Type type) => typeof(IUniverseObject).IsAssignableFrom(type); public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string id; string name; IUniverseObject universeObject; IStateEnable stateEnable; IBehaviourController behaviourController; List children; parser.Consume(); if (parser.Consume().Value.CompareTo(nameof(IUniverseObject.Id)) != 0) throw new(); id = parser.Consume().Value; if (parser.Consume().Value.CompareTo(nameof(IUniverseObject.Name)) != 0) throw new(); name = parser.Consume().Value; if (parser.Consume().Value.CompareTo(SERIALIZED_SCALAR_NAME) != 0) throw new(); SerializedClass instanceSerializedClass = (SerializedClass)rootDeserializer(typeof(SerializedClass))!; universeObject = (IUniverseObject)instanceSerializedClass.CreateInstance(); if (parser.Consume().Value.CompareTo(nameof(IUniverseObject.StateEnable)) != 0) throw new(); stateEnable = (IStateEnable)rootDeserializer(typeof(IStateEnable))!; if (parser.Consume().Value.CompareTo(nameof(IUniverseObject.BehaviourController)) != 0) throw new(); behaviourController = (IBehaviourController)rootDeserializer(typeof(IBehaviourController))!; if (parser.Consume().Value.CompareTo(nameof(IUniverseObject.Children)) != 0) throw new(); children = (List)rootDeserializer(typeof(List))!; parser.Consume(); universeObject.Id = id; universeObject.Name = name; stateEnable.Assign(universeObject); universeObject.Assign(stateEnable); behaviourController.Assign(universeObject); universeObject.Assign(behaviourController); foreach (IUniverseObject child in children) universeObject.AddChild(child); return universeObject; } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { IUniverseObject universeObject = (IUniverseObject)value!; emitter.Emit(new MappingStart()); emitter.Emit(new Scalar(nameof(IUniverseObject.Id))); emitter.Emit(new Scalar(universeObject.Id)); emitter.Emit(new Scalar(nameof(IUniverseObject.Name))); emitter.Emit(new Scalar(universeObject.Name)); emitter.Emit(new Scalar(SERIALIZED_SCALAR_NAME)); serializer(new SerializedClass(universeObject)); emitter.Emit(new Scalar(nameof(IUniverseObject.StateEnable))); serializer(universeObject.StateEnable); emitter.Emit(new Scalar(nameof(IUniverseObject.BehaviourController))); serializer(universeObject.BehaviourController); emitter.Emit(new Scalar(nameof(IUniverseObject.Children))); serializer(universeObject.Children.Where(c => !c.GetType().HasAttribute())); emitter.Emit(new MappingEnd()); } }