-
Notifications
You must be signed in to change notification settings - Fork 146
/
AppEngine.cs
402 lines (342 loc) · 13.1 KB
/
AppEngine.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
#region Copyright (c) 2015 KEngine / Kelly <http://github.com/mr-kelly>, All rights reserved.
// KEngine - Toolset and framework for Unity3D
// ===================================
//
// Filename: AppEngine.cs
// Date: 2015/12/03
// Author: Kelly
// Email: 23110388@qq.com
// Github: https://github.com/mr-kelly/KEngine
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3.0 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library.
#endregion
#define USE_UGUI_FPS
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using KEngine.Table;
using UnityEngine;
using UnityEngine.UI;
namespace KEngine
{
/// <summary>
/// Entry
/// </summary>
public interface IAppEntry
{
IEnumerator OnBeforeInit();
IEnumerator OnGameStart();
}
/// <summary>
/// Cosmos Engine - Unity3D Game Develop Framework
/// </summary>
public class AppEngine : MonoBehaviour
{
public static bool IsDebugBuild { get; private set; } // cache Debug.isDebugBuild for multi thread
public bool ShowFps = false;
/// <summary>
/// To Display FPS in the Debug Mode (Debug.isDebugBuild is true)
/// </summary>
static FpsWatcher RenderWatcher { get; set; } // 帧数监听器
/// <summary>
/// In Init func has a check if the user has the write privillige
/// </summary>
public static bool IsRootUser; // 是否越狱iOS
public static AppEngine EngineInstance { get; private set; }
//private static AppVersion _appVersion = null;
/// <summary>
/// Get App Version from KEngineConfig.txt
/// </summary>
//public static AppVersion AppVersion
//{
// get
// {
// if (_appVersion == null)
// {
// var appVersionStr = GetConfig(KEngineDefaultConfigs.AppVersion);
// if (string.IsNullOrEmpty(appVersionStr))
// {
// Log.Error("Cannot find AppVersion in KEngineConfig.txt, use 1.0.0.0 as default");
// appVersionStr = "1.0.0.0.alpha.default";
// }
// _appVersion = new AppVersion(appVersionStr);
// }
// return _appVersion;
// }
//}
/// <summary>
/// Read Tab file (CEngineConfig.txt), cache to here
/// </summary>
/// <summary>
/// Modules passed from the CosmosEngine.New function. All your custom game logic modules
/// </summary>
public IList<IModuleInitable> GameModules { get; private set; }
/// <summary>
/// 是否初始化完成
/// </summary>
public bool IsInited { get; private set; }
/// <summary>
/// AppEngine must be new by static function New(xxx)!
/// This is a flag to identity whether AddComponent from Unity
/// </summary>
private bool _isNewByStatic = false;
public IAppEntry AppEntry { get; private set; }
[Obsolete("Use New(GameObject, IAppEntry, IModuleInitable[]) instead!")]
public static AppEngine New(GameObject gameObjectToAttach, IModuleInitable[] modules)
{
return New(gameObjectToAttach, null, modules);
}
/// <summary>
/// Engine entry.... all begins from here
/// </summary>
public static AppEngine New(GameObject gameObjectToAttach, IAppEntry entry, IList<IModuleInitable> modules)
{
Debuger.Assert(gameObjectToAttach != null && modules != null);
AppEngine appEngine = gameObjectToAttach.AddComponent<AppEngine>();
appEngine._isNewByStatic = true;
appEngine.GameModules = modules;
appEngine.AppEntry = entry;
return appEngine;
}
private void Awake()
{
IsDebugBuild = Debug.isDebugBuild;
ShowFps = IsDebugBuild;
if (EngineInstance != null)
{
Log.Error("Duplicated Instance Engine!!!");
}
EngineInstance = this;
Init();
}
void Start()
{
Debuger.Assert(_isNewByStatic);
}
private void Init()
{
IsRootUser = KTool.HasWriteAccessToFolder(Application.dataPath); // Root User运行时,能穿越沙盒写DataPath, 以此为依据
if (Debug.isDebugBuild)
{
Log.Info("====================================================================================");
Log.Info("Application.platform = {0}", Application.platform);
Log.Info("Application.dataPath = {0} , WritePermission: {1}", Application.dataPath, IsRootUser);
Log.Info("Application.streamingAssetsPath = {0} , WritePermission: {1}",
Application.streamingAssetsPath, KTool.HasWriteAccessToFolder(Application.streamingAssetsPath));
Log.Info("Application.persistentDataPath = {0} , WritePermission: {1}", Application.persistentDataPath,
KTool.HasWriteAccessToFolder(Application.persistentDataPath));
Log.Info("Application.temporaryCachePath = {0} , WritePermission: {1}", Application.temporaryCachePath,
KTool.HasWriteAccessToFolder(Application.temporaryCachePath));
Log.Info("Application.unityVersion = {0}", Application.unityVersion);
Log.Info("SystemInfo.deviceModel = {0}", SystemInfo.deviceModel);
Log.Info("SystemInfo.deviceUniqueIdentifier = {0}", SystemInfo.deviceUniqueIdentifier);
Log.Info("SystemInfo.graphicsDeviceVersion = {0}", SystemInfo.graphicsDeviceVersion);
Log.Info("====================================================================================");
}
StartCoroutine(DoInit());
}
/// <summary>
/// Use Coroutine to initialize the two base modules: Resource & UI
/// </summary>
private IEnumerator DoInit()
{
yield return null;
if (AppEntry != null)
yield return StartCoroutine(AppEntry.OnBeforeInit());
// if (GameModules != null)
yield return StartCoroutine(DoInitModules(GameModules));
if (AppEntry != null)
{
yield return StartCoroutine(AppEntry.OnGameStart());
}
IsInited = true;
}
private IEnumerator DoInitModules(IList<IModuleInitable> modules)
{
var startInitTime = 0f;
var startMem = 0f;
foreach (IModuleInitable initModule in modules)
{
if (Debug.isDebugBuild)
{
startInitTime = Time.time;
startMem = GC.GetTotalMemory(false);
}
yield return StartCoroutine(initModule.Init());
if (Debug.isDebugBuild)
{
var nowMem = GC.GetTotalMemory(false);
Log.Info("Init Module: #{0}# Time:{1}, DiffMem:{2}, NowMem:{3}", initModule.GetType().FullName,
Time.time - startInitTime, nowMem - startMem, nowMem);
}
}
}
#if USE_UGUI_FPS
protected virtual void Update()
#else
protected virtual void OnGUI()
#endif
{
if (ShowFps)
{
if (RenderWatcher == null)
RenderWatcher = new FpsWatcher(0.95f);
RenderWatcher.OnUIUpdate();
}
}
private static EngineConfigs _engineConfigs;
/// <summary>
/// Ensure Configs load
/// </summary>
/// <param name="forceReload"></param>
public static EngineConfigs PreloadConfigs(bool forceReload = false)
{
if (_engineConfigs != null && !forceReload)
return _engineConfigs;
string configContent = null;
if (Application.isEditor && !Application.isPlaying)
{
// prevent Resources.Load fail on Batch Mode
var filePath = "Assets/Resources/AppConfigs.txt";
if (File.Exists(filePath))
configContent = System.IO.File.ReadAllText(filePath);
}
else
{
var textAsset = Resources.Load<TextAsset>("AppConfigs");
if (textAsset != null)
configContent = textAsset.text;
}
_engineConfigs = new EngineConfigs(configContent);
return _engineConfigs;
}
/// <summary>
/// Get config from ini config file or the default ini string
/// </summary>
/// <param name="section"></param>
/// <param name="key"></param>
/// <param name="showLog"></param>
/// <returns></returns>
public static string GetConfig(string section, string key, bool showLog = true)
{
PreloadConfigs();
var value = _engineConfigs.GetConfig(section, key, false);
if (value == null)
{
if (showLog)
Log.Error("Cannot get config, section: {0}, key: {1}", section, key);
}
return value;
}
public static string GetConfig(KEngineDefaultConfigs cfg)
{
return GetConfig("KEngine", cfg.ToString());
}
}
public enum KEngineDefaultConfigs
{
AssetBundleExt,
ProductRelPath,
AssetBundleBuildRelPath, // FromRelPath
StreamingBundlesFolderName,
// StreamingAssets inner folder name, when build, will link the Bundle build Path to here
}
class FpsWatcher
{
private float Value;
private float Sensitivity;
private string _cacheMemoryStr;
private string _cacheFPSStr;
#if USE_UGUI_FPS
private Text CacheText;
#endif
public FpsWatcher(float sensitivity)
{
Value = 0f;
Sensitivity = sensitivity;
#if USE_UGUI_FPS
var canvasGameObj = new GameObject("__FPSCanvas__").AddComponent<Canvas>();
canvasGameObj.renderMode = RenderMode.ScreenSpaceOverlay;
var fpsTextObj = new GameObject("FPSText").AddComponent<Text>();
fpsTextObj.transform.SetParent(canvasGameObj.transform);
fpsTextObj.rectTransform.pivot = new Vector2(0, 1);
fpsTextObj.rectTransform.localPosition = Vector3.zero;
fpsTextObj.rectTransform.anchorMin = new Vector2(0, 1);
fpsTextObj.rectTransform.anchorMax = new Vector2(0, 1);
fpsTextObj.rectTransform.sizeDelta = new Vector2(300, 100);
var font = Resources.GetBuiltinResource<Font>("Arial.ttf");
fpsTextObj.font = font;
CacheText = fpsTextObj;
#endif
}
public void OnUIUpdate()
{
if (Time.frameCount % 30 == 0 || _cacheMemoryStr == null || _cacheFPSStr == null)
{
_cacheMemoryStr = string.Format("Memory: {0:F3}KB",
#if UNITY_5_5
UnityEngine.Profiling.Profiler.GetMonoUsedSize() / 1024f
#else
UnityEngine.Profiler.GetMonoUsedSize() / 1024f
#endif
);
_cacheFPSStr = Watch("FPS: {0:N0}", 1f / Time.deltaTime);
#if USE_UGUI_FPS
if (CacheText == null) return;
CacheText.text = _cacheMemoryStr + "\n" + _cacheFPSStr;
#endif
}
#if !USE_UGUI_FPS
// Must run in OnGUI
GUILayout.BeginVertical(GUILayout.Width(300));
GUILayout.Label(_cacheMemoryStr);
GUILayout.Label(_cacheFPSStr);
GUILayout.EndVertical();
#endif
}
public string Watch(string format, float value)
{
Value = Value * Sensitivity + value * (1f - Sensitivity);
return string.Format(format, Value);
}
}
/// <summary>
/// Engine Config, Wrapper of the TableRow
/// </summary>
public class KEngineInfo
{
private static KEngineInfo _instance;
public static KEngineInfo Wrap(TableRow row)
{
if (_instance == null)
_instance = new KEngineInfo();
_instance._row = row;
return _instance;
}
private TableRow _row;
private KEngineInfo()
{
}
public string Key
{
get { return _row["Key"]; }
}
public string Value
{
get { return _row["Value"]; }
set { _row["Value"] = value; }
}
}
}