Application.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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 TaskCompletionSource<bool> exitTask;
  25. static int renderThreadId = -1;
  26. List<Action> actionsToDispatch = new List<Action>();
  27. static List<Action> staticActionsToDispatch;
  28. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  29. public delegate void ActionIntPtr (IntPtr value);
  30. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  31. static extern IntPtr ApplicationProxy_ApplicationProxy (IntPtr contextHandle, ActionIntPtr setup, ActionIntPtr start, ActionIntPtr stop, string args, IntPtr externalWindow);
  32. static Application current;
  33. public static Application Current
  34. {
  35. get
  36. {
  37. if (current == null)
  38. throw new InvalidOperationException("The application is not configured yet");
  39. return current;
  40. }
  41. private set { current = value; }
  42. }
  43. public static bool HasCurrent => current != null;
  44. static Context currentContext;
  45. public static Context CurrentContext
  46. {
  47. get
  48. {
  49. if (currentContext == null)
  50. throw new InvalidOperationException("The application is not configured yet");
  51. return currentContext;
  52. }
  53. private set { currentContext = value; }
  54. }
  55. public Application(ApplicationOptions options) : this(new Context(), options) {}
  56. Application (Context context, ApplicationOptions options = null) : base (UrhoObjectFlag.Empty)
  57. {
  58. if (context == null)
  59. throw new ArgumentNullException (nameof(context));
  60. //keep references to callbacks (supposed to be passed to native code) as long as the App is alive
  61. setupCallback = ProxySetup;
  62. startCallback = ProxyStart;
  63. stopCallback = ProxyStop;
  64. #if !ANDROID
  65. if (context.Refs() < 1)
  66. context.AddRef();
  67. #endif
  68. Options = options ?? new ApplicationOptions(assetsFolder: null);
  69. handle = ApplicationProxy_ApplicationProxy (context.Handle, setupCallback, startCallback, stopCallback, Options.ToString(), Options.ExternalWindow);
  70. Runtime.RegisterObject (this);
  71. }
  72. public bool IsClosed { get; private set; }
  73. public IntPtr Handle => handle;
  74. public IUrhoSurface UrhoSurface { get; internal set; }
  75. /// <summary>
  76. /// Application options
  77. /// </summary>
  78. public ApplicationOptions Options { get; private set; }
  79. /// <summary>
  80. /// Frame update event
  81. /// </summary>
  82. public event Action<UpdateEventArgs> Update;
  83. /// <summary>
  84. /// Invoke actions in the Main Thread (the next Update call)
  85. /// </summary>
  86. public static void InvokeOnMain(Action action)
  87. {
  88. if (!HasCurrent)
  89. {
  90. Urho.IO.Log.Write(LogLevel.Warning, "InvokeOnMain was invoked before an Application was initialized.");
  91. if (staticActionsToDispatch == null)
  92. staticActionsToDispatch = new List<Action>();
  93. lock (staticActionsToDispatch)
  94. staticActionsToDispatch.Add(action);
  95. return;
  96. }
  97. var actions = Current.actionsToDispatch;
  98. lock (actions)
  99. {
  100. actions.Add(action);
  101. }
  102. }
  103. /// <summary>
  104. /// Yield a frame
  105. /// </summary>
  106. public Task YieldFrame() => InvokeOnMainAsync(null);
  107. /// <summary>
  108. /// Invoke actions in the Main Thread (the next Update call)
  109. /// </summary>
  110. public static Task InvokeOnMainAsync(Action action)
  111. {
  112. var tcs = new TaskCompletionSource<bool>();
  113. InvokeOnMain(() =>
  114. {
  115. action?.Invoke();
  116. tcs.TrySetResult(true);
  117. });
  118. return tcs.Task;
  119. }
  120. static Application GetApp(IntPtr h) => Runtime.LookupObject<Application>(h);
  121. void HandleUpdate(UpdateEventArgs args)
  122. {
  123. var timeStep = args.TimeStep;
  124. Update?.Invoke(args);
  125. ActionManager.Update(timeStep);
  126. OnUpdate(timeStep);
  127. if (staticActionsToDispatch != null)
  128. {
  129. lock (staticActionsToDispatch)
  130. foreach (var action in staticActionsToDispatch)
  131. action();
  132. staticActionsToDispatch = null;
  133. }
  134. if (actionsToDispatch.Count > 0)
  135. {
  136. lock (actionsToDispatch)
  137. {
  138. foreach (var action in actionsToDispatch)
  139. action();
  140. actionsToDispatch.Clear();
  141. }
  142. }
  143. }
  144. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  145. static void ProxySetup (IntPtr h)
  146. {
  147. Runtime.Setup();
  148. Current = GetApp(h);
  149. CurrentContext = Current.Context;
  150. Current.Setup ();
  151. }
  152. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  153. static void ProxyStart (IntPtr h)
  154. {
  155. Runtime.Start();
  156. Current = GetApp(h);
  157. Current.SubscribeToAppEvents();
  158. Current.Start();
  159. Started?.Invoke();
  160. #if ANDROID
  161. renderThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
  162. #endif
  163. }
  164. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  165. static async void ProxyStop (IntPtr h)
  166. {
  167. LogSharp.Debug("ProxyStop");
  168. UrhoPlatformInitializer.Initialized = false;
  169. var context = Current.Context;
  170. var app = GetApp (h);
  171. app.IsClosed = true;
  172. app.UnsubscribeFromAppEvents();
  173. app.Stop ();
  174. LogSharp.Debug("ProxyStop: Runtime.Cleanup");
  175. Runtime.Cleanup();
  176. LogSharp.Debug("ProxyStop: Disposing context");
  177. context.Dispose();
  178. Current = null;
  179. Stoped?.Invoke();
  180. LogSharp.Debug("ProxyStop: end");
  181. exitTask?.TrySetResult(true);
  182. }
  183. Subscription updateSubscription = null;
  184. void SubscribeToAppEvents()
  185. {
  186. updateSubscription = Engine.SubscribeToUpdate(HandleUpdate);
  187. }
  188. void UnsubscribeFromAppEvents()
  189. {
  190. updateSubscription?.Unsubscribe();
  191. }
  192. internal static async Task StopCurrent()
  193. {
  194. if (current == null)
  195. return;
  196. #if WINDOWS_UWP && !UWP_HOLO
  197. UWP.UrhoSurface.StopRendering().Wait();
  198. #endif
  199. #if ANDROID
  200. if (Current.UrhoSurface?.IsAlive == false)
  201. {
  202. Current.Engine.Exit();
  203. }
  204. else if (System.Threading.Thread.CurrentThread.ManagedThreadId != renderThreadId)
  205. {
  206. exitTask = new TaskCompletionSource<bool>();
  207. InvokeOnMainAsync(() => Current.Engine.Exit()).Wait();
  208. Current.UrhoSurface?.Remove();
  209. Current.UrhoSurface = null;
  210. await exitTask.Task;//.Wait();
  211. }
  212. else
  213. {
  214. Current.Engine.Exit();
  215. new Android.OS.Handler(Android.OS.Looper.MainLooper).PostAtFrontOfQueue(() => {
  216. Current.UrhoSurface?.Remove();
  217. Current.UrhoSurface = null;
  218. });
  219. }
  220. #else
  221. Current.Engine.Exit ();
  222. #endif
  223. #if IOS || WINDOWS_UWP
  224. ProxyStop(Current.Handle);
  225. #endif
  226. }
  227. public bool IsExiting => Runtime.IsClosing || Engine.Exiting;
  228. public Task Exit()
  229. {
  230. if (IsClosed)
  231. return Task.FromResult<object>(null);
  232. IsClosed = true;
  233. return StopCurrent();
  234. }
  235. protected override bool AllowNativeDelete => false;
  236. protected virtual void Setup () {}
  237. public static event Action Started;
  238. protected virtual void Start () {}
  239. public static event Action Stoped;
  240. protected virtual void Stop () {}
  241. protected virtual void OnUpdate(float timeStep) { }
  242. internal ActionManager ActionManager { get; } = new ActionManager();
  243. [DllImport(Consts.NativeImport, EntryPoint = "Urho_GetPlatform", CallingConvention = CallingConvention.Cdecl)]
  244. static extern IntPtr GetPlatform();
  245. static Platforms platform;
  246. public static Platforms Platform {
  247. get
  248. {
  249. Runtime.Validate(typeof(Application));
  250. if (platform == Platforms.Unknown)
  251. platform = PlatformsMap.FromString(Marshal.PtrToStringAnsi(GetPlatform()));
  252. return platform;
  253. }
  254. }
  255. //
  256. // GetSubsystem helpers
  257. //
  258. ResourceCache resourceCache;
  259. public ResourceCache ResourceCache {
  260. get
  261. {
  262. Runtime.Validate(typeof(Application));
  263. if (resourceCache == null)
  264. resourceCache = new ResourceCache (UrhoObject_GetSubsystem (handle, ResourceCache.TypeStatic.Code));
  265. return resourceCache;
  266. }
  267. }
  268. UrhoConsole console;
  269. public UrhoConsole Console {
  270. get
  271. {
  272. Runtime.Validate(typeof(Application));
  273. if (console == null)
  274. console = new UrhoConsole (UrhoObject_GetSubsystem (handle, UrhoConsole.TypeStatic.Code));
  275. return console;
  276. }
  277. }
  278. Urho.Network.Network network;
  279. public Urho.Network.Network Network {
  280. get
  281. {
  282. Runtime.Validate(typeof(Application));
  283. if (network == null)
  284. network = new Urho.Network.Network (UrhoObject_GetSubsystem (handle, Urho.Network.Network.TypeStatic.Code));
  285. return network;
  286. }
  287. }
  288. Time time;
  289. public Time Time {
  290. get
  291. {
  292. Runtime.Validate(typeof(Application));
  293. if (time == null)
  294. time = new Time (UrhoObject_GetSubsystem (handle, Time.TypeStatic.Code));
  295. return time;
  296. }
  297. }
  298. WorkQueue workQueue;
  299. public WorkQueue WorkQueue {
  300. get
  301. {
  302. Runtime.Validate(typeof(Application));
  303. if (workQueue == null)
  304. workQueue = new WorkQueue (UrhoObject_GetSubsystem (handle, WorkQueue.TypeStatic.Code));
  305. return workQueue;
  306. }
  307. }
  308. Profiler profiler;
  309. public Profiler Profiler {
  310. get
  311. {
  312. Runtime.Validate(typeof(Application));
  313. if (profiler == null)
  314. profiler = new Profiler (UrhoObject_GetSubsystem (handle, Profiler.TypeStatic.Code));
  315. return profiler;
  316. }
  317. }
  318. FileSystem fileSystem;
  319. public FileSystem FileSystem {
  320. get
  321. {
  322. Runtime.Validate(typeof(Application));
  323. if (fileSystem == null)
  324. fileSystem = new FileSystem (UrhoObject_GetSubsystem (handle, FileSystem.TypeStatic.Code));
  325. return fileSystem;
  326. }
  327. }
  328. Log log;
  329. public Log Log {
  330. get
  331. {
  332. Runtime.Validate(typeof(Application));
  333. if (log == null)
  334. log = new Log (UrhoObject_GetSubsystem (handle, Log.TypeStatic.Code));
  335. return log;
  336. }
  337. }
  338. Input input;
  339. public Input Input {
  340. get
  341. {
  342. Runtime.Validate(typeof(Application));
  343. if (input == null)
  344. input = new Input (UrhoObject_GetSubsystem (handle, Input.TypeStatic.Code));
  345. return input;
  346. }
  347. }
  348. Urho.Audio.Audio audio;
  349. public Urho.Audio.Audio Audio {
  350. get
  351. {
  352. Runtime.Validate(typeof(Application));
  353. if (audio == null)
  354. audio = new Audio.Audio (UrhoObject_GetSubsystem (handle, Urho.Audio.Audio.TypeStatic.Code));
  355. return audio;
  356. }
  357. }
  358. UI uI;
  359. public UI UI {
  360. get
  361. {
  362. Runtime.Validate(typeof(Application));
  363. if (uI == null)
  364. uI = new UI (UrhoObject_GetSubsystem (handle, UI.TypeStatic.Code));
  365. return uI;
  366. }
  367. }
  368. Graphics graphics;
  369. public Graphics Graphics {
  370. get
  371. {
  372. Runtime.Validate(typeof(Application));
  373. if (graphics == null)
  374. graphics = new Graphics (UrhoObject_GetSubsystem (handle, Graphics.TypeStatic.Code));
  375. return graphics;
  376. }
  377. }
  378. Renderer renderer;
  379. public Renderer Renderer {
  380. get
  381. {
  382. Runtime.Validate(typeof(Application));
  383. if (renderer == null)
  384. renderer = new Renderer (UrhoObject_GetSubsystem (handle, Renderer.TypeStatic.Code));
  385. return renderer;
  386. }
  387. }
  388. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  389. extern static IntPtr Application_GetEngine (IntPtr handle);
  390. Engine engine;
  391. public Engine Engine {
  392. get
  393. {
  394. if (engine == null)
  395. engine = new Engine (Application_GetEngine (handle));
  396. return engine;
  397. }
  398. }
  399. public static T CreateInstance<T>(ApplicationOptions options = null) where T : Application
  400. {
  401. return (T)CreateInstance(typeof (T), options);
  402. }
  403. public static Application CreateInstance(Type applicationType, ApplicationOptions options = null)
  404. {
  405. try
  406. {
  407. return (Application)Activator.CreateInstance(applicationType, options);
  408. }
  409. catch (Exception exc)
  410. {
  411. throw new InvalidOperationException($"Constructor {applicationType}(ApplicationOptions) was not found.", exc);
  412. }
  413. }
  414. }
  415. public interface IUrhoSurface
  416. {
  417. void Remove();
  418. bool IsAlive { get; }
  419. }
  420. }