Application.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //
  2. // Support for bubbling up to C# the virtual methods calls for Setup, Start and Stop in Application
  3. //
  4. // This is done by using an ApplicationProxy in C++ that bubbles up
  5. //
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Runtime.InteropServices;
  12. using System.Threading.Tasks;
  13. using Urho.IO;
  14. using Urho.Audio;
  15. using Urho.Resources;
  16. using Urho.Actions;
  17. using Urho.Gui;
  18. namespace Urho {
  19. public partial class Application {
  20. // references needed to prevent GC from collecting callbacks passed to native code
  21. static ActionIntPtr setupCallback;
  22. static ActionIntPtr startCallback;
  23. static ActionIntPtr stopCallback;
  24. static readonly List<Action> actionsToDipatch = new List<Action>();
  25. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  26. public delegate void ActionIntPtr (IntPtr value);
  27. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  28. static extern IntPtr ApplicationProxy_ApplicationProxy (IntPtr contextHandle, ActionIntPtr setup, ActionIntPtr start, ActionIntPtr stop, string args, IntPtr externalWindow);
  29. static Application current;
  30. public static Application Current
  31. {
  32. get
  33. {
  34. if (current == null)
  35. throw new InvalidOperationException("The application is not configured yet");
  36. return current;
  37. }
  38. private set { current = value; }
  39. }
  40. public static bool HasCurrent => current != null;
  41. static Context currentContext;
  42. public static Context CurrentContext
  43. {
  44. get
  45. {
  46. if (currentContext == null)
  47. throw new InvalidOperationException("The application is not configured yet");
  48. return currentContext;
  49. }
  50. private set { currentContext = value; }
  51. }
  52. public Application() : this(new Context(), null) {}
  53. public Application(ApplicationOptions options) : this(new Context(), options) {}
  54. /// <summary>
  55. /// Supports the simple style with callbacks
  56. /// </summary>
  57. Application (Context context, ApplicationOptions options = null) : base (UrhoObjectFlag.Empty)
  58. {
  59. if (context == null)
  60. throw new ArgumentNullException (nameof(context));
  61. if (context.Refs() < 1)
  62. context.AddRef();
  63. //keep references to callbacks (supposed to be passed to native code) as long as the App is alive
  64. setupCallback = ProxySetup;
  65. startCallback = ProxyStart;
  66. stopCallback = ProxyStop;
  67. Options = options ?? new ApplicationOptions(assetsFolder: null);
  68. handle = ApplicationProxy_ApplicationProxy (context.Handle, setupCallback, startCallback, stopCallback, Options.ToString(), Options.ExternalWindow);
  69. Runtime.RegisterObject (this);
  70. Engine.SubscribeToUpdate(HandleUpdate);
  71. }
  72. public IntPtr Handle => handle;
  73. /// <summary>
  74. /// Application options
  75. /// </summary>
  76. public ApplicationOptions Options { get; private set; }
  77. /// <summary>
  78. /// Frame update event
  79. /// </summary>
  80. public event Action<UpdateEventArgs> Update;
  81. /// <summary>
  82. /// Waits given _game_ time.
  83. /// </summary>
  84. public static Task Delay(float durationSec)
  85. {
  86. var tcs = new TaskCompletionSource<bool>();
  87. var state = Current.ActionManager.AddAction(new Sequence(new DelayTime(durationSec), new CallFunc(() => tcs.TrySetResult(true))), null);
  88. return tcs.Task;
  89. }
  90. /// <summary>
  91. /// Invoke actions in the Main Thread (the next Update call)
  92. /// </summary>
  93. public static void InvokeOnMain(Action action)
  94. {
  95. lock (actionsToDipatch)
  96. {
  97. actionsToDipatch.Add(action);
  98. }
  99. }
  100. static Application GetApp(IntPtr h) => Runtime.LookupObject<Application>(h);
  101. void HandleUpdate(UpdateEventArgs args)
  102. {
  103. var timeStep = args.TimeStep;
  104. Update?.Invoke(args);
  105. ActionManager.Update(timeStep);
  106. OnUpdate(timeStep);
  107. if (actionsToDipatch.Count > 0)
  108. {
  109. lock (actionsToDipatch)
  110. {
  111. foreach (var action in actionsToDipatch)
  112. action();
  113. actionsToDipatch.Clear();
  114. }
  115. }
  116. }
  117. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  118. static void ProxySetup (IntPtr h)
  119. {
  120. Current = GetApp(h);
  121. CurrentContext = Current.Context;
  122. Current.Setup ();
  123. }
  124. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  125. static void ProxyStart (IntPtr h)
  126. {
  127. Runtime.Initialize();
  128. GetApp (h).Start ();
  129. Started?.Invoke();
  130. }
  131. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  132. static void ProxyStop (IntPtr h)
  133. {
  134. UrhoPlatformInitializer.Initialized = false;
  135. var context = Current.Context;
  136. GetApp (h).Stop ();
  137. Runtime.Cleanup();
  138. #if !IOS && !DESKTOP
  139. if (context.Refs() > 0)
  140. context.ReleaseRef();
  141. #endif
  142. context.Dispose();
  143. Current = null;
  144. Stoped?.Invoke();
  145. }
  146. public static void StopCurrent()
  147. {
  148. Current.Engine.Exit ();
  149. #if IOS
  150. ProxyStop(Current.Handle);
  151. #endif
  152. }
  153. protected virtual void Setup () {}
  154. public static event Action Started;
  155. protected virtual void Start () {}
  156. public static event Action Stoped;
  157. protected virtual void Stop () {}
  158. protected virtual void OnUpdate(float timeStep) { }
  159. internal ActionManager ActionManager { get; } = new ActionManager();
  160. [DllImport(Consts.NativeImport, EntryPoint = "Urho_GetPlatform", CallingConvention = CallingConvention.Cdecl)]
  161. static extern IntPtr GetPlatform();
  162. static Platforms platform;
  163. public static Platforms Platform {
  164. get {
  165. if (platform == Platforms.Unknown)
  166. platform = PlatformsMap.FromString(Marshal.PtrToStringAnsi(GetPlatform()));
  167. return platform;
  168. }
  169. }
  170. //
  171. // GetSubsystem helpers
  172. //
  173. ResourceCache resourceCache;
  174. public ResourceCache ResourceCache {
  175. get {
  176. if (resourceCache == null)
  177. resourceCache = new ResourceCache (UrhoObject_GetSubsystem (handle, ResourceCache.TypeStatic.Code));
  178. return resourceCache;
  179. }
  180. }
  181. UrhoConsole console;
  182. public UrhoConsole Console {
  183. get {
  184. if (console == null)
  185. console = new UrhoConsole (UrhoObject_GetSubsystem (handle, UrhoConsole.TypeStatic.Code));
  186. return console;
  187. }
  188. }
  189. Urho.Network.Network network;
  190. public Urho.Network.Network Network {
  191. get {
  192. if (network == null)
  193. network = new Urho.Network.Network (UrhoObject_GetSubsystem (handle, Urho.Network.Network.TypeStatic.Code));
  194. return network;
  195. }
  196. }
  197. Time time;
  198. public Time Time {
  199. get {
  200. if (time == null)
  201. time = new Time (UrhoObject_GetSubsystem (handle, Time.TypeStatic.Code));
  202. return time;
  203. }
  204. }
  205. WorkQueue workQueue;
  206. public WorkQueue WorkQueue {
  207. get {
  208. if (workQueue == null)
  209. workQueue = new WorkQueue (UrhoObject_GetSubsystem (handle, WorkQueue.TypeStatic.Code));
  210. return workQueue;
  211. }
  212. }
  213. Profiler profiler;
  214. public Profiler Profiler {
  215. get {
  216. if (profiler == null)
  217. profiler = new Profiler (UrhoObject_GetSubsystem (handle, Profiler.TypeStatic.Code));
  218. return profiler;
  219. }
  220. }
  221. FileSystem fileSystem;
  222. public FileSystem FileSystem {
  223. get {
  224. if (fileSystem == null)
  225. fileSystem = new FileSystem (UrhoObject_GetSubsystem (handle, FileSystem.TypeStatic.Code));
  226. return fileSystem;
  227. }
  228. }
  229. Log log;
  230. public Log Log {
  231. get {
  232. if (log == null)
  233. log = new Log (UrhoObject_GetSubsystem (handle, Log.TypeStatic.Code));
  234. return log;
  235. }
  236. }
  237. Input input;
  238. public Input Input {
  239. get {
  240. if (input == null)
  241. input = new Input (UrhoObject_GetSubsystem (handle, Input.TypeStatic.Code));
  242. return input;
  243. }
  244. }
  245. Urho.Audio.Audio audio;
  246. public Urho.Audio.Audio Audio {
  247. get {
  248. if (audio == null)
  249. audio = new Audio.Audio (UrhoObject_GetSubsystem (handle, Urho.Audio.Audio.TypeStatic.Code));
  250. return audio;
  251. }
  252. }
  253. UI uI;
  254. public UI UI {
  255. get {
  256. if (uI == null)
  257. uI = new UI (UrhoObject_GetSubsystem (handle, UI.TypeStatic.Code));
  258. return uI;
  259. }
  260. }
  261. Graphics graphics;
  262. public Graphics Graphics {
  263. get {
  264. if (graphics == null)
  265. graphics = new Graphics (UrhoObject_GetSubsystem (handle, Graphics.TypeStatic.Code));
  266. return graphics;
  267. }
  268. }
  269. Renderer renderer;
  270. public Renderer Renderer {
  271. get {
  272. if (renderer == null)
  273. renderer = new Renderer (UrhoObject_GetSubsystem (handle, Renderer.TypeStatic.Code));
  274. return renderer;
  275. }
  276. }
  277. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  278. extern static IntPtr Application_GetEngine (IntPtr handle);
  279. Engine engine;
  280. public Engine Engine {
  281. get {
  282. if (engine == null)
  283. engine = new Engine (Application_GetEngine (handle));
  284. return engine;
  285. }
  286. }
  287. public static T CreateInstance<T>(ApplicationOptions options = null) where T : Application
  288. {
  289. return (T)CreateInstance(typeof (T), options);
  290. }
  291. public static Application CreateInstance(Type applicationType, ApplicationOptions options = null)
  292. {
  293. var ctors = applicationType.GetTypeInfo().DeclaredConstructors.ToArray();
  294. var ctorWithOptions = ctors.FirstOrDefault(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof (ApplicationOptions));
  295. if (ctorWithOptions != null)
  296. {
  297. return (Application) Activator.CreateInstance(applicationType, options);
  298. }
  299. var ctorDefault = ctors.FirstOrDefault(c => c.GetParameters().Length == 0);
  300. if (ctorDefault != null)
  301. {
  302. return (Application) Activator.CreateInstance(applicationType);
  303. }
  304. throw new InvalidOperationException($"{applicationType} doesn't have parameterless constructor.");
  305. }
  306. }
  307. }