LoadDll.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. public 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. "System.Runtime.CompilerServices.Unsafe.dll.bytes",
  57. "netstandard.dll.bytes"
  58. };
  59. public Text text;
  60. public Text text2;
  61. public Slider slider;
  62. string HotUpdateScripts = "HotUpdateScripts";
  63. string HotUpdateAssets = "HotUpdateAssets";
  64. private AssetBundleCreateRequest acr;
  65. IEnumerator DownLoadAssets()
  66. {
  67. text.text = "正在获取网关数据";
  68. for (int i = 0; i < AOTMetaAssemblyFiles.Count; i++)
  69. {
  70. yield return DownLoadLocal(AOTMetaAssemblyFiles[i]);
  71. }
  72. slider.gameObject.SetActive(false);
  73. while (HttpSDKAction.Instance.jsonData == null || HttpSDKAction.Instance.jsonData == "")
  74. {
  75. yield return null;
  76. }
  77. JsonData data = new JsonData();
  78. string scUrl = "";
  79. string artUrl = "";
  80. try
  81. {
  82. data = JsonMapper.ToObject(HttpSDKAction.Instance.jsonData);
  83. scUrl = data[HotUpdateScripts].ToString();
  84. artUrl = data[HotUpdateAssets].ToString();
  85. }
  86. catch
  87. {
  88. }
  89. if (scUrl != "")
  90. {
  91. if (!bool.Parse(data["isHotUpdate"].ToString()))
  92. {
  93. text.text = "正在下载代码";
  94. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  95. text.text = "正在下载配置";
  96. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  97. }
  98. else if (PlayerPrefs.GetString("HotUpdateVersion") == data["HotUpdateVersion"].ToString())
  99. {
  100. text.text = "正在编译代码";
  101. string filePath = PlayerPrefs.GetString(HotUpdateScripts);
  102. Task<byte[]> Tb = File.ReadAllBytesAsync(filePath);
  103. yield return Tb;
  104. slider.gameObject.SetActive(false);
  105. Assembly.Load(Tb.Result);
  106. text.text = "正在解析配置";
  107. filePath = PlayerPrefs.GetString(HotUpdateAssets);
  108. Task<byte[]> Tb2 = File.ReadAllBytesAsync(filePath);
  109. yield return Tb2;
  110. text.text = "正在解析配置";
  111. slider.gameObject.SetActive(false);
  112. acr = AssetBundle.LoadFromMemoryAsync(Tb2.Result);
  113. while (!acr.isDone)
  114. {
  115. text2.text = (acr.progress * 100).ToString("F2") + "%";
  116. slider.value = float.Parse((acr.progress).ToString("F2"));
  117. yield return null;
  118. }
  119. slider.gameObject.SetActive(true);
  120. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LangChaoStart");
  121. text.text = "正在加载配置";
  122. while (!abr.isDone)
  123. {
  124. text2.text = (abr.progress * 100).ToString("F2") + "%";
  125. slider.value = float.Parse((abr.progress).ToString("F2"));
  126. yield return null;
  127. }
  128. copyGameObject(abr.asset);
  129. this.gameObject.SetActive(false);
  130. }
  131. else
  132. {
  133. text.text = "正在下载代码";
  134. yield return DownLoadAssets(scUrl, HotUpdateScripts);
  135. text.text = "正在下载配置";
  136. yield return DownLoadAssets(artUrl, HotUpdateAssets);
  137. }
  138. }
  139. else
  140. {
  141. text.text = "正在下载代码";
  142. yield return DownLoadAssets(scUrl, HotUpdateScripts, false);
  143. text.text = "正在下载配置";
  144. yield return DownLoadAssets(artUrl, HotUpdateAssets, false);
  145. }
  146. }
  147. public IEnumerator DownLoadLocal(string name)
  148. {
  149. slider.gameObject.SetActive(true);
  150. UnityWebRequest www = UnityWebRequest.Get(GetWebRequestPath(name));
  151. www.SendWebRequest();
  152. while (!www.isDone)
  153. {
  154. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  155. slider.value = float.Parse((www.downloadProgress).ToString("F2"));
  156. yield return null;
  157. }
  158. #if UNITY_2020_1_OR_NEWER
  159. if (www.result != UnityWebRequest.Result.Success)
  160. {
  161. Debug.Log(www.error);
  162. }
  163. #else
  164. if (www.isHttpError || www.isNetworkError)
  165. {
  166. Debug.Log(www.error);
  167. }
  168. #endif
  169. HomologousImageMode mode = HomologousImageMode.SuperSet;
  170. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(www.downloadHandler.data, mode);
  171. Debug.Log($"LoadMetadataForAOTAssembly:{name}. mode:{mode} ret:{err}");
  172. }
  173. public IEnumerator DownLoadAssets(string dllPath, string name, bool isRemote = true)
  174. {
  175. slider.gameObject.SetActive(true);
  176. if (!isRemote)
  177. {
  178. dllPath = GetWebRequestPath(name);
  179. }
  180. UnityWebRequest www = UnityWebRequest.Get(dllPath);
  181. www.SendWebRequest();
  182. while (!www.isDone)
  183. {
  184. text2.text = (www.downloadProgress * 100).ToString("F2") + "%";
  185. slider.value = float.Parse((www.downloadProgress).ToString("F2"));
  186. yield return null;
  187. }
  188. #if UNITY_2020_1_OR_NEWER
  189. if (www.result != UnityWebRequest.Result.Success)
  190. {
  191. Debug.Log(www.error);
  192. }
  193. #else
  194. if (www.isHttpError || www.isNetworkError)
  195. {
  196. Debug.Log(www.error);
  197. }
  198. #endif
  199. else
  200. {
  201. if (name == HotUpdateScripts)
  202. {
  203. text.text = "正在编译代码";
  204. slider.gameObject.SetActive(false);
  205. Assembly.Load(www.downloadHandler.data);
  206. string fileName = HotUpdateScripts;
  207. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  208. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate");
  209. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  210. // if (File.Exists(filePathname))
  211. // File.Delete(filePathname);
  212. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  213. PlayerPrefs.SetString(HotUpdateScripts, filePathname);
  214. }
  215. else
  216. {
  217. text.text = "正在解析配置";
  218. slider.gameObject.SetActive(false);
  219. AssetBundleCreateRequest acr = AssetBundle.LoadFromMemoryAsync(www.downloadHandler.data);
  220. while (!acr.isDone)
  221. {
  222. text2.text = (acr.progress * 100).ToString("F2") + "%";
  223. slider.value = float.Parse((acr.progress).ToString("F2"));
  224. yield return null;
  225. }
  226. slider.gameObject.SetActive(true);
  227. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<GameObject>("LangChaoStart");
  228. text.text = "正在加载配置";
  229. while (!abr.isDone)
  230. {
  231. text2.text = (abr.progress * 100).ToString("F2") + "%";
  232. slider.value = float.Parse((abr.progress).ToString("F2"));
  233. yield return null;
  234. }
  235. copyGameObject(abr.asset);
  236. this.gameObject.SetActive(false);
  237. string fileName = HotUpdateAssets;
  238. if (!Directory.Exists(Application.persistentDataPath + "/HotUpdate"))
  239. Directory.CreateDirectory(Application.persistentDataPath + "/HotUpdate");
  240. string filePathname = Application.persistentDataPath + "/HotUpdate/" + fileName;
  241. // if (File.Exists(filePathname))
  242. // File.Delete(filePathname);
  243. File.WriteAllBytes(filePathname, www.downloadHandler.data);
  244. PlayerPrefs.SetString(HotUpdateAssets, filePathname);
  245. }
  246. }
  247. }
  248. void copyGameObject(UnityEngine.Object o)
  249. {
  250. Instantiate(o);
  251. }
  252. private static Assembly _hotUpdateAss;
  253. /// <summary>
  254. /// 为aot assembly加载原始metadata, 这个代码放aot或者热更新都行。
  255. /// 一旦加载后,如果AOT泛型函数对应native实现不存在,则自动替换为解释模式执行
  256. /// </summary>
  257. private static void LoadMetadataForAOTAssemblies()
  258. {
  259. /// 注意,补充元数据是给AOT dll补充元数据,而不是给热更新dll补充元数据。
  260. /// 热更新dll不缺元数据,不需要补充,如果调用LoadMetadataForAOTAssembly会返回错误
  261. ///
  262. HomologousImageMode mode = HomologousImageMode.SuperSet;
  263. foreach (var aotDllName in AOTMetaAssemblyFiles)
  264. {
  265. byte[] dllBytes = ReadBytesFromStreamingAssets(aotDllName);
  266. // 加载assembly对应的dll,会自动为它hook。一旦aot泛型函数的native函数不存在,用解释器版本代码
  267. LoadImageErrorCode err = RuntimeApi.LoadMetadataForAOTAssembly(dllBytes, mode);
  268. Debug.Log($"LoadMetadataForAOTAssembly:{aotDllName}. mode:{mode} ret:{err}");
  269. }
  270. }
  271. void StartGame()
  272. {
  273. // LoadMetadataForAOTAssemblies();
  274. /*
  275. #if !UNITY_EDITOR
  276. _hotUpdateAss = Assembly.Load(ReadBytesFromStreamingAssets("HotUpdate.dll.bytes"));
  277. #else
  278. _hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
  279. #endif
  280. */
  281. // Type entryType = _hotUpdateAss.GetType("Entry");
  282. // entryType.GetMethod("Start").Invoke(null, null);
  283. }
  284. public IEnumerator LoadAssetsBundleObj( string path , string name , Action<TextAsset> callBack )
  285. {
  286. AssetBundleRequest abr = acr.assetBundle.LoadAssetAsync<TextAsset>(path);
  287. while (!abr.isDone)
  288. {
  289. yield return null;
  290. }
  291. callBack(abr.asset as TextAsset);
  292. // GameObject obj = copyGameObject(abr.asset);
  293. }
  294. }