LoadDll.cs 9.7 KB

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