Syntriax.Engine/Engine.Serialization/GameManagerYamlConverter.cs

54 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using Engine.Serialization.DTOs;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Engine.Serialization;
internal class GameManagerYamlConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(GameManagerDTO);
public object ReadYaml(IParser parser, Type type)
{
if (parser.Current is not MappingStart)
throw new InvalidOperationException("Expected MappingStart");
parser.MoveNext();
var gameManager = new GameManagerDTO();
while (parser.Current != null && parser.Current is not MappingEnd)
{
var propertyName = ((Scalar)parser.Current).Value;
parser.MoveNext();
switch (propertyName)
{
case nameof(GameManagerDTO.ClassType):
gameManager.ClassType = ((Scalar)parser.Current).Value;
break;
case nameof(GameManagerDTO.GameObjects):
gameManager.GameObjects = (List<GameObjectDTO>)new GameObjectDTOListConverter().ReadYaml(parser, typeof(List<GameObjectDTO>));
break;
}
parser.MoveNext();
}
return gameManager;
}
public void WriteYaml(IEmitter emitter, object? value, Type type)
{
var gameManager = (GameManagerDTO)(value ?? throw new Exception());
GameObjectDTOListConverter gameObjectDTOListConverter = new();
emitter.Emit(new MappingStart());
emitter.Emit(new Scalar(nameof(GameManagerDTO.ClassType)));
emitter.Emit(new Scalar(gameManager.ClassType));
emitter.Emit(new Scalar(nameof(GameManagerDTO.GameObjects)));
gameObjectDTOListConverter.WriteYaml(emitter, gameManager.GameObjects, typeof(List<GameObjectDTO>));
emitter.Emit(new MappingEnd());
}
}