NLDClient-yudde/ProjectNLD/Assets/Code/Scripts/HotUpdate/GameLauncher.cs

383 lines
12 KiB
C#
Raw Normal View History

2025-09-04 14:01:19 +08:00
using HotUpdate.UI;
2024-02-22 13:24:26 +08:00
using Cysharp.Threading.Tasks;
2024-02-21 16:24:29 +08:00
using PhxhSDK.AOT;
2024-02-22 12:41:18 +08:00
using PhxhSDK.AOT.SimpleLoader;
2024-02-22 14:53:23 +08:00
using PhxhSDK.AOT.VersionUpdate;
2024-07-24 12:43:10 +08:00
using System;
2024-08-22 12:45:38 +08:00
using PhxhSDK.AOT.PreConfig;
2023-10-19 15:00:19 +08:00
using UnityEngine;
2024-07-17 12:51:08 +08:00
using UnityEngine.SceneManagement;
2024-09-26 19:16:39 +08:00
using Assets.PhxhSDK.AOT.BI;
2025-09-04 14:41:40 +08:00
using Obfuz.EncryptionVM;
using Obfuz;
2025-11-28 13:52:15 +08:00
using static ProgressBarData;
2025-05-13 15:27:38 +08:00
#if PLATFORM_ANDROID || UNITY_EDITOR
using UnityEngine.Android;
#endif
2023-10-19 15:00:19 +08:00
#if SDK_BILIBILI
using PhxhSDK.AOT.Bilibili;
#endif
2023-10-19 15:00:19 +08:00
public class GameLauncher : MonoBehaviour
{
2025-10-17 13:12:28 +08:00
private static bool _isSetUpStaticSecret = false;
2025-09-04 14:41:40 +08:00
/// <summary>
/// 初始化EncryptionService后被混淆的代码才能正常运行
/// 因此尽可能地早地初始化它。
/// </summary>
[ObfuzIgnore]
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
2025-10-17 13:12:28 +08:00
private static void _SetUpStaticSecretKey()
2025-09-04 14:41:40 +08:00
{
2025-10-17 13:12:28 +08:00
if (_isSetUpStaticSecret)
{
return;
}
_isSetUpStaticSecret = true;
Debug.Log("[Obfz] SetUpStaticSecret begin");
var loadedAsset = Resources.Load<TextAsset>("us5af47s54fsa1z90sf");
if (loadedAsset == null)
{
Debug.LogError("[Obfz] SetUpStaticSecret failed: could not load static secret asset");
return;
}
EncryptionService<DefaultStaticEncryptionScope>.Encryptor = new GeneratedEncryptionVirtualMachine(loadedAsset.bytes);
Debug.Log("[Obfz] SetUpStaticSecret end");
2025-09-04 14:41:40 +08:00
}
2025-10-17 13:12:28 +08:00
private static void _SetUpDynamicSecret(byte[] bytes)
2025-09-04 14:41:40 +08:00
{
2025-10-17 13:12:28 +08:00
Debug.Log("[Obfz] SetUpDynamicSecret begin");
2025-09-04 14:41:40 +08:00
EncryptionService<DefaultDynamicEncryptionScope>.Encryptor = new GeneratedEncryptionVirtualMachine(bytes);
2025-10-17 13:12:28 +08:00
Debug.Log("[Obfz] SetUpDynamicSecret end");
2025-09-04 14:41:40 +08:00
}
private const string START_SCENE_NAME = "Assets/Scenes/StartScene.unity";
private const string DYNAMIC_SECRET_PATH = "Assets/Config/Obfuz/defaultDynamicSecretKey.bytes";
2024-07-16 14:00:58 +08:00
2024-01-30 19:42:52 +08:00
//最大能容忍的下载卡住时长,一旦超过则重新开始下载
2024-01-31 18:33:47 +08:00
// private const float DOWNLOAD_STUCK_TIME_MAX = 10;
2025-11-28 13:52:15 +08:00
#region 进度条优化
/// <summary>
/// 进度条
/// </summary>
private ProgressBarData progressBarData;
/// <summary>
/// 假进度
/// </summary>
private float fakeProgess;
/// <summary>
/// 真进度
/// </summary>
private float realProgess;
/// <summary>
/// 假进度计时
/// </summary>
private float fakeProgessTimer;
/// <summary>
/// 假进度下一次增长的值
/// </summary>
private float fakeNextAddValue;
#endregion
2024-01-30 19:42:52 +08:00
2025-11-28 13:52:15 +08:00
/// <summary>
/// 最终进度
/// </summary>
public float FinalProgess { get { return Mathf.Max(realProgess, fakeProgess); } }
2024-07-16 14:00:58 +08:00
#if USE_HCLR
2024-02-22 12:41:18 +08:00
private HybridCLRHelper _hybridCLRHelper;
2024-07-16 14:00:58 +08:00
#endif
2024-02-22 14:53:23 +08:00
private VersionUpdateHandle _versionUpdateHandle;
private ISimpleLoader _simpleLoader;
2024-08-01 15:46:36 +08:00
private IVersionUpdateUI versionUpdateUI;
2023-10-19 15:00:19 +08:00
public bool enableHotUpdate = true;
2024-12-20 18:15:56 +08:00
private void Awake()
{
2025-10-17 13:12:28 +08:00
_SetUpStaticSecretKey();
2025-10-24 13:43:51 +08:00
Screen.sleepTimeout = SleepTimeout.NeverSleep; // 保持屏幕常亮
2025-11-28 13:52:15 +08:00
fakeProgess = 0f;
realProgess = 0f;
fakeProgessTimer = 0f;
progressBarData = Resources.Load<ProgressBarData>("ProgressBarData");
2025-10-24 13:43:51 +08:00
2024-12-20 18:15:56 +08:00
#if SDK_BILIBILI
GameObject goBiliBiliSDK = new()
{
name = "BiliBiliSDK"
};
2024-12-23 19:31:27 +08:00
if (!goBiliBiliSDK.TryGetComponent<GSCSdkInterface>(out _))
goBiliBiliSDK.AddComponent<GSCSdkInterface>();
2024-12-20 18:15:56 +08:00
2024-12-23 19:31:27 +08:00
if (!goBiliBiliSDK.TryGetComponent<GSCCallbackListerner>(out _))
goBiliBiliSDK.AddComponent<GSCCallbackListerner>();
2024-12-20 18:15:56 +08:00
DontDestroyOnLoad(goBiliBiliSDK);
#endif
2025-08-08 17:12:34 +08:00
}
private void Start()
{
#if SDK_BILIBILI
GSCSdkInterface.init();
#endif
2025-08-07 18:51:01 +08:00
#if SDK_ADJUST
2025-08-08 20:35:32 +08:00
var YourAppToken = "shw96lfwisqo"; // 替换为你的Adjust App Token
AdjustInitTool.Instance.InitAdjustSDK(YourAppToken);
2025-08-07 18:51:01 +08:00
#endif
2025-08-22 14:02:23 +08:00
#if SDK_FIREBASE
Firebase.Analytics.FirebaseAnalytics.LogEvent("First_open");
#endif
2025-08-08 20:35:32 +08:00
versionUpdateUI = new TempUIHandle();
2024-12-23 15:02:21 +08:00
bool agreement = PlayerPrefs.GetInt("PrivacyAgreement", 0) == 1;
2025-09-01 17:21:29 +08:00
BIToolinAOT.Instance.TrackEventInAOT("app_open", null);
2024-12-23 16:15:03 +08:00
if (!agreement) // 弹隐私弹窗
{
TempUpdateUI.Instance.PrivacyAgreeCallback = () =>
{
TempUpdateUI.Instance.m_ProgressObj.SetActive(true);
Launch();
};
TempUpdateUI.Instance.m_PrivacyDialogObj.SetActive(true);
}
else
{
TempUpdateUI.Instance.m_ProgressObj.SetActive(true);
Launch();
}
2023-10-19 15:00:19 +08:00
}
2025-11-28 13:52:15 +08:00
private void Update()
{
2025-12-03 16:55:52 +08:00
if (null == versionUpdateUI)
return;
2025-11-28 13:52:15 +08:00
versionUpdateUI.UpdateProgress(FinalProgess);
if (realProgess >= 1f)
return;
2025-12-03 16:55:52 +08:00
if (null == _versionUpdateHandle)
return;
2025-11-28 14:14:32 +08:00
if (!_versionUpdateHandle.IsUpdating)
return;
2025-11-28 13:52:15 +08:00
if (null == progressBarData)
return;
if (0 >= progressBarData.ListProgressDatas.Count) // 没有配置数量
return;
ProgressData lastProgressData = progressBarData.ListProgressDatas[^1];
if (fakeProgess >= lastProgressData.Target) // 进度满了
return;
if (fakeProgessTimer <= 0f)
{
foreach (ProgressData progressData in progressBarData.ListProgressDatas)
{
if (fakeProgess >= progressData.Target)
continue;
fakeProgessTimer += UnityEngine.Random.Range(progressData.MinInterval, progressData.MaxInterval);
fakeNextAddValue = UnityEngine.Random.Range(progressData.MinAddValue, progressData.MaxAddValue);
break;
}
}
fakeProgessTimer -= Time.deltaTime;
if (fakeProgessTimer <= 0f)
{
fakeProgess += fakeNextAddValue;
if (fakeProgess > lastProgressData.Target)
fakeProgess = lastProgressData.Target;
}
}
2024-02-22 14:53:23 +08:00
private async void Launch()
2023-10-19 15:00:19 +08:00
{
#if UNITY_EDITOR
enableHotUpdate = false;
#endif
2025-04-11 15:38:36 +08:00
#if PLATFORM_ANDROID && !SDK_BILIBILI //B站在隐私协议之后才申请权限
if (!Permission.HasUserAuthorizedPermission(Permission.ExternalStorageWrite))
{
2025-04-14 15:05:56 +08:00
Debug.Log("申请权限: " + Permission.ExternalStorageWrite);
Permission.RequestUserPermission(Permission.ExternalStorageWrite);
}
2024-02-21 16:24:29 +08:00
#endif
2025-11-28 13:52:15 +08:00
realProgess = 0f;
2025-01-10 18:40:47 +08:00
versionUpdateUI.UpdateProgressText(LocalizeMono.Instance.GetLocalizeText("NetworkConnection")); // 尝试网络连接中...
2025-11-28 13:52:15 +08:00
_versionUpdateHandle = new VersionUpdateHandle(versionUpdateUI, SetRealProgress);
VersionUpdateInfo versionUpdateInfo = _versionUpdateHandle.GetVersionInfo();
2024-09-11 19:32:40 +08:00
PackDataInst.CreateInst();
2025-05-26 19:26:29 +08:00
UpdateLocalInfo localInfo = PackDataInst.Inst.localInfo;
2025-01-10 18:40:47 +08:00
string acquiring = LocalizeMono.Instance.GetLocalizeText("Acquiring"); // 获取中...
versionUpdateUI.ShowVersion(Application.version, localInfo.workSpace, localInfo.localFullVersion, acquiring, acquiring);
2025-10-29 15:17:55 +08:00
BIToolinAOT.Instance.Init();//TalkingData初始化
2025-11-17 12:40:48 +08:00
try
{
DeviceIdHandle.Instance.Initialize();//设备ID获取初始化
}
catch (Exception e)
{
Debug.LogError($"DeviceIdHandle Initialize Error:{e}");
}
2025-10-29 15:17:55 +08:00
//PlayerPrefs.SetString("BI_Platform", TalkingDataInitTool.channel);
2025-11-17 12:40:48 +08:00
#region 更新AppConfig
2024-08-23 12:44:50 +08:00
bool downloadResult;
do
2024-08-22 12:45:38 +08:00
{
2024-08-23 13:21:34 +08:00
try
{
2025-01-10 18:40:47 +08:00
versionUpdateUI.UpdateProgressText(LocalizeMono.Instance.GetLocalizeText("RequestConfiguration")); // 开始请求APPConfig
2024-09-26 19:16:39 +08:00
BIToolinAOT.Instance.TrackEventInAOT("app_config_request", null);
2024-08-23 13:21:34 +08:00
downloadResult = await PreConfig.instance.DownloadConfig();
2024-09-26 19:16:39 +08:00
2025-01-10 18:40:47 +08:00
versionUpdateUI.UpdateProgressText(LocalizeMono.Instance.GetLocalizeText("RequestConfigurationComplete")); // 请求APPConfig结束
versionUpdateUI.ShowVersion(Application.version, localInfo.workSpace, localInfo.localFullVersion, acquiring, PreConfig.instance.ServerName);
2024-09-26 19:16:39 +08:00
BIToolinAOT.Instance.TrackEventInAOT("app_config_response", new System.Collections.Generic.Dictionary<string, object>(){
{"result", downloadResult? 0 : 1 }
});
2024-08-23 13:21:34 +08:00
}
catch (Exception)
{
downloadResult = false;
}
2024-10-12 18:29:13 +08:00
}
2025-01-10 18:40:47 +08:00
while (!downloadResult && await versionUpdateUI.ShowDialog(LocalizeMono.Instance.GetLocalizeText("Tip"), LocalizeMono.Instance.GetLocalizeText("DownloadConfigErrorRetry"))); // 下载配置文件失败,是否重试?
2024-09-30 16:04:37 +08:00
2024-08-23 12:44:50 +08:00
if (!downloadResult)
TempUpdateUI.Instance.OnClickCancel();
#endregion
2024-08-22 12:45:38 +08:00
if (!PreConfig.instance.isConfigValid)
{
// 配置错误,没有读取到ResUrl
Debug.LogError("配置文件错误");
2025-01-10 18:40:47 +08:00
await versionUpdateUI.ShowDialog(LocalizeMono.Instance.GetLocalizeText("Tip"), LocalizeMono.Instance.GetLocalizeText("ConfigError")); // 配置文件错误
2024-08-23 12:44:50 +08:00
TempUpdateUI.Instance.OnClickCancel();
2024-08-22 12:45:38 +08:00
return;
}
2024-07-16 14:00:58 +08:00
2024-02-22 13:24:26 +08:00
await YooAssetHelper.Init();
2024-02-22 14:53:23 +08:00
_simpleLoader = new SimpleLoader_YooAsset();
2025-10-16 12:29:49 +08:00
2023-10-19 15:00:19 +08:00
Debug.Log($"Launch Game! enableHotUpdate:{enableHotUpdate}");
2024-07-16 14:00:58 +08:00
2024-09-26 19:16:39 +08:00
bool result = await _versionUpdateHandle.CheckUpdate();//这里会打点资源检测更新事件
2024-02-22 14:53:23 +08:00
if (!result)
{
Debug.LogError("更新失败!,无法进入游戏");
return;
}
2024-07-16 14:00:58 +08:00
2023-10-19 15:00:19 +08:00
if (enableHotUpdate)
2024-02-22 12:41:18 +08:00
{
2024-07-16 14:00:58 +08:00
#if USE_HCLR
2025-09-04 14:41:40 +08:00
byte[] dynamicSecret = await _simpleLoader.LoadDllBytes(DYNAMIC_SECRET_PATH);
2025-10-17 13:12:28 +08:00
_SetUpDynamicSecret(dynamicSecret);
2025-09-04 14:41:40 +08:00
await _simpleLoader.UnloadDll(DYNAMIC_SECRET_PATH);
2024-02-22 12:41:18 +08:00
Debug.Log("需要热更新,开始加载程序集");
_hybridCLRHelper = new HybridCLRHelper();
_hybridCLRHelper.SetDllList(AOTGenericReferences.PatchedAOTAssemblyList);
2024-02-22 14:53:23 +08:00
_hybridCLRHelper.RegistLoader(_simpleLoader);
2024-07-16 14:19:27 +08:00
2024-02-22 13:24:26 +08:00
await _hybridCLRHelper.LoadAssemblies();
2024-02-22 12:41:18 +08:00
Debug.Log("加载程序集结束!");
2024-07-16 14:00:58 +08:00
#endif
2024-02-22 12:41:18 +08:00
}
2024-08-27 18:25:16 +08:00
await _simpleLoader.WarmUpShader();
2024-07-16 14:00:58 +08:00
2024-02-22 13:24:26 +08:00
await EnterGame();
2023-10-19 15:00:19 +08:00
}
2024-02-22 14:53:23 +08:00
private async UniTask EnterGame()
2023-10-19 15:00:19 +08:00
{
2024-02-22 14:53:23 +08:00
Debug.Log("开始加载游戏场景");
2024-08-01 15:46:36 +08:00
SimulationProgress(versionUpdateUI.GetCurProgress());
2024-07-24 12:43:10 +08:00
try
2024-07-16 14:00:58 +08:00
{
2024-07-24 12:43:10 +08:00
Scene scene = await _simpleLoader.LoadSceneAsync(START_SCENE_NAME, LoadSceneMode.Additive);
foreach (GameObject go in scene.GetRootGameObjects())
2024-07-16 14:00:58 +08:00
{
2024-07-24 12:43:10 +08:00
if ("EventSystem".Equals(go.name))
{
Destroy(go);
break;
}
2024-07-16 14:00:58 +08:00
}
}
2024-07-24 12:43:10 +08:00
catch (Exception e)
{
Debug.LogError(e);
}
finally
{
await LoadOver();
Debug.Log("加载游戏场景结束");
}
2023-10-19 15:00:19 +08:00
}
2024-07-30 18:51:27 +08:00
private async void SimulationProgress(float startProgress)
2024-07-16 14:00:58 +08:00
{
2025-01-10 18:40:47 +08:00
versionUpdateUI.UpdateProgressText(LocalizeMono.Instance.GetLocalizeText("InitGaming")); // 初始化游戏...
2025-11-28 13:52:15 +08:00
realProgess = startProgress;
2024-02-22 12:41:18 +08:00
2024-07-30 18:51:27 +08:00
float step = (1f - startProgress) * 0.02f;
2024-08-01 15:46:36 +08:00
while (startProgress + step <= 0.99f)
2024-07-30 18:51:27 +08:00
{
await UniTask.Delay(20);
startProgress += step;
2025-11-28 13:52:15 +08:00
realProgess = startProgress;
2024-07-30 18:51:27 +08:00
}
2024-07-16 14:00:58 +08:00
}
private async UniTask LoadOver()
{
while (true)
{
await UniTask.Yield();
2024-08-08 13:00:58 +08:00
// Debug.Log($"校验是否加载完:{IVersionUpdateUI.IsLoadOver}");
2025-06-12 16:32:47 +08:00
if (StartSceneLoadingManager.IsLoadOver)
2024-07-16 14:00:58 +08:00
{
2025-11-28 13:52:15 +08:00
realProgess = 1f;
2025-01-10 18:40:47 +08:00
versionUpdateUI.UpdateProgressText(LocalizeMono.Instance.GetLocalizeText("Complete")); // 完成
2024-07-16 14:00:58 +08:00
await UniTask.Delay(200);
2024-08-01 15:46:36 +08:00
versionUpdateUI.CloseAll();
2025-06-12 16:17:35 +08:00
await SceneManager.UnloadSceneAsync(0);
2024-07-16 14:00:58 +08:00
return;
2024-07-16 14:19:27 +08:00
}
2024-07-16 14:00:58 +08:00
}
}
2025-11-28 13:52:15 +08:00
/// <summary>
/// 设置进度
/// </summary>
/// <param name="progress"></param>
private void SetRealProgress(float progress)
{
realProgess = progress;
}
2023-11-08 19:04:23 +08:00
}