feat: added universe serializer

This commit is contained in:
Syntriax 2025-04-27 22:27:01 +03:00
parent 6e7a0993f5
commit fa3a4d1e0d

View File

@ -0,0 +1,77 @@
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 UniverseSerializer : IEngineTypeYamlSerializer
{
private const string SERIALIZED_SCALAR_NAME = "Properties";
public bool Accepts(Type type) => typeof(IUniverse).IsAssignableFrom(type);
public object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer)
{
string id;
IUniverse universe;
IStateEnable stateEnable;
List<IUniverseObject> universeObjects;
parser.Consume<MappingStart>();
if (parser.Consume<Scalar>().Value.CompareTo(nameof(IUniverse.Id)) != 0)
throw new();
id = parser.Consume<Scalar>().Value;
if (parser.Consume<Scalar>().Value.CompareTo(SERIALIZED_SCALAR_NAME) != 0)
throw new();
SerializedClass instanceSerializedClass = (SerializedClass)rootDeserializer(typeof(SerializedClass))!;
universe = (IUniverse)instanceSerializedClass.CreateInstance();
if (parser.Consume<Scalar>().Value.CompareTo(nameof(IUniverse.StateEnable)) != 0)
throw new();
stateEnable = (IStateEnable)rootDeserializer(typeof(IStateEnable))!;
if (parser.Consume<Scalar>().Value.CompareTo(nameof(IUniverse.UniverseObjects)) != 0)
throw new();
universeObjects = (List<IUniverseObject>)rootDeserializer(typeof(List<IUniverseObject>))!;
parser.Consume<MappingEnd>();
universe.Id = id;
stateEnable.Assign(universe);
universe.Assign(stateEnable);
foreach (IUniverseObject uo in universeObjects)
universe.Register(uo);
return universe;
}
public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
{
IUniverse universe = (IUniverse)value!;
emitter.Emit(new MappingStart());
emitter.Emit(new Scalar(nameof(IUniverse.Id)));
emitter.Emit(new Scalar(universe.Id));
emitter.Emit(new Scalar(SERIALIZED_SCALAR_NAME));
serializer(new SerializedClass(universe));
emitter.Emit(new Scalar(nameof(IUniverse.StateEnable)));
serializer(universe.StateEnable);
emitter.Emit(new Scalar(nameof(IUniverse.UniverseObjects)));
serializer(universe.UniverseObjects.Where(uo => !uo.GetType().HasAttribute<IgnoreSerializationAttribute>()));
emitter.Emit(new MappingEnd());
}
}