ComponentCore.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using System.Reflection;
  5. namespace AtomicEngine
  6. {
  7. internal enum CSComponentMethod
  8. {
  9. Start,
  10. DelayedStart,
  11. Update,
  12. PostUpdate,
  13. FixedUpdate,
  14. PostFixedUpdate
  15. };
  16. static internal class ComponentCore
  17. {
  18. static Dictionary<String, Type> componentTypes = new Dictionary<String, Type>();
  19. static Dictionary<uint, GCHandle> liveComponents = new Dictionary<uint, GCHandle>();
  20. static uint idGen = 1;
  21. public static IntPtr CurrentCSComponentNativeInstance = default(IntPtr);
  22. public static void CallComponentMethod(uint componentID, CSComponentMethod method, float value)
  23. {
  24. GCHandle handle;
  25. if (liveComponents.TryGetValue (componentID, out handle)) {
  26. var component = (CSComponent)handle.Target;
  27. switch (method) {
  28. case CSComponentMethod.Update:
  29. component.Update (value);
  30. break;
  31. }
  32. }
  33. }
  34. public static void RegisterCSComponent(CSComponent component)
  35. {
  36. // keep the instance from being GC'd as it may be referenced solely in native code
  37. // attached to a node
  38. GCHandle handle = GCHandle.Alloc (component);
  39. // register
  40. liveComponents [idGen] = handle;
  41. component.SetManagedID (idGen);
  42. idGen++;
  43. }
  44. // native create CSComponent
  45. public static void CreateCSComponent(string name, IntPtr nativeCSComponent)
  46. {
  47. Type type;
  48. if (componentTypes.TryGetValue (name, out type)) {
  49. // create an instance of the component type
  50. CurrentCSComponentNativeInstance = nativeCSComponent;
  51. var component = (CSComponent) Activator.CreateInstance(type);
  52. CurrentCSComponentNativeInstance = IntPtr.Zero;
  53. RegisterCSComponent (component);
  54. }
  55. }
  56. static void RegisterComponentType(Type componentType)
  57. {
  58. // TODO: Check for name clash, we don't want to use assembly qualified names, etc to keep it simple
  59. componentTypes [componentType.Name] = componentType;
  60. }
  61. public static void RegisterAssemblyComponents(Assembly assembly)
  62. {
  63. Type csComponentType = typeof(CSComponent);
  64. Type[] types = assembly.GetTypes ();
  65. List<Type> componentTypes = new List<Type> ();
  66. foreach (Type type in types)
  67. {
  68. for (var current = type.BaseType; current != null; current = current.BaseType) {
  69. if (current == csComponentType) {
  70. componentTypes.Add(type);
  71. break;
  72. }
  73. }
  74. }
  75. foreach (Type type in componentTypes) {
  76. RegisterComponentType (type);
  77. }
  78. }
  79. }
  80. }