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:
2026-09-14 06:58:40 +02:00
parent a7754f3137
commit 0fc3972cea
24 changed files with 527 additions and 792 deletions
@@ -58,13 +58,11 @@ namespace FlaxEditor.CustomEditors
if (targetType.Type == typeof(object) && values.Count > 0 && values[0] != null && !values.HasDifferentTypes)
return CreateEditor(TypeUtils.GetObjectType(values[0]), canUseRefPicker);
// Use editor for the property type
if (canUseRefPicker &&
targetType.IsInterface &&
values.GetAttributes().Any(x => x is ScriptingObjectInterfaceReferenceAttribute || x is SoftObjectInterfaceReferenceAttribute))
{
// Special case if property is interface but the value is implemented as Scripting Object that should use reference picker (or all interface impl are by Scripting Objects)
if (canUseRefPicker && targetType.IsInterface && values.Count > 0 && values[0] is FlaxEngine.Object)
return new FlaxObjectRefEditor();
}
// Use editor for the property type
return CreateEditor(targetType, canUseRefPicker);
}
@@ -2,6 +2,7 @@
using System;
using System.Linq;
using System.Reflection;
using FlaxEditor.Content;
using FlaxEditor.CustomEditors.Elements;
using FlaxEditor.GUI;
@@ -156,44 +157,32 @@ namespace FlaxEditor.CustomEditors.Editors
private void ShowDropDownMenu()
{
Focus();
var pos = new Float2(0, Height);
if (_type.IsInterface)
{
SceneObjectSearchPopup.Show(this, new Float2(0, Height), IsValid, obj =>
{
Value = obj;
RootWindow.Focus();
Focus();
}, PresenterContext);
SceneObjectSearchPopup.Show(this, pos, IsValid, SetDropDownResult, PresenterContext);
}
else if (new ScriptType(typeof(Actor)).IsAssignableFrom(_type))
{
ActorSearchPopup.Show(this, new Float2(0, Height), IsValid, actor =>
{
Value = actor;
RootWindow.Focus();
Focus();
}, PresenterContext);
ActorSearchPopup.Show(this, pos, IsValid, SetDropDownResult, PresenterContext);
}
else if (new ScriptType(typeof(Control)).IsAssignableFrom(_type))
{
ActorSearchPopup.Show(this, new Float2(0, Height), IsValid, actor =>
{
Value = actor as UIControl;
RootWindow.Focus();
Focus();
}, PresenterContext);
ActorSearchPopup.Show(this, pos, IsValid, actor => { SetDropDownResult(actor as UIControl); }, PresenterContext);
}
else
{
ScriptSearchPopup.Show(this, new Float2(0, Height), IsValid, script =>
{
Value = script;
RootWindow.Focus();
Focus();
}, PresenterContext);
ScriptSearchPopup.Show(this, pos, IsValid, SetDropDownResult, PresenterContext);
}
}
private void SetDropDownResult(Object value)
{
Value = value;
RootWindow.Focus();
Focus();
}
/// <summary>
/// Called when value gets changed.
/// </summary>
@@ -228,7 +217,7 @@ namespace FlaxEditor.CustomEditors.Editors
{
// Draw info
Render2D.PushClip(nameRect);
Render2D.DrawText(style.FontMedium, Type != null ? $"Multiple Values ({Utilities.Utils.GetPropertyNameUI(Type.ToString())})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center);
Render2D.DrawText(style.FontMedium, Type != null ? $"Multiple Values ({Utilities.Utils.GetTypeNameUI(_type)})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center);
Render2D.PopClip();
}
else if (isSelected)
@@ -245,7 +234,7 @@ namespace FlaxEditor.CustomEditors.Editors
{
// Draw info
Render2D.PushClip(nameRect);
Render2D.DrawText(style.FontMedium, Type != null ? $"None ({Utilities.Utils.GetPropertyNameUI(Type.ToString())})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center);
Render2D.DrawText(style.FontMedium, Type != null ? $"None ({Utilities.Utils.GetTypeNameUI(_type)})" : "-", nameRect, isEnabled ? style.ForegroundGrey : style.ForegroundGrey.AlphaMultiplied(0.75f), TextAlignment.Near, TextAlignment.Center);
Render2D.PopClip();
}
@@ -670,4 +659,58 @@ namespace FlaxEditor.CustomEditors.Editors
}
}
}
/// <summary>
/// Default implementation of the inspector used to edit reference to the <see cref="ScriptingObjectInterfaceReference{T}"/>.
/// </summary>
internal sealed class ScriptingObjectInterfaceReferenceEditor : CustomEditor
{
private CustomElement<FlaxObjectRefPickerControl> _element;
/// <inheritdoc />
public override DisplayStyle Style => DisplayStyle.Inline;
/// <inheritdoc />
public override void Initialize(LayoutElementsContainer layout)
{
if (!HasDifferentTypes)
{
_element = layout.Custom<FlaxObjectRefPickerControl>();
_element.CustomControl.PresenterContext = Presenter.Owner;
_element.CustomControl.Type = new ScriptType(Values.Type.GetGenericArguments()[0]);
_element.CustomControl.ValueChanged += OnValueChanged;
}
}
private void OnValueChanged()
{
// Set value
var obj = _element.CustomControl.Value;
var v = Values.Type.CreateInstance();
var objectField = v.GetType().GetField("_object", BindingFlags.Instance | BindingFlags.NonPublic);
objectField.SetValue(v, obj);
SetValue(v);
}
/// <inheritdoc />
public override void Refresh()
{
base.Refresh();
var differentValues = HasDifferentValues;
_element.CustomControl.DifferentValues = differentValues;
if (!differentValues)
{
// Get value
var v = Values[0];
var obj = v as Object;
if (v != null && obj == null)
{
var objectField = v.GetType().GetField("_object", BindingFlags.Instance | BindingFlags.NonPublic);
obj = objectField.GetValue(v) as Object;
}
_element.CustomControl.Value = obj;
}
}
}
}
@@ -26,9 +26,11 @@ namespace FlaxEditor.CustomEditors
/// </summary>
/// <param name="elementType">Type of the collection elements.</param>
/// <param name="key">The key.</param>
public DictionaryValueContainer(ScriptType elementType, object key)
/// <param name="attributes">The dictionary property attributes to inherit.</param>
public DictionaryValueContainer(ScriptType elementType, object key, object[] attributes = null)
: base(ScriptMemberInfo.Null, elementType)
{
_attributes = attributes;
Key = key;
}
@@ -40,10 +42,8 @@ namespace FlaxEditor.CustomEditors
/// <param name="values">The collection values.</param>
/// <param name="attributes">The dictionary property attributes to inherit.</param>
public DictionaryValueContainer(ScriptType elementType, object key, ValueContainer values, object[] attributes = null)
: this(elementType, key)
: this(elementType, key, attributes)
{
_attributes = attributes;
Capacity = values.Count;
for (int i = 0; i < values.Count; i++)
{
+51 -4
View File
@@ -1,15 +1,62 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using FlaxEditor.Content;
using FlaxEngine;
using FlaxEngine.TypeConverters;
using FlaxEngine.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using FlaxEditor.Content;
using FlaxEngine;
using FlaxEngine.Utilities;
namespace FlaxEngine.TypeConverters
{
/// <summary>
/// Internal ITypeDescriptorContext used to pass some context for custom TypeConvert implementations.
/// Allows passing CurrentType to TypeConverter.ConvertFrom method to support custom type conversion for FlaxEngine types (simpler than PropertyDescriptor.PropertyType).
/// </summary>
internal sealed class DummyTypeDescriptorContext : ITypeDescriptorContext
{
private static DummyTypeDescriptorContext _cached;
public Type CurrentType;
public static object ConvertFrom(TypeConverter converter, object value, Type type)
{
if (_cached == null)
_cached = new DummyTypeDescriptorContext();
_cached.CurrentType = type;
var result = converter.ConvertFrom(_cached, CultureInfo.CurrentUICulture, value);
_cached.CurrentType = null;
return result;
}
public object GetService(Type serviceType)
{
return null;
}
public void OnComponentChanged()
{
}
public bool OnComponentChanging()
{
return false;
}
public IContainer Container => null;
public object Instance => null;
public PropertyDescriptor PropertyDescriptor => null;
}
}
namespace FlaxEditor.Scripting
{
@@ -681,7 +728,7 @@ namespace FlaxEditor.Scripting
if (converter.CanConvertTo(type))
value = converter.ConvertTo(value, type);
else if (converter.CanConvertFrom(valueType))
value = converter.ConvertFrom(null, null, value);
value = DummyTypeDescriptorContext.ConvertFrom(converter, value, type);
}
if (_managed is PropertyInfo propertyInfo)
+1 -1
View File
@@ -212,7 +212,7 @@ namespace FlaxEditor.Surface
color = Colors.Enum;
else if (type.IsValueType)
color = Colors.Structures;
else if (type.IsScriptingObject || type.IsInterface)
else if (type.IsScriptingObject || type.IsInterface || type.Name.StartsWith("ScriptingObjectInterfaceReference"))
color = Colors.Object;
else if (hint == ConnectionsHint.Vector)
color = Colors.Vector;
+18
View File
@@ -833,6 +833,24 @@ namespace FlaxEditor.Utilities
}
}
/// <summary>
/// Gets the type name for UI. Removes unnecessary characters and filters text. Makes it more user-friendly.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The result.</returns>
public static string GetTypeNameUI(Scripting.ScriptType type)
{
var name = type.ToString();
// Don't format interfaces to maintain code-name (eg. prefix 'I')
if (type.IsInterface)
return name;
if (type.IsGenericType && name.StartsWith("ScriptingObjectInterfaceReference", StringComparison.Ordinal))
return type.GetGenericArguments()[0].GetTypeDisplayName();
return GetPropertyNameUI(name);
}
/// <summary>
/// Gets the property name for UI. Removes unnecessary characters and filters text. Makes it more user-friendly.
/// </summary>
@@ -188,7 +188,7 @@ namespace FlaxEngine
/// </summary>
/// <param name="knowledge">The knowledge container to access.</param>
/// <param name="value">The value to set.</param>
/// <returns>True if set value value, otherwise false.</returns>
/// <returns>True if set value, otherwise false.</returns>
public bool Set(BehaviorKnowledge knowledge, T value)
{
return knowledge != null && knowledge.Set(Path, value);
+25 -1
View File
@@ -263,12 +263,36 @@ namespace FlaxEngine.Interop
/// <returns>The output array.</returns>
public static TDst[] ConvertArray<TSrc, TDst>(this TSrc[] src, Func<TSrc, TDst> convertFunc)
{
TDst[] dst = new TDst[src.Length];
if (src == null)
return null;
var dst = new TDst[src.Length];
for (int i = 0; i < src.Length; i++)
dst[i] = convertFunc(src[i]);
return dst;
}
/// <summary>
/// Converts dictionary with a custom converter function for each pair of keys and values.
/// </summary>
/// <typeparam name="TSrcKey">Input dictionary key type.</typeparam>
/// <typeparam name="TSrcValue">Input dictionary value type.</typeparam>
/// <typeparam name="TDstKey">Output dictionary key type.</typeparam>
/// <typeparam name="TDstValue">Output dictionary value type.</typeparam>
/// <param name="src">The input dictionary.</param>
/// <param name="convertFuncKey">Converter callback for keys.</param>
/// <param name="convertFuncValue">Converter callback for values.</param>
/// <returns>The output dictionary.</returns>
public static Dictionary<TDstKey, TDstValue> ConvertDictionary<TSrcKey, TSrcValue, TDstKey, TDstValue>(this Dictionary<TSrcKey, TSrcValue> src, Func<TSrcKey, TDstKey> convertFuncKey, Func<TSrcValue, TDstValue> convertFuncValue)
{
if (src == null)
return null;
var dst = new Dictionary<TDstKey, TDstValue>();
dst.EnsureCapacity(src.Count);
foreach (var e in src)
dst.Add(convertFuncKey(e.Key), convertFuncValue(e.Value));
return dst;
}
/// <summary>Find <paramref name="assemblyName"/> among the scripting assemblies.</summary>
/// <param name="assemblyName">The name to find</param>
/// <param name="allowPartial">If true, partial names should be allowed to be resolved.</param>
@@ -1,14 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using System;
namespace FlaxEngine
{
/// <summary>
/// Marks a generated interface property as a native scripting object interface reference.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class ScriptingObjectInterfaceReferenceAttribute : Attribute
{
}
}
@@ -1,14 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using System;
namespace FlaxEngine
{
/// <summary>
/// Marks a generated interface property as a native soft object interface reference.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public sealed class SoftObjectInterfaceReferenceAttribute : Attribute
{
}
}
+23 -88
View File
@@ -281,102 +281,22 @@ class ScriptingObjectReference;
template<typename T>
class ScriptingObjectInterfaceReference;
template<typename T>
class SoftObjectInterfaceReference;
template<typename T>
struct MConverter<ScriptingObjectReference<T>>
{
MObject* Box(const ScriptingObjectReference<T>& data, const MClass* klass)
{
return data.GetManagedInstance();
}
void Unbox(ScriptingObjectReference<T>& result, MObject* data)
{
result = (T*)ScriptingObject::ToNative(data);
}
void ToManagedArray(MArray* result, const Span<ScriptingObjectReference<T>>& data)
{
if (data.Length() == 0)
return;
MObject** objects = (MObject**)Allocator::Allocate(data.Length() * sizeof(MObject*));
for (int32 i = 0; i < data.Length(); i++)
objects[i] = data[i].GetManagedInstance();
MCore::GC::WriteArrayRef(result, Span<MObject*>(objects, data.Length()));
Allocator::Free(objects);
}
void ToNativeArray(Span<ScriptingObjectReference<T>>& result, const MArray* data)
{
MObject** dataPtr = MCore::Array::GetAddress<MObject*>(data);
for (int32 i = 0; i < result.Length(); i++)
result.Get()[i] = (T*)ScriptingObject::ToNative(dataPtr[i]);
}
};
template<typename TReference, typename TInterface>
struct MInterfaceReferenceConverter
{
MObject* Box(const TReference& data, const MClass* klass)
{
return data.GetManagedInstance();
}
void Unbox(TReference& result, MObject* data)
{
result = ScriptingObject::ToInterface<TInterface>(ScriptingObject::ToNative(data));
}
void ToManagedArray(MArray* result, const Span<TReference>& data)
{
if (data.Length() == 0)
return;
MObject** objects = (MObject**)Allocator::Allocate(data.Length() * sizeof(MObject*));
for (int32 i = 0; i < data.Length(); i++)
objects[i] = data[i].GetManagedInstance();
MCore::GC::WriteArrayRef(result, Span<MObject*>(objects, data.Length()));
Allocator::Free(objects);
}
void ToNativeArray(Span<TReference>& result, const MArray* data)
{
MObject** dataPtr = MCore::Array::GetAddress<MObject*>(data);
for (int32 i = 0; i < result.Length(); i++)
result.Get()[i] = ScriptingObject::ToInterface<TInterface>(ScriptingObject::ToNative(dataPtr[i]));
}
};
// Converter for Scripting Interface References.
template<typename T>
struct MConverter<ScriptingObjectInterfaceReference<T>> : MInterfaceReferenceConverter<ScriptingObjectInterfaceReference<T>, T>
{
};
// Converter for Soft Object Interface References.
template<typename T>
struct MConverter<SoftObjectInterfaceReference<T>> : MInterfaceReferenceConverter<SoftObjectInterfaceReference<T>, T>
{
};
// Converter for Asset References.
template<typename T>
class AssetReference;
template<typename T>
struct MConverter<AssetReference<T>>
template<typename Reference, typename Object>
struct MObjectReferenceConverter
{
MObject* Box(const AssetReference<T>& data, const MClass* klass)
MObject* Box(const Reference& data, const MClass* klass)
{
return data.GetManagedInstance();
}
void Unbox(AssetReference<T>& result, MObject* data)
void Unbox(Reference& result, MObject* data)
{
result = (T*)ScriptingObject::ToNative(data);
result = (Object*)ScriptingObject::ToNative(data);
}
void ToManagedArray(MArray* result, const Span<AssetReference<T>>& data)
void ToManagedArray(MArray* result, const Span<Reference>& data)
{
if (data.Length() == 0)
return;
@@ -387,14 +307,29 @@ struct MConverter<AssetReference<T>>
Allocator::Free(objects);
}
void ToNativeArray(Span<AssetReference<T>>& result, const MArray* data)
void ToNativeArray(Span<Reference>& result, const MArray* data)
{
MObject** dataPtr = MCore::Array::GetAddress<MObject*>(data);
for (int32 i = 0; i < result.Length(); i++)
result.Get()[i] = (T*)ScriptingObject::ToNative(dataPtr[i]);
result.Get()[i] = (Object*)ScriptingObject::ToNative(dataPtr[i]);
}
};
template<typename T>
struct MConverter<ScriptingObjectReference<T>> : MObjectReferenceConverter<ScriptingObjectReference<T>, T>
{
};
template<typename T>
struct MConverter<ScriptingObjectInterfaceReference<T>> : MObjectReferenceConverter<ScriptingObjectInterfaceReference<T>, ScriptingObject>
{
};
template<typename T>
struct MConverter<AssetReference<T>> : MObjectReferenceConverter<AssetReference<T>, T>
{
};
// TODO: use MarshalAs=Guid on SoftAssetReference to pass guid over bindings and not load asset in glue code
template<typename T>
class SoftAssetReference;
@@ -0,0 +1,188 @@
// Copyright (c) Wojciech Figat. All rights reserved.
using System;
#if FLAX_EDITOR
using System.Globalization;
using System.ComponentModel;
#endif
namespace FlaxEngine
{
/// <summary>
/// The scripting object reference with interface.
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
#if FLAX_EDITOR
[CustomEditor(typeof(FlaxEditor.CustomEditors.Editors.ScriptingObjectInterfaceReferenceEditor))]
[TypeConverter(typeof(TypeConverters.ScriptingObjectInterfaceReferenceConverter))]
#endif
public struct ScriptingObjectInterfaceReference<T> : IComparable, IComparable<ScriptingObjectInterfaceReference<T>> where T : class
{
private Object _object;
/// <summary>
/// Gets or sets the referenced object that implements the interface.
/// </summary>
public Object Object
{
get => _object;
set => _object = value != null && value is T ? value : null;
}
/// <summary>
/// Gets or sets the referenced object that implements the interface.
/// </summary>
[NoSerialize]
public T Interface
{
get => _object as T;
set
{
var obj = value as Object;
if (value == null || obj != null)
_object = obj;
else
throw new InvalidCastException($"Cannot use object of type {value.GetType().FullName} for ScriptingObjectInterfaceReference<{typeof(T).FullName}>. It needs to inherit from {typeof(Object).FullName}.");
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptingObjectInterfaceReference{T}"/> structure.
/// </summary>
/// <param name="obj">The object to link.</param>
public ScriptingObjectInterfaceReference(Object obj)
{
Object = obj;
}
/// <summary>
/// Initializes a new instance of the <see cref="ScriptingObjectInterfaceReference{T}"/> structure.
/// </summary>
/// <param name="interfaceObj">The interface object to link.</param>
public ScriptingObjectInterfaceReference(T interfaceObj)
{
Interface = interfaceObj;
}
/// <summary>
/// Implicit cast operator to typed interface.
/// </summary>
/// <param name="value">Reference</param>
/// <returns>Interface</returns>
public static explicit operator T(ScriptingObjectInterfaceReference<T> value)
{
return value._object as T;
}
/// <summary>
/// Implicit cast operator from object to reference.
/// </summary>
/// <param name="obj">The object to link.</param>
/// <returns>Reference</returns>
public static explicit operator ScriptingObjectInterfaceReference<T>(T obj)
{
return new ScriptingObjectInterfaceReference<T>(obj);
}
/// <summary>
/// Implicit cast operator to object.
/// </summary>
/// <param name="value">Reference</param>
/// <returns>Object</returns>
public static implicit operator Object(ScriptingObjectInterfaceReference<T> value)
{
return value._object;
}
/// <summary>
/// Implicit cast operator from object to reference.
/// </summary>
/// <param name="obj">Object</param>
/// <returns>Reference</returns>
public static implicit operator ScriptingObjectInterfaceReference<T>(Object obj)
{
return new ScriptingObjectInterfaceReference<T>(obj);
}
/// <inheritdoc />
public override string ToString()
{
return _object?.ToString() ?? "<null>";
}
/// <inheritdoc />
public override int GetHashCode()
{
return Object.GetUnmanagedPtr(_object).GetHashCode();
}
/// <inheritdoc />
public int CompareTo(object obj)
{
if (obj is ScriptingObjectInterfaceReference<T> other)
return CompareTo(other);
return 0;
}
/// <inheritdoc />
public int CompareTo(ScriptingObjectInterfaceReference<T> other)
{
return Object.GetUnmanagedPtr(_object).CompareTo(Object.GetUnmanagedPtr(other._object));
}
}
}
#if FLAX_EDITOR
namespace FlaxEngine.TypeConverters
{
internal class ScriptingObjectInterfaceReferenceConverter : TypeConverter
{
/// <inheritdoc />
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
/// <inheritdoc />
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(string))
return false;
return base.CanConvertTo(context, destinationType);
}
/// <inheritdoc />
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is string str && context is DummyTypeDescriptorContext internalContext)
{
var type = internalContext.CurrentType;
Json.JsonSerializer.ParseID(str, out var id);
var obj = Object.Find(ref id, type.GetGenericArguments()[0]);
var objectField = type.GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
value = Activator.CreateInstance(type);
objectField.SetValue(value, obj);
return value;
}
return base.ConvertFrom(context, culture, value);
}
/// <inheritdoc />
public override unsafe object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
var objectField = value.GetType().GetField("_object", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
var obj = objectField.GetValue(value) as Object;
if (obj == null)
return string.Empty;
var id = obj.ID;
return Json.JsonSerializer.GetStringID(&id);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
#endif
@@ -2,17 +2,15 @@
#pragma once
#include "Engine/Scripting/ScriptingObjectInterfaceReferenceUtils.h"
#include "ScriptingObjectReference.h"
/// <summary>
/// The scene object interface reference.
/// The scripting object reference with interface.
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
template<typename T>
API_CLASS(InBuild) class ScriptingObjectInterfaceReference : public ScriptingObjectReferenceBase
API_CLASS(Template, MarshalAs=ScriptingObject*) class ScriptingObjectInterfaceReference : public ScriptingObjectReferenceBase
{
typedef ScriptingObjectInterfaceReferenceHelper<T> Helper;
public:
typedef ScriptingObjectInterfaceReference<T> Type;
@@ -28,8 +26,8 @@ public:
/// Initializes a new instance of the <see cref="ScriptingObjectInterfaceReference"/> class.
/// </summary>
/// <param name="obj">The object to link.</param>
ScriptingObjectInterfaceReference(SceneObject* obj)
: ScriptingObjectReferenceBase(Helper::IsValidObject(obj) ? obj : nullptr)
ScriptingObjectInterfaceReference(ScriptingObject* obj)
: ScriptingObjectReferenceBase(IsValid(obj) ? obj : nullptr)
{
}
@@ -38,7 +36,7 @@ public:
/// </summary>
/// <param name="interfaceObj">The interface object to link.</param>
ScriptingObjectInterfaceReference(T* interfaceObj)
: ScriptingObjectReferenceBase(Helper::GetSceneObject(interfaceObj))
: ScriptingObjectReferenceBase(ScriptingObject::FromInterface<T>(interfaceObj))
{
}
@@ -64,12 +62,12 @@ public:
}
public:
FORCE_INLINE bool operator==(SceneObject* other) const
FORCE_INLINE bool operator==(ScriptingObject* other) const
{
return _object == other;
}
FORCE_INLINE bool operator!=(SceneObject* other) const
FORCE_INLINE bool operator!=(ScriptingObject* other) const
{
return _object != other;
}
@@ -94,33 +92,34 @@ public:
return _object != other._object;
}
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(SceneObject* other)
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(ScriptingObject* other)
{
OnSet(Helper::IsValidObject(other) ? other : nullptr);
OnSet(IsValid(other) ? other : nullptr);
return *this;
}
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(T* other)
{
OnSet(Helper::GetSceneObject(other));
OnSet(ScriptingObject::FromInterface<T>(other));
return *this;
}
ScriptingObjectInterfaceReference& operator=(const ScriptingObjectInterfaceReference& other)
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(const ScriptingObjectInterfaceReference& other)
{
OnSet(other._object);
return *this;
}
ScriptingObjectInterfaceReference& operator=(ScriptingObjectInterfaceReference&& other) noexcept
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(ScriptingObjectInterfaceReference&& other) noexcept
{
ScriptingObjectReferenceBase::operator=(MoveTemp(other));
return *this;
}
FORCE_INLINE ScriptingObjectInterfaceReference& operator=(const Guid& id)
ScriptingObjectInterfaceReference& operator=(const Guid& id)
{
OnSet(Helper::FindSceneObject(id));
ScriptingObject* obj = FindObject(id, ScriptingObject::GetStaticClass());
OnSet(IsValid(obj) ? obj : nullptr);
return *this;
}
@@ -132,6 +131,14 @@ public:
return Get();
}
/// <summary>
/// Implicit conversion to the object.
/// </summary>
FORCE_INLINE operator ScriptingObject*() const
{
return _object;
}
/// <summary>
/// Implicit conversion to boolean value.
/// </summary>
@@ -159,33 +166,24 @@ public:
/// <summary>
/// Gets the referenced object.
/// </summary>
FORCE_INLINE SceneObject* GetObject() const
FORCE_INLINE ScriptingObject* GetObject() const
{
return static_cast<SceneObject*>(_object);
return _object;
}
/// <summary>
/// Copies the object ID into the raw storage.
/// Gets managed instance object.
/// </summary>
FORCE_INLINE void CopyID(uint32 id[4]) const
FORCE_INLINE MObject* GetManagedInstance() const
{
memset(id, 0, sizeof(uint32) * 4);
if (_object)
{
const Guid value = GetID();
memcpy(id, &value, sizeof(uint32) * 4);
}
return _object ? _object->GetOrCreateManagedInstance() : nullptr;
}
/// <summary>
/// Gets the object as a given type (static cast).
/// </summary>
template<typename U>
FORCE_INLINE U* As() const
private:
FORCE_INLINE static bool IsValid(const ScriptingObject* obj)
{
return static_cast<U*>(_object);
return !obj || obj->GetType().GetInterface(T::TypeInitializer);
}
};
template<typename T>
@@ -1,30 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
#pragma once
#include "Engine/Scripting/ScriptingObjectReference.h"
#include "Engine/Level/SceneObject.h"
/// <summary>
/// Utility methods for scene object interface references.
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
template<typename T>
struct ScriptingObjectInterfaceReferenceHelper
{
FORCE_INLINE static bool IsValidObject(const SceneObject* obj)
{
return !obj || obj->GetType().GetInterface(T::TypeInitializer) != nullptr;
}
FORCE_INLINE static SceneObject* GetSceneObject(T* interfaceObj)
{
return ScriptingObject::Cast<SceneObject>(ScriptingObject::FromInterface<T>(interfaceObj));
}
FORCE_INLINE static SceneObject* FindSceneObject(const Guid& id)
{
SceneObject* obj = static_cast<SceneObject*>(FindObject(id, SceneObject::GetStaticClass()));
return IsValidObject(obj) ? obj : nullptr;
}
};
@@ -72,7 +72,7 @@ public:
}
/// <summary>
/// Gets managed instance object (or null if no object linked).
/// Gets managed instance object.
/// </summary>
FORCE_INLINE MObject* GetManagedInstance() const
{
@@ -1,258 +0,0 @@
// Copyright (c) Wojciech Figat. All rights reserved.
#pragma once
#include "Engine/Scripting/SoftObjectReference.h"
#include "Engine/Scripting/ScriptingObjectInterfaceReferenceUtils.h"
/// <summary>
/// The scene object soft interface reference. Objects gets referenced on use (ID reference is resolving it).
/// </summary>
/// <typeparam name="T">The type of the scripting interface.</typeparam>
template<typename T>
API_CLASS(InBuild) class SoftObjectInterfaceReference : public SoftObjectReferenceBase
{
typedef ScriptingObjectInterfaceReferenceHelper<T> Helper;
public:
typedef SoftObjectInterfaceReference<T> Type;
public:
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
SoftObjectInterfaceReference()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="obj">The object to link.</param>
SoftObjectInterfaceReference(SceneObject* obj)
{
OnSet(Helper::IsValidObject(obj) ? obj : nullptr);
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="interfaceObj">The interface object to link.</param>
SoftObjectInterfaceReference(T* interfaceObj)
{
OnSet(Helper::GetSceneObject(interfaceObj));
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="other">The other property.</param>
SoftObjectInterfaceReference(const SoftObjectInterfaceReference& other)
{
OnSet(other.GetID());
}
/// <summary>
/// Initializes a new instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
/// <param name="other">The other property.</param>
SoftObjectInterfaceReference(SoftObjectInterfaceReference&& other)
{
OnSet(other.GetID());
other.OnSet(nullptr);
}
/// <summary>
/// Finalizes an instance of the <see cref="SoftObjectInterfaceReference"/> class.
/// </summary>
~SoftObjectInterfaceReference()
{
}
public:
FORCE_INLINE bool operator==(SceneObject* other)
{
return GetObject() == other;
}
FORCE_INLINE bool operator!=(SceneObject* other)
{
return GetObject() != other;
}
FORCE_INLINE bool operator==(T* other)
{
return Get() == other;
}
FORCE_INLINE bool operator!=(T* other)
{
return Get() != other;
}
FORCE_INLINE bool operator==(const SoftObjectInterfaceReference& other)
{
return GetID() == other.GetID();
}
FORCE_INLINE bool operator!=(const SoftObjectInterfaceReference& other)
{
return GetID() != other.GetID();
}
SoftObjectInterfaceReference& operator=(const SoftObjectInterfaceReference& other)
{
if (this != &other)
OnSet(other.GetID());
return *this;
}
SoftObjectInterfaceReference& operator=(SoftObjectInterfaceReference&& other)
{
if (this != &other)
{
OnSet(other.GetID());
other.OnSet(nullptr);
}
return *this;
}
FORCE_INLINE SoftObjectInterfaceReference& operator=(SceneObject* other)
{
OnSet(Helper::IsValidObject(other) ? other : nullptr);
return *this;
}
FORCE_INLINE SoftObjectInterfaceReference& operator=(T* other)
{
OnSet(Helper::GetSceneObject(other));
return *this;
}
FORCE_INLINE SoftObjectInterfaceReference& operator=(const Guid& id)
{
OnSet(id);
return *this;
}
/// <summary>
/// Implicit conversion to the interface.
/// </summary>
FORCE_INLINE operator T*() const
{
return Get();
}
/// <summary>
/// Implicit conversion to boolean value.
/// </summary>
FORCE_INLINE operator bool() const
{
return Get() != nullptr;
}
/// <summary>
/// Interface accessor.
/// </summary>
FORCE_INLINE T* operator->() const
{
return Get();
}
/// <summary>
/// Gets the object as a given type (static cast).
/// </summary>
template<typename U>
FORCE_INLINE U* As() const
{
return static_cast<U*>(GetObject());
}
public:
/// <summary>
/// Gets the interface pointer.
/// </summary>
FORCE_INLINE T* Get() const
{
return ScriptingObject::ToInterface<T>(GetObject());
}
/// <summary>
/// Gets the referenced object.
/// </summary>
SceneObject* GetObject() const
{
if (!_object)
const_cast<SoftObjectInterfaceReference*>(this)->OnResolve(SceneObject::GetStaticClass());
return Helper::IsValidObject(static_cast<SceneObject*>(_object)) ? static_cast<SceneObject*>(_object) : nullptr;
}
/// <summary>
/// Gets managed instance object (or null if no object linked).
/// </summary>
MObject* GetManagedInstance() const
{
auto object = GetObject();
return object ? object->GetOrCreateManagedInstance() : nullptr;
}
/// <summary>
/// Determines whether object is assigned and managed instance of the object is alive.
/// </summary>
bool HasManagedInstance() const
{
auto object = GetObject();
return object && object->HasManagedInstance();
}
/// <summary>
/// Gets the managed instance object or creates it if missing or null if not assigned.
/// </summary>
MObject* GetOrCreateManagedInstance() const
{
auto object = GetObject();
return object ? object->GetOrCreateManagedInstance() : nullptr;
}
/// <summary>
/// Copies the object ID into the raw storage.
/// </summary>
FORCE_INLINE void CopyID(uint32 id[4]) const
{
const Guid value = GetID();
memcpy(id, &value, sizeof(uint32) * 4);
}
/// <summary>
/// Sets the object.
/// </summary>
/// <param name="id">The object ID. Uses Scripting to find the registered object of the given ID.</param>
FORCE_INLINE void Set(const Guid& id)
{
OnSet(id);
}
/// <summary>
/// Sets the object.
/// </summary>
/// <param name="object">The object.</param>
FORCE_INLINE void Set(SceneObject* object)
{
OnSet(Helper::IsValidObject(object) ? object : nullptr);
}
/// <summary>
/// Sets the object.
/// </summary>
/// <param name="interfaceObj">The interface object.</param>
FORCE_INLINE void Set(T* interfaceObj)
{
OnSet(Helper::GetSceneObject(interfaceObj));
}
};
template<typename T>
uint32 GetHash(const SoftObjectInterfaceReference<T>& key)
{
return GetHash(key.GetID());
}
@@ -233,7 +233,7 @@ public:
}
/// <summary>
/// Gets managed instance object (or null if no object linked).
/// Gets managed instance object.
/// </summary>
MObject* GetManagedInstance() const
{
+47 -1
View File
@@ -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>
@@ -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);
}
+16 -55
View File
@@ -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;
}
}
}
+1 -3
View File
@@ -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>
@@ -107,8 +107,6 @@ namespace Flax.Build.Bindings
{
if (attribute && valueType != null && !valueType.IsArray)
{
//if (valueType.Type == "")
//ScriptingObjectReference, ScriptingObjectInterfaceReference, SoftObjectInterfaceReference
apiType = FindApiTypeInfo(buildData, valueType, caller);
// Object reference
@@ -315,83 +313,6 @@ namespace Flax.Build.Bindings
return value;
}
private static bool IsInterfaceRefArrayLike(TypeInfo typeInfo)
{
return typeInfo != null &&
(typeInfo.Type == "Array" || typeInfo.Type == "Span" || typeInfo.Type == "DataContainer") &&
typeInfo.GenericArgs != null &&
typeInfo.GenericArgs.Count != 0 &&
typeInfo.GenericArgs[0].IsInterfaceRef;
}
private static bool IsInterfaceRefDictionary(TypeInfo typeInfo)
{
return typeInfo != null &&
typeInfo.Type == "Dictionary" &&
typeInfo.GenericArgs != null &&
typeInfo.GenericArgs.Count == 2 &&
(typeInfo.GenericArgs[0].IsInterfaceRef || typeInfo.GenericArgs[1].IsInterfaceRef);
}
private static bool IsInterfaceRefContainer(TypeInfo typeInfo)
{
return IsInterfaceRefArrayLike(typeInfo) || IsInterfaceRefDictionary(typeInfo);
}
private static TypeInfo GetInterfaceRefElementType(TypeInfo typeInfo)
{
if (typeInfo == null)
return null;
if (typeInfo.IsInterfaceRef)
return typeInfo;
if (IsInterfaceRefArrayLike(typeInfo))
return typeInfo.GenericArgs[0];
if (IsInterfaceRefDictionary(typeInfo))
return typeInfo.GenericArgs[1].IsInterfaceRef ? typeInfo.GenericArgs[1] : typeInfo.GenericArgs[0];
return null;
}
private static string GenerateInterfaceRefToNative(BuildData buildData, TypeInfo interfaceRefType, ApiTypeInfo caller, string value)
{
return $"FlaxEngine.Object.GetUnmanagedInterface({value}, typeof({GenerateCSharpNativeToManaged(buildData, interfaceRefType.GenericArgs[0], caller)}))";
}
private static string GenerateInterfaceRefToManaged(BuildData buildData, TypeInfo interfaceRefType, ApiTypeInfo caller, string value, bool fromHandle)
{
var managedType = GenerateCSharpNativeToManaged(buildData, interfaceRefType.GenericArgs[0], caller);
return fromHandle
? $"{value} != IntPtr.Zero ? Unsafe.As<{managedType}>(ManagedHandle.FromIntPtr({value}).Target) : null"
: $"{value} != null ? Unsafe.As<{managedType}>({value}) : null";
}
private static string GenerateInterfaceRefContainerToNative(TypeInfo typeInfo)
{
if (IsInterfaceRefArrayLike(typeInfo))
return "{0} != null ? FlaxEngine.Interop.NativeInterop.ManagedArrayToGCHandleArray({0}) : null";
if (IsInterfaceRefDictionary(typeInfo))
{
var keyConverter = typeInfo.GenericArgs[0].IsInterfaceRef ? "(object)x.Key" : "x.Key";
var valueConverter = typeInfo.GenericArgs[1].IsInterfaceRef ? "(object)x.Value" : "x.Value";
return $"{{0}} != null ? System.Linq.Enumerable.ToDictionary({{0}}, x => {keyConverter}, x => {valueConverter}) : null";
}
return string.Empty;
}
private static string GenerateInterfaceRefContainerToManaged(BuildData buildData, TypeInfo typeInfo, ApiTypeInfo caller, string value)
{
if (IsInterfaceRefArrayLike(typeInfo))
return $"{value}?.ConvertArray(x => {GenerateInterfaceRefToManaged(buildData, typeInfo.GenericArgs[0], caller, "x", true)})";
if (IsInterfaceRefDictionary(typeInfo))
{
var keyTypeInfo = typeInfo.GenericArgs[0];
var valueTypeInfo = typeInfo.GenericArgs[1];
var keyConverter = keyTypeInfo.IsInterfaceRef ? GenerateInterfaceRefToManaged(buildData, keyTypeInfo, caller, "x.Key", false) : "x.Key";
var valueConverter = valueTypeInfo.IsInterfaceRef ? GenerateInterfaceRefToManaged(buildData, valueTypeInfo, caller, "x.Value", false) : "x.Value";
return $"{value} != null ? System.Linq.Enumerable.ToDictionary({value}, x => {keyConverter}, x => {valueConverter}) : null";
}
return value;
}
private static string GenerateCSharpNativeToManaged(BuildData buildData, TypeInfo typeInfo, ApiTypeInfo caller, bool marshalling = false)
{
string result;
@@ -427,10 +348,6 @@ namespace Flax.Build.Bindings
if (CSharpNativeToManagedDefault.TryGetValue(typeInfo.Type, out result))
return result;
// Interface reference property
if (typeInfo.IsInterfaceRef)
return marshalling ? "IntPtr" : GenerateCSharpNativeToManaged(buildData, typeInfo.GenericArgs[0], caller, marshalling);
// Object reference property
if (typeInfo.IsObjectRef)
return GenerateCSharpNativeToManaged(buildData, typeInfo.GenericArgs[0], caller, marshalling);
@@ -457,11 +374,7 @@ namespace Flax.Build.Bindings
// Dictionary
if (typeInfo.Type == "Dictionary" && typeInfo.GenericArgs != null)
{
var keyType = marshalling && typeInfo.GenericArgs[0].IsInterfaceRef ? "object" : GenerateCSharpNativeToManaged(buildData, typeInfo.GenericArgs[0], caller, marshalling);
var valueType = marshalling && typeInfo.GenericArgs[1].IsInterfaceRef ? "object" : GenerateCSharpNativeToManaged(buildData, typeInfo.GenericArgs[1], caller, marshalling);
return string.Format("System.Collections.Generic.Dictionary<{0}, {1}>", keyType, valueType);
}
return string.Format("System.Collections.Generic.Dictionary<{0}, {1}>", GenerateCSharpNativeToManaged(buildData, typeInfo.GenericArgs[0], caller, marshalling), GenerateCSharpNativeToManaged(buildData, typeInfo.GenericArgs[1], caller, marshalling));
// HashSet
if (typeInfo.Type == "HashSet" && typeInfo.GenericArgs != null)
@@ -631,8 +544,6 @@ namespace Flax.Build.Bindings
case "Array":
case "Span":
case "DataContainer":
if (IsInterfaceRefArrayLike(typeInfo))
return GenerateInterfaceRefContainerToNative(typeInfo);
if (typeInfo.GenericArgs != null)
{
// Convert array that uses different type for marshalling
@@ -643,14 +554,21 @@ namespace Flax.Build.Bindings
}
return string.Empty;
case "Dictionary":
if (IsInterfaceRefDictionary(typeInfo))
return GenerateInterfaceRefContainerToNative(typeInfo);
if (typeInfo.GenericArgs != null && typeInfo.GenericArgs.Count == 2)
{
// Convert dictionary that uses different type for marshalling
var keyApiType = FindApiTypeInfo(buildData, typeInfo.GenericArgs[0], caller);
var valueApiType = FindApiTypeInfo(buildData, typeInfo.GenericArgs[1], caller);
if ((keyApiType != null && keyApiType.MarshalAs != null) || (valueApiType != null && valueApiType.MarshalAs != null))
{
var keyConverter = keyApiType != null && keyApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, keyApiType.MarshalAs, caller)})" : "";
var valueConverter = valueApiType != null && valueApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, valueApiType.MarshalAs, caller)})" : "";
//return $"{{0}} != null ? System.Linq.Enumerable.ToDictionary({{0}}, x => {keyConverter}, x => {valueConverter}) : null";
return $"{{0}}.ConvertDictionary(key => {keyConverter}key, value => {valueConverter}value)";
}
}
return string.Empty;
default:
// Interface reference property
if (typeInfo.IsInterfaceRef)
return GenerateInterfaceRefToNative(buildData, typeInfo, caller, "{0}");
var apiType = FindApiTypeInfo(buildData, typeInfo, caller);
if (apiType != null)
{
@@ -873,24 +791,12 @@ namespace Flax.Build.Bindings
}
}
#endif
const string interfaceResultName = "__interfaceResult";
const string interfaceContainerResultName = "__interfaceContainerResult";
var returnInterfaceRef = !functionInfo.Glue.UseReferenceForResult && functionInfo.ReturnType.IsInterfaceRef;
var returnInterfaceRefContainer = !functionInfo.Glue.UseReferenceForResult && IsInterfaceRefContainer(functionInfo.ReturnType);
var returnType = functionInfo.ReturnType;
if (functionInfo.Glue.UseReferenceForResult)
{
}
else if (returnInterfaceRef)
{
contents.Append("var ").Append(interfaceResultName).Append(" = ");
}
else if (returnInterfaceRefContainer)
{
contents.Append("var ").Append(interfaceContainerResultName).Append(" = ");
}
else if (!functionInfo.ReturnType.IsVoid)
else if (!returnType.IsVoid)
{
contents.Append("return ");
}
@@ -960,22 +866,27 @@ namespace Flax.Build.Bindings
}
contents.Append(')');
if (returnInterfaceRef)
{
contents.Append("; return ").Append(GenerateInterfaceRefToManaged(buildData, functionInfo.ReturnType, caller, interfaceResultName, true));
}
else if (returnInterfaceRefContainer)
{
contents.Append("; return ").Append(GenerateInterfaceRefContainerToManaged(buildData, functionInfo.ReturnType, caller, interfaceContainerResultName));
}
else if ((functionInfo.ReturnType.Type == "Array" || functionInfo.ReturnType.Type == "Span" || functionInfo.ReturnType.Type == "DataContainer") && functionInfo.ReturnType.GenericArgs != null)
if ((returnType.Type == "Array" || returnType.Type == "Span" || returnType.Type == "DataContainer") && returnType.GenericArgs != null)
{
// Convert array that uses different type for marshalling
var arrayTypeInfo = functionInfo.ReturnType.GenericArgs[0];
var arrayTypeInfo = returnType.GenericArgs[0];
var arrayApiType = FindApiTypeInfo(buildData, arrayTypeInfo, caller);
if (arrayApiType != null && arrayApiType.MarshalAs != null)
contents.Append($".ConvertArray(x => ({GenerateCSharpNativeToManaged(buildData, arrayTypeInfo, caller)})x)");
}
else if (returnType.Type == "Dictionary" && returnType.GenericArgs != null && returnType.GenericArgs.Count == 2)
{
// Convert dictionary that uses different type for marshalling
var keyApiType = FindApiTypeInfo(buildData, returnType.GenericArgs[0], caller);
var valueApiType = FindApiTypeInfo(buildData, returnType.GenericArgs[1], caller);
if ((keyApiType != null && keyApiType.MarshalAs != null) || (valueApiType != null && valueApiType.MarshalAs != null))
{
var keyConverter = keyApiType != null && keyApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, returnType.GenericArgs[0], caller)})" : "";
var valueConverter = valueApiType != null && valueApiType.MarshalAs != null ? $"({GenerateCSharpNativeToManaged(buildData, returnType.GenericArgs[1], caller)})" : "";
contents.Append($".ConvertDictionary(key => {keyConverter}key, value => {valueConverter}value)");
}
}
contents.Append(';');
// Return result
@@ -1104,13 +1015,6 @@ namespace Flax.Build.Bindings
private static void GenerateCSharpAttributes(BuildData buildData, StringBuilder contents, string indent, ApiTypeInfo apiTypeInfo, MemberInfo memberInfo, bool useUnmanaged, string defaultValue = null, TypeInfo defaultValueType = null)
{
GenerateCSharpAttributes(buildData, contents, indent, apiTypeInfo, memberInfo.Attributes, memberInfo.Comment, true, useUnmanaged, defaultValue, memberInfo.DeprecatedMessage, defaultValueType);
var memberType = (memberInfo as FieldInfo)?.Type ?? (memberInfo as PropertyInfo)?.Type;
var interfaceRefType = GetInterfaceRefElementType(memberType);
if (interfaceRefType != null)
{
var attribute = interfaceRefType.Type == "SoftObjectInterfaceReference" ? "SoftObjectInterfaceReference" : "ScriptingObjectInterfaceReference";
contents.Append(indent).Append("[FlaxEngine.").Append(attribute).AppendLine("]");
}
}
private static bool GenerateCSharpStructureUseDefaultInitialize(BuildData buildData, StructureInfo structureInfo)
@@ -167,12 +167,12 @@ namespace Flax.Build.Bindings
return $"Variant(StringView({value}))";
if (typeInfo.Type == "StringAnsi")
return $"Variant(StringAnsiView({value}))";
if (typeInfo.IsInterfaceRef)
return $"Variant({value}.GetObject())";
if (typeInfo.IsObjectRef)
return $"Variant({value}.Get())";
if (typeInfo.Type == "SoftTypeReference")
return $"Variant::Typename(StringAnsiView({value}))";
if (typeInfo.Type == "ScriptingObjectInterfaceReference")
return $"Variant({value}.GetObject())";
if (typeInfo.IsArray)
{
var wrapperName = GenerateCppWrapperNativeToVariantMethodName(typeInfo);
@@ -307,14 +307,12 @@ namespace Flax.Build.Bindings
return $"(StringAnsiView){value}";
if (typeInfo.IsPtr && typeInfo.IsConst && typeInfo.Type == "Char")
return $"((StringView){value}).GetText()"; // (StringView)Variant, if not empty, is guaranteed to point to a null-terminated buffer.
if (typeInfo.Type == "ScriptingObjectReference" || typeInfo.Type == "SoftObjectReference")
return $"ScriptingObject::Cast<{typeInfo.GenericArgs[0].Type}>((ScriptingObject*){value})";
if (typeInfo.IsInterfaceRef)
return $"ScriptingObject::ToInterface<{typeInfo.GenericArgs[0].Type}>((ScriptingObject*){value})";
if (typeInfo.IsObjectRef)
return $"ScriptingObject::Cast<{typeInfo.GenericArgs[0].Type}>((Asset*){value})";
return $"ScriptingObject::Cast<{typeInfo.GenericArgs[0].Type}>((ScriptingObject*){value})";
if (typeInfo.Type == "SoftTypeReference")
return $"(StringAnsiView){value}";
if (typeInfo.Type == "ScriptingObjectInterfaceReference")
return $"ScriptingObjectInterfaceReference<{typeInfo.GenericArgs[0].Type}>((ScriptingObject*){value})";
if (typeInfo.IsArray)
throw new Exception($"Not supported type to convert from the Variant to fixed-size array '{typeInfo}[{typeInfo.ArraySize}]'.");
if (typeInfo.Type == "Array" && typeInfo.GenericArgs != null)
@@ -656,8 +654,8 @@ namespace Flax.Build.Bindings
{
CppIncludeFiles.Add("Engine/Scripting/Internal/ManagedDictionary.h");
type = "MObject*";
var keyClass = typeInfo.GenericArgs[0].IsInterfaceRef ? "MCore::TypeCache::Object->GetType()" : GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[0], caller, functionInfo);
var valueClass = typeInfo.GenericArgs[1].IsInterfaceRef ? "MCore::TypeCache::Object->GetType()" : GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[1], caller, functionInfo);
var keyClass = GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[0], caller, functionInfo);
var valueClass = GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[1], caller, functionInfo);
return "ManagedDictionary::ToManaged({0}, " + keyClass + ", " + valueClass + ")";
}
@@ -801,19 +799,6 @@ namespace Flax.Build.Bindings
type = "MObject*";
return "MUtils::ToNative({0})";
default:
// Interface reference property
if (typeInfo.IsInterfaceRef)
{
if (CppNonPodTypesConvertingGeneration)
{
type = "MObject*";
return "ScriptingObject::ToInterface<" + typeInfo.GenericArgs[0].Type + ">(ScriptingObject::ToNative({0}))";
}
type = typeInfo.GenericArgs[0].Type + '*';
return string.Empty;
}
// Object reference property
if (typeInfo.IsObjectRef)
{
@@ -1023,8 +1008,8 @@ namespace Flax.Build.Bindings
if (typeInfo.Type == "Dictionary" && typeInfo.GenericArgs != null)
{
CppIncludeFiles.Add("Engine/Scripting/Internal/ManagedDictionary.h");
var keyClass = typeInfo.GenericArgs[0].IsInterfaceRef ? "MCore::TypeCache::Object->GetType()" : GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[0], caller);
var valueClass = typeInfo.GenericArgs[1].IsInterfaceRef ? "MCore::TypeCache::Object->GetType()" : GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[1], caller);
var keyClass = GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[0], caller);
var valueClass = GenerateCppGetNativeType(buildData, typeInfo.GenericArgs[1], caller);
return $"ManagedDictionary::ToManaged({value}, {keyClass}, {valueClass})";
}
+1 -9
View File
@@ -38,18 +38,10 @@ namespace Flax.Build.Bindings
/// Gets a value indicating whether this type is a reference to another object.
/// </summary>
public bool IsObjectRef => (Type == "ScriptingObjectReference" ||
Type == "ScriptingObjectInterfaceReference" ||
Type == "AssetReference" ||
Type == "WeakAssetReference" ||
Type == "SoftAssetReference" ||
Type == "SoftObjectReference" ||
Type == "SoftObjectInterfaceReference") && GenericArgs != null;
/// <summary>
/// Gets a value indicating whether this type is a reference to another object filtered by interface.
/// </summary>
public bool IsInterfaceRef => (Type == "ScriptingObjectInterfaceReference" ||
Type == "SoftObjectInterfaceReference") && GenericArgs != null;
Type == "SoftObjectReference") && GenericArgs != null;
public TypeInfo()
{