LoadDll.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using HybridCLR;
  2. using System;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Threading.Tasks;
  9. using UnityEngine;
  10. using UnityEngine.Networking;
  11. using LitJson;
  12. using TMPro;
  13. using UnityEngine.UI;
  14. public class LoadDll : MonoBehaviour
  15. {
  16. public GameObject EditorGame;
  17. static LoadDll instance;
  18. private void Awake()
  19. {
  20. instance = this;
  21. }
  22. void Start()
  23. {
  24. this.transform.SetParent(OpenXRCamera.Instance.head.transform);
  25. this.transform.localPosition = Vector3.zero;
  26. this.transform.localEulerAngles = Vector3.zero;
  27. //PlayerPrefs.DeleteAll();
  28. #if ISLOCAL
  29. EditorGame.SetActive(true);
  30. this.gameObject.SetActive(false);
  31. #else
  32. StartCoroutine(DownLoadAssets());
  33. #endif
  34. }
  35. private static Dictionary<string, byte[]> s_assetDatas = new Dictionary<string, byte[]>();
  36. public static byte[] ReadBytesFromStreamingAssets(string dllName)
  37. {
  38. return s_assetDatas[dllName];
  39. }
  40. private string GetWebRequestPath(string asset)
  41. {
  42. var path = $"{Application.streamingAssetsPath}/{asset}";
  43. if (!path.Contains("://"))
  44. {
  45. path = "file://" + path;
  46. }
  47. return path;
  48. }
  49. private static List<string> AOTMetaAssemblyFiles { get; } = new List<string>()
  50. {
  51. "mscorlib.dll.bytes",
  52. "System.dll.bytes",
  53. "System.Core.dll.bytes",
  54. "UniTask.dll.bytes",
  55. "Minio.dll.bytes",
  56. "COSXML.dll.bytes",
  57. "System.Runtime.CompilerServices.Unsafe.dll.bytes"
  58. };
  59. public Text text;
  60. public Text text2;
  61. public Slider slider;
  62. string HotUpdateScripts = "HotUpdateScripts";
  63. string HotUpdateAssets = "HotUpdateAssets";
  64. IEnumerator DownLoadAssets()
  65. {
  66. text.text = "正在获取网关数据";
  67. for (int i = 0; i < AOTMetaAssemblyFiles.Count; i++)
  68. {
  69. yield return DownLoadLocal(AOTMetaAssemblyFiles[i]);
  70. }
  71. slider.gameObject.SetActive(false);
  72. while (HttpSDKAction.Instance.jsonData==null || HttpSDKAction.Instance.jsonData=="")
  73. {
  74. yield return null;
  75. }
  76. JsonData data = new JsonData();
  77. string scUrl = "";
  78. string artUrl = "";
  79. try
  80. {
  81. data = JsonMapper.ToObject(HttpSDKAction.Instance.jsonData);
  82. scUrl = data[HotUpdateScripts].ToString();
  83. artUrl = data[HotUpdateAssets].ToString();
  84. }
  85. catch
  86. {
  87. }
  88. if(scUrl != "")
  89. {
  90. if (!bool.Parse(data["isHotUpdate"].ToString()))
  91. {
  92. text.text = "正在下载代码";
  93. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  94. text.text = "正在下载配置";
  95. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  96. }
  97. else if (PlayerPrefs.GetString("HotUpdateVersion") == data["HotUpdateVersion"].ToString())
  98. {
  99. text.text = "正在编译代码";
  100. string filePath = PlayerPrefs.GetString(HotUpdateScripts);
  101. Task<byte[]> Tb = File.ReadAllBytesAsync(filePath);
  102. yield return Tb;
  103. slider.gameObject.SetActive(false);
  104. Assembly.Load(Tb.Result);
  105. text.text = "正在解析配置";
  106. filePath = PlayerPrefs.GetString(HotUpdateAssets);
  107. Task<byte[]> Tb2 = File.ReadAllBytesAsync(filePath);
  108. yield return Tb2;
  109. text.text = "正在解析配置";
  110. slider.gameObject.SetActive(false);
  111. AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(Tb2.Result);
  112. while (!acr.isDone)
  113. {
  114. text2.text = (acr.progress*100).ToString("F2") + "%";
  115. slider.value = float.Parse((acr.progress ).ToString("F2"));
  116. yield return null;
  117. }
  118. slider.gameObject.SetActive(true);
  119. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LocalAsset");
  120. text.text = "正在加载配置";
  121. while (!abr.isDone)
  122. {
  123. text2.text = (abr.progress * 100).ToString("F2") + "%";
  124. slider.value = float.Parse((abr.progress ).ToString("F2"));
  125. yield return null;
  126. }
  127. copyGameObject(abr.asset);
  128. this.gameObject.SetActive(false);
  129. }
  130. else
  131. {
  132. text.text = "正在下载代码";
  133. yield return DownLoadAssets(scUrl, HotUpdateScripts);
  134. text.text = "正在下载配置";
  135. yield return DownLoadAssets(artUrl, HotUpdateAssets);
  136. }
  137. }
  138. else
  139. {
  140. text.text = "正在下载代码";
  141. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  142. text.text = "正在下载配置";
  143. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  144. }
  145. }
  146. public IEnumerator DownLoadLocal(string name)
  147. {
  148. slider.gameObject.SetActive(true);
  149. UnityWebRequest www = UnityWebRequest.Get(GetWebRequestPath(name));
  150. www.SendWebRequest();
  151. while (!www.isDone)
  152. {
  153. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  154. slider.value = float.Parse((www.downloadProgress).ToString("F2"));
  155. yield return null;
  156. }
  157. #if UNITY_2020_1_OR_NEWER
  158. if (www.result != UnityWebRequest.Result.Success)
  159. {
  160. Debug.Log(www.error);
  161. }
  162. #else
  163. if (www.isHttpError || www.isNetworkError)
  164. {
  165. Debug.Log(www.error);
  166. }
  167. #endif
  168. HomologousImageMode mode = HomologousImageMode.SuperSet;
  169. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(www.downloadHandler.data, mode);
  170. Debug.Log($"LoadMetadataForAOTAssembly:{name}. mode:{mode} ret:{err}");
  171. }
  172. public IEnumerator DownLoadAssets(string dllPath,string name,bool isRemote=true)
  173. {
  174. slider.gameObject.SetActive(true);
  175. if(!isRemote)
  176. {
  177. dllPath = GetWebRequestPath(name);
  178. }
  179. UnityWebRequest www = UnityWebRequest.Get(dllPath);
  180. www.SendWebRequest();
  181. while (!www.isDone)
  182. {
  183. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  184. slider.value = float.Parse((www.downloadProgress ).ToString("F2"));
  185. yield return null;
  186. }
  187. #if UNITY_2020_1_OR_NEWER
  188. if (www.result != UnityWebRequest.Result.Success)
  189. {
  190. Debug.Log(www.error);
  191. }
  192. #else
  193. if (www.isHttpError || www.isNetworkError)
  194. {
  195. Debug.Log(www.error);
  196. }
  197. #endif
  198. else
  199. {
  200. if(name == HotUpdateScripts)
  201. {
  202. text.text = "正在编译代码";
  203. slider.gameObject.SetActive(false);
  204. Assembly.Load(www.downloadHandler.data);
  205. string fileName = HotUpdateScripts;
  206. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  207. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate" );
  208. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  209. // if (File.Exists(filePathname))
  210. // File.Delete(filePathname);
  211. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  212. PlayerPrefs.SetString(HotUpdateScripts, filePathname);
  213. }
  214. else
  215. {
  216. text.text = "正在解析配置";
  217. slider.gameObject.SetActive(false);
  218. AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(www.downloadHandler.data);
  219. while (!acr.isDone)
  220. {
  221. text2.text = (acr.progress * 100).ToString("F2") + "%";
  222. slider.value = float.Parse((acr.progress ).ToString("F2"));
  223. yield return null;
  224. }
  225. slider.gameObject.SetActive(true);
  226. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LocalAsset");
  227. text.text = "正在加载配置";
  228. while (!abr.isDone)
  229. {
  230. text2.text = (abr.progress * 100).ToString("F2") + "%";
  231. slider.value = float.Parse((abr.progress ).ToString("F2"));
  232. yield return null;
  233. }
  234. copyGameObject(abr.asset);
  235. this.gameObject.SetActive(false);
  236. string fileName = HotUpdateAssets;
  237. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  238. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate");
  239. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  240. // if (File.Exists(filePathname))
  241. // File.Delete(filePathname);
  242. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  243. PlayerPrefs.SetString(HotUpdateAssets, filePathname);
  244. }
  245. }
  246. }
  247. void copyGameObject(UnityEngine.Object o)
  248. {
  249. Instantiate(o);
  250. }
  251. private static Assembly _hotUpdateAss;
  252. /// <summary>
  253. /// 为aot assembly加载原始metadata, 这个代码放aot或者热更新都行。
  254. /// 一旦加载后,如果AOT泛型函数对应native实现不存在,则自动替换为解释模式执行
  255. /// </summary>
  256. private static void LoadMetadataForAOTAssemblies()
  257. {
  258. /// 注意,补充元数据是给AOT dll补充元数据,而不是给热更新dll补充元数据。
  259. /// 热更新dll不缺元数据,不需要补充,如果调用LoadMetadataForAOTAssembly会返回错误
  260. ///
  261. HomologousImageMode mode = HomologousImageMode.SuperSet;
  262. foreach (var aotDllName in AOTMetaAssemblyFiles)
  263. {
  264. byte[] dllBytes = ReadBytesFromStreamingAssets(aotDllName);
  265. // 加载assembly对应的dll,会自动为它hook。一旦aot泛型函数的native函数不存在,用解释器版本代码
  266. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(dllBytes, mode);
  267. Debug.Log($"LoadMetadataForAOTAssembly:{aotDllName}. mode:{mode} ret:{err}");
  268. }
  269. }
  270. void StartGame()
  271. {
  272. // LoadMetadataForAOTAssemblies();
  273. /*
  274. #if !UNITY_EDITOR
  275. _hotUpdateAss = Assembly.Load(ReadBytesFromStreamingAssets("HotUpdate.dll.bytes"));
  276. #else
  277. _hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
  278. #endif
  279. */
  280. // Type entryType = _hotUpdateAss.GetType("Entry");
  281. // entryType.GetMethod("Start").Invoke(null, null);
  282. }
  283. }