GameLoadDll.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Net.Http;
  8. using System.Threading.Tasks;
  9. using hirdParty.DownloadSystem;
  10. using HybridCLR;
  11. using ThirdParty;
  12. using ThirdParty.DownloadSystem;
  13. using UnityEditor;
  14. using UnityEngine;
  15. public class GameLoadDll
  16. {
  17. private bool _isHadNetwork;
  18. private bool _hadEnterGame;
  19. private float _per;
  20. private float _currentProgress;
  21. private bool _isMarkClose;
  22. private readonly Dictionary<string, byte[]> _assetBytes = new Dictionary<string, byte[]>();
  23. string versionName = "versionInfo.txt";
  24. private System.Action callBack;
  25. private AssetMD5Info remoteMD5Info;
  26. private IDownloadUI _downloadUI;
  27. private string[] localVersionInfo;
  28. private GameStart gameStart;
  29. public void StartLoadDll(IDownloadUI downloadUI,GameStart gameStart, string url, System.Action callBack)
  30. {
  31. this.gameStart = gameStart;
  32. _downloadUI =downloadUI;
  33. _downloadUI.SetMassge("开始校验脚本");
  34. this.callBack = callBack;
  35. if (HotSyncContent.isOpenHotFix)
  36. {
  37. if (HotSyncContent.isOpenDllStreamingLoad)
  38. {
  39. LoadStreamingDllLoad();
  40. }
  41. else
  42. {
  43. LoadBenDiVersion();
  44. }
  45. }
  46. else
  47. {
  48. callBack?.Invoke();
  49. }
  50. }
  51. private void LoadStreamingDllLoad()
  52. {
  53. string DllMD5 = HotSyncContent.GetDllWebRequestPath("DllMD5.txt");
  54. DownloadFileData versiondownloadFileData = new DownloadFileData();
  55. versiondownloadFileData.remoteUrl = DllMD5;
  56. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  57. downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  58. {
  59. remoteMD5Info =
  60. JsonUtility.FromJson(hander.Text, typeof(AssetMD5Info)) as AssetMD5Info;
  61. LoadLoaclDll();
  62. };
  63. }
  64. private byte[] GetAssetBytes(string dllName)
  65. {
  66. if (_assetBytes.ContainsKey(dllName))
  67. {
  68. return _assetBytes[dllName];
  69. }
  70. else
  71. {
  72. Debug.Log("没有找到dll数据" + dllName);
  73. return new byte[] { };
  74. }
  75. }
  76. // private void LoadVersion()
  77. // {
  78. // string md5Name = "DllMD5.txt";
  79. // string versionInfoUrl = ($"{HotSyncContent.AssetURL}/{HotSyncContent.platform}/{versionName}");
  80. // DownloadFileData versiondownloadFileData = new DownloadFileData();
  81. // versiondownloadFileData.remoteUrl = versionInfoUrl;
  82. // DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  83. // downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  84. // {
  85. // string[] remoteVersionInfo = hander.Text.Split('\n');
  86. // string versionInfo =
  87. // $"{remoteVersionInfo[0].Split('=')[1]}.{remoteVersionInfo[1].Split('=')[1]}.{remoteVersionInfo[2].Split('=')[1]}";
  88. // HotSyncContent.Currversion = versionInfo;
  89. // if (localVersionInfo[0]!=remoteVersionInfo[0])
  90. // {
  91. // // 本地版本和远程一致也需要更新,防止散文件错误
  92. // Debug.Log("本地版本更大,不需要更新");
  93. // }
  94. // else
  95. // {
  96. // LoadMD5();
  97. // }
  98. // };
  99. // }
  100. private void LoadBenDiVersion()
  101. {
  102. string versionInfoUrl = HotSyncContent.GetWebRequestPath(versionName);
  103. DownloadFileData versiondownloadFileData = new DownloadFileData();
  104. versiondownloadFileData.remoteUrl = versionInfoUrl;
  105. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  106. downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  107. {
  108. localVersionInfo = hander.Text.Split('\n');
  109. GetAssetUrl();
  110. };
  111. }
  112. private async void GetAssetUrl()
  113. {
  114. #if UNITY_EDITOR || UNITY_STANDALONE_WIN
  115. string appSettingPath = "file://" + Application.streamingAssetsPath + "/AppSetting.txt";
  116. #elif UNITY_ANDROID
  117. string appSettingPath = Application.streamingAssetsPath + "/AppSetting.txt";
  118. #elif UNITY_IPHONE
  119. string appSettingPath = "file://"+ Application.streamingAssetsPath+"/AppSetting.txt";
  120. #else
  121. string appSettingPath = "";
  122. #endif
  123. WWW loader = new WWW(appSettingPath);
  124. while (!loader.isDone)
  125. {
  126. }
  127. if (!string.IsNullOrEmpty(loader.error))
  128. {
  129. Debug.LogError(appSettingPath);
  130. Debug.LogError(loader.error);
  131. }
  132. string url = "";
  133. string settingData = loader.text;
  134. string[] datas = settingData.Split('\n');
  135. for (int i = 0; i < datas.Length; i++)
  136. {
  137. datas[i] = datas[i].Replace("\r", "");
  138. string[] configInfo = datas[i].Split('=');
  139. if (configInfo[0].Contains("//") || configInfo.Length <= 1)
  140. {
  141. continue;
  142. }
  143. if (configInfo[0].Equals("loginServer"))
  144. {
  145. url = configInfo[1];
  146. }
  147. }
  148. url += "/client_config";
  149. LoadAsset(url, localVersionInfo[0].Split('=')[1]);
  150. }
  151. private async Task LoadAsset(string url, string v)
  152. {
  153. var replace = v.Replace("\r", "");
  154. _downloadUI.SetMassge($"等待服务器地址");
  155. Debug.Log("等待下载资源服地址" + url);
  156. Dictionary<string, string> dictionary = new Dictionary<string, string>();
  157. dictionary.Add("buildVer", replace);
  158. FormUrlEncodedContent formUrlEncodedContent = new FormUrlEncodedContent(dictionary);
  159. HttpClient httpClient = new HttpClient();
  160. httpClient.Timeout = TimeSpan.FromSeconds(5);
  161. string json = "";
  162. try
  163. {
  164. HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(url, formUrlEncodedContent);
  165. if (httpResponseMessage.StatusCode != HttpStatusCode.OK)
  166. {
  167. Debug.LogError(httpResponseMessage.RequestMessage);
  168. _downloadUI.SetMassge($"获取配置错误,正在在重新获取!");
  169. LoadAsset(url, v);
  170. return;
  171. }
  172. json = await httpResponseMessage.Content.ReadAsStringAsync();
  173. }
  174. catch (Exception e)
  175. {
  176. Debug.LogError(e);
  177. LoadAsset(url, v);
  178. return;
  179. }
  180. httpClient.Dispose();
  181. Debug.Log(json);
  182. _downloadUI.SetMassge($"地址获取成功");
  183. // UnityWebRequest webRequest = UnityWebRequest.Post(url, dictionary);
  184. // webRequest.timeout = 5;
  185. // UnityWebRequestAsyncOperation unityWebRequestAsyncOperation = webRequest.SendWebRequest();
  186. // while (!unityWebRequestAsyncOperation.isDone)
  187. // {
  188. // yield return 0;
  189. // }
  190. // if (!string.IsNullOrEmpty(webRequest.error))
  191. // {
  192. // Debug.LogError(webRequest.error);
  193. // _downloadUI.SetMassge($"获取配置错误,正在在重新获取!");
  194. // gameStart.StartCoroutine(LoadAsset(url, v));
  195. // }
  196. // string json = webRequest.downloadHandler.text;
  197. AssetUrlInfo assetUrlInfo = JsonUtility.FromJson<AssetUrlInfo>(json);
  198. HotSyncContent.AssetURL = assetUrlInfo.assetsUrl;
  199. // webRequest.Dispose();
  200. //HotSyncContent.AssetURL = "http://42.192.110.229/010";
  201. HotSyncContent.loadType = assetUrlInfo.loadType;
  202. HotSyncContent.assetsVer = assetUrlInfo.assetsVer;
  203. HotSyncContent.Currversion = $"{assetUrlInfo.apkVer}.{assetUrlInfo.buildVer}.{assetUrlInfo.assetsVer}";
  204. Debug.Log("版本号:" + HotSyncContent.Currversion);
  205. Debug.Log(HotSyncContent.Currversion + "获得的下载资源服地址" + HotSyncContent.AssetURL);
  206. if (localVersionInfo[0].Split('=')[1] != assetUrlInfo.apkVer.ToString())
  207. {
  208. Debug.Log("版本号:" + HotSyncContent.Currversion);
  209. Debug.Log(HotSyncContent.Currversion + "获得的下载资源服地址" + HotSyncContent.AssetURL);
  210. if (localVersionInfo[0].Split('=')[1] != assetUrlInfo.apkVer.ToString())
  211. {
  212. // 本地版本和远程一致也需要更新,防止散文件错误
  213. Debug.LogError("本地版本更大,不需要更新");
  214. }
  215. else
  216. {
  217. LoadMD5();
  218. }
  219. }
  220. else
  221. {
  222. LoadMD5();
  223. }
  224. // LoadVersion();
  225. // Debug.Log(assetUrlInfo.assetsUrl);
  226. }
  227. private void LoadBenDiVersion(string[] remoteVersionInfo)
  228. {
  229. string versionInfoUrl = HotSyncContent.GetWebRequestPath(versionName);
  230. DownloadFileData versiondownloadFileData = new DownloadFileData();
  231. versiondownloadFileData.remoteUrl = versionInfoUrl;
  232. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  233. downloadHander.OnFinishCallBack = delegate(DownloadHander hander) { };
  234. }
  235. private void LoadMD5()
  236. {
  237. _downloadUI.SetMassge($"资源检查中");
  238. string md5Url =
  239. $"{HotSyncContent.AssetURL}/{HotSyncContent.platform}/{HotSyncContent.Currversion}/DLL/DllMD5.txt";
  240. DownloadFileData versiondownloadFileData = new DownloadFileData();
  241. versiondownloadFileData.remoteUrl = md5Url;
  242. versiondownloadFileData.maxCount = int.MaxValue;
  243. versiondownloadFileData.timeOut = 10;
  244. DownloadHander downloadHander = FileDownloadSystem.Instance.DownloadFile(versiondownloadFileData);
  245. downloadHander.OnFinishCallBack = delegate(DownloadHander hander)
  246. {
  247. remoteMD5Info =
  248. JsonUtility.FromJson(hander.Text, typeof(AssetMD5Info)) as AssetMD5Info;
  249. if (HotSyncContent.loadType == 1)
  250. {
  251. LoadLoaclDll();
  252. }
  253. else
  254. {
  255. JianYan();
  256. }
  257. };
  258. }
  259. private void JianYan()
  260. {
  261. List<MD5FileInfo> CheckFile = new List<MD5FileInfo>();
  262. CheckFile.AddRange(remoteMD5Info.fileInfo);
  263. string rootPath = HotSyncContent.AppHotfixResPath;
  264. CheckFilePool _checkFileThrans = new CheckFilePool();
  265. _checkFileThrans.isStreamingAssetsPath = true;
  266. _checkFileThrans.streamingAssetsPath = HotSyncContent.RootStreamingURL + "/Dll/";
  267. SliderData sliderData = new SliderData();
  268. sliderData.maxValue = CheckFile.Count;
  269. _downloadUI.SetMassge($"校验本地文件");
  270. sliderData.CcurrValue = delegate
  271. {
  272. float m = _checkFileThrans.FileCount();
  273. if (_checkFileThrans.isFinish)
  274. {
  275. // _downloadUI.ClearSlider();
  276. if (_checkFileThrans.shiBaiFile != null && _checkFileThrans.shiBaiFile.Count > 0)
  277. {
  278. DownJiaoBen(_checkFileThrans.shiBaiFile);
  279. }
  280. else
  281. {
  282. LoadLoaclDll();
  283. }
  284. }
  285. else
  286. {
  287. _downloadUI.SetMassge(
  288. $"校验本地文件{m} / {sliderData.maxValue}");
  289. }
  290. return m;
  291. };
  292. // _downloadUI.SetSlider(sliderData);
  293. _checkFileThrans.Start(rootPath, CheckFile);
  294. }
  295. private void DownJiaoBen(List<MD5FileInfo> updateFlieInfo)
  296. {
  297. DownLoadHanderGroup downLoadHanderGroup = new DownLoadHanderGroup();
  298. long size = 0;
  299. for (int i = 0; i < updateFlieInfo.Count; i++)
  300. {
  301. MD5FileInfo md5FileInfo = updateFlieInfo[i];
  302. if (md5FileInfo.size <= 0)
  303. {
  304. continue;
  305. }
  306. DownloadFileData downloadFileData = new DownloadFileData();
  307. size += md5FileInfo.size;
  308. downloadFileData.remoteUrl =
  309. $"{HotSyncContent.AssetURL}/{HotSyncContent.platform}/{HotSyncContent.Currversion}/DLL/{md5FileInfo.fileName}";
  310. Debug.Log("下载文件" + downloadFileData.remoteUrl);
  311. downloadFileData.localPath = Path.Combine(HotSyncContent.AppHotfixResPath, md5FileInfo.fileName);
  312. DownloadHander fileDow = FileDownloadSystem.Instance.DownloadFile(downloadFileData);
  313. downLoadHanderGroup.AddHander(fileDow);
  314. }
  315. float sizeM = size / 1024f / 1024f;
  316. SliderData sliderData = new SliderData();
  317. sliderData.maxValue = size;
  318. _downloadUI.SetMassge($"开始下载文件,个数{updateFlieInfo.Count} 大小{sizeM}");
  319. sliderData.CcurrValue = delegate
  320. {
  321. float m = downLoadHanderGroup.size / 1024f / 1024f;
  322. float speed = downLoadHanderGroup.speed / 1024f;
  323. _downloadUI.SetMassge(
  324. $"开始下载文件,个数{updateFlieInfo.Count} 大小{m.ToString("0.00")}M / {sizeM.ToString("0.00")}M 速度{speed.ToString(".00")} Kb");
  325. return downLoadHanderGroup.size;
  326. };
  327. // _downloadUI.SetSlider(sliderData);
  328. downLoadHanderGroup.OnCallBack = JianYan;
  329. downLoadHanderGroup.StartUpdate();
  330. }
  331. private void LoadLoaclDll()
  332. {
  333. DownLoadHanderGroup downLoadHanderGroup = new DownLoadHanderGroup();
  334. for (int i = 0; i < remoteMD5Info.fileInfo.Count; i++)
  335. {
  336. MD5FileInfo md5FileInfo = remoteMD5Info.fileInfo[i];
  337. DownloadFileData downloadFileData = new DownloadFileData();
  338. downloadFileData.remoteUrl = HotSyncContent.GetDllWebRequestPath(md5FileInfo.fileName);
  339. Debug.Log("下载文件" + downloadFileData.remoteUrl);
  340. DownloadHander fileDow = FileDownloadSystem.Instance.DownloadFile(downloadFileData);
  341. fileDow.OnFinishCallBack = delegate(DownloadHander hander)
  342. {
  343. byte[] dllBytes = hander.Data;
  344. // dllBytes = DllTool.Instance.KeyDecryption(dllBytes);
  345. _assetBytes[md5FileInfo.fileName] = dllBytes;
  346. Debug.Log($"资源:{md5FileInfo.fileName} 大小:{dllBytes.Length}");
  347. HomologousImageMode mode = HomologousImageMode.SuperSet;
  348. // 加载Assembly对应的Dll,会自动为它hook。一旦AOT泛型函数的Native函数不存在,用解释器版本代码
  349. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(dllBytes, mode);
  350. Debug.Log($"LoadMetadataForAOTAssembly:{md5FileInfo.fileName}. mode:{mode} ret:{err}");
  351. };
  352. downLoadHanderGroup.AddHander(fileDow);
  353. }
  354. downLoadHanderGroup.OnCallBack = LoadDll;
  355. downLoadHanderGroup.StartUpdate();
  356. }
  357. private void LoadDll()
  358. {
  359. _downloadUI.SetMassge($"初始化资源中,请稍等");
  360. Debug.Log("开始Fort23.Proto");
  361. // System.Reflection.Assembly.Load(GetAssetBytes("Fort23.Proto.dll.bytes"));
  362. // Debug.Log("开始FMODUnity");
  363. // System.Reflection.Assembly.Load(GetAssetBytes("FMODUnity.dll.bytes"));
  364. // Debug.Log("开始FMODUnityResonance");
  365. // System.Reflection.Assembly.Load(GetAssetBytes("FMODUnityResonance.dll.bytes"));
  366. Debug.Log("开始Fort23.Core");
  367. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.Core.dll.bytes"));
  368. Debug.Log("开始BGMController");
  369. // System.Reflection.Assembly.Load(GetAssetBytes("BGMController.dll.bytes"));
  370. Debug.Log("开始Fort23.GameData");
  371. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.GameData.dll.bytes"));
  372. Debug.Log("开始Fort23.GameTimeLine");
  373. System.Reflection.Assembly.Load(GetAssetBytes("GameTimeLine.dll.bytes"));
  374. Debug.Log("开始Fort23.GameLogic");
  375. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.GameLogic.dll.bytes"));
  376. Debug.Log("开始Fort23.Mono");
  377. System.Reflection.Assembly.Load(GetAssetBytes("Fort23.Mono.dll.bytes"));
  378. // Debug.Log("spine-unity");
  379. // System.Reflection.Assembly.Load(GetAssetBytes("spine-unity.dll"));
  380. // Debug.Log("spine-timeline");
  381. // System.Reflection.Assembly.Load(GetAssetBytes("spine-timeline.dll"));
  382. Debug.Log("开始Assembly-CSharp");
  383. System.Reflection.Assembly.Load(GetAssetBytes("Assembly-CSharp.dll.bytes"));
  384. // AppDomain.CurrentDomain.GetAssemblies()
  385. // .First(assembly => assembly.GetName().Name == "Assembly-CSharp");
  386. Debug.Log("Assembly-CSharp.dll加载成功");
  387. // 2. 开始执行热更新代码逻辑,加载Init进入游戏流程
  388. Debug.Log("开始加载进入游戏");
  389. // string path = Application.persistentDataPath + "/Bundle/init";
  390. //
  391. // if (!File.Exists(path))
  392. // {
  393. // path = Application.streamingAssetsPath + "/Bundle/init";
  394. // }
  395. //
  396. // Debug.Log("path=" + path);
  397. // string[] assemblyNames =
  398. // {
  399. // "Fort23.Core.dll", "Fort23.MonoCore.dll", "Fort23.Mono.dll", "Fort23.Model.dll",
  400. // "Fort23.CommonCore.dll", "Fort23.Common.dll", "Assembly-CSharp.dll", "Fort23.UTool.dll",
  401. // "Fort23.GameData.dll", "spine-unity.dll", "spine-timeline.dll", "BGMController.dll", "Fort23.Combat.dll",
  402. // "Fort23.CombatCore.dll"
  403. // };
  404. // int addCount = 0;
  405. // foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
  406. // {
  407. // string assemblyName = $"{assembly.GetName().Name}.dll";
  408. // if (!((IList) assemblyNames).Contains(assemblyName))
  409. // {
  410. // continue;
  411. // }
  412. // Debug.Log(assemblyName);
  413. // foreach (var type in assembly.GetTypes())
  414. // {
  415. //
  416. // if ((typeof(MonoBehaviour).IsAssignableFrom(type)))
  417. // {
  418. // Debug.Log(type.Name);
  419. // var go = new GameObject();
  420. // // 我们不希望挂载到这个GameObject上的脚本执行
  421. // go.SetActive(false);
  422. // go.AddComponent(type);
  423. // GameObject.Destroy(go);
  424. // addCount++;
  425. // }
  426. // }
  427. //
  428. // }
  429. callBack?.Invoke();
  430. }
  431. }