Refactor #2746 to use ScriptingObjectInterfaceReference for C# too instead of attribute
Use `MarshalAs=ScriptingObject*` for more universal way of marshaling data between C++ and C#
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
// Copyright (c) Wojciech Figat. All rights reserved.
|
||||
|
||||
using System;
|
||||
using FlaxEngine.GUI;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
|
||||
namespace FlaxEngine.Json
|
||||
{
|
||||
@@ -138,6 +138,52 @@ namespace FlaxEngine.Json
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialize <see cref="ScriptingObjectInterfaceReference{T}"/> as path string in internal format.
|
||||
/// </summary>
|
||||
/// <seealso cref="Newtonsoft.Json.JsonConverter" />
|
||||
internal class ScriptingObjectInterfaceReferenceConverter : JsonConverter
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override unsafe void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
|
||||
{
|
||||
if (value == null)
|
||||
writer.WriteNull();
|
||||
else
|
||||
{
|
||||
var objectField = value.GetType().GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
|
||||
var obj = objectField.GetValue(value) as Object;
|
||||
if (obj == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
return;
|
||||
}
|
||||
var id = obj.ID;
|
||||
writer.WriteValue(JsonSerializer.GetStringID(&id));
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
|
||||
{
|
||||
var result = existingValue ?? Activator.CreateInstance(objectType);
|
||||
if (reader.TokenType == JsonToken.String)
|
||||
{
|
||||
JsonSerializer.ParseID((string)reader.Value, out var id);
|
||||
var obj = Object.Find(ref id, objectType.GetGenericArguments()[0]);
|
||||
var objectField = objectType.GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
|
||||
objectField.SetValue(result, obj);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(ScriptingObjectInterfaceReference<>);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Serialize <see cref="BehaviorKnowledgeSelectorAny"/> as path string in internal format.
|
||||
/// </summary>
|
||||
|
||||
+4
-90
@@ -13,7 +13,6 @@ namespace FlaxEngine.Json.JsonCustomSerializers
|
||||
internal class ExtendedDefaultContractResolver : DefaultContractResolver
|
||||
{
|
||||
private readonly Type _flaxType = typeof(Object);
|
||||
private static readonly JsonConverter InterfaceObjectReferenceConverterInstance = new InterfaceObjectReferenceConverter();
|
||||
|
||||
private readonly Type[] AttributesIgnoreList =
|
||||
{
|
||||
@@ -35,86 +34,13 @@ namespace FlaxEngine.Json.JsonCustomSerializers
|
||||
_attributesIgnoreList = isManagedOnly ? AttributesIgnoreListManaged : AttributesIgnoreList;
|
||||
}
|
||||
|
||||
private static bool HasObjectInterfaceReferenceAttribute(IEnumerable<Attribute> attributes)
|
||||
private void SetupProperty(JsonProperty jsonProperty, Type type, IEnumerable<Attribute> attributes)
|
||||
{
|
||||
return attributes.Any(x => x is ScriptingObjectInterfaceReferenceAttribute || x is SoftObjectInterfaceReferenceAttribute);
|
||||
}
|
||||
|
||||
private static Type GetCollectionItemType(Type type)
|
||||
{
|
||||
if (type.IsArray)
|
||||
return type.GetElementType();
|
||||
if (!type.IsGenericType || type == typeof(string))
|
||||
return null;
|
||||
|
||||
var types = type.GetInterfaces().Concat(new[] { type });
|
||||
var dictionaryType = types.FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDictionary<,>));
|
||||
if (dictionaryType != null)
|
||||
return dictionaryType.GetGenericArguments()[1];
|
||||
var enumerableType = types.FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable<>));
|
||||
return enumerableType?.GetGenericArguments()[0];
|
||||
}
|
||||
|
||||
private static void SetupInterfaceObjectReferenceItems(JsonContainerContract contract, Type itemType)
|
||||
{
|
||||
if (itemType?.IsInterface == true)
|
||||
{
|
||||
contract.ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize;
|
||||
contract.ItemConverter = InterfaceObjectReferenceConverterInstance;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetupObjectReferenceProperty(JsonProperty jsonProperty, Type type, IEnumerable<Attribute> attributes)
|
||||
{
|
||||
var hasObjectInterfaceReferenceAttribute = HasObjectInterfaceReferenceAttribute(attributes);
|
||||
if (_flaxType.IsAssignableFrom(type) || (type.IsInterface && hasObjectInterfaceReferenceAttribute))
|
||||
if (_flaxType.IsAssignableFrom(type))
|
||||
{
|
||||
jsonProperty.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
|
||||
jsonProperty.Converter = JsonSerializer.ObjectConverter;
|
||||
}
|
||||
if (hasObjectInterfaceReferenceAttribute && GetCollectionItemType(type)?.IsInterface == true)
|
||||
{
|
||||
jsonProperty.ItemReferenceLoopHandling = ReferenceLoopHandling.Serialize;
|
||||
jsonProperty.ItemConverter = JsonSerializer.ObjectConverter;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class InterfaceObjectReferenceConverter : JsonConverter
|
||||
{
|
||||
public override unsafe void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
|
||||
{
|
||||
if (value is Object obj)
|
||||
{
|
||||
var id = obj.ID;
|
||||
writer.WriteValue(JsonSerializer.GetStringID(&id));
|
||||
}
|
||||
else if (value == null)
|
||||
{
|
||||
writer.WriteNull();
|
||||
}
|
||||
else
|
||||
{
|
||||
serializer.Serialize(writer, value, value.GetType());
|
||||
}
|
||||
}
|
||||
|
||||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
|
||||
{
|
||||
if (reader.TokenType == JsonToken.String && JsonSerializer.TryParseID((string)reader.Value, out var id))
|
||||
{
|
||||
return Object.Find(ref id, objectType, true);
|
||||
}
|
||||
if (reader.TokenType == JsonToken.Null)
|
||||
return null;
|
||||
// objectType is the same interface item type that selected this converter. Passing it back to
|
||||
// Newtonsoft can cause this converter to be chosen again and recurse until the stack overflows.
|
||||
return Newtonsoft.Json.Linq.JToken.Load(reader).ToObject<object>(serializer);
|
||||
}
|
||||
|
||||
public override bool CanConvert(Type objectType)
|
||||
{
|
||||
return objectType.IsInterface;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -138,23 +64,11 @@ namespace FlaxEngine.Json.JsonCustomSerializers
|
||||
return contract;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override JsonArrayContract CreateArrayContract(Type objectType)
|
||||
{
|
||||
var contract = base.CreateArrayContract(objectType);
|
||||
|
||||
SetupInterfaceObjectReferenceItems(contract, contract.CollectionItemType);
|
||||
|
||||
return contract;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
|
||||
{
|
||||
var contract = base.CreateDictionaryContract(objectType);
|
||||
|
||||
SetupInterfaceObjectReferenceItems(contract, contract.DictionaryValueType);
|
||||
|
||||
// Override contract to save enums keys as integer
|
||||
var keyType = contract.DictionaryKeyType;
|
||||
if ((keyType?.IsEnum ?? false) && keyType.GetCustomAttribute<EnumStringAttribute>() == null)
|
||||
@@ -211,7 +125,7 @@ namespace FlaxEngine.Json.JsonCustomSerializers
|
||||
jsonProperty.Writable = true;
|
||||
jsonProperty.Readable = true;
|
||||
|
||||
SetupObjectReferenceProperty(jsonProperty, f.FieldType, attributes);
|
||||
SetupProperty(jsonProperty, f.FieldType, attributes);
|
||||
|
||||
result.Add(jsonProperty);
|
||||
}
|
||||
@@ -250,7 +164,7 @@ namespace FlaxEngine.Json.JsonCustomSerializers
|
||||
jsonProperty.Writable = true;
|
||||
jsonProperty.Readable = !isObsolete;
|
||||
|
||||
SetupObjectReferenceProperty(jsonProperty, p.PropertyType, attributes);
|
||||
SetupProperty(jsonProperty, p.PropertyType, attributes);
|
||||
|
||||
result.Add(jsonProperty);
|
||||
}
|
||||
|
||||
@@ -198,6 +198,7 @@ namespace FlaxEngine.Json
|
||||
settings.Converters.Add(new SceneReferenceConverter());
|
||||
settings.Converters.Add(new SoftObjectReferenceConverter());
|
||||
settings.Converters.Add(new SoftTypeReferenceConverter());
|
||||
settings.Converters.Add(new ScriptingObjectInterfaceReferenceConverter());
|
||||
settings.Converters.Add(new BehaviorKnowledgeSelectorAnyConverter());
|
||||
settings.Converters.Add(new ControlReferenceConverter());
|
||||
settings.Converters.Add(new MarginConverter());
|
||||
@@ -623,68 +624,29 @@ namespace FlaxEngine.Json
|
||||
/// </summary>
|
||||
/// <param name="str">The ID string.</param>
|
||||
/// <param name="id">The identifier.</param>
|
||||
/// <returns>True if parsing succeeded, otherwise false.</returns>
|
||||
public static unsafe bool TryParseID(string str, out Guid id)
|
||||
/// <returns>True if cannot parse text, otherwise false</returns>
|
||||
public static unsafe bool ParseID(string str, out Guid id)
|
||||
{
|
||||
id = Guid.Empty;
|
||||
if (str == null || str.Length != 32)
|
||||
return false;
|
||||
|
||||
bool result = true;
|
||||
GuidInterop g;
|
||||
if (!TryParseHex(str, 0, 8, out g.A) ||
|
||||
!TryParseHex(str, 8, 8, out g.B) ||
|
||||
!TryParseHex(str, 16, 8, out g.C) ||
|
||||
!TryParseHex(str, 24, 8, out g.D))
|
||||
if (str != null && str.Length == 32)
|
||||
{
|
||||
return false;
|
||||
// Matches Flax Guid parsing of FormatType::N
|
||||
result = ParseHex(str, 0, 8, out g.A) ||
|
||||
ParseHex(str, 8, 8, out g.B) ||
|
||||
ParseHex(str, 16, 8, out g.C) ||
|
||||
ParseHex(str, 24, 8, out g.D);
|
||||
}
|
||||
|
||||
id = *(Guid*)&g;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses the given object identifier represented in the internal serialization format.
|
||||
/// </summary>
|
||||
/// <param name="str">The ID string.</param>
|
||||
/// <param name="id">The identifier.</param>
|
||||
public static unsafe void ParseID(string str, out Guid id)
|
||||
{
|
||||
TryParseID(str, out id);
|
||||
return result;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static unsafe void ParseHex(char* str, int length, out uint result)
|
||||
{
|
||||
TryParseHex(new ReadOnlySpan<char>(str, length), out result);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static void ParseHex(string str, int start, int length, out uint result)
|
||||
{
|
||||
TryParseHex(str, start, length, out result);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static bool TryParseHex(string str, int start, int length, out uint result)
|
||||
{
|
||||
if (str.Length < start + length)
|
||||
{
|
||||
result = 0;
|
||||
return false;
|
||||
}
|
||||
return TryParseHex(str.AsSpan(start, length), out result);
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
internal static bool TryParseHex(ReadOnlySpan<char> str, out uint result)
|
||||
internal static bool ParseHex(string str, int start, int length, out uint result)
|
||||
{
|
||||
uint sum = 0;
|
||||
int p = 0;
|
||||
int end = str.Length;
|
||||
|
||||
if (p + 1 < end && str[p] == '0' && str[p + 1] == 'x')
|
||||
p += 2;
|
||||
int p = start;
|
||||
int end = start + length;
|
||||
|
||||
while (p < end && str[p] != 0)
|
||||
{
|
||||
@@ -696,17 +658,16 @@ namespace FlaxEngine.Json
|
||||
if (c < 10 || c > 15)
|
||||
{
|
||||
result = 0;
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
sum = 16 * sum + (uint)c;
|
||||
|
||||
p++;
|
||||
}
|
||||
|
||||
result = sum;
|
||||
return p == end;
|
||||
return p != end;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,9 +160,7 @@ public:
|
||||
template<typename T>
|
||||
FORCE_INLINE void Write(const ScriptingObjectInterfaceReference<T>& v)
|
||||
{
|
||||
uint32 id[4];
|
||||
v.CopyID(id);
|
||||
WriteBytes(id, sizeof(id));
|
||||
Write(v.GetObject());
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
|
||||
Reference in New Issue
Block a user