forked from ZelimDamian/frame3Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FPlatform.cs
567 lines (426 loc) · 19.5 KB
/
FPlatform.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using g3;
using UnityEngine;
namespace f3
{
public class FPlatform
{
static public int GetLayerID(string sLayerName)
{
return LayerMask.NameToLayer(sLayerName);
}
static public int GeometryLayer { get { return GetLayerID(SceneGraphConfig.GeometryLayerName); } }
static public int WidgetOverlayLayer { get { return GetLayerID(SceneGraphConfig.WidgetOverlayLayerName); } }
static public int HUDLayer { get { return GetLayerID(SceneGraphConfig.HUDLayerName); } }
static public int UILayer { get { return GetLayerID(SceneGraphConfig.UILayerName); } }
static public int CursorLayer { get { return GetLayerID(SceneGraphConfig.CursorLayerName); } }
// these should probably be accessors? Initialized by CameraTracking right now...
static public fCamera MainCamera;
static public fCamera WidgetCamera;
static public fCamera HUDCamera;
static public fCamera OrthoUICamera;
static public fCamera CursorCamera;
// argh unity can't even return paths to background thread?!?
static string app_dataPath = null;
static string persistent_dataPath = null;
static string temp_dataPath = null;
/// <summary>
/// returns path to xyz_Data\ in builds, and path to Assets\ in editor
/// </summary>
public static string GameDataFolderPath() {
if (app_dataPath == null)
app_dataPath = Path.GetFullPath(Application.dataPath);
return app_dataPath;
}
public static string PersistentDataPath() {
if (persistent_dataPath == null)
persistent_dataPath = Path.GetFullPath(Application.persistentDataPath);
return persistent_dataPath;
}
public static string TemporaryDataPath() {
if (temp_dataPath == null)
temp_dataPath = Path.GetFullPath(Application.temporaryCachePath);
return temp_dataPath;
}
public static string GameExecutablePath() {
return Path.GetFullPath(Path.Combine(GameDataFolderPath(), ".."));
}
private static float _last_realtime = 0;
/// <summary> Return clock time since start of program. Can only be called from main thread !! </summary>
static public float RealTime()
{
_last_realtime = Time.realtimeSinceStartup;
return _last_realtime;
}
/// <summary> Return last requested RealTime() - can be called from any thread, but may be out-of-date</summary>
static public float SafeRealTime()
{
return _last_realtime;
}
static private int frame_counter = 0;
static public int FrameCounter()
{
return frame_counter;
}
static internal void IncrementFrameCounter()
{
frame_counter++;
}
static public int ScreenWidth {
get { return Screen.width; }
}
static public int ScreenHeight {
get { return Screen.height; }
}
static public float ScreenDPI {
get { return (Screen.dpi == 0) ? 96 : Screen.dpi; }
}
// multiplier on Cockpit.GetPixelScale() applied when *not* running in editor.
static public float PixelScaleFactor = 1.0f;
// multiplier on Cockpit.GetPixelScale() applied when running in editor.
static public float EditorPixelScaleFactor = 1.0f;
// argh unity does not have a window resize event built-in ?!??
static private int window_width = -1, window_height = -1;
//static private int startup_height = -1;
static public bool IsWindowResized()
{
if ( window_width == -1 || window_height == -1 ) {
window_height = Screen.height;
window_width = Screen.width;
//startup_height = window_height;
return false;
}
if ( window_height != Screen.height || window_width != Screen.width ) {
window_height = Screen.height;
window_width = Screen.width;
return true;
}
return false;
}
// [RMS] Cockpit uses this to clamp screen-size used for PixelScale. Set to
// larger min / smaller max to prevent crazy huge/tiny UI.
static Interval1i valid_screen_dim_range = new Interval1i(512, 8096);
static public Interval1i ValidScreenDimensionRange
{
get { return valid_screen_dim_range; }
set { valid_screen_dim_range = value; }
}
static private bool _in_unity_editor = Application.isEditor;
static public bool InUnityEditor()
{
return _in_unity_editor;
}
[Flags]
public enum fDeviceType {
WindowsDesktop = 1,
WindowsVR = 2,
OSXDesktop = 4,
IPhone = 8,
IPad = 16,
AndroidPhone = 32
}
static public fDeviceType GetDeviceType()
{
#if UNITY_IOS
switch( UnityEngine.iOS.Device.generation ) {
case UnityEngine.iOS.DeviceGeneration.iPad1Gen:
case UnityEngine.iOS.DeviceGeneration.iPad2Gen:
case UnityEngine.iOS.DeviceGeneration.iPad3Gen:
case UnityEngine.iOS.DeviceGeneration.iPad4Gen:
//case UnityEngine.iOS.DeviceGeneration.iPad5Gen: // same as iPadAir1 ?
case UnityEngine.iOS.DeviceGeneration.iPadAir1:
case UnityEngine.iOS.DeviceGeneration.iPadAir2:
case UnityEngine.iOS.DeviceGeneration.iPadMini1Gen:
case UnityEngine.iOS.DeviceGeneration.iPadMini2Gen:
case UnityEngine.iOS.DeviceGeneration.iPadMini3Gen:
case UnityEngine.iOS.DeviceGeneration.iPadMini4Gen:
case UnityEngine.iOS.DeviceGeneration.iPadPro1Gen:
case UnityEngine.iOS.DeviceGeneration.iPadPro10Inch1Gen:
case UnityEngine.iOS.DeviceGeneration.iPadUnknown:
return fDeviceType.IPad;
default:
return fDeviceType.IPhone;
}
#elif UNITY_ANDROID
return fDeviceType.AndroidPhone;
#elif UNITY_STANDALONE_WIN
return IsUsingVR() ? fDeviceType.WindowsVR : fDeviceType.WindowsDesktop;
#elif UNITY_STANDALONE_OSX
return fDeviceType.OSXDesktop;
#else
throw new NotSupportedException("FPlatform.GetDeviceType: unknown device type");
#endif
}
public static bool IsMobile() {
return (GetDeviceType() & (fDeviceType.IPad | fDeviceType.IPhone | fDeviceType.AndroidPhone)) != 0 ;
}
static public bool IsUsingVR()
{
return UnityEngine.XR.XRSettings.enabled;
//return UnityEngine.VR.VRSettings.isDeviceActive;
}
static public bool IsTouchDevice()
{
#if UNITY_EDITOR
if ( UnityEditor.EditorApplication.isRemoteConnected )
return true;
#endif
return (Application.platform == RuntimePlatform.IPhonePlayer
|| Application.platform == RuntimePlatform.Android );
}
static Thread _main_thread;
static public void InitializeMainThreadID()
{
_main_thread = Thread.CurrentThread;
// for some stupid reason Unity cannot return these paths in background threads, so we have to cache
GameDataFolderPath();
PersistentDataPath();
TemporaryDataPath();
}
static public bool InMainThread()
{
if (_main_thread == null)
throw new Exception("FPlatform.InMainThread: Must call InitializeMainThreadID() first!!");
return Thread.CurrentThread == _main_thread;
}
public interface CoroutineExecutor
{
void StartAnonymousCoroutine(IEnumerator routine);
}
/// <summary>
/// Global object you can use at any time to start a Coroutine. Generally set to
/// active BaseSceneConfig
/// </summary>
static public CoroutineExecutor CoroutineExec {
get {
if (coroutine_exec == null)
throw new Exception("FPlatform.CoroutineExec is null! Probably need to call BaseSceneConfig.Awake().");
return coroutine_exec;
}
set { coroutine_exec = value; }
}
static CoroutineExecutor coroutine_exec;
static public System.IntPtr GetWindowHandle()
{
#if UNITY_STANDALONE_WIN
return GetActiveWindow();
#else
return System.IntPtr.Zero;
#endif
}
static public void SetWindowTitle(string text)
{
#if UNITY_STANDALONE_WIN
IntPtr winPtr = GetActiveWindow();
if (winPtr != IntPtr.Zero)
SetWindowText(winPtr, text);
#else
#endif
}
// background threads should kill themselves if this ever becomes true...
static public bool ShutdownBackgroundThreadsOnQuit = false;
static public void QuitApplication() {
Cursor.lockState = CursorLockMode.None;
ShutdownBackgroundThreadsOnQuit = true;
Application.Quit();
}
static public void SuggestGarbageCollection()
{
// [RMS] collective wisdom is that the GC is smart enough that we should never do this,
// except if we *know* many objects just became invalid. Like, when we clear the scene.
// Comment out the call to disable this behavior.
GC.Collect();
}
static public bool ShowingExternalPopup = false;
/// <summary>
/// Show an open-file dialog and with the provided file types.
/// Returns path to selected file, or null if Cancel is clicked.
/// Uses system file dialog, via tinyfiledialogs.
/// filterPatterns specified like this: new string[] { "*.stl", "*.obj" }
/// Note that tinyfiledialogs does not support multiple save-types in save dialog
/// </summary>
[System.Obsolete("This blocks Unity main thread and in 2017.3 this causes disasters. Use GetOpenFileName_Async() instead.")]
static public string GetOpenFileName(string sDialogTitle, string sInitialPathAndFile,
string[] filterPatterns, string sPatternDesc)
{
ShowingExternalPopup = true;
#if (UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX)
// tinyfd changes CWD (?), and this makes Unity unhappy
string curDirectory = Directory.GetCurrentDirectory();
IntPtr p = tinyfd_openFileDialog(sDialogTitle, sInitialPathAndFile,
filterPatterns.Length, filterPatterns, sPatternDesc, 0);
ShowingExternalPopup = false;
try {
Directory.SetCurrentDirectory(curDirectory);
} catch (Exception) {
// [RMS] sometimes this results in an exception? I am confused...
}
if (p == IntPtr.Zero)
return null;
string s = stringFromChar(p);
return s;
#else
// [TODO] implement
return null;
#endif
}
/// <summary>
/// Show an open-file dialog and with the provided file types.
/// Returns path to selected file, or null if Cancel is clicked.
/// Uses system file dialog, via tinyfiledialogs.
/// filterPatterns specified like this: new string[] { "*.stl", "*.obj" }
/// Note that tinyfiledialogs does not support multiple save-types in save dialog
/// </summary>
static public void GetOpenFileName_Async(string sDialogTitle, string sInitialPathAndFile,
string[] filterPatterns, string sPatternDesc, Action<string> OnSelectedF, Action OnCanceledF = null )
{
#if (UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX)
ThreadPool.QueueUserWorkItem(delegate {
// tinyfd changes CWD (?), and this makes Unity unhappy
string curDirectory = Directory.GetCurrentDirectory();
IntPtr p = tinyfd_openFileDialog(sDialogTitle, sInitialPathAndFile,
filterPatterns.Length, filterPatterns, sPatternDesc, 0);
try {
Directory.SetCurrentDirectory(curDirectory);
} catch (Exception) {
// [RMS] sometimes this results in an exception? I am confused...
}
if (p == IntPtr.Zero) {
if (OnCanceledF != null)
ThreadMailbox.PostToMainThread(OnCanceledF);
return;
}
string s = stringFromChar(p);
ThreadMailbox.PostToMainThread(() => {
OnSelectedF(s);
});
});
#else
// [TODO] implement
#endif
}
/// <summary>
/// Show a save-file dialog and with the provided file types.
/// Returns path to selected file, or null if Cancel is clicked.
/// Uses system file dialog, via tinyfiledialogs.
/// filterPatterns specified like this: new string[] { "*.stl", "*.obj" }
/// Note that tinyfiledialogs does not support multiple save-types in save dialog
/// </summary>
[System.Obsolete("This blocks Unity main thread and in 2017.3 this causes disasters. Use GetSaveFileName_Async() instead.")]
static public string GetSaveFileName(string sDialogTitle, string sInitialPathAndFile,
string[] filterPatterns, string sPatternDesc)
{
ShowingExternalPopup = true;
#if (UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX)
// tinyfd changes CWD (?), and this makes Unity unhappy
string curDirectory = Directory.GetCurrentDirectory();
IntPtr p = tinyfd_saveFileDialog(sDialogTitle, sInitialPathAndFile,
filterPatterns.Length, filterPatterns, sPatternDesc);
ShowingExternalPopup = false;
try {
Directory.SetCurrentDirectory(curDirectory);
} catch ( Exception ) {
// [RMS] sometimes this results in an exception? I am confused...
}
if (p == IntPtr.Zero)
return null;
string s = stringFromChar(p);
return s;
#else
// [TODO] implement
return null;
#endif
}
/// <summary>
/// Show a save-file dialog and with the provided file types.
/// Returns path to selected file, or null if Cancel is clicked.
/// Uses system file dialog, via tinyfiledialogs.
/// filterPatterns specified like this: new string[] { "*.stl", "*.obj" }
/// Note that tinyfiledialogs does not support multiple save-types in save dialog
/// </summary>
static public void GetSaveFileName_Async(string sDialogTitle, string sInitialPathAndFile,
string[] filterPatterns, string sPatternDesc, Action<string> OnSelectedF, Action OnCanceledF = null)
{
#if (UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX)
ThreadPool.QueueUserWorkItem(delegate {
// tinyfd changes CWD (?), and this makes Unity unhappy
string curDirectory = Directory.GetCurrentDirectory();
IntPtr p = tinyfd_saveFileDialog(sDialogTitle, sInitialPathAndFile,
filterPatterns.Length, filterPatterns, sPatternDesc);
try {
Directory.SetCurrentDirectory(curDirectory);
} catch (Exception) {
// [RMS] sometimes this results in an exception? I am confused...
}
if (p == IntPtr.Zero) {
if (OnCanceledF != null)
ThreadMailbox.PostToMainThread(OnCanceledF);
return;
}
string s = stringFromChar(p);
ThreadMailbox.PostToMainThread(() => {
OnSelectedF(s);
});
});
#else
// [TODO] implement
#endif
}
// platform-specific interop functions
#if UNITY_STANDALONE_WIN
[DllImport("user32.dll")]
private static extern System.IntPtr GetActiveWindow();
[DllImport("user32.dll", EntryPoint = "SetWindowText")]
public static extern bool SetWindowText(System.IntPtr hwnd, System.String lpString);
[DllImport("user32.dll", EntryPoint = "FindWindow")]
public static extern System.IntPtr FindWindow(System.String className, System.String windowName);
#endif
#if (UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX)
// NOTE: tinyfiledialogs is compiled with a flag that means it should output UTF8.
// However, seems like it only works if I interpret result with Marshal.PtrToStringAnsi()... ??
[DllImport("tinyfiledialogs", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tinyfd_inputBox(string aTitle, string aMessage, string aDefaultInput);
//IntPtr lulu = tinyfd_inputBox("input box", "gimme a string", "lolo");
[DllImport("tinyfiledialogs", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tinyfd_openFileDialog(string aTitle, string aDefaultPathAndFile, int aNumOfFilterPatterns, string[] aFilterPatterns, string aSingleFilterDescription, int aAllowMultipleSelects);
//IntPtr p = tinyfd_openFileDialog("select a mesh file", "c:\\scratch\\", 2, new string[] { "*.stl", "*.obj" }, "mesh files", 0);
[DllImport("tinyfiledialogs", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr tinyfd_saveFileDialog(string aTitle, string aDefaultPathAndFile, int aNumOfFilterPatterns, string[] aFilterPatterns, string aSingleFilterDescription);
//IntPtr p = tinyfd_openFileDialog("select a mesh file", "c:\\scratch\\default.stl", 2, new string[] { "*.stl", "*.obj" }, "mesh files", 0);
#endif
private static string stringFromChar(IntPtr ptr) {
return Marshal.PtrToStringAnsi(ptr);
}
/*
* Preferences API wrapper
*/
public static void DeletePrefsKey(string key) {
PlayerPrefs.DeleteKey(key);
}
public static bool HasPrefsKey(string key) {
return PlayerPrefs.HasKey(key);
}
public static float GetPrefsFloat(string key, float defaultValue) {
return PlayerPrefs.GetFloat(key, defaultValue);
}
public static int GetPrefsInt(string key, int defaultValue) {
return PlayerPrefs.GetInt(key, defaultValue);
}
public static string GetPrefsString(string key, string defaultValue) {
return PlayerPrefs.GetString(key, defaultValue);
}
public static void SetPrefsFloat(string key, float value) {
PlayerPrefs.SetFloat(key, value); PlayerPrefs.Save();
}
public static void SetPrefsInt(string key, int value) {
PlayerPrefs.SetInt(key, value); PlayerPrefs.Save();
}
public static void SetPrefsString(string key, string value) {
PlayerPrefs.SetString(key, value); PlayerPrefs.Save();
}
}
}