SerializableProperty.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Runtime.CompilerServices;
  7. namespace BansheeEngine
  8. {
  9. /** @addtogroup Serialization
  10. * @{
  11. */
  12. /// <summary>
  13. /// Allows you to transparently retrieve and set values of an entry, whether that entry is an object field or
  14. /// an array/list/dictionary entry.
  15. /// </summary>
  16. public sealed class SerializableProperty : ScriptObject
  17. {
  18. /// <summary>
  19. /// Object field types support by the serializable property.
  20. /// </summary>
  21. public enum FieldType
  22. {
  23. Int,
  24. Float,
  25. Bool,
  26. String,
  27. Color,
  28. Vector2,
  29. Vector3,
  30. Vector4,
  31. GameObjectRef,
  32. Resource,
  33. Object,
  34. Array,
  35. List,
  36. Dictionary,
  37. RRef,
  38. ColorGradient,
  39. Curve,
  40. FloatDistribution,
  41. ColorDistribution,
  42. Quaternion
  43. }
  44. public delegate object Getter();
  45. public delegate void Setter(object value);
  46. private FieldType type;
  47. private Type internalType;
  48. private Getter getter;
  49. private Setter setter;
  50. /// <summary>
  51. /// Constructor for internal use by the native code.
  52. /// </summary>
  53. private SerializableProperty()
  54. { }
  55. /// <summary>
  56. /// Creates a new serializable property.
  57. /// </summary>
  58. /// <param name="type">Type of data the property contains.</param>
  59. /// <param name="internalType">Type of data the property contains, as C# type.</param>
  60. /// <param name="getter">Method that allows you to retrieve contents of the property.</param>
  61. /// <param name="setter">Method that allows you to set contents of the property</param>
  62. public SerializableProperty(FieldType type, Type internalType, Getter getter, Setter setter)
  63. {
  64. this.type = type;
  65. this.internalType = internalType;
  66. this.getter = getter;
  67. this.setter = setter;
  68. Internal_CreateInstance(this, internalType);
  69. }
  70. /// <summary>
  71. /// Finalizes construction of the serializable property. Must be called after creation.
  72. /// </summary>
  73. /// <param name="type">Type of data the property contains.</param>
  74. /// <param name="internalType">Type of data the property contains, as C# type.</param>
  75. /// <param name="getter">Method that allows you to retrieve contents of the property.</param>
  76. /// <param name="setter">Method that allows you to set contents of the property</param>
  77. internal void Construct(FieldType type, Type internalType, Getter getter, Setter setter)
  78. {
  79. this.type = type;
  80. this.internalType = internalType;
  81. this.getter = getter;
  82. this.setter = setter;
  83. }
  84. /// <summary>
  85. /// Returns type of data the property contains.
  86. /// </summary>
  87. public FieldType Type
  88. {
  89. get { return type; }
  90. }
  91. /// <summary>
  92. /// Returns type of data the property contains, as C# type.
  93. /// </summary>
  94. public Type InternalType
  95. {
  96. get { return internalType; }
  97. }
  98. /// <summary>
  99. /// Is the containing type a value type (true), or a reference type (false).
  100. /// </summary>
  101. public bool IsValueType
  102. {
  103. get { return internalType.IsValueType; }
  104. }
  105. /// <summary>
  106. /// Retrieves the value contained in the property.
  107. /// </summary>
  108. /// <typeparam name="T">Type of the value to retrieve. Caller must ensure the type matches the property type.</typeparam>
  109. /// <returns>Value of the property.</returns>
  110. public T GetValue<T>()
  111. {
  112. // Cast if possible
  113. if (typeof(T) != internalType)
  114. {
  115. // Note: Not checking cast operators
  116. if (internalType.IsPrimitive || internalType.IsEnum)
  117. {
  118. if (internalType == typeof(bool) || typeof(T) == typeof(bool))
  119. throw new Exception("Attempted to retrieve a serializable value using an invalid type. " +
  120. "Provided type: " + typeof(T) + ". Needed type: " + internalType);
  121. return (T) Convert.ChangeType(getter(), typeof(T));
  122. }
  123. if(!typeof(T).IsAssignableFrom(internalType))
  124. throw new Exception("Attempted to retrieve a serializable value using an invalid type. " +
  125. "Provided type: " + typeof(T) + ". Needed type: " + internalType);
  126. }
  127. return (T)getter();
  128. }
  129. /// <summary>
  130. /// Changes the value of the property.
  131. /// </summary>
  132. /// <typeparam name="T">Type of the value to set. Caller must ensure the type matches the property type.</typeparam>
  133. /// <param name="value">New value to assign to the property.</param>
  134. public void SetValue<T>(T value)
  135. {
  136. if (!typeof(T).IsAssignableFrom(internalType))
  137. throw new Exception("Attempted to set a serializable value using an invalid type. Provided type: " + typeof(T) + ". Needed type: " + internalType);
  138. setter(value);
  139. }
  140. /// <summary>
  141. /// Returns a serializable object wrapper around the value contained in the property.
  142. /// </summary>
  143. /// <returns>Serializable object wrapper around the value contained in the property.</returns>
  144. public SerializableObject GetObject()
  145. {
  146. if (type != FieldType.Object)
  147. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  148. return Internal_CreateObject(mCachedPtr, this);
  149. }
  150. /// <summary>
  151. /// Returns a serializable array around the value contained in the property. Caller must ensure the property
  152. /// contains an array.
  153. /// </summary>
  154. /// <returns>Serializable array around the value contained in the property.</returns>
  155. public SerializableArray GetArray()
  156. {
  157. if (type != FieldType.Array)
  158. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  159. return Internal_CreateArray(mCachedPtr, this);
  160. }
  161. /// <summary>
  162. /// Returns a serializable list around the value contained in the property. Caller must ensure the property
  163. /// contains a list.
  164. /// </summary>
  165. /// <returns>Serializable list around the value contained in the property.</returns>
  166. public SerializableList GetList()
  167. {
  168. if (type != FieldType.List)
  169. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  170. return Internal_CreateList(mCachedPtr, this);
  171. }
  172. /// <summary>
  173. /// Returns a serializable dictionary around the value contained in the property. Caller must ensure the property
  174. /// contains a dictionary.
  175. /// </summary>
  176. /// <returns>Serializable dictionary around the value contained in the property.</returns>
  177. public SerializableDictionary GetDictionary()
  178. {
  179. if (type != FieldType.Dictionary)
  180. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  181. return Internal_CreateDictionary(mCachedPtr, this);
  182. }
  183. /// <summary>
  184. /// Creates a new instance of the type wrapped by this property.
  185. /// </summary>
  186. /// <typeparam name="T">Type of the object to create. Caller must ensure the type matches the property type and that
  187. /// the property wraps an object.</typeparam>
  188. /// <returns>A new instance of an object of type <typeparamref name="T"/>.</returns>
  189. public T CreateObjectInstance<T>()
  190. {
  191. if (type != FieldType.Object)
  192. throw new Exception("Attempting to retrieve object information from a field that doesn't contain an object.");
  193. return (T)Internal_CreateManagedObjectInstance(mCachedPtr);
  194. }
  195. /// <summary>
  196. /// Creates a new instance of the array wrapped by this property. Caller must ensure this property contains an array.
  197. /// </summary>
  198. /// <param name="lengths">Size of each dimension of the array. Number of dimensions must match the number
  199. /// of dimensions in the array wrapped by this property.</param>
  200. /// <returns>A new array containing the same element type as the array wrapped by this property, of
  201. /// <paramref name="lengths"/> sizes.</returns>
  202. public Array CreateArrayInstance(int[] lengths)
  203. {
  204. if (type != FieldType.Array)
  205. throw new Exception("Attempting to retrieve array information from a field that doesn't contain an array.");
  206. return Internal_CreateManagedArrayInstance(mCachedPtr, lengths);
  207. }
  208. /// <summary>
  209. /// Creates a new instance of the list wrapped by this property. Caller must ensure this property contains a list.
  210. /// </summary>
  211. /// <param name="length">Size of the list.</param>
  212. /// <returns>A new list containing the same element type as the list wrapped by this property, of
  213. /// <paramref name="length"/> size.</returns>
  214. public IList CreateListInstance(int length)
  215. {
  216. if (type != FieldType.List)
  217. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a list.");
  218. return Internal_CreateManagedListInstance(mCachedPtr, length);
  219. }
  220. /// <summary>
  221. /// Creates a new instance of the dictionary wrapped by this property. Caller must ensure this property contains
  222. /// a dictionary.
  223. /// </summary>
  224. /// <returns>A new dictionary containing the same key/value types as the dictionary wrapped by this property.
  225. /// </returns>
  226. public IDictionary CreateDictionaryInstance()
  227. {
  228. if (type != FieldType.Dictionary)
  229. throw new Exception("Attempting to retrieve array information from a field that doesn't contain a dictionary.");
  230. return Internal_CreateManagedDictionaryInstance(mCachedPtr);
  231. }
  232. /// <summary>
  233. /// Helper method used for finding child properties of the specified property, using a property path.
  234. /// <see cref="SerializableObject.FindProperty(string)"/>.
  235. /// </summary>
  236. /// <param name="pathElements">Path elements representing field names and keys to look for.</param>
  237. /// <param name="elementIdx">Index in the <paramref name="pathElements"/> array to start the search at.</param>
  238. /// <returns>Property representing the final path element, or null if not found (array index is out of range, or
  239. /// property with that path doesn't exist).</returns>
  240. internal SerializableProperty FindProperty(PropertyPathElement[] pathElements, int elementIdx)
  241. {
  242. switch (type)
  243. {
  244. case FieldType.Object:
  245. {
  246. SerializableObject childObject = GetObject();
  247. return childObject.FindProperty(pathElements, elementIdx);
  248. }
  249. case FieldType.Array:
  250. {
  251. SerializableArray childArray = GetArray();
  252. return childArray.FindProperty(pathElements, elementIdx);
  253. }
  254. case FieldType.List:
  255. {
  256. SerializableList childList = GetList();
  257. return childList.FindProperty(pathElements, elementIdx);
  258. }
  259. case FieldType.Dictionary:
  260. {
  261. SerializableDictionary childDictionary = GetDictionary();
  262. return childDictionary.FindProperty(pathElements, elementIdx);
  263. }
  264. }
  265. return null;
  266. }
  267. [MethodImpl(MethodImplOptions.InternalCall)]
  268. private static extern void Internal_CreateInstance(SerializableProperty instance, Type type);
  269. [MethodImpl(MethodImplOptions.InternalCall)]
  270. private static extern SerializableObject Internal_CreateObject(IntPtr nativeInstance, object managedInstance);
  271. [MethodImpl(MethodImplOptions.InternalCall)]
  272. private static extern SerializableArray Internal_CreateArray(IntPtr nativeInstance, object managedInstance);
  273. [MethodImpl(MethodImplOptions.InternalCall)]
  274. private static extern SerializableList Internal_CreateList(IntPtr nativeInstance, object managedInstance);
  275. [MethodImpl(MethodImplOptions.InternalCall)]
  276. private static extern SerializableDictionary Internal_CreateDictionary(IntPtr nativeInstance, object managedInstance);
  277. [MethodImpl(MethodImplOptions.InternalCall)]
  278. private static extern object Internal_CreateManagedObjectInstance(IntPtr nativeInstance);
  279. [MethodImpl(MethodImplOptions.InternalCall)]
  280. private static extern Array Internal_CreateManagedArrayInstance(IntPtr nativeInstance, int[] lengths);
  281. [MethodImpl(MethodImplOptions.InternalCall)]
  282. private static extern IList Internal_CreateManagedListInstance(IntPtr nativeInstance, int length);
  283. [MethodImpl(MethodImplOptions.InternalCall)]
  284. private static extern IDictionary Internal_CreateManagedDictionaryInstance(IntPtr nativeInstance);
  285. [MethodImpl(MethodImplOptions.InternalCall)]
  286. private static extern object Internal_CloneManagedInstance(IntPtr nativeInstance, object original);
  287. /// <summary>
  288. /// Converts a C# type into Banshee-specific serialization type.
  289. /// </summary>
  290. /// <param name="internalType">C# to convert.</param>
  291. /// <returns>Banshee-specific serialization type. Throws an exception if matching type cannot be found.</returns>
  292. public static FieldType DetermineFieldType(Type internalType)
  293. {
  294. if (!internalType.IsArray)
  295. {
  296. if (internalType == typeof (Byte))
  297. return FieldType.Int;
  298. else if (internalType == typeof (SByte))
  299. return FieldType.Int;
  300. else if (internalType == typeof (Int16))
  301. return FieldType.Int;
  302. else if (internalType == typeof (UInt16))
  303. return FieldType.Int;
  304. else if (internalType == typeof (Int32))
  305. return FieldType.Int;
  306. else if (internalType == typeof (UInt32))
  307. return FieldType.Int;
  308. else if (internalType == typeof (Int64))
  309. return FieldType.Int;
  310. else if (internalType == typeof (UInt64))
  311. return FieldType.Int;
  312. else if (internalType == typeof (bool))
  313. return FieldType.Bool;
  314. else if (internalType == typeof (float))
  315. return FieldType.Float;
  316. else if (internalType == typeof (double))
  317. return FieldType.Float;
  318. else if (internalType == typeof (string))
  319. return FieldType.String;
  320. else if (internalType == typeof (Vector2))
  321. return FieldType.Vector2;
  322. else if (internalType == typeof (Vector3))
  323. return FieldType.Vector3;
  324. else if (internalType == typeof (Vector4))
  325. return FieldType.Vector4;
  326. else if (internalType == typeof(Quaternion))
  327. return FieldType.Quaternion;
  328. else if (internalType == typeof (Color))
  329. return FieldType.Color;
  330. else if (internalType == typeof(ColorGradient))
  331. return FieldType.ColorGradient;
  332. else if (internalType == typeof(AnimationCurve))
  333. return FieldType.Curve;
  334. else if (internalType == typeof(FloatDistribution))
  335. return FieldType.FloatDistribution;
  336. else if (internalType == typeof(ColorDistribution))
  337. return FieldType.ColorDistribution;
  338. else if (internalType.IsSubclassOf(typeof (GameObject)))
  339. return FieldType.GameObjectRef;
  340. else if (internalType.IsSubclassOf(typeof (Resource)))
  341. return FieldType.Resource;
  342. else if (internalType.IsSubclassOf(typeof (RRefBase)))
  343. return FieldType.RRef;
  344. else if (internalType.IsGenericType)
  345. {
  346. Type genericType = internalType.GetGenericTypeDefinition();
  347. if (genericType == typeof (List<>))
  348. return FieldType.List;
  349. else if (genericType == typeof (Dictionary<,>))
  350. return FieldType.Dictionary;
  351. else if (genericType == typeof(RRef<>))
  352. return FieldType.RRef;
  353. // Shouldn't happen because native code should only supply us with supported types
  354. throw new Exception("Cannot determine field type. Found an unsupported generic type.");
  355. }
  356. // Otherwise the type must be an object, unless some error occurred
  357. return FieldType.Object;
  358. }
  359. return FieldType.Array;
  360. }
  361. }
  362. /** @} */
  363. }