Syntriax.Engine/Engine.Serialization/GameObjectYamlConverter.cs

75 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Engine.Serialization.DTOs;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;
namespace Engine.Serialization;
internal class GameObjectYamlConverter : IYamlTypeConverter
{
public bool Accepts(Type type) => type == typeof(GameObjectDTO);
public object ReadYaml(IParser parser, Type type)
{
if (parser.Current is not MappingStart)
throw new InvalidOperationException("Expected MappingStart");
parser.MoveNext();
var gameObject = new GameObjectDTO();
while (parser.Current != null && parser.Current is not MappingEnd)
{
var propertyName = ((Scalar)parser.Current).Value;
parser.MoveNext();
switch (propertyName)
{
case nameof(GameObjectDTO.Id):
gameObject.Id = ((Scalar)parser.Current).Value;
break;
case nameof(GameObjectDTO.Name):
gameObject.Name = ((Scalar)parser.Current).Value;
break;
case nameof(GameObjectDTO.Transform):
gameObject.Transform = (TransformDTO)(new TransformYamlConverter().ReadYaml(parser, typeof(TransformDTO)) ?? new Exception());
break;
// case nameof(GameObjectDTO.Behaviours):
// gameObject.Rotation = (List<BehaviourDTO>)(new BehaviourYamlConverter().ReadYaml(parser, typeof(BehaviourDTO)) ?? new Exception());
// break;
case nameof(GameObjectDTO.StateEnable):
gameObject.StateEnable = (StateEnableDTO)(new StateEnableYamlConverter().ReadYaml(parser, typeof(StateEnableDTO)) ?? new Exception());
break;
}
parser.MoveNext();
}
return gameObject;
}
public void WriteYaml(IEmitter emitter, object? value, Type type)
{
var gameObject = (GameObjectDTO)(value ?? throw new Exception());
TransformYamlConverter transformYamlConverter = new();
StateEnableYamlConverter stateEnableYamlConverter = new();
BehaviourControllerYamlConverter behaviourControllerYamlConverter = new();
emitter.Emit(new MappingStart());
emitter.Emit(new Scalar(nameof(GameObjectDTO.Id)));
emitter.Emit(new Scalar(gameObject.Id.ToString()));
emitter.Emit(new Scalar(nameof(GameObjectDTO.ClassType)));
emitter.Emit(new Scalar(gameObject.ClassType));
emitter.Emit(new Scalar(nameof(GameObjectDTO.Name)));
emitter.Emit(new Scalar(gameObject.Name.ToString()));
emitter.Emit(new Scalar(nameof(GameObjectDTO.Transform)));
transformYamlConverter.WriteYaml(emitter, gameObject.Transform, typeof(TransformDTO));
emitter.Emit(new Scalar(nameof(GameObjectDTO.StateEnable)));
stateEnableYamlConverter.WriteYaml(emitter, gameObject.StateEnable, typeof(StateEnableDTO));
emitter.Emit(new Scalar(nameof(GameObjectDTO.BehaviourController)));
behaviourControllerYamlConverter.WriteYaml(emitter, gameObject.BehaviourController, typeof(BehaviourControllerDTO));
emitter.Emit(new MappingEnd());
}
}