Syntriax.Engine/Engine.Serialization/TransformYamlConverter.cs

72 lines
2.7 KiB
C#

using System;
using System.Linq;
using Engine.Serialization.DTOs;
using Syntriax.Engine.Core;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Engine.Serialization;
internal class TransformYamlConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(TransformDTO);
public object ReadYaml(IParser parser, Type type)
{
if (parser.Current is not MappingStart)
throw new InvalidOperationException("Expected MappingStart");
parser.MoveNext();
var transform = new TransformDTO();
while (parser.Current != null && parser.Current is not MappingEnd)
{
var propertyName = ((Scalar)parser.Current).Value;
parser.MoveNext();
switch (propertyName)
{
case nameof(TransformDTO.ParentId):
transform.ParentId = new Vector2DYamlConverter().ReadYaml(parser, typeof(Vector2D))?.ToString();
break;
case nameof(TransformDTO.Position):
transform.Position = (Vector2D)(new Vector2DYamlConverter().ReadYaml(parser, typeof(Vector2D)) ?? new Exception());
break;
case nameof(TransformDTO.Scale):
transform.Scale = (Vector2D)(new Vector2DYamlConverter().ReadYaml(parser, typeof(Vector2D)) ?? new Exception());
break;
case nameof(TransformDTO.Rotation):
transform.Rotation = float.Parse(((Scalar)parser.Current).Value);
break;
}
parser.MoveNext();
}
return transform;
}
public void WriteYaml(IEmitter emitter, object? value, Type type)
{
var transform = (TransformDTO)(value ?? throw new Exception());
Vector2DYamlConverter vector2DYamlConverter = new();
emitter.Emit(new MappingStart());
if (transform.ParentId is not null)
{
emitter.Emit(new Scalar(nameof(TransformDTO.ParentId)));
emitter.Emit(new Scalar(transform.ParentId));
}
emitter.Emit(new Scalar(nameof(TransformDTO.ClassType)));
emitter.Emit(new Scalar(transform.ClassType));
emitter.Emit(new Scalar(nameof(TransformDTO.Position)));
vector2DYamlConverter.WriteYaml(emitter, transform.Position, typeof(Vector2D));
emitter.Emit(new Scalar(nameof(TransformDTO.Scale)));
vector2DYamlConverter.WriteYaml(emitter, transform.Scale, typeof(Vector2D));
emitter.Emit(new Scalar(nameof(TransformDTO.Rotation)));
emitter.Emit(new Scalar(transform.Rotation.ToString()));
emitter.Emit(new MappingEnd());
}
}