diff --git a/Assets/RedHotRoast/Define/Model/Config/Game/CommonModel.cs b/Assets/RedHotRoast/Define/Model/Config/Game/CommonModel.cs index 7f00b953..f5f82809 100644 --- a/Assets/RedHotRoast/Define/Model/Config/Game/CommonModel.cs +++ b/Assets/RedHotRoast/Define/Model/Config/Game/CommonModel.cs @@ -1,68 +1,70 @@ -using SGModule.ConfigLoader; - -namespace RedHotRoast -{ - [ConfigKey("Common", false)] - public class CommonModel - { - public int InitialNum; - public int[] inlineLoginDown; - public int inlineMin; - public int Purchaseprops; - public int rewardrate; - public int RevivalCoins; - public int[] wheelTimes; - public float Passportgift; - public float Passportgift2; - public float addspace; - public float addspace2; - public int playtimes; - public int interstitialtype; - public int lobbyrewrdtime; - public int roomrewardrate; - public int Activetimes; - public int adrate; - public int roomrate; - public float afSendLimit; - public float afSendNum; - public int rewardinsertion; - public int exchangeCD = 120; - - public int AddSpaceLevel; - - public int RemoveADsPackDuration; - public int RemoveADsPackPopup; - - public string contactUs; - public int[] UnlockSecret; - - public int[] UnlockLive; - public int Live; - public int Secret; - public int Assitant; - public int LivePreview; - public int SecretPreview; - public int AssitantPreview; - public int HomeGuideRate; - public int roomGuideRate; - public int VIPGuide; - public int VIPGuideRate; - public int HomeInterstitialAd; - public int FreeClaims; - public int TurnOffPackRate; - public int TurnOffRewardsRate; - public int TurnOffRewardsCD; - public int TurnOffRewardslimit; - public int PayRate; - public int FreeMessages; - public int[] CoinsAccess; - public int AdAccess; - public int UnlockAIAssistant; - public int ClearRAM; - public int CoinsDownload; - public string ResVersion; - public int MultiModal; - public int[] eggReward; - public int eggCD; - } -} +using SGModule.ConfigLoader; + +namespace RedHotRoast +{ + [ConfigKey("Common", false)] + public class CommonModel + { + public int InitialNum; + public int[] inlineLoginDown; + public int inlineMin; + public int Purchaseprops; + public int rewardrate; + public int RevivalCoins; + public int[] wheelTimes; + public float Passportgift; + public float Passportgift2; + public float addspace; + public float addspace2; + public int playtimes; + public int interstitialtype; + public int lobbyrewrdtime; + public int roomrewardrate; + public int Activetimes; + public int adrate; + public int roomrate; + public float afSendLimit; + public float afSendNum; + public int rewardinsertion; + public int exchangeCD = 120; + + public int AddSpaceLevel; + + public int RemoveADsPackDuration; + public int RemoveADsPackPopup; + + public string contactUs; + public int[] UnlockSecret; + + public int[] UnlockLive; + public int Live; + public int Secret; + public int Assitant; + public int LivePreview; + public int SecretPreview; + public int AssitantPreview; + public int HomeGuideRate; + public int roomGuideRate; + public int VIPGuide; + public int VIPGuideRate; + public int HomeInterstitialAd; + public int FreeClaims; + public int TurnOffPackRate; + public int TurnOffRewardsRate; + public int TurnOffRewardsCD; + public int TurnOffRewardslimit; + public int PayRate; + public int FreeMessages; + public int[] CoinsAccess; + public int AdAccess; + public int UnlockAIAssistant; + public int ClearRAM; + public int CoinsDownload; + public string ResVersion; + public int MultiModal; + public int[] eggReward; + public int eggCD; + public string ResVersion1; + public int IsOrganic; + } +} diff --git a/Assets/RedHotRoast/Helper/TextureHelper.cs b/Assets/RedHotRoast/Helper/TextureHelper.cs index cb0b4d3e..7d1a8bc6 100644 --- a/Assets/RedHotRoast/Helper/TextureHelper.cs +++ b/Assets/RedHotRoast/Helper/TextureHelper.cs @@ -1,1012 +1,1012 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using FairyGUI; -using RedHotRoast; -using SGModule.Common; -using SGModule.NetKit; -using UnityEngine; -using UnityEngine.Events; -using UnityEngine.Networking; -using UnityEngine.Video; -using Object = UnityEngine.Object; - -public class TextureHelper -{ - public static void GetNTexture(string path, string name, UnityAction action) - { - if (!nTexturesDic.TryGetValue(path + name, out var spr)) - try - { - LoadKit.Instance.LoadSprite(path, name, sprite => - { - if (sprite != null) - { - spr = new NTexture(sprite); - action?.Invoke(spr); - nTexturesDic.TryAdd(path + name, spr); - } - }); - } - catch (Exception e) - { - Debug.LogError(e); - } - else - action?.Invoke(spr); - } - - - public static void GetItemIcon(int itemId, UnityAction action = null) - { - var itemIconPath = "Atlas.Item"; - var name = itemId.ToString(); - if (!true) - if (itemId is 101 or 111) - name = "102"; - - if (itemId is 102 or 106) name += "_normal"; - - GetNTexture(itemIconPath, name, action); - } - - - public static IEnumerator GetGalleryFromNet(int imageID, Action action = null) - { - if (imageID == 0) - { - action?.Invoke(true); - } - else - { - var picInfoUrl = $"{LoginKit.Instance.LoginModel.CdnURL}gallery/{imageID}.jpg"; - yield return GetTextureFromNet("Gallery", imageID, picInfoUrl, action); - } - } - - public static string GetBankIconUrl(string icon_name) - { - return string.Format("ui://G002_main/{0}", icon_name); - } - - public static void GetGalleryLocal(int imageID, Action action) - { - if (!galleryNTexturesDic.TryGetValue(imageID, out var spr)) - { - var path = $"Gallery/{imageID}"; - var asset = Resources.Load($"Atlas/{path}"); - if (asset) - { - } - else - { - CrazyAsyKit.StartCoroutine(GetGalleryFromNet(imageID, isSuccess => - { - if (isSuccess) - CrazyAsyKit.StartCoroutine(GetLocalTexture($"{path}.jpg", texture => - { - if (texture == null) - { - action?.Invoke(null); - - return; - } - - var spr1 = new NTexture(texture); - galleryNTexturesDic.TryAdd(imageID, spr1); - action?.Invoke(spr1); - })); - else - action?.Invoke(null); - })); - } - } - else - { - action?.Invoke(spr); - } - } - - #region 缓存 - - private static readonly Dictionary nTexturesDic = new(); - private static readonly Dictionary avatarNTexturesDic = new(); - private static readonly Dictionary galleryNTexturesDic = new(); - - #endregion - - #region 加载Texture - - private static IEnumerator GetLocalTexture(string imagePath, Action action) - { - var file = $"{Application.persistentDataPath}/{imagePath}"; - var fileInfo = new FileInfo(file); - if (!fileInfo.Exists) - { - action?.Invoke(null); - yield break; - } - - var avatarPath = $"file://{file}"; - var uwr = UnityWebRequestTexture.GetTexture(avatarPath); - yield return uwr.SendWebRequest(); - if (uwr.result is UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError) - { - action?.Invoke(null); - yield break; - } - - var texture2D = DownloadHandlerTexture.GetContent(uwr); - - action?.Invoke(texture2D); - } - - private class DownloadTask - { - public Action Callback; - public string FileName; - public string Folder; - public GLoader Loader; - public string LocalFolder; - public bool IsGameBg; - - } - - public static string imgUrl = ""; - - // 普通队列 - private static readonly Queue normalQueue = new(); - - private static Coroutine normalCoroutine; - - // 优先队列 - private static readonly Queue priorityQueue = new(); - private static Coroutine priorityCoroutine; - - - // ====================== 并发配置 ====================== - private static int maxPriorityConcurrent = 3; // ✅ 可配置最大并发数 - private static int priorityRunning = 0; // 当前正在运行的任务数 - - #region 材质池 - - private static class MaterialPool - { - private static readonly Stack blurMats = new(); - private static readonly Stack normalMats = new(); - - public static Material GetBlur() - { - if (blurMats.Count > 0) return blurMats.Pop(); - var shader = Resources.Load("RedHotRoastAssets/Shader/Blur"); - if (!shader) return null; - return new Material(shader); - } - - public static Material GetNormal() - { - if (normalMats.Count > 0) return normalMats.Pop(); - var shader = Resources.Load("RedHotRoastAssets/Shader/FairyGUI/FairyGUI-Image"); - if (!shader) return null; - return new Material(shader); - } - - public static void Return(Material mat) - { - if (!mat) return; - var name = mat.shader.name; - if (name.Contains("Blur")) blurMats.Push(mat); - else normalMats.Push(mat); - } - - public static void Clear() - { - foreach (var mat in blurMats) Object.Destroy(mat); - blurMats.Clear(); - foreach (var mat in normalMats) Object.Destroy(mat); - normalMats.Clear(); - } - } - - #endregion - - #region 图片加载接口 - - public static string getResPath() - { - // 删除旧资源 - if (!DataMgr.curResVersion.Value.IsNullOrWhiteSpace() && DataMgr.curResVersion.Value != ConfigSystem.GetCommonConf().ResVersion) - { - var oldFolder = Path.Combine(Application.persistentDataPath, DataMgr.curResVersion.Value); - if (Directory.Exists(oldFolder)) - { - Directory.Delete(oldFolder, true); - } - DataMgr.curResVersion.Value = ConfigSystem.GetCommonConf().ResVersion; - } - else if (DataMgr.curResVersion.Value.IsNullOrWhiteSpace()) - { - DataMgr.curResVersion.Value = ConfigSystem.GetCommonConf().ResVersion; - } - - if (ConfigSystem.GetCommonConf().ResVersion.IsNullOrWhiteSpace()) - { - Debug.LogError("获取资源路径失败"); - return Application.persistentDataPath; - } - - string curFolder = Path.Combine(Application.persistentDataPath, ConfigSystem.GetCommonConf().ResVersion); - return curFolder; - } - - public static void SetImgLoader(GLoader loader, string fileName, Action callback, - string folder, string localFolder, bool priority = true, bool isLoad = false, bool isGameBg = false) - { - var localPath = Path.Combine(getResPath(), localFolder, fileName + ".jpg"); - if (File.Exists(localPath)) - { - Debug.Log($"[SetImgLoader] 本地存在,直接加载 {fileName}"); - CrazyAsyKit.StartCoroutine(LoadTexture(fileName, loader, callback, localFolder, isGameBg)); - return; - } - - if (isLoad) - { - Debug.Log($"[SetImgLoader] 兼容老逻辑,直接加载 {fileName}"); - return; - } - - var task = new DownloadTask - { - Loader = loader, - FileName = fileName, - Folder = folder, - Callback = callback, - LocalFolder = localFolder, - IsGameBg = isGameBg - - }; - - if (priority) - EnqueuePriorityTask(task, isBatch: false); // 👈 单任务标记 - else - EnqueueNormalTask(loader, fileName, callback, folder, localFolder); - } - - - /// - /// 批量加载任务(优先队列,串行) - /// - public static void SetImgLoaders( - List<(GLoader loader, string fileName, Action callback, string folder, string localFolder)> tasks) - { - Debug.Log($"[BatchSetImgLoader] 收到 {tasks.Count} 个任务"); - - // 清空旧任务(批量任务才清空) - if (priorityCoroutine != null) - { - CrazyAsyKit.StopCoroutine(priorityCoroutine); - priorityCoroutine = null; - } - - priorityQueue.Clear(); - - foreach (var task in tasks) - { - var downloadTask = new DownloadTask - { - Loader = task.loader, - FileName = task.fileName, - Folder = task.folder, - Callback = task.callback, - LocalFolder = task.localFolder, - IsGameBg = false - - }; - - EnqueuePriorityTask(downloadTask, isBatch: true); // 👈 批量标记 - } - - if (priorityCoroutine == null) - priorityCoroutine = CrazyAsyKit.StartCoroutine(ProcessPriorityQueue()); - } - - - private static void EnqueuePriorityTask(DownloadTask task, bool isBatch) - { - // 去重:如果已在队列中就跳过 - foreach (var queued in priorityQueue) - { - if (queued.FileName == task.FileName) - { - Debug.Log($"[PriorityQueue] 跳过重复任务 {task.FileName}"); - return; - } - } - - if (isBatch) - Debug.Log($"[PriorityQueue] 批量添加任务 {task.FileName}"); - else - Debug.Log($"[PriorityQueue] 单任务添加 {task.FileName}"); - - priorityQueue.Enqueue(task); - - if (priorityCoroutine == null) - priorityCoroutine = CrazyAsyKit.StartCoroutine(ProcessPriorityQueue()); - } - - - #endregion - - #region 普通队列逻辑 - - private static void EnqueueNormalTask(GLoader loader, string fileName, Action callback, string folder, string localFolder) - { - normalQueue.Enqueue(new DownloadTask - { - Loader = loader, - FileName = fileName, - Folder = folder, - Callback = callback, - LocalFolder = localFolder - }); - - if (normalCoroutine == null) - normalCoroutine = CrazyAsyKit.StartCoroutine(ProcessNormalQueue()); - } - - private static IEnumerator ProcessNormalQueue() - { - while (normalQueue.Count > 0) - { - var task = normalQueue.Dequeue(); - yield return DownloadCoroutine(task); - } - - normalCoroutine = null; - } - - private static IEnumerator ProcessPriorityQueue() - { - while (priorityQueue.Count > 0 || priorityRunning > 0) - { - // 如果没达到最大并发,就从队列里拉一个任务出来 - while (priorityRunning < maxPriorityConcurrent && priorityQueue.Count > 0) - { - var task = priorityQueue.Dequeue(); - priorityRunning++; - Debug.Log($"[PriorityQueue] 开始下载 {task.FileName}"); - - // 启动一个子协程跑下载 - CrazyAsyKit.StartCoroutine(RunPriorityTask(task)); - } - - yield return null; // 每帧检查一次 - } - - priorityCoroutine = null; - Debug.Log("[PriorityQueue] 批量任务完成"); - } - - - private static IEnumerator RunPriorityTask(DownloadTask task) - { - yield return DownloadCoroutine(task); - - priorityRunning--; - Debug.Log($"[PriorityQueue] 完成 {task.FileName}"); - } - - private static IEnumerator DownloadCoroutine(DownloadTask task) - { - var localPath = Path.Combine(getResPath(), task.LocalFolder, task.FileName + ".jpg"); - - var tempPath = localPath + ".tmp"; - var url = imgUrl + task.Folder + task.FileName + ".jpg"; - Debug.Log($"[Download] 下载 tempPath=0== {tempPath} \n url==={url}"); - if (File.Exists(localPath)) - { - Debug.Log($"[SetImgLoader] 本地存在,直接加载 {task.FileName}"); - yield return LoadTexture(task.FileName, task.Loader, task.Callback, task.LocalFolder, task.IsGameBg); - yield break; - } - - // ⚠️ 确保遗留的临时文件被清理掉 - Debug.Log($"[Download] tempPath=1== {tempPath}"); - if (File.Exists(tempPath)) - { - Debug.Log($"[Download] 删除遗留临时文件 {tempPath}"); - File.Delete(tempPath); - } - - // 确保目录存在 - string tempDir = Path.GetDirectoryName(tempPath); - if (!Directory.Exists(tempDir)) - { - Directory.CreateDirectory(tempDir); - } - - var attempt = 0; - while (attempt < 3) - { - Debug.Log($"[Download] 正在下载 {task.FileName} 次数:{attempt}"); - attempt++; - using (var www = UnityWebRequest.Get(url)) - { - yield return www.SendWebRequest(); - if (www.result == UnityWebRequest.Result.Success) - { - try - { - Debug.Log($"[Download] 下载成功,保存临时文件 {tempPath}"); - File.WriteAllBytes(tempPath, www.downloadHandler.data); - - if (File.Exists(localPath)) File.Delete(localPath); - - File.Move(tempPath, localPath); - // 解密文件 - // Debug.Log($"[Download] 开始解密文件 {task.FileName}"); - // Rescrypt.DecryptFile(tempPath, localPath, ConfigManager.GameConfig.packageName); - // Debug.Log($"[Download] 解密完成,保存路径:{localPath}"); - } - catch (Exception e) - { - Debug.LogError($"[Download] 解密或保存失败:{e}"); - yield break; - } - - if (task.Loader != null) - yield return LoadTexture(task.FileName, task.Loader, task.Callback, task.LocalFolder, task.IsGameBg); - yield break; - } - - yield return new WaitForSeconds(1f); - } - } - - task.Callback?.Invoke(null); - } - -// 用字典记录每个 loader 的当前请求 -private static readonly Dictionary loaderRequests = new(); - -public static IEnumerator LoadTexture(string fileName, GLoader loader, Action callback = null, - string folder = "", bool isGameBg = false) -{ - string encryptedPath = Path.Combine(getResPath(), folder, fileName + ".jpg"); - - if (!File.Exists(encryptedPath)) - { - Debug.LogWarning($"[LoadEncryptedTexture] 加密文件不存在: {encryptedPath}"); - callback?.Invoke(null); - yield break; - } - - Debug.Log($"[LoadTexture] 开始加载本地图片 {fileName}"); - - // 如果这个 loader 已经有旧请求,先取消掉 - if (loader != null && loaderRequests.TryGetValue(loader, out var oldReq)) - { - if (!oldReq.isDone) - { - Debug.Log($"[LoadTexture] 取消上一次未完成的加载 {fileName}"); - oldReq.Abort(); - } - loaderRequests.Remove(loader); - } - - using (var www = UnityWebRequestTexture.GetTexture("file://" + GetDecryptedImagePath(fileName, folder))) - { - // 记录当前请求 - if (loader != null) loaderRequests[loader] = www; - - yield return www.SendWebRequest(); - - // 如果这个 loader 的请求已经被替换,就直接丢弃结果 - if (loader != null && (!loaderRequests.ContainsKey(loader) || loaderRequests[loader] != www)) - { - Debug.Log($"[LoadTexture] 请求已被新任务替换,丢弃结果 {fileName}"); - yield break; - } - - if (loader != null) loaderRequests.Remove(loader); - - if (www.result == UnityWebRequest.Result.Success) - { - var tex = DownloadHandlerTexture.GetContent(www); - var nTex = new NTexture(tex) { destroyMethod = DestroyMethod.Destroy }; - tex.name = fileName; - - // 清理旧纹理 - if (loader != null && loader.texture != null) - { - loader.texture.Dispose(); - if (loader.texture.nativeTexture != null) - { - UnityEngine.Object.Destroy(loader.texture.nativeTexture); - } - loader.texture = null; - } - - if (loader != null && !loader.isDisposed) - { - loader.texture = nTex; - Debug.Log($"[LoadTexture] 图片已设置到 Loader {fileName}"); - callback?.Invoke(nTex); - } - else - { - Debug.Log($"[LoadTexture] Loader 不存在或已销毁 {fileName}"); - } - - if (isGameBg) - { - callback?.Invoke(nTex); - } - } - else - { - Debug.LogError($"[LoadTexture] 加载失败 {www.error}"); - callback?.Invoke(null); - } - } - - if (loader != null && !loader.isDisposed) - loader.visible = true; -} - - public static string GetDecryptedImagePath(string fileName, string localFolder) - { - string tempPath = Path.Combine(Application.temporaryCachePath, FolderNames.GameCache, localFolder, fileName + "_temp.jpg"); - // Debug.Log($"获取解密路径: {tempPath}"); - - if (!File.Exists(tempPath)) - { - Debug.Log($"!!!!!!!!!!!!临时文件不存在: {fileName}"); - // 确保目录存在 - Directory.CreateDirectory(Path.GetDirectoryName(tempPath)); - - string encPath = Path.Combine(getResPath(), localFolder, fileName + ".jpg"); - Debug.Log(encPath); - if (!File.Exists(encPath)) return null; - Debug.Log($"!!!!!!!!!!!!写入一张: {fileName}"); - byte[] decryptedBytes = Rescrypt.DecryptFileToBytes(encPath); - File.WriteAllBytes(tempPath, decryptedBytes); - } - return tempPath; - } - - public static IEnumerator WriteTempBeforeOpenCoroutine_() - { - System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); - - var levelUnlocks = ConfigSystem.GetConfig(); - var FreeImageLibrary_ = ConfigSystem.GetConfig(); - var ADImageLibrary_ = ConfigSystem.GetConfig(); - var SpecialImageLibrary_ = ConfigSystem.GetConfig(); - var VIPImageLibrary_ = ConfigSystem.GetConfig(); - for (int i = 0; i < GameHelper.GetCommonModel().MultiModal - 1; i++) - { - GetDecryptedImagePath(levelUnlocks[i].Name, FolderNames.AlbumName); - yield return null; - } - var LevelUnlockListNew = DataMgr.LevelUnlockListNew.Value; - for (int i = 0; i - // { - // if (success) - // { - // GameHelper.ShowTips("save_successed", true); - // onSuccess?.Invoke(); - // } - // else - // { - // Debug.LogWarning("保存到相册失败"); - // } - // - // // 可选:清理临时文件 - // if (File.Exists(tempPath)) - // File.Delete(tempPath); - // }); - } - catch (Exception ex) - { - Debug.LogError($"保存加密图片到相册失败: {ex.Message}"); - } - } - - - public static void SaveVideoToAlbum(string fileName, Action onSuccess = null) - { - try - { - string localPath = Path.Combine(getResPath(), FolderNames.VideoName, fileName + ".mp4"); - BrigdeIOS.SaveVideoWithCustomDate(localPath); - // File.SetCreationTime(localPath, DateTime.Now); - // File.SetCreationTimeUtc(localPath, DateTime.Now); - // File.SetLastWriteTime(localPath, DateTime.Now); - // File.SetLastWriteTimeUtc(localPath, DateTime.Now); - // // CrazyAsyKit.StartCoroutine(GetSaveVideo(fileName, (isSuccess) => - // // { - // - // // })); - // NativeGallery.SaveVideoToGallery(localPath, "MyAlbum", "my_video.mp4", (bool success, string path) => - // { - // if (success) - // { - // GameHelper.ShowTips("save_successed", true); - // onSuccess?.Invoke(); - // } - // }); - } - catch (Exception ex) - { - Debug.LogError($"保存加密视频到相册失败: {ex.Message}"); - } - } - - - - public static void SetVideoLoader(VideoPlayer player, GLoader loader, string fileName, - Action action = null, bool play = true) - { - - VideoLoadScheduler.EnqueueLoad(player, fileName, loader, videoPlayer => - { - Debug.Log("RendererList------视频加载成功!-" + fileName); - Debug.Log("[绑定播放器 EnqueueLoad]=========1=== "); - if (videoPlayer != null) - { - Debug.Log("视频加载成功!"); - action?.Invoke(videoPlayer); - } - else - { - Debug.Log("视频加载失败!"); - VideoPlayerPool.Instance.ReturnPlayer(player); - action?.Invoke(null); - } - }, play); - } - - public static void SetImageMosaic(GLoader loader, int num = 80) - { - var shader = Resources.Load("RedHotRoastAssets/Shader/Mosaic"); - if (shader == null) - { - Debug.LogError("找不到 Shader:Custom/Mosaic。请确保 shader 名称正确并已包含到构建中。"); - return; - } - - var material = new Material(shader); - material.SetFloat("_BlockSize", num); // 假设你 shader 中的 blockSize 参数是这个 - loader.material = material; - } - - #region 材质处理 - - public static void SetImageBlur(GLoader loader) - { - if (loader == null || loader.isDisposed || loader.texture == null || loader.material.name == "Custom/Blur") return; - if (loader.material != null) MaterialPool.Return(loader.material); - loader.material = MaterialPool.GetBlur(); - } - - public static void CancelImageBlur(GLoader loader) - { - if (loader == null || loader.isDisposed || loader.texture == null || loader.material == null || loader.material.name != "Custom/Blur") return; - - if (loader.material != null) MaterialPool.Return(loader.material); - loader.material = MaterialPool.GetNormal(); - } - - #endregion - - /// - /// 彻底清理材质池(切场景/退出游戏时调用) - /// - public static void ClearMaterialPool() - { - MaterialPool.Clear(); - } - - private static Sprite _currentBackgroundSprite; - private static SpriteRenderer _spriteRenderer; - private static NTexture _currentNTexture; // 新增:缓存 NTexture - public static void setGamebg(string fileName) - { - // 只获取一次组件 - if (_spriteRenderer == null) - { - var go = GameObject.Find("game_bg"); - if (go == null) - { - Debug.LogError("找不到名为 'game_bg' 的 GameObject!"); - return; - } - _spriteRenderer = go.GetComponent(); - if (_spriteRenderer == null) - { - Debug.LogError("'game_bg' 上没有找到 SpriteRenderer 组件!"); - return; - } - } - - if (_spriteRenderer && _spriteRenderer.sprite && _spriteRenderer.sprite.texture.name == fileName) - { - return; - } - - // 调用统一的 SetImgLoader,不需要再自己写下载逻辑 - SetImgLoader(null, fileName, nTex => - { - if (nTex != null && nTex.nativeTexture != null) - { - Debug.Log("背景图片加载成功!"); - - var tex2D = nTex.nativeTexture as Texture2D; - if (tex2D == null) - { - Debug.LogError("NTexture 转换失败!"); - return; - } - tex2D.name = fileName; - // 创建 Sprite - var sprite = Sprite.Create( - tex2D, - new Rect(0, 0, tex2D.width, tex2D.height), - new Vector2(0.5f, 0.5f) - ); - _spriteRenderer.sprite = sprite; - - if (_currentNTexture != null) - { - _currentNTexture.Dispose(); - _currentNTexture = null; - } - if (_currentBackgroundSprite != null) - { - Object.Destroy(_currentBackgroundSprite); - _currentBackgroundSprite = null; - } - - _currentNTexture = nTex; - _currentBackgroundSprite = sprite; - - var currentWidth = _spriteRenderer.sprite.bounds.size.x; - var scaleFactor = 64f / currentWidth; - - // 等比缩放 - _spriteRenderer.transform.localScale = new Vector3(scaleFactor, scaleFactor, 1); - } - else - { - Debug.LogError("背景图片加载失败!"); - } - }, "LevelAlbums/", FolderNames.AlbumName, true, false, true); // ✅ 背景一般是立刻需要的,走优先下载 - } - - - public static void GetCardIcon(bool isLogo = false, UnityAction action = null) - { - var cardIconPath = "logo_default"; - // var paymentTypeVo = GameHelper.GetPaymentTypeVO(); - // if (isLogo) - // { - // cardIconPath = paymentTypeVo.logo_id; - // } - // else - // { - // cardIconPath = paymentTypeVo.card_name; - // } - - - GetNTexture("Atlas.Pay", cardIconPath, action); - } - - private static IEnumerator GetTextureFromNet(string type, int imgId, string imgUrl, Action action = null) - { - var imagePath = $"{CommonHelper.GetAppSavePath()}/{type}/{imgId}.jpg"; - var fileInfo = new FileInfo(imagePath); - if (fileInfo.Exists) - { - action?.Invoke(true); - yield break; - } - - var avatarRequest = UnityWebRequest.Get(imgUrl); - yield return avatarRequest.SendWebRequest(); - if (avatarRequest.result == UnityWebRequest.Result.ConnectionError || - avatarRequest.result == UnityWebRequest.Result.ProtocolError) - { - action?.Invoke(false); - } - else - { - var avatarData = avatarRequest.downloadHandler.data; - var dirPath = Path.GetDirectoryName(imagePath); - if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); - - if (fileInfo.Exists) - yield break; - Stream stream = fileInfo.Create(); - stream.Write(avatarData, 0, avatarData.Length); - stream.Close(); - stream.Dispose(); - action?.Invoke(true); - } - } - - #endregion - - #region 头像相关 - - public static void SetAvatarToLoader(int avatarId, GLoader _GLoader, bool IsNeedDefAvatar = true) - { - if (!avatarNTexturesDic.TryGetValue(avatarId, out var spr)) - try - { - Sprite sprite = null; - if (avatarId == 0) - { - if (!PlayerPrefsKit.ReadBool("IsLogin")) - { - avatarId = 1; - SetAvatarToLoader(avatarId, _GLoader); - return; - } - - if (PlayerPrefsKit.ReadString("AvatarUrl").IsNullOrWhiteSpace()) - { - _GLoader.url = "ui://pmf3wbjicxrg4"; - return; - } - - GetSelfFaceBookAvatar(texture => - { - if (_GLoader != null) - { - if (texture != null) - _GLoader.texture = texture; - else - _GLoader.url = "ui://pmf3wbjicxrg4"; - } - }); - return; - } - - if (avatarId > 100) - { - if (IsNeedDefAvatar) _GLoader.url = "ui://pmf3wbjicxrg4"; - - GetFaceBookAvatar(avatarId, e => - { - if (_GLoader != null) - { - if (e == null) - _GLoader.url = "ui://pmf3wbjicxrg4"; - else - _GLoader.texture = e; - } - }); - return; - } - - LoadKit.Instance.LoadSprite("Atlas.Avatar", avatarId.ToString(), spr => - { - sprite = spr; - var spr1 = new NTexture(sprite); - _GLoader.texture = spr1; - avatarNTexturesDic.Add(avatarId, spr1); - }); - } - catch (Exception e) - { - Debug.LogError(e); - } - else - _GLoader.texture = spr; - } - - - private static IEnumerator GetAvatarLocal(int avatarId, Action action) - { - yield return GetLocalTexture($"Avatar/{avatarId}.jpg", action); - } - - #endregion - - #region FaceBook头像相关 - - public static void GetFaceBookAvatar(int avatarId, Action action) - { - if (!avatarNTexturesDic.TryGetValue(avatarId, out var spr)) - HallManager.Instance.StartCoroutine(GetAvatarLocal(avatarId, texture => - { - if (texture == null) - { - action?.Invoke(null); - return; - } - - spr = new NTexture(texture); - if (avatarNTexturesDic.ContainsKey(avatarId)) avatarNTexturesDic.Add(avatarId, spr); - - action?.Invoke(spr); - })); - else - action?.Invoke(spr); - } - - - public static void GetSelfFaceBookAvatar(Action action) - { - if (!avatarNTexturesDic.TryGetValue(0, out var spr)) - { - } - else - { - action?.Invoke(spr); - } - } - - #endregion +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using FairyGUI; +using RedHotRoast; +using SGModule.Common; +using SGModule.NetKit; +using UnityEngine; +using UnityEngine.Events; +using UnityEngine.Networking; +using UnityEngine.Video; +using Object = UnityEngine.Object; + +public class TextureHelper +{ + public static void GetNTexture(string path, string name, UnityAction action) + { + if (!nTexturesDic.TryGetValue(path + name, out var spr)) + try + { + LoadKit.Instance.LoadSprite(path, name, sprite => + { + if (sprite != null) + { + spr = new NTexture(sprite); + action?.Invoke(spr); + nTexturesDic.TryAdd(path + name, spr); + } + }); + } + catch (Exception e) + { + Debug.LogError(e); + } + else + action?.Invoke(spr); + } + + + public static void GetItemIcon(int itemId, UnityAction action = null) + { + var itemIconPath = "Atlas.Item"; + var name = itemId.ToString(); + if (!true) + if (itemId is 101 or 111) + name = "102"; + + if (itemId is 102 or 106) name += "_normal"; + + GetNTexture(itemIconPath, name, action); + } + + + public static IEnumerator GetGalleryFromNet(int imageID, Action action = null) + { + if (imageID == 0) + { + action?.Invoke(true); + } + else + { + var picInfoUrl = $"{LoginKit.Instance.LoginModel.CdnURL}gallery/{imageID}.jpg"; + yield return GetTextureFromNet("Gallery", imageID, picInfoUrl, action); + } + } + + public static string GetBankIconUrl(string icon_name) + { + return string.Format("ui://G002_main/{0}", icon_name); + } + + public static void GetGalleryLocal(int imageID, Action action) + { + if (!galleryNTexturesDic.TryGetValue(imageID, out var spr)) + { + var path = $"Gallery/{imageID}"; + var asset = Resources.Load($"Atlas/{path}"); + if (asset) + { + } + else + { + CrazyAsyKit.StartCoroutine(GetGalleryFromNet(imageID, isSuccess => + { + if (isSuccess) + CrazyAsyKit.StartCoroutine(GetLocalTexture($"{path}.jpg", texture => + { + if (texture == null) + { + action?.Invoke(null); + + return; + } + + var spr1 = new NTexture(texture); + galleryNTexturesDic.TryAdd(imageID, spr1); + action?.Invoke(spr1); + })); + else + action?.Invoke(null); + })); + } + } + else + { + action?.Invoke(spr); + } + } + + #region 缓存 + + private static readonly Dictionary nTexturesDic = new(); + private static readonly Dictionary avatarNTexturesDic = new(); + private static readonly Dictionary galleryNTexturesDic = new(); + + #endregion + + #region 加载Texture + + private static IEnumerator GetLocalTexture(string imagePath, Action action) + { + var file = $"{Application.persistentDataPath}/{imagePath}"; + var fileInfo = new FileInfo(file); + if (!fileInfo.Exists) + { + action?.Invoke(null); + yield break; + } + + var avatarPath = $"file://{file}"; + var uwr = UnityWebRequestTexture.GetTexture(avatarPath); + yield return uwr.SendWebRequest(); + if (uwr.result is UnityWebRequest.Result.ConnectionError or UnityWebRequest.Result.ProtocolError) + { + action?.Invoke(null); + yield break; + } + + var texture2D = DownloadHandlerTexture.GetContent(uwr); + + action?.Invoke(texture2D); + } + + private class DownloadTask + { + public Action Callback; + public string FileName; + public string Folder; + public GLoader Loader; + public string LocalFolder; + public bool IsGameBg; + + } + + public static string imgUrl = ""; + + // 普通队列 + private static readonly Queue normalQueue = new(); + + private static Coroutine normalCoroutine; + + // 优先队列 + private static readonly Queue priorityQueue = new(); + private static Coroutine priorityCoroutine; + + + // ====================== 并发配置 ====================== + private static int maxPriorityConcurrent = 3; // ✅ 可配置最大并发数 + private static int priorityRunning = 0; // 当前正在运行的任务数 + + #region 材质池 + + private static class MaterialPool + { + private static readonly Stack blurMats = new(); + private static readonly Stack normalMats = new(); + + public static Material GetBlur() + { + if (blurMats.Count > 0) return blurMats.Pop(); + var shader = Resources.Load("RedHotRoastAssets/Shader/Blur"); + if (!shader) return null; + return new Material(shader); + } + + public static Material GetNormal() + { + if (normalMats.Count > 0) return normalMats.Pop(); + var shader = Resources.Load("RedHotRoastAssets/Shader/FairyGUI/FairyGUI-Image"); + if (!shader) return null; + return new Material(shader); + } + + public static void Return(Material mat) + { + if (!mat) return; + var name = mat.shader.name; + if (name.Contains("Blur")) blurMats.Push(mat); + else normalMats.Push(mat); + } + + public static void Clear() + { + foreach (var mat in blurMats) Object.Destroy(mat); + blurMats.Clear(); + foreach (var mat in normalMats) Object.Destroy(mat); + normalMats.Clear(); + } + } + + #endregion + + #region 图片加载接口 + + public static string getResPath() + { + // 删除旧资源 + if (!DataMgr.curResVersion.Value.IsNullOrWhiteSpace() && DataMgr.curResVersion.Value != ConfigSystem.GetCommonConf().ResVersion) + { + var oldFolder = Path.Combine(Application.persistentDataPath, DataMgr.curResVersion.Value); + if (Directory.Exists(oldFolder)) + { + Directory.Delete(oldFolder, true); + } + DataMgr.curResVersion.Value = ConfigSystem.GetCommonConf().ResVersion; + } + else if (DataMgr.curResVersion.Value.IsNullOrWhiteSpace()) + { + DataMgr.curResVersion.Value = ConfigSystem.GetCommonConf().ResVersion; + } + + if (ConfigSystem.GetCommonConf().ResVersion.IsNullOrWhiteSpace()) + { + Debug.LogError("获取资源路径失败"); + return Application.persistentDataPath; + } + + string curFolder = Path.Combine(Application.persistentDataPath, ConfigSystem.GetCommonConf().ResVersion); + return curFolder; + } + + public static void SetImgLoader(GLoader loader, string fileName, Action callback, + string folder, string localFolder, bool priority = true, bool isLoad = false, bool isGameBg = false) + { + var localPath = Path.Combine(getResPath(), localFolder, fileName + ".jpg"); + if (File.Exists(localPath)) + { + Debug.Log($"[SetImgLoader] 本地存在,直接加载 {fileName}"); + CrazyAsyKit.StartCoroutine(LoadTexture(fileName, loader, callback, localFolder, isGameBg)); + return; + } + + if (isLoad) + { + Debug.Log($"[SetImgLoader] 兼容老逻辑,直接加载 {fileName}"); + return; + } + + var task = new DownloadTask + { + Loader = loader, + FileName = fileName, + Folder = folder, + Callback = callback, + LocalFolder = localFolder, + IsGameBg = isGameBg + + }; + + if (priority) + EnqueuePriorityTask(task, isBatch: false); // 👈 单任务标记 + else + EnqueueNormalTask(loader, fileName, callback, folder, localFolder); + } + + + /// + /// 批量加载任务(优先队列,串行) + /// + public static void SetImgLoaders( + List<(GLoader loader, string fileName, Action callback, string folder, string localFolder)> tasks) + { + Debug.Log($"[BatchSetImgLoader] 收到 {tasks.Count} 个任务"); + + // 清空旧任务(批量任务才清空) + if (priorityCoroutine != null) + { + CrazyAsyKit.StopCoroutine(priorityCoroutine); + priorityCoroutine = null; + } + + priorityQueue.Clear(); + + foreach (var task in tasks) + { + var downloadTask = new DownloadTask + { + Loader = task.loader, + FileName = task.fileName, + Folder = task.folder, + Callback = task.callback, + LocalFolder = task.localFolder, + IsGameBg = false + + }; + + EnqueuePriorityTask(downloadTask, isBatch: true); // 👈 批量标记 + } + + if (priorityCoroutine == null) + priorityCoroutine = CrazyAsyKit.StartCoroutine(ProcessPriorityQueue()); + } + + + private static void EnqueuePriorityTask(DownloadTask task, bool isBatch) + { + // 去重:如果已在队列中就跳过 + foreach (var queued in priorityQueue) + { + if (queued.FileName == task.FileName) + { + Debug.Log($"[PriorityQueue] 跳过重复任务 {task.FileName}"); + return; + } + } + + if (isBatch) + Debug.Log($"[PriorityQueue] 批量添加任务 {task.FileName}"); + else + Debug.Log($"[PriorityQueue] 单任务添加 {task.FileName}"); + + priorityQueue.Enqueue(task); + + if (priorityCoroutine == null) + priorityCoroutine = CrazyAsyKit.StartCoroutine(ProcessPriorityQueue()); + } + + + #endregion + + #region 普通队列逻辑 + + private static void EnqueueNormalTask(GLoader loader, string fileName, Action callback, string folder, string localFolder) + { + normalQueue.Enqueue(new DownloadTask + { + Loader = loader, + FileName = fileName, + Folder = folder, + Callback = callback, + LocalFolder = localFolder + }); + + if (normalCoroutine == null) + normalCoroutine = CrazyAsyKit.StartCoroutine(ProcessNormalQueue()); + } + + private static IEnumerator ProcessNormalQueue() + { + while (normalQueue.Count > 0) + { + var task = normalQueue.Dequeue(); + yield return DownloadCoroutine(task); + } + + normalCoroutine = null; + } + + private static IEnumerator ProcessPriorityQueue() + { + while (priorityQueue.Count > 0 || priorityRunning > 0) + { + // 如果没达到最大并发,就从队列里拉一个任务出来 + while (priorityRunning < maxPriorityConcurrent && priorityQueue.Count > 0) + { + var task = priorityQueue.Dequeue(); + priorityRunning++; + Debug.Log($"[PriorityQueue] 开始下载 {task.FileName}"); + + // 启动一个子协程跑下载 + CrazyAsyKit.StartCoroutine(RunPriorityTask(task)); + } + + yield return null; // 每帧检查一次 + } + + priorityCoroutine = null; + Debug.Log("[PriorityQueue] 批量任务完成"); + } + + + private static IEnumerator RunPriorityTask(DownloadTask task) + { + yield return DownloadCoroutine(task); + + priorityRunning--; + Debug.Log($"[PriorityQueue] 完成 {task.FileName}"); + } + + private static IEnumerator DownloadCoroutine(DownloadTask task) + { + var localPath = Path.Combine(getResPath(), task.LocalFolder, task.FileName + ".jpg"); + + var tempPath = localPath + ".tmp"; + var url = imgUrl + task.Folder + task.FileName + ".jpg"; + Debug.Log($"[Download] 下载 tempPath=0== {tempPath} \n url==={url}"); + if (File.Exists(localPath)) + { + Debug.Log($"[SetImgLoader] 本地存在,直接加载 {task.FileName}"); + yield return LoadTexture(task.FileName, task.Loader, task.Callback, task.LocalFolder, task.IsGameBg); + yield break; + } + + // ⚠️ 确保遗留的临时文件被清理掉 + Debug.Log($"[Download] tempPath=1== {tempPath}"); + if (File.Exists(tempPath)) + { + Debug.Log($"[Download] 删除遗留临时文件 {tempPath}"); + File.Delete(tempPath); + } + + // 确保目录存在 + string tempDir = Path.GetDirectoryName(tempPath); + if (!Directory.Exists(tempDir)) + { + Directory.CreateDirectory(tempDir); + } + + var attempt = 0; + while (attempt < 3) + { + Debug.Log($"[Download] 正在下载 {task.FileName} 次数:{attempt}"); + attempt++; + using (var www = UnityWebRequest.Get(url)) + { + yield return www.SendWebRequest(); + if (www.result == UnityWebRequest.Result.Success) + { + try + { + Debug.Log($"[Download] 下载成功,保存临时文件 {tempPath}"); + File.WriteAllBytes(tempPath, www.downloadHandler.data); + + if (File.Exists(localPath)) File.Delete(localPath); + + File.Move(tempPath, localPath); + // 解密文件 + // Debug.Log($"[Download] 开始解密文件 {task.FileName}"); + // Rescrypt.DecryptFile(tempPath, localPath, ConfigManager.GameConfig.packageName); + // Debug.Log($"[Download] 解密完成,保存路径:{localPath}"); + } + catch (Exception e) + { + Debug.LogError($"[Download] 解密或保存失败:{e}"); + yield break; + } + + if (task.Loader != null) + yield return LoadTexture(task.FileName, task.Loader, task.Callback, task.LocalFolder, task.IsGameBg); + yield break; + } + + yield return new WaitForSeconds(1f); + } + } + + task.Callback?.Invoke(null); + } + +// 用字典记录每个 loader 的当前请求 +private static readonly Dictionary loaderRequests = new(); + +public static IEnumerator LoadTexture(string fileName, GLoader loader, Action callback = null, + string folder = "", bool isGameBg = false) +{ + string encryptedPath = Path.Combine(getResPath(), folder, fileName + ".jpg"); + + if (!File.Exists(encryptedPath)) + { + Debug.LogWarning($"[LoadEncryptedTexture] 加密文件不存在: {encryptedPath}"); + callback?.Invoke(null); + yield break; + } + + Debug.Log($"[LoadTexture] 开始加载本地图片 {fileName}"); + + // 如果这个 loader 已经有旧请求,先取消掉 + if (loader != null && loaderRequests.TryGetValue(loader, out var oldReq)) + { + if (!oldReq.isDone) + { + Debug.Log($"[LoadTexture] 取消上一次未完成的加载 {fileName}"); + oldReq.Abort(); + } + loaderRequests.Remove(loader); + } + + using (var www = UnityWebRequestTexture.GetTexture("file://" + GetDecryptedImagePath(fileName, folder))) + { + // 记录当前请求 + if (loader != null) loaderRequests[loader] = www; + + yield return www.SendWebRequest(); + + // 如果这个 loader 的请求已经被替换,就直接丢弃结果 + if (loader != null && (!loaderRequests.ContainsKey(loader) || loaderRequests[loader] != www)) + { + Debug.Log($"[LoadTexture] 请求已被新任务替换,丢弃结果 {fileName}"); + yield break; + } + + if (loader != null) loaderRequests.Remove(loader); + + if (www.result == UnityWebRequest.Result.Success) + { + var tex = DownloadHandlerTexture.GetContent(www); + var nTex = new NTexture(tex) { destroyMethod = DestroyMethod.Destroy }; + tex.name = fileName; + + // 清理旧纹理 + if (loader != null && loader.texture != null) + { + loader.texture.Dispose(); + if (loader.texture.nativeTexture != null) + { + UnityEngine.Object.Destroy(loader.texture.nativeTexture); + } + loader.texture = null; + } + + if (loader != null && !loader.isDisposed) + { + loader.texture = nTex; + Debug.Log($"[LoadTexture] 图片已设置到 Loader {fileName}"); + callback?.Invoke(nTex); + } + else + { + Debug.Log($"[LoadTexture] Loader 不存在或已销毁 {fileName}"); + } + + if (isGameBg) + { + callback?.Invoke(nTex); + } + } + else + { + Debug.LogError($"[LoadTexture] 加载失败 {www.error}"); + callback?.Invoke(null); + } + } + + if (loader != null && !loader.isDisposed) + loader.visible = true; +} + + public static string GetDecryptedImagePath(string fileName, string localFolder) + { + string tempPath = Path.Combine(Application.temporaryCachePath, FolderNames.GameCache, localFolder, fileName + "_temp.jpg"); + // Debug.Log($"获取解密路径: {tempPath}"); + + if (!File.Exists(tempPath)) + { + Debug.Log($"!!!!!!!!!!!!临时文件不存在: {fileName}"); + // 确保目录存在 + Directory.CreateDirectory(Path.GetDirectoryName(tempPath)); + + string encPath = Path.Combine(getResPath(), localFolder, fileName + ".jpg"); + Debug.Log(encPath); + if (!File.Exists(encPath)) return null; + Debug.Log($"!!!!!!!!!!!!写入一张: {fileName}"); + byte[] decryptedBytes = Rescrypt.DecryptFileToBytes(encPath); + File.WriteAllBytes(tempPath, decryptedBytes); + } + return tempPath; + } + + public static IEnumerator WriteTempBeforeOpenCoroutine_() + { + System.Diagnostics.Stopwatch stopwatch = System.Diagnostics.Stopwatch.StartNew(); + + var levelUnlocks = ConfigSystem.GetLevelUnlockConfig(); + var FreeImageLibrary_ = ConfigSystem.GetFreeImageConfig(); + var ADImageLibrary_ = ConfigSystem.GetADImageConfig(); + var SpecialImageLibrary_ = ConfigSystem.GetSpecialImageConfig(); + var VIPImageLibrary_ = ConfigSystem.GetVIPImageConfig(); + for (int i = 0; i < GameHelper.GetCommonModel().MultiModal - 1; i++) + { + GetDecryptedImagePath(levelUnlocks[i].Name, FolderNames.AlbumName); + yield return null; + } + var LevelUnlockListNew = DataMgr.LevelUnlockListNew.Value; + for (int i = 0; i + // { + // if (success) + // { + // GameHelper.ShowTips("save_successed", true); + // onSuccess?.Invoke(); + // } + // else + // { + // Debug.LogWarning("保存到相册失败"); + // } + // + // // 可选:清理临时文件 + // if (File.Exists(tempPath)) + // File.Delete(tempPath); + // }); + } + catch (Exception ex) + { + Debug.LogError($"保存加密图片到相册失败: {ex.Message}"); + } + } + + + public static void SaveVideoToAlbum(string fileName, Action onSuccess = null) + { + try + { + string localPath = Path.Combine(getResPath(), FolderNames.VideoName, fileName + ".mp4"); + BrigdeIOS.SaveVideoWithCustomDate(localPath); + // File.SetCreationTime(localPath, DateTime.Now); + // File.SetCreationTimeUtc(localPath, DateTime.Now); + // File.SetLastWriteTime(localPath, DateTime.Now); + // File.SetLastWriteTimeUtc(localPath, DateTime.Now); + // // CrazyAsyKit.StartCoroutine(GetSaveVideo(fileName, (isSuccess) => + // // { + // + // // })); + // NativeGallery.SaveVideoToGallery(localPath, "MyAlbum", "my_video.mp4", (bool success, string path) => + // { + // if (success) + // { + // GameHelper.ShowTips("save_successed", true); + // onSuccess?.Invoke(); + // } + // }); + } + catch (Exception ex) + { + Debug.LogError($"保存加密视频到相册失败: {ex.Message}"); + } + } + + + + public static void SetVideoLoader(VideoPlayer player, GLoader loader, string fileName, + Action action = null, bool play = true) + { + + VideoLoadScheduler.EnqueueLoad(player, fileName, loader, videoPlayer => + { + Debug.Log("RendererList------视频加载成功!-" + fileName); + Debug.Log("[绑定播放器 EnqueueLoad]=========1=== "); + if (videoPlayer != null) + { + Debug.Log("视频加载成功!"); + action?.Invoke(videoPlayer); + } + else + { + Debug.Log("视频加载失败!"); + VideoPlayerPool.Instance.ReturnPlayer(player); + action?.Invoke(null); + } + }, play); + } + + public static void SetImageMosaic(GLoader loader, int num = 80) + { + var shader = Resources.Load("RedHotRoastAssets/Shader/Mosaic"); + if (shader == null) + { + Debug.LogError("找不到 Shader:Custom/Mosaic。请确保 shader 名称正确并已包含到构建中。"); + return; + } + + var material = new Material(shader); + material.SetFloat("_BlockSize", num); // 假设你 shader 中的 blockSize 参数是这个 + loader.material = material; + } + + #region 材质处理 + + public static void SetImageBlur(GLoader loader) + { + if (loader == null || loader.isDisposed || loader.texture == null || loader.material.name == "Custom/Blur") return; + if (loader.material != null) MaterialPool.Return(loader.material); + loader.material = MaterialPool.GetBlur(); + } + + public static void CancelImageBlur(GLoader loader) + { + if (loader == null || loader.isDisposed || loader.texture == null || loader.material == null || loader.material.name != "Custom/Blur") return; + + if (loader.material != null) MaterialPool.Return(loader.material); + loader.material = MaterialPool.GetNormal(); + } + + #endregion + + /// + /// 彻底清理材质池(切场景/退出游戏时调用) + /// + public static void ClearMaterialPool() + { + MaterialPool.Clear(); + } + + private static Sprite _currentBackgroundSprite; + private static SpriteRenderer _spriteRenderer; + private static NTexture _currentNTexture; // 新增:缓存 NTexture + public static void setGamebg(string fileName) + { + // 只获取一次组件 + if (_spriteRenderer == null) + { + var go = GameObject.Find("game_bg"); + if (go == null) + { + Debug.LogError("找不到名为 'game_bg' 的 GameObject!"); + return; + } + _spriteRenderer = go.GetComponent(); + if (_spriteRenderer == null) + { + Debug.LogError("'game_bg' 上没有找到 SpriteRenderer 组件!"); + return; + } + } + + if (_spriteRenderer && _spriteRenderer.sprite && _spriteRenderer.sprite.texture.name == fileName) + { + return; + } + + // 调用统一的 SetImgLoader,不需要再自己写下载逻辑 + SetImgLoader(null, fileName, nTex => + { + if (nTex != null && nTex.nativeTexture != null) + { + Debug.Log("背景图片加载成功!"); + + var tex2D = nTex.nativeTexture as Texture2D; + if (tex2D == null) + { + Debug.LogError("NTexture 转换失败!"); + return; + } + tex2D.name = fileName; + // 创建 Sprite + var sprite = Sprite.Create( + tex2D, + new Rect(0, 0, tex2D.width, tex2D.height), + new Vector2(0.5f, 0.5f) + ); + _spriteRenderer.sprite = sprite; + + if (_currentNTexture != null) + { + _currentNTexture.Dispose(); + _currentNTexture = null; + } + if (_currentBackgroundSprite != null) + { + Object.Destroy(_currentBackgroundSprite); + _currentBackgroundSprite = null; + } + + _currentNTexture = nTex; + _currentBackgroundSprite = sprite; + + var currentWidth = _spriteRenderer.sprite.bounds.size.x; + var scaleFactor = 64f / currentWidth; + + // 等比缩放 + _spriteRenderer.transform.localScale = new Vector3(scaleFactor, scaleFactor, 1); + } + else + { + Debug.LogError("背景图片加载失败!"); + } + }, "LevelAlbums/", FolderNames.AlbumName, true, false, true); // ✅ 背景一般是立刻需要的,走优先下载 + } + + + public static void GetCardIcon(bool isLogo = false, UnityAction action = null) + { + var cardIconPath = "logo_default"; + // var paymentTypeVo = GameHelper.GetPaymentTypeVO(); + // if (isLogo) + // { + // cardIconPath = paymentTypeVo.logo_id; + // } + // else + // { + // cardIconPath = paymentTypeVo.card_name; + // } + + + GetNTexture("Atlas.Pay", cardIconPath, action); + } + + private static IEnumerator GetTextureFromNet(string type, int imgId, string imgUrl, Action action = null) + { + var imagePath = $"{CommonHelper.GetAppSavePath()}/{type}/{imgId}.jpg"; + var fileInfo = new FileInfo(imagePath); + if (fileInfo.Exists) + { + action?.Invoke(true); + yield break; + } + + var avatarRequest = UnityWebRequest.Get(imgUrl); + yield return avatarRequest.SendWebRequest(); + if (avatarRequest.result == UnityWebRequest.Result.ConnectionError || + avatarRequest.result == UnityWebRequest.Result.ProtocolError) + { + action?.Invoke(false); + } + else + { + var avatarData = avatarRequest.downloadHandler.data; + var dirPath = Path.GetDirectoryName(imagePath); + if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); + + if (fileInfo.Exists) + yield break; + Stream stream = fileInfo.Create(); + stream.Write(avatarData, 0, avatarData.Length); + stream.Close(); + stream.Dispose(); + action?.Invoke(true); + } + } + + #endregion + + #region 头像相关 + + public static void SetAvatarToLoader(int avatarId, GLoader _GLoader, bool IsNeedDefAvatar = true) + { + if (!avatarNTexturesDic.TryGetValue(avatarId, out var spr)) + try + { + Sprite sprite = null; + if (avatarId == 0) + { + if (!PlayerPrefsKit.ReadBool("IsLogin")) + { + avatarId = 1; + SetAvatarToLoader(avatarId, _GLoader); + return; + } + + if (PlayerPrefsKit.ReadString("AvatarUrl").IsNullOrWhiteSpace()) + { + _GLoader.url = "ui://pmf3wbjicxrg4"; + return; + } + + GetSelfFaceBookAvatar(texture => + { + if (_GLoader != null) + { + if (texture != null) + _GLoader.texture = texture; + else + _GLoader.url = "ui://pmf3wbjicxrg4"; + } + }); + return; + } + + if (avatarId > 100) + { + if (IsNeedDefAvatar) _GLoader.url = "ui://pmf3wbjicxrg4"; + + GetFaceBookAvatar(avatarId, e => + { + if (_GLoader != null) + { + if (e == null) + _GLoader.url = "ui://pmf3wbjicxrg4"; + else + _GLoader.texture = e; + } + }); + return; + } + + LoadKit.Instance.LoadSprite("Atlas.Avatar", avatarId.ToString(), spr => + { + sprite = spr; + var spr1 = new NTexture(sprite); + _GLoader.texture = spr1; + avatarNTexturesDic.Add(avatarId, spr1); + }); + } + catch (Exception e) + { + Debug.LogError(e); + } + else + _GLoader.texture = spr; + } + + + private static IEnumerator GetAvatarLocal(int avatarId, Action action) + { + yield return GetLocalTexture($"Avatar/{avatarId}.jpg", action); + } + + #endregion + + #region FaceBook头像相关 + + public static void GetFaceBookAvatar(int avatarId, Action action) + { + if (!avatarNTexturesDic.TryGetValue(avatarId, out var spr)) + HallManager.Instance.StartCoroutine(GetAvatarLocal(avatarId, texture => + { + if (texture == null) + { + action?.Invoke(null); + return; + } + + spr = new NTexture(texture); + if (avatarNTexturesDic.ContainsKey(avatarId)) avatarNTexturesDic.Add(avatarId, spr); + + action?.Invoke(spr); + })); + else + action?.Invoke(spr); + } + + + public static void GetSelfFaceBookAvatar(Action action) + { + if (!avatarNTexturesDic.TryGetValue(0, out var spr)) + { + } + else + { + action?.Invoke(spr); + } + } + + #endregion } \ No newline at end of file diff --git a/Assets/Scripts/ModuleUI/AlbumDetail/AlbumDetailUI.cs b/Assets/Scripts/ModuleUI/AlbumDetail/AlbumDetailUI.cs index a08f4a57..4babb10c 100644 --- a/Assets/Scripts/ModuleUI/AlbumDetail/AlbumDetailUI.cs +++ b/Assets/Scripts/ModuleUI/AlbumDetail/AlbumDetailUI.cs @@ -1,299 +1,299 @@ - -using FGUI.ZM_Common_01; -using UnityEngine; -using FairyGUI; -using System.Collections.Generic; -using FGUI.LG_albums; -using FGUI.LG_Common; -using SGModule.DataStorage; -using DG.Tweening; -using SGModule.Common.Extensions; -using System.Linq; -using SGModule.NetKit; -namespace RedHotRoast -{ - public class AlbumDetailUI : BaseUI - { - private AlbumDetailUICtrl ctrl; - private AlbumDetailModel model; - private FGUI.LG_albums.com_albumsDetail ui; - - public AlbumDetailUI(AlbumDetailUICtrl ctrl) : base(ctrl) - { - uiName = UIConst.AlbumDetailUI; - this.ctrl = ctrl; - } - - protected override void SetUIInfo(UIInfo uiInfo) - { - uiInfo.packageName = "LG_albums"; - uiInfo.assetName = "com_albumsDetail"; - uiInfo.layerType = UILayerType.Popup; - uiInfo.isNeedOpenAnim = false; - uiInfo.isNeedCloseAnim = false; - uiInfo.isNeedUIMask = true; - } - - #region 生命周期 - protected override void OnInit() - { - //model = ModuleManager.Instance.GetModel(ModelConst.AlbumDetailModel) as AlbumDetailModel; - } - - protected override void OnClose() - { - if (loader != null && !loader.isDisposed && loader.texture != null) - { - loader.texture.Dispose(); - loader.texture = null; - } - loader = null; - - if (new_index != -1) - { - GameDispatcher.Instance.Dispatch(GameMsg.UnlockAlbums, index); - } - } - - protected override void OnBind() - { - ui = baseUI as FGUI.LG_albums.com_albumsDetail; - } - private List LevelData; - private int new_index = -1; - private int index; - - private GLoader loader = new GLoader(); - protected override void OnOpenBefore(object args) - { - index = (int)args; - Debug.Log(index); - ui.btn_close.SetClick(() => - { - CtrlCloseUI(); - }); - LevelData = ConfigSystem.GetConfig(); - // ui.list_.SetVirtual(); - // ui.list_.itemRenderer = RendererList; - // ui.list_.numItems = GameHelper.GetLevel() - 1; - // ui.list_.ScrollToView(new_index); - - RendererList(); - } - - protected override void OnOpen(object args) - { - } - - protected override void OnHide() - { - } - - protected override void OnDisplay(object args) - { - } - #endregion - - #region 消息 - protected override void AddListener() - { - GameDispatcher.Instance.AddListener(GameMsg.BuyVip, refrsh); - } - protected override void RemoveListener() - { - GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, refrsh); - } - #endregion - - //初始化页面逻辑 - private void refrsh(object a = null) - { - DOVirtual.DelayedCall(0.5f, () => - { - // ui.list_.numItems = GameHelper.GetLevel() - 1; - RendererList(); - }); - - } - // void RendererList(int index, GObject obj) - void RendererList() - { - - item_albumsDetails item = (item_albumsDetails)ui.com_item; - - loader = item.com_loader.GetChild("loader") as GLoader; - - // if (GameHelper.GetVipPrivilege(Subscription.VipLevel.As())) - // { - // (item.btn_vip as btn_claim_2).have_vip.selectedIndex = 1; - - // } - // if (GameHelper.GetVipPrivilege(Subscription.SLVLevel.As())) - // { - // (item.btn_watch as btn_claim_1).have_vip.selectedIndex = 1; - - // } - - - var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; - var btn_down_coin = (FGUI.LG_Common.btn_unlock_1)item.btn_download_coin; - btn_down_coin.title = downloadCoinNum.As(); - btn_down_coin.down_load.selectedIndex = GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As()) ? 0 : 1; - - - if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) - { - (item.btn_download as FGUI.LG_Common.btn_claim).have_vip.selectedIndex = 1; - item.is_vip.selectedIndex = 1; - } - else - { - item.is_vip.selectedIndex = 0; - } - if (index < GameHelper.GetCommonModel().MultiModal - 1) - { - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, null, "LevelAlbums/", FolderNames.AlbumName); - item.btn_download.SetClick(() => - { - if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) - { - TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); - } - else - { - GameHelper.ShowVideoAd("DownloadImage", isSuccess => - { - if (isSuccess) - { - TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); - } - }); - } - - }); - btn_down_coin.SetClick(() => - { - if (GameHelper.Get101() >= downloadCoinNum) - { - GameHelper.AddGold(-downloadCoinNum); - TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); - TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - } - }); - } - else - { - Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == index + 1); - string file_name = ""; - if (levelunlock_ != null) - { - if (levelunlock_.type == 0) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - FreeImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - else if (levelunlock_.type == 1) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - ADImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - else if (levelunlock_.type == 2) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - SpecialImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - else if (levelunlock_.type == 3) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - VIPImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - item.btn_download.SetClick(() => - { - if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) - { - TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); - } - else - { - GameHelper.ShowVideoAd("DownloadImage", isSuccess => - { - if (isSuccess) - { - TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); - } - }); - } - - }); - btn_down_coin.SetClick(() => - { - if (GameHelper.Get101() >= downloadCoinNum) - { - GameHelper.AddGold(-downloadCoinNum); - TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); - TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - } - }); - } - else - { - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, null, "LevelAlbums/", FolderNames.AlbumName); - item.btn_download.SetClick(() => - { - if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) - { - TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); - } - else - { - GameHelper.ShowVideoAd("DownloadImage", isSuccess => - { - if (isSuccess) - { - TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); - } - }); - } - - }); - btn_down_coin.SetClick(() => - { - if (GameHelper.Get101() >= downloadCoinNum) - { - GameHelper.AddGold(-downloadCoinNum); - TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); - TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - - } - }); - } - } - } - } + +using FGUI.ZM_Common_01; +using UnityEngine; +using FairyGUI; +using System.Collections.Generic; +using FGUI.LG_albums; +using FGUI.LG_Common; +using SGModule.DataStorage; +using DG.Tweening; +using SGModule.Common.Extensions; +using System.Linq; +using SGModule.NetKit; +namespace RedHotRoast +{ + public class AlbumDetailUI : BaseUI + { + private AlbumDetailUICtrl ctrl; + private AlbumDetailModel model; + private FGUI.LG_albums.com_albumsDetail ui; + + public AlbumDetailUI(AlbumDetailUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.AlbumDetailUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "LG_albums"; + uiInfo.assetName = "com_albumsDetail"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.AlbumDetailModel) as AlbumDetailModel; + } + + protected override void OnClose() + { + if (loader != null && !loader.isDisposed && loader.texture != null) + { + loader.texture.Dispose(); + loader.texture = null; + } + loader = null; + + if (new_index != -1) + { + GameDispatcher.Instance.Dispatch(GameMsg.UnlockAlbums, index); + } + } + + protected override void OnBind() + { + ui = baseUI as FGUI.LG_albums.com_albumsDetail; + } + private List LevelData; + private int new_index = -1; + private int index; + + private GLoader loader = new GLoader(); + protected override void OnOpenBefore(object args) + { + index = (int)args; + Debug.Log(index); + ui.btn_close.SetClick(() => + { + CtrlCloseUI(); + }); + LevelData = ConfigSystem.GetLevelUnlockConfig(); + // ui.list_.SetVirtual(); + // ui.list_.itemRenderer = RendererList; + // ui.list_.numItems = GameHelper.GetLevel() - 1; + // ui.list_.ScrollToView(new_index); + + RendererList(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.BuyVip, refrsh); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, refrsh); + } + #endregion + + //初始化页面逻辑 + private void refrsh(object a = null) + { + DOVirtual.DelayedCall(0.5f, () => + { + // ui.list_.numItems = GameHelper.GetLevel() - 1; + RendererList(); + }); + + } + // void RendererList(int index, GObject obj) + void RendererList() + { + + item_albumsDetails item = (item_albumsDetails)ui.com_item; + + loader = item.com_loader.GetChild("loader") as GLoader; + + // if (GameHelper.GetVipPrivilege(Subscription.VipLevel.As())) + // { + // (item.btn_vip as btn_claim_2).have_vip.selectedIndex = 1; + + // } + // if (GameHelper.GetVipPrivilege(Subscription.SLVLevel.As())) + // { + // (item.btn_watch as btn_claim_1).have_vip.selectedIndex = 1; + + // } + + + var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; + var btn_down_coin = (FGUI.LG_Common.btn_unlock_1)item.btn_download_coin; + btn_down_coin.title = downloadCoinNum.As(); + btn_down_coin.down_load.selectedIndex = GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As()) ? 0 : 1; + + + if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) + { + (item.btn_download as FGUI.LG_Common.btn_claim).have_vip.selectedIndex = 1; + item.is_vip.selectedIndex = 1; + } + else + { + item.is_vip.selectedIndex = 0; + } + if (index < GameHelper.GetCommonModel().MultiModal - 1) + { + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, null, "LevelAlbums/", FolderNames.AlbumName); + item.btn_download.SetClick(() => + { + if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) + { + TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); + } + else + { + GameHelper.ShowVideoAd("DownloadImage", isSuccess => + { + if (isSuccess) + { + TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); + } + }); + } + + }); + btn_down_coin.SetClick(() => + { + if (GameHelper.Get101() >= downloadCoinNum) + { + GameHelper.AddGold(-downloadCoinNum); + TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); + TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + } + }); + } + else + { + Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == index + 1); + string file_name = ""; + if (levelunlock_ != null) + { + if (levelunlock_.type == 0) + { + if (levelunlock_.config_index >= ConfigSystem.GetFreeImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetFreeImageConfig().Count - 1; + FreeImageLibrary _leveldata = ConfigSystem.GetFreeImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + else if (levelunlock_.type == 1) + { + if (levelunlock_.config_index >= ConfigSystem.GetADImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetADImageConfig().Count - 1; + ADImageLibrary _leveldata = ConfigSystem.GetADImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + else if (levelunlock_.type == 2) + { + if (levelunlock_.config_index >= ConfigSystem.GetSpecialImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetSpecialImageConfig().Count - 1; + SpecialImageLibrary _leveldata = ConfigSystem.GetSpecialImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + else if (levelunlock_.type == 3) + { + if (levelunlock_.config_index >= ConfigSystem.GetVIPImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetVIPImageConfig().Count - 1; + VIPImageLibrary _leveldata = ConfigSystem.GetVIPImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + item.btn_download.SetClick(() => + { + if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) + { + TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); + } + else + { + GameHelper.ShowVideoAd("DownloadImage", isSuccess => + { + if (isSuccess) + { + TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); + } + }); + } + + }); + btn_down_coin.SetClick(() => + { + if (GameHelper.Get101() >= downloadCoinNum) + { + GameHelper.AddGold(-downloadCoinNum); + TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); + TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + } + }); + } + else + { + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, null, "LevelAlbums/", FolderNames.AlbumName); + item.btn_download.SetClick(() => + { + if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) + { + TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); + } + else + { + GameHelper.ShowVideoAd("DownloadImage", isSuccess => + { + if (isSuccess) + { + TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); + } + }); + } + + }); + btn_down_coin.SetClick(() => + { + if (GameHelper.Get101() >= downloadCoinNum) + { + GameHelper.AddGold(-downloadCoinNum); + TextureHelper.SaveImageToAlbum(LevelData[index].Name, FolderNames.AlbumName); + TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + + } + }); + } + } + } + } } \ No newline at end of file diff --git a/Assets/Scripts/ModuleUI/Alubum/AlubumUI.cs b/Assets/Scripts/ModuleUI/Alubum/AlubumUI.cs index 8a0d2516..c3fa0190 100644 --- a/Assets/Scripts/ModuleUI/Alubum/AlubumUI.cs +++ b/Assets/Scripts/ModuleUI/Alubum/AlubumUI.cs @@ -1,494 +1,494 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using DG.Tweening; -using FairyGUI; -using FGUI.LG_albums; -using UnityEngine; -using System; -using System.Threading; -using System.Threading.Tasks; -namespace RedHotRoast - -{ - public class AlubumUI : BaseUI - { - private AlubumUICtrl ctrl; - private AlubumModel model; - private com_albums ui; - private long[] UpDatatime; - - public AlubumUI(AlubumUICtrl ctrl) : base(ctrl) - { - uiName = UIConst.AlubumUI; - this.ctrl = ctrl; - } - - protected override void SetUIInfo(UIInfo uiInfo) - { - uiInfo.packageName = "LG_albums"; - uiInfo.assetName = "com_albums"; - uiInfo.layerType = UILayerType.Popup; - uiInfo.isNeedOpenAnim = false; - uiInfo.isNeedCloseAnim = false; - uiInfo.isNeedUIMask = true; - } - - //初始化页面逻辑 - private void InitView(object a = null) - { - UpDatatime = new long[LevelData.Count]; - ImageName = new string[LevelData.Count]; - ui.list_albums.itemRenderer = RendererList; - ui.list_albums.numItems = LevelData.Count; - - InitScroll(); - } - - private void SetItemData(object obj = null) - { - UpDatatime[(int)obj] = 0; - ui.list_albums.RefreshVirtualList(); - } - - #region 生命周期 - - protected override void OnInit() - { - GLoaderPool.Instance.Init(null, 24, 312, 310); - } - - protected override void OnClose() - { - foreach (var t in loader_list) - if (t != null && !t.isDisposed && t.texture != null) - { - t.texture.Dispose(); - t.texture = null; - } - - // 1. 解除 UI 对 Loader 的引用 - for (var i = 0; i < ui.list_albums.numChildren; i++) - { - var item = ui.list_albums.GetChildAt(i) as item_albums; - if (item != null && item.com_loader.loader != null) item.com_loader.loader = null; // 清掉 GLoader 引用 - } - - activeLoaders.Clear(); - _fileIsExist.Clear(); - - GLoaderPool.Instance.DisposeAll(); - - TextureHelper.ClearMaterialPool(); - - // 强制卸载未使用的资源 - Resources.UnloadUnusedAssets(); - MemoryManager.CleanMemoryMonitor(); - } - - protected override void OnBind() - { - ui = baseUI as com_albums; - } - - private List LevelData; - - private readonly List loader_list = new(); - public SmartInvoker invoker; - protected override void OnOpenBefore(object args) - { - invoker = new SmartInvoker(() => - { - for (int i = 0; i < UpDatatime.Length; i++) - { - UpDatatime[i] = 0; - // ImageName[i] = ""; - } - ui.list_albums.RefreshVirtualList(); - }, TimeSpan.FromSeconds(0.2f)); - - LevelData = ConfigSystem.GetConfig(); - ui.list_albums.SetVirtual(); - ui.btn_close1.SetClick(() => { CtrlCloseUI(); }); - InitView(); - } - - - private const int MaxVisibleCount = 18; // 一屏显示18个 - private const int PreloadCount = 3; // 上下各预加载一屏 - private readonly Dictionary activeLoaders = new(); - private readonly Dictionary _fileIsExist = new(); - - private Throttle _throttle; - - private void InitScroll() - { - // ui.list_albums.scrollPane.onScroll.Add(OnScrollUpdate); - ui.list_albums.scrollPane.onScrollEnd.Add(OnScrollEndCB); // 保留结束时的整理 - - OnScrollEnd(); - } - - - private void OnScrollEndCB() - { - // UpdateVisibleAndPreload(); - - OnScrollEnd(); - - // Debug.Log("更新一次"); - } - - private void UpdateVisibleAndPreload() - { - // Debug.Log("[UpdateVisibleAndPreload]--------111111--------- "); - // if (LevelData == null || LevelData.Count == 0) return; - - // var firstVisibleIndex = ui.list_albums.GetFirstChildInView(); - // var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_albums.numItems - 1); - - // var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); - // var endIndex = Mathf.Min(ui.list_albums.numItems - 1, lastVisibleIndex + PreloadCount); - - // // 回收超出范围 loader - // var keysToRemove = new List(); - // foreach (var kv in activeLoaders) - // { - // var idx = kv.Key; - // if (idx < startIndex || idx > endIndex) - // { - // GLoaderPool.Instance.ReturnLoader(kv.Value); - // var oldItem = ui.list_albums.GetChildAt(idx) as item_albums; - // if (oldItem != null) oldItem.com_loader.loader = null; - // keysToRemove.Add(idx); - // } - // } - - // foreach (var k in keysToRemove) activeLoaders.Remove(k); - - - // // 分配 loader 并加载图片 - // for (var i = startIndex; i <= endIndex; i++) - // { - // if (activeLoaders.ContainsKey(i)) continue; - - // var item = ui.list_albums.GetChildAt(i) as item_albums; - // if (item == null) continue; - - // if (item.com_loader.loader != null && !item.com_loader.loader.isDisposed) - // GLoaderPool.Instance.ReturnLoader(item.com_loader.loader); - - // var loader = GLoaderPool.Instance.GetLoader(); - // item.com_loader.loader = loader; - // item.com_loader.AddChild(loader); - // loader.SetSize(item.com_loader.loader.width, item.com_loader.loader.height); - - // _fileIsExist.TryGetValue(i, out var value); - // if (!value) - // { - // var localPath = Path.Combine(TextureHelper.getResPath(), LevelData[i].Name + ".jpg"); - - // if (File.Exists(localPath)) - // { - // _fileIsExist[i] = true; - // Debug.Log($"[SetImgLoader] 本地存在,直接加载 {LevelData[i].Name}"); - // CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LevelData[i].Name, loader, null, - // "LevelAlbums/")); - // } - // else - // { - // _fileIsExist[i] = false; - // } - // } - // else - // { - // CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LevelData[i].Name, loader, null, - // "LevelAlbums/")); - // } - - // activeLoaders[i] = loader; - // } - // Debug.Log($"[ScrollUpdate] active loaders={activeLoaders.Count}, pool={GLoaderPool.Instance.GetPoolCount()}, inUse={GLoaderPool.Instance.GetInUseCount()}"); - } - - private void OnScrollEnd() - { - invoker.Invoke(); - // for (int i = 0; i < UpDatatime.Length; i++) - // { - // UpDatatime[i] = 0; - // // ImageName[i] = ""; - // } - - // DOVirtual.DelayedCall(0.1f, () => - // { - // ui.list_albums.RefreshVirtualList(); - // }); - - // if (LevelData == null || LevelData.Count == 0) return; - - // var firstVisibleIndex = ui.list_albums.GetFirstChildInView(); - // var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_albums.numItems - 1); - - // var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); - // var endIndex = Mathf.Min(ui.list_albums.numItems - 1, lastVisibleIndex + PreloadCount); - - // // Debug.Log($"[ScrollEnd] start index={startIndex} end index={endIndex}"); - - - // var tasks = new List<(GLoader loader, string fileName, Action callback, string folder)>(); - // // 分配 loader 并加载图片 - // for (var i = startIndex; i <= endIndex; i++) - // { - // _fileIsExist.TryGetValue(i, out var value); - - // if (value) continue; - - // if (GameHelper.GetLevel() < i + 1) continue; - - // var item = ui.list_albums.GetChildAt(i) as item_albums; - // if (item == null) continue; - // if (item.com_loader.loader != null && !item.com_loader.loader.isDisposed) - // GLoaderPool.Instance.ReturnLoader(item.com_loader.loader); - // var loader = GLoaderPool.Instance.GetLoader(); - // item.com_loader.loader = loader; - // item.com_loader.AddChild(loader); - // loader.SetSize(item.com_loader.loader.width, item.com_loader.loader.height); - - // var idx = i; - // tasks.Add((loader, LevelData[i].Name, NTexture => - // { - // if (NTexture != null) _fileIsExist[idx] = true; - // }, "LevelAlbums/")); - - // activeLoaders[i] = loader; - // } - - // if (tasks.Count > 0) TextureHelper.SetImgLoaders(tasks); - } - - private string[] ImageName; - - private void RendererList(int index, GObject obj) - { - // Debug.Log("Render list" ); - - // Debug.Log(JsonConvert.SerializeObject(LevelData[index])); - - item_albums item = (item_albums)obj; - item.text_num.text = (index + 1).ToString(); - if (index < GameHelper.GetCommonModel().MultiModal - 1) - { - item.type_.selectedIndex = 0; - if (GameHelper.GetLevel() > index + 1) - { - item.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.AlbumDetailUI_Open, index); }); - } - else - { - item.SetClick(() => { GameHelper.ShowTips("lv_unlock", true); }); - } - } - else - { - Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == index + 1); - if (levelunlock_ != null) - { - item.type_.selectedIndex = levelunlock_.type; - } - else item.type_.selectedIndex = 0; - if (GameHelper.GetLevel() > index + 1) - { - item.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.AlbumDetailUI_Open, index); }); - } - else - { - item.SetClick(() => { GameHelper.ShowTips("lv_unlock", true); }); - } - } - - - if (GameHelper.GetNowTime() < UpDatatime[index] + 1) return; - UpDatatime[index] = GameHelper.GetNowTime(); - // if (!activeLoaders.ContainsValue(item.com_loader.loader)) activeLoaders[index] = item.com_loader.loader; - if (!loader_list.Contains(item.com_loader.GetChild("loader") as GLoader)) - loader_list.Add(item.com_loader.GetChild("loader") as GLoader); - - - if (index < GameHelper.GetCommonModel().MultiModal - 1) - { - if (GameHelper.GetLevel() > index + 1) - { - item.isUnlock.selectedIndex = 1; - if (item.com_loader.loader.texture == null || - item.com_loader.loader.texture.nativeTexture.name != LevelData[index].Name) - { - // item.isUnlock.selectedIndex = 0; - // if (item.com_loader.loader.texture != null) - // { - // item.com_loader.loader.texture.Dispose(); // 释放 GPU 资源 - // item.com_loader.loader.texture = null; // 断开引用 - // } - - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, - (a) => { Debug.Log(item.com_loader.loader.texture.nativeTexture.name); }, "LevelAlbums/", FolderNames.AlbumName); - - ImageName[index] = LevelData[index].Name; - } - - item.touchable = true; - } - else - { - item.isUnlock.selectedIndex = 0; - // item.touchable = false; - } - } - else - { - Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == index + 1); - - if (GameHelper.GetLevel() > index + 1) - { - if (levelunlock_ != null) - { - item.isUnlock.selectedIndex = 1; - - if (item.com_loader.loader.texture == null || item.com_loader.loader.texture.nativeTexture.name != ImageName[index]) - { - - if (levelunlock_.type == 0) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - FreeImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - ImageName[index] = LevelData[index].Name; - } - else if (levelunlock_.type == 1) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - ADImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - ImageName[index] = LevelData[index].Name; - } - else if (levelunlock_.type == 2) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - SpecialImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - ImageName[index] = LevelData[index].Name; - } - else if (levelunlock_.type == 3) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - VIPImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - ImageName[index] = LevelData[index].Name; - } - - } - - } - else - { - item.isUnlock.selectedIndex = 1; - if (item.com_loader.loader.texture == null || item.com_loader.loader.texture.nativeTexture.name != LevelData[index].Name) - { - TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, null, "LevelAlbums/", FolderNames.AlbumName); - ImageName[index] = LevelData[index].Name; - } - } - } - else - { - // item.touchable = false; - item.isUnlock.selectedIndex = 0; - } - } - } - - protected override void OnOpen(object args) - { - } - - protected override void OnHide() - { - } - - protected override void OnDisplay(object args) - { - } - - #endregion - - #region 消息 - - protected override void AddListener() - { - GameDispatcher.Instance.AddListener(GameMsg.UnlockAlbums, SetItemData); - } - - protected override void RemoveListener() - { - GameDispatcher.Instance.RemoveListener(GameMsg.UnlockAlbums, SetItemData); - } - - #endregion - } - public class SmartInvoker - { - private readonly Action _action; - private readonly TimeSpan _delay; - private DateTime _lastImmediateInvoke = DateTime.MinValue; - private CancellationTokenSource _cts = null; - private readonly object _lock = new object(); - private bool _hasPending = false; - - public SmartInvoker(Action action, TimeSpan delay) - { - _action = action; - _delay = delay; - } - - public void Invoke() - { - lock (_lock) - { - var now = DateTime.UtcNow; - var timeSinceLast = now - _lastImmediateInvoke; - - if (timeSinceLast >= _delay) - { - _lastImmediateInvoke = now; - _action(); - Debug.Log("diaoyongyiciiiiiiiiiiiiiii"); - } - else - { - _hasPending = true; - _cts?.Cancel(); - _cts = new CancellationTokenSource(); - var token = _cts.Token; - - Task.Delay(_delay, token).ContinueWith(t => - { - if (!t.IsCanceled) - { - lock (_lock) - { - if (_hasPending) - { - _lastImmediateInvoke = DateTime.UtcNow; - _hasPending = false; - _action(); - Debug.Log("diaoyongyiciiiiiiiiiiiiiii"); - } - } - } - }, TaskScheduler.Default); - } - } - } - } +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using DG.Tweening; +using FairyGUI; +using FGUI.LG_albums; +using UnityEngine; +using System; +using System.Threading; +using System.Threading.Tasks; +namespace RedHotRoast + +{ + public class AlubumUI : BaseUI + { + private AlubumUICtrl ctrl; + private AlubumModel model; + private com_albums ui; + private long[] UpDatatime; + + public AlubumUI(AlubumUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.AlubumUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "LG_albums"; + uiInfo.assetName = "com_albums"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + //初始化页面逻辑 + private void InitView(object a = null) + { + UpDatatime = new long[LevelData.Count]; + ImageName = new string[LevelData.Count]; + ui.list_albums.itemRenderer = RendererList; + ui.list_albums.numItems = LevelData.Count; + + InitScroll(); + } + + private void SetItemData(object obj = null) + { + UpDatatime[(int)obj] = 0; + ui.list_albums.RefreshVirtualList(); + } + + #region 生命周期 + + protected override void OnInit() + { + GLoaderPool.Instance.Init(null, 24, 312, 310); + } + + protected override void OnClose() + { + foreach (var t in loader_list) + if (t != null && !t.isDisposed && t.texture != null) + { + t.texture.Dispose(); + t.texture = null; + } + + // 1. 解除 UI 对 Loader 的引用 + for (var i = 0; i < ui.list_albums.numChildren; i++) + { + var item = ui.list_albums.GetChildAt(i) as item_albums; + if (item != null && item.com_loader.loader != null) item.com_loader.loader = null; // 清掉 GLoader 引用 + } + + activeLoaders.Clear(); + _fileIsExist.Clear(); + + GLoaderPool.Instance.DisposeAll(); + + TextureHelper.ClearMaterialPool(); + + // 强制卸载未使用的资源 + Resources.UnloadUnusedAssets(); + MemoryManager.CleanMemoryMonitor(); + } + + protected override void OnBind() + { + ui = baseUI as com_albums; + } + + private List LevelData; + + private readonly List loader_list = new(); + public SmartInvoker invoker; + protected override void OnOpenBefore(object args) + { + invoker = new SmartInvoker(() => + { + for (int i = 0; i < UpDatatime.Length; i++) + { + UpDatatime[i] = 0; + // ImageName[i] = ""; + } + ui.list_albums.RefreshVirtualList(); + }, TimeSpan.FromSeconds(0.2f)); + + LevelData = ConfigSystem.GetLevelUnlockConfig(); + ui.list_albums.SetVirtual(); + ui.btn_close1.SetClick(() => { CtrlCloseUI(); }); + InitView(); + } + + + private const int MaxVisibleCount = 18; // 一屏显示18个 + private const int PreloadCount = 3; // 上下各预加载一屏 + private readonly Dictionary activeLoaders = new(); + private readonly Dictionary _fileIsExist = new(); + + private Throttle _throttle; + + private void InitScroll() + { + // ui.list_albums.scrollPane.onScroll.Add(OnScrollUpdate); + ui.list_albums.scrollPane.onScrollEnd.Add(OnScrollEndCB); // 保留结束时的整理 + + OnScrollEnd(); + } + + + private void OnScrollEndCB() + { + // UpdateVisibleAndPreload(); + + OnScrollEnd(); + + // Debug.Log("更新一次"); + } + + private void UpdateVisibleAndPreload() + { + // Debug.Log("[UpdateVisibleAndPreload]--------111111--------- "); + // if (LevelData == null || LevelData.Count == 0) return; + + // var firstVisibleIndex = ui.list_albums.GetFirstChildInView(); + // var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_albums.numItems - 1); + + // var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); + // var endIndex = Mathf.Min(ui.list_albums.numItems - 1, lastVisibleIndex + PreloadCount); + + // // 回收超出范围 loader + // var keysToRemove = new List(); + // foreach (var kv in activeLoaders) + // { + // var idx = kv.Key; + // if (idx < startIndex || idx > endIndex) + // { + // GLoaderPool.Instance.ReturnLoader(kv.Value); + // var oldItem = ui.list_albums.GetChildAt(idx) as item_albums; + // if (oldItem != null) oldItem.com_loader.loader = null; + // keysToRemove.Add(idx); + // } + // } + + // foreach (var k in keysToRemove) activeLoaders.Remove(k); + + + // // 分配 loader 并加载图片 + // for (var i = startIndex; i <= endIndex; i++) + // { + // if (activeLoaders.ContainsKey(i)) continue; + + // var item = ui.list_albums.GetChildAt(i) as item_albums; + // if (item == null) continue; + + // if (item.com_loader.loader != null && !item.com_loader.loader.isDisposed) + // GLoaderPool.Instance.ReturnLoader(item.com_loader.loader); + + // var loader = GLoaderPool.Instance.GetLoader(); + // item.com_loader.loader = loader; + // item.com_loader.AddChild(loader); + // loader.SetSize(item.com_loader.loader.width, item.com_loader.loader.height); + + // _fileIsExist.TryGetValue(i, out var value); + // if (!value) + // { + // var localPath = Path.Combine(TextureHelper.getResPath(), LevelData[i].Name + ".jpg"); + + // if (File.Exists(localPath)) + // { + // _fileIsExist[i] = true; + // Debug.Log($"[SetImgLoader] 本地存在,直接加载 {LevelData[i].Name}"); + // CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LevelData[i].Name, loader, null, + // "LevelAlbums/")); + // } + // else + // { + // _fileIsExist[i] = false; + // } + // } + // else + // { + // CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LevelData[i].Name, loader, null, + // "LevelAlbums/")); + // } + + // activeLoaders[i] = loader; + // } + // Debug.Log($"[ScrollUpdate] active loaders={activeLoaders.Count}, pool={GLoaderPool.Instance.GetPoolCount()}, inUse={GLoaderPool.Instance.GetInUseCount()}"); + } + + private void OnScrollEnd() + { + invoker.Invoke(); + // for (int i = 0; i < UpDatatime.Length; i++) + // { + // UpDatatime[i] = 0; + // // ImageName[i] = ""; + // } + + // DOVirtual.DelayedCall(0.1f, () => + // { + // ui.list_albums.RefreshVirtualList(); + // }); + + // if (LevelData == null || LevelData.Count == 0) return; + + // var firstVisibleIndex = ui.list_albums.GetFirstChildInView(); + // var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_albums.numItems - 1); + + // var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); + // var endIndex = Mathf.Min(ui.list_albums.numItems - 1, lastVisibleIndex + PreloadCount); + + // // Debug.Log($"[ScrollEnd] start index={startIndex} end index={endIndex}"); + + + // var tasks = new List<(GLoader loader, string fileName, Action callback, string folder)>(); + // // 分配 loader 并加载图片 + // for (var i = startIndex; i <= endIndex; i++) + // { + // _fileIsExist.TryGetValue(i, out var value); + + // if (value) continue; + + // if (GameHelper.GetLevel() < i + 1) continue; + + // var item = ui.list_albums.GetChildAt(i) as item_albums; + // if (item == null) continue; + // if (item.com_loader.loader != null && !item.com_loader.loader.isDisposed) + // GLoaderPool.Instance.ReturnLoader(item.com_loader.loader); + // var loader = GLoaderPool.Instance.GetLoader(); + // item.com_loader.loader = loader; + // item.com_loader.AddChild(loader); + // loader.SetSize(item.com_loader.loader.width, item.com_loader.loader.height); + + // var idx = i; + // tasks.Add((loader, LevelData[i].Name, NTexture => + // { + // if (NTexture != null) _fileIsExist[idx] = true; + // }, "LevelAlbums/")); + + // activeLoaders[i] = loader; + // } + + // if (tasks.Count > 0) TextureHelper.SetImgLoaders(tasks); + } + + private string[] ImageName; + + private void RendererList(int index, GObject obj) + { + // Debug.Log("Render list" ); + + // Debug.Log(JsonConvert.SerializeObject(LevelData[index])); + + item_albums item = (item_albums)obj; + item.text_num.text = (index + 1).ToString(); + if (index < GameHelper.GetCommonModel().MultiModal - 1) + { + item.type_.selectedIndex = 0; + if (GameHelper.GetLevel() > index + 1) + { + item.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.AlbumDetailUI_Open, index); }); + } + else + { + item.SetClick(() => { GameHelper.ShowTips("lv_unlock", true); }); + } + } + else + { + Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == index + 1); + if (levelunlock_ != null) + { + item.type_.selectedIndex = levelunlock_.type; + } + else item.type_.selectedIndex = 0; + if (GameHelper.GetLevel() > index + 1) + { + item.SetClick(() => { uiCtrlDispatcher.Dispatch(UICtrlMsg.AlbumDetailUI_Open, index); }); + } + else + { + item.SetClick(() => { GameHelper.ShowTips("lv_unlock", true); }); + } + } + + + if (GameHelper.GetNowTime() < UpDatatime[index] + 1) return; + UpDatatime[index] = GameHelper.GetNowTime(); + // if (!activeLoaders.ContainsValue(item.com_loader.loader)) activeLoaders[index] = item.com_loader.loader; + if (!loader_list.Contains(item.com_loader.GetChild("loader") as GLoader)) + loader_list.Add(item.com_loader.GetChild("loader") as GLoader); + + + if (index < GameHelper.GetCommonModel().MultiModal - 1) + { + if (GameHelper.GetLevel() > index + 1) + { + item.isUnlock.selectedIndex = 1; + if (item.com_loader.loader.texture == null || + item.com_loader.loader.texture.nativeTexture.name != LevelData[index].Name) + { + // item.isUnlock.selectedIndex = 0; + // if (item.com_loader.loader.texture != null) + // { + // item.com_loader.loader.texture.Dispose(); // 释放 GPU 资源 + // item.com_loader.loader.texture = null; // 断开引用 + // } + + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, + (a) => { Debug.Log(item.com_loader.loader.texture.nativeTexture.name); }, "LevelAlbums/", FolderNames.AlbumName); + + ImageName[index] = LevelData[index].Name; + } + + item.touchable = true; + } + else + { + item.isUnlock.selectedIndex = 0; + // item.touchable = false; + } + } + else + { + Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == index + 1); + + if (GameHelper.GetLevel() > index + 1) + { + if (levelunlock_ != null) + { + item.isUnlock.selectedIndex = 1; + + if (item.com_loader.loader.texture == null || item.com_loader.loader.texture.nativeTexture.name != ImageName[index]) + { + + if (levelunlock_.type == 0) + { + if (levelunlock_.config_index >= ConfigSystem.GetFreeImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetFreeImageConfig().Count - 1; + FreeImageLibrary _leveldata = ConfigSystem.GetFreeImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + ImageName[index] = LevelData[index].Name; + } + else if (levelunlock_.type == 1) + { + if (levelunlock_.config_index >= ConfigSystem.GetADImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetADImageConfig().Count - 1; + ADImageLibrary _leveldata = ConfigSystem.GetADImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + ImageName[index] = LevelData[index].Name; + } + else if (levelunlock_.type == 2) + { + if (levelunlock_.config_index >= ConfigSystem.GetSpecialImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetSpecialImageConfig().Count - 1; + SpecialImageLibrary _leveldata = ConfigSystem.GetSpecialImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + ImageName[index] = LevelData[index].Name; + } + else if (levelunlock_.type == 3) + { + if (levelunlock_.config_index >= ConfigSystem.GetVIPImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetVIPImageConfig().Count - 1; + VIPImageLibrary _leveldata = ConfigSystem.GetVIPImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + ImageName[index] = LevelData[index].Name; + } + + } + + } + else + { + item.isUnlock.selectedIndex = 1; + if (item.com_loader.loader.texture == null || item.com_loader.loader.texture.nativeTexture.name != LevelData[index].Name) + { + TextureHelper.SetImgLoader(item.com_loader.GetChild("loader") as GLoader, LevelData[index].Name, null, "LevelAlbums/", FolderNames.AlbumName); + ImageName[index] = LevelData[index].Name; + } + } + } + else + { + // item.touchable = false; + item.isUnlock.selectedIndex = 0; + } + } + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.UnlockAlbums, SetItemData); + } + + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.UnlockAlbums, SetItemData); + } + + #endregion + } + public class SmartInvoker + { + private readonly Action _action; + private readonly TimeSpan _delay; + private DateTime _lastImmediateInvoke = DateTime.MinValue; + private CancellationTokenSource _cts = null; + private readonly object _lock = new object(); + private bool _hasPending = false; + + public SmartInvoker(Action action, TimeSpan delay) + { + _action = action; + _delay = delay; + } + + public void Invoke() + { + lock (_lock) + { + var now = DateTime.UtcNow; + var timeSinceLast = now - _lastImmediateInvoke; + + if (timeSinceLast >= _delay) + { + _lastImmediateInvoke = now; + _action(); + Debug.Log("diaoyongyiciiiiiiiiiiiiiii"); + } + else + { + _hasPending = true; + _cts?.Cancel(); + _cts = new CancellationTokenSource(); + var token = _cts.Token; + + Task.Delay(_delay, token).ContinueWith(t => + { + if (!t.IsCanceled) + { + lock (_lock) + { + if (_hasPending) + { + _lastImmediateInvoke = DateTime.UtcNow; + _hasPending = false; + _action(); + Debug.Log("diaoyongyiciiiiiiiiiiiiiii"); + } + } + } + }, TaskScheduler.Default); + } + } + } + } } \ No newline at end of file diff --git a/Assets/Scripts/ModuleUI/Hall/HallUI.cs b/Assets/Scripts/ModuleUI/Hall/HallUI.cs index d6dbc845..f2ddad7f 100644 --- a/Assets/Scripts/ModuleUI/Hall/HallUI.cs +++ b/Assets/Scripts/ModuleUI/Hall/HallUI.cs @@ -218,8 +218,8 @@ namespace RedHotRoast { int level_ = GameHelper.GetLevel() - 2; if (level_ <= 0) level_ = 0; - if (level_ >= ConfigSystem.GetConfig().Count) level_ = ConfigSystem.GetConfig().Count - 1; - TextureHelper.SetImgLoader(ui.bg_loader, ConfigSystem.GetConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); + if (level_ >= ConfigSystem.GetLevelUnlockConfig().Count) level_ = ConfigSystem.GetLevelUnlockConfig().Count - 1; + TextureHelper.SetImgLoader(ui.bg_loader, ConfigSystem.GetLevelUnlockConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); } else { @@ -228,26 +228,26 @@ namespace RedHotRoast { if (levelunlock_.type == 0) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - FreeImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetFreeImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetFreeImageConfig().Count - 1; + FreeImageLibrary _leveldata = ConfigSystem.GetFreeImageConfig()[levelunlock_.config_index]; TextureHelper.SetImgLoader(ui.bg_loader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); } else if (levelunlock_.type == 1) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - ADImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetADImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetADImageConfig().Count - 1; + ADImageLibrary _leveldata = ConfigSystem.GetADImageConfig()[levelunlock_.config_index]; TextureHelper.SetImgLoader(ui.bg_loader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); } else if (levelunlock_.type == 2) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - SpecialImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetSpecialImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetSpecialImageConfig().Count - 1; + SpecialImageLibrary _leveldata = ConfigSystem.GetSpecialImageConfig()[levelunlock_.config_index]; TextureHelper.SetImgLoader(ui.bg_loader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); } else if (levelunlock_.type == 3) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - VIPImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetVIPImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetVIPImageConfig().Count - 1; + VIPImageLibrary _leveldata = ConfigSystem.GetVIPImageConfig()[levelunlock_.config_index]; TextureHelper.SetImgLoader(ui.bg_loader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); } } @@ -255,8 +255,8 @@ namespace RedHotRoast { int level_ = GameHelper.GetLevel() - 1; if (level_ < 0) level_ = 0; - if (level_ >= ConfigSystem.GetConfig().Count) level_ = ConfigSystem.GetConfig().Count - 1; - TextureHelper.SetImgLoader(ui.bg_loader, ConfigSystem.GetConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); + if (level_ >= ConfigSystem.GetLevelUnlockConfig().Count) level_ = ConfigSystem.GetLevelUnlockConfig().Count - 1; + TextureHelper.SetImgLoader(ui.bg_loader, ConfigSystem.GetLevelUnlockConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); } } diff --git a/Assets/Scripts/ModuleUI/Live/LiveUI.cs b/Assets/Scripts/ModuleUI/Live/LiveUI.cs index ed002afe..d146b8e8 100644 --- a/Assets/Scripts/ModuleUI/Live/LiveUI.cs +++ b/Assets/Scripts/ModuleUI/Live/LiveUI.cs @@ -1,419 +1,419 @@ -// using System; -using System; -using System.Collections.Generic; -using System.IO; - -// using System.IO; - -using FairyGUI; -using FGUI.LG_Common; -using FGUI.LG_live; -using SGModule.Common.Extensions; -using UnityEngine; -using UnityEngine.Video; - -namespace RedHotRoast -{ - public class LiveUI : BaseUI - { - private const int MaxVisibleCount = 6; // 一屏最多6个播放器 - private const int PreloadCount = 2; // 上下各预加载一屏 - private static readonly Dictionary dictionary_ = new(); - private readonly Dictionary activeLoaders = new(); - private readonly Dictionary _fileIsExist = new(); - private LiveUICtrl ctrl; - - private float late_time = 0.1f; - private List LiveConfig; - private LiveModel model; - private com_live ui; - - - private GameObject videoParent; - - public LiveUI(LiveUICtrl ctrl) : base(ctrl) - { - uiName = UIConst.LiveUI; - this.ctrl = ctrl; - } - - protected override void SetUIInfo(UIInfo uiInfo) - { - uiInfo.packageName = "LG_live"; - uiInfo.assetName = "com_live"; - uiInfo.layerType = UILayerType.Popup; - uiInfo.isNeedOpenAnim = false; - uiInfo.isNeedCloseAnim = false; - uiInfo.isNeedUIMask = true; - } - - private void UpdateEvent() - { - late_time = 0.1f; - } - - private void Refresh(object param = null) - { - var index = param.As(); - // ui.list_.itemRenderer = RendererList; - // Debug.Log($"LiveConfig.Count==2=== {LiveConfig.Count}"); - // ui.list_.numItems = LiveConfig.Count; - - - if (ui.list_.GetChildAt(index) is item_live item) - { - var livedata_ = PreDownloadManager.GetLiveDataByIndex(LiveConfig[index], index); - item.state.selectedIndex = livedata_.progress >= 100 ? 0 : 1; - item.img_mask.fillAmount = (float)(100 - livedata_.progress) / 100; - BindPlayerToItem(item, index); - - if (LiveConfig[index].SubscribeUnlock == 1) - { - if (livedata_.progress < 100) item.vip.selectedIndex = 1; - else item.vip.selectedIndex = 2; - } - else item.vip.selectedIndex = 0; - } - } - - // 初始化页面逻辑 - private void InitView() - { - } - - #region 生命周期 - - protected override void OnInit() - { - videoParent = new GameObject("VideoPlayerParent"); - VideoPlayerPool.Instance.Init(videoParent, MaxVisibleCount); - } - - protected override void OnClose() - { - // 归还所有播放器 - foreach (var kvp in dictionary_) - VideoPlayerPool.Instance.ReturnPlayer(kvp.Value); - - dictionary_.Clear(); - VideoPlayerPool.Instance.DisposeAll(); - UnityEngine.Object.Destroy(videoParent); - - foreach (var t in loader_list) - if (t != null && !t.isDisposed && t.texture != null) - { - t.texture.Dispose(); - t.texture = null; - } - - MemoryManager.CleanMemoryMonitor(); - activeLoaders.Clear(); - _fileIsExist.Clear(); - - GLoaderPool.Instance.DisposeAll(); - } - - protected override void OnBind() - { - ui = baseUI as com_live; - } - - private readonly List loader_list = new(); - - - protected override void OnOpenBefore(object args) - { - LiveConfig = ConfigSystem.GetConfig(); - - ui.list_.itemRenderer = RendererList; - Debug.Log($"LiveConfig.Count==1=== {LiveConfig.Count}"); - ui.list_.numItems = LiveConfig.Count; - - ui.btn_close.SetClick(() => { CtrlCloseUI(); }); - - InitView(); - - // 滚动过程中实时刷新可见播放器 - ui.list_.scrollPane.onScroll.Add(OnScrollUpdate); - ui.list_.scrollPane.onScrollEnd.Add(OnScrollEnd); - - // 打开页面时初始化一次 - OnScrollEnd(); - } - - private void OnScrollUpdate() - { - if (LiveConfig == null || LiveConfig.Count == 0) return; - var firstVisibleIndex = ui.list_.GetFirstChildInView(); - var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_.numItems - 1); - - var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); - var endIndex = Mathf.Min(ui.list_.numItems - 1, lastVisibleIndex + PreloadCount); - - // 回收超出范围 loader - var keysToRemove = new List(); - foreach (var kv in activeLoaders) - { - var idx = kv.Key; - if (idx < startIndex || idx > endIndex) - { - GLoaderPool.Instance.ReturnLoader(kv.Value); - var oldItem = ui.list_.GetChildAt(idx) as item_live; - if (oldItem != null) { - (oldItem.img_cover as com_loaderMask_circlle).loader = null; - } - keysToRemove.Add(idx); - } - } - - foreach (var k in keysToRemove) activeLoaders.Remove(k); - - // 分配 loader 并加载图片 - for (var i = startIndex; i <= endIndex; i++) - { - if (activeLoaders.ContainsKey(i)) continue; - - var item = ui.list_.GetChildAt(i) as item_live; - if (item == null) continue; - - if ((item.img_cover as com_loaderMask_circlle).loader != null && !(item.img_cover as com_loaderMask_circlle).loader.isDisposed) - GLoaderPool.Instance.ReturnLoader((item.img_cover as com_loaderMask_circlle).loader); - - var loader = GLoaderPool.Instance.GetLoader(); - (item.img_cover as com_loaderMask_circlle).loader = loader; - item.img_cover.AddChild(loader); - loader.SetSize(item.img_cover.width, item.img_cover.height); - item.img_cover.visible = true; - - _fileIsExist.TryGetValue(i, out var value); - if (!value) - { - var localPath = Path.Combine(TextureHelper.getResPath(), "LiveVideoCovers", LiveConfig[i].Name + "_cover" + ".jpg"); - if (File.Exists(localPath)) - { - _fileIsExist[i] = true; - Debug.Log($"[SetImgLoader] 本地存在,直接加载 {LiveConfig[i].Name + "_cover"}"); - CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LiveConfig[i].Name + "_cover", loader, null, - "LiveVideoCovers/")); - } - else - { - _fileIsExist[i] = false; - CrazyAsyKit.StartCoroutine(LiveVideoManager.Instance.LoadCover(LiveConfig[i].Name + "_cover", tex => - { - if (tex != null) - { - if (loader != null) - { - loader.texture = new NTexture(tex); - loader.visible = true; - } - } - else - { - Debug.LogWarning("封面获取失败"); - } - })); - } - } - else - { - CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LiveConfig[i].Name + "_cover", loader, null, - "LiveVideoCovers/")); - } - - activeLoaders[i] = loader; - } - } - - - private HashSet lastVisibleItems = new(); - - private void OnScrollEnd() - { - var tasks = new List<(GLoader loader, string fileName, Action callback, string folder, string localFolder)>(); - var firstVisibleIndex = ui.list_.GetFirstChildInView(); - var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_.numItems - 1); - - var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); - var endIndex = Mathf.Min(ui.list_.numItems - 1, lastVisibleIndex + PreloadCount); - for (var i = startIndex; i <= endIndex; i++) - { - _fileIsExist.TryGetValue(i, out var value); - - if (value) continue; - if (ui.list_.GetChildAt(i) is item_live item) - { - if ((item.img_cover as com_loaderMask_circlle).loader != null && !(item.img_cover as com_loaderMask_circlle).loader.isDisposed) - GLoaderPool.Instance.ReturnLoader((item.img_cover as com_loaderMask_circlle).loader); - var loader = GLoaderPool.Instance.GetLoader(); - (item.img_cover as com_loaderMask_circlle).loader = loader; - item.img_cover.AddChild(loader); - loader.SetSize(item.img_cover.width, item.img_cover.height); - - var idx = i; - tasks.Add((loader, LiveConfig[i].Name + "_cover", texture => - { - if (texture != null) _fileIsExist[idx] = true; - }, "LiveAlbums/", FolderNames.VideoCoversName)); - - activeLoaders[i] = loader; - } - } - - TextureHelper.SetImgLoaders(tasks); - - Debug.Log($"[OnScrollEnd]==lastVisibleItems=== {lastVisibleItems.Count}"); - VideoLoadScheduler.ClearAll(); - // 1️⃣ 回收上一次的可见播放器 - foreach (var oldItem in lastVisibleItems) - if (dictionary_.TryGetValue(oldItem, out var player)) - { - player.Pause(); - player.targetTexture?.Release(); - VideoPlayerPool.Instance.ReturnPlayer(player); - dictionary_.Remove(oldItem); - oldItem.com_loader.visible = false; - oldItem.img_cover.visible = true; - } - - lastVisibleItems.Clear(); - - - // 2️⃣ 获取当前可见项 - var firstIndex = ui.list_.GetFirstChildInView(); - var lastIndex = Mathf.Min(firstIndex + MaxVisibleCount, ui.list_.numItems); - - HashSet newVisibleItems = new(); - for (var i = firstIndex; i < lastIndex; i++) - { - if (ui.list_.GetChildAt(i) is item_live item) - { - // 分配播放器 - newVisibleItems.Add(item); - if (!dictionary_.ContainsKey(item)) - { - var player = VideoPlayerPool.Instance.GetPlayer(); - if (player != null) - { - dictionary_[item] = player; - BindPlayerToItem(item, i); - } - } - } - } - - // 3️⃣ 保存为“上一次可见项” - lastVisibleItems = newVisibleItems; - } - - private void BindPlayerToItem(item_live item, int index) - { - var data = PreDownloadManager.GetLiveDataByIndex(LiveConfig[index], index); - - Debug.Log($"[绑定播放器 进度] progress==1=== {data.progress}"); - if (data.progress < 100) return; - - var player = dictionary_[item]; - var loader = item.com_loader.GetChild("loader") as GLoader; - item.com_loader.visible = true; - - if (!loader_list.Contains(loader)) loader_list.Add(loader); - - TextureHelper.SetVideoLoader(player, loader, LiveConfig[index].Name, vp => - { - if (vp != null && !item.isDisposed) - { - if (data.progress >= 100) - { - item.img_cover.visible = false; - GameDispatcher.Instance.Dispatch(GameMsg.liveVideoLoaded); - } - } - }); - } - - - private void RendererList(int index, GObject obj) - { - var livedata_ = PreDownloadManager.GetLiveDataByIndex(LiveConfig[index], index); - - var item = (item_live)obj; - - // UI状态显示 - item.state.selectedIndex = livedata_.progress < 100 ? 1 : 0; - - if (LiveConfig[index].SubscribeUnlock == 1) - { - if (livedata_.progress < 100) item.vip.selectedIndex = 1; - else item.vip.selectedIndex = 2; - } - else item.vip.selectedIndex = 0; - - item.img_mask.fillAmount = (float)(100 - livedata_.progress) / 100; - - // 点击事件 - item.SetClick(() => - { - if (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockLive[1]) - { - if (DataMgr.IsUnlockLive.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockLive.As())) - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretUnlockUI_Open, 2); - else if (DataMgr.IsUnlockLive.Value == 0) - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.UnlockTipsUI_Open, 2); - else - HandleDetailOpen(item, index); - } - else - { - HandleDetailOpen(item, index); - } - }); - } - - private void HandleDetailOpen(item_live item, int index) - { - dictionary_.TryGetValue(item, out var player); - // if (dictionary_.TryGetValue(item, out var player)) - uiCtrlDispatcher.Dispatch(UICtrlMsg.LiveDetailUI_Open, (index, player)); - } - - protected override void OnOpen(object args) - { - } - - protected override void OnHide() - { - } - - protected override void OnDisplay(object args) - { - } - - #endregion - - #region 消息 - - protected override void AddListener() - { - GameDispatcher.Instance.AddListener(GameMsg.LiveChange, Refresh); - HallManager.Instance.UpdateEvent += UpdateEvent; - } - - protected override void RemoveListener() - { - GameDispatcher.Instance.RemoveListener(GameMsg.LiveChange, Refresh); - HallManager.Instance.UpdateEvent -= UpdateEvent; - } - - #endregion - } - - public class LiveData - { - public int AD_num; - public int progress; - public int Singleprogress; - public long LiveADTime; - } +// using System; +using System; +using System.Collections.Generic; +using System.IO; + +// using System.IO; + +using FairyGUI; +using FGUI.LG_Common; +using FGUI.LG_live; +using SGModule.Common.Extensions; +using UnityEngine; +using UnityEngine.Video; + +namespace RedHotRoast +{ + public class LiveUI : BaseUI + { + private const int MaxVisibleCount = 6; // 一屏最多6个播放器 + private const int PreloadCount = 2; // 上下各预加载一屏 + private static readonly Dictionary dictionary_ = new(); + private readonly Dictionary activeLoaders = new(); + private readonly Dictionary _fileIsExist = new(); + private LiveUICtrl ctrl; + + private float late_time = 0.1f; + private List LiveConfig; + private LiveModel model; + private com_live ui; + + + private GameObject videoParent; + + public LiveUI(LiveUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.LiveUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "LG_live"; + uiInfo.assetName = "com_live"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + private void UpdateEvent() + { + late_time = 0.1f; + } + + private void Refresh(object param = null) + { + var index = param.As(); + // ui.list_.itemRenderer = RendererList; + // Debug.Log($"LiveConfig.Count==2=== {LiveConfig.Count}"); + // ui.list_.numItems = LiveConfig.Count; + + + if (ui.list_.GetChildAt(index) is item_live item) + { + var livedata_ = PreDownloadManager.GetLiveDataByIndex(LiveConfig[index], index); + item.state.selectedIndex = livedata_.progress >= 100 ? 0 : 1; + item.img_mask.fillAmount = (float)(100 - livedata_.progress) / 100; + BindPlayerToItem(item, index); + + if (LiveConfig[index].SubscribeUnlock == 1) + { + if (livedata_.progress < 100) item.vip.selectedIndex = 1; + else item.vip.selectedIndex = 2; + } + else item.vip.selectedIndex = 0; + } + } + + // 初始化页面逻辑 + private void InitView() + { + } + + #region 生命周期 + + protected override void OnInit() + { + videoParent = new GameObject("VideoPlayerParent"); + VideoPlayerPool.Instance.Init(videoParent, MaxVisibleCount); + } + + protected override void OnClose() + { + // 归还所有播放器 + foreach (var kvp in dictionary_) + VideoPlayerPool.Instance.ReturnPlayer(kvp.Value); + + dictionary_.Clear(); + VideoPlayerPool.Instance.DisposeAll(); + UnityEngine.Object.Destroy(videoParent); + + foreach (var t in loader_list) + if (t != null && !t.isDisposed && t.texture != null) + { + t.texture.Dispose(); + t.texture = null; + } + + MemoryManager.CleanMemoryMonitor(); + activeLoaders.Clear(); + _fileIsExist.Clear(); + + GLoaderPool.Instance.DisposeAll(); + } + + protected override void OnBind() + { + ui = baseUI as com_live; + } + + private readonly List loader_list = new(); + + + protected override void OnOpenBefore(object args) + { + LiveConfig = ConfigSystem.GetLiveConfig(); + + ui.list_.itemRenderer = RendererList; + Debug.Log($"LiveConfig.Count==1=== {LiveConfig.Count}"); + ui.list_.numItems = LiveConfig.Count; + + ui.btn_close.SetClick(() => { CtrlCloseUI(); }); + + InitView(); + + // 滚动过程中实时刷新可见播放器 + ui.list_.scrollPane.onScroll.Add(OnScrollUpdate); + ui.list_.scrollPane.onScrollEnd.Add(OnScrollEnd); + + // 打开页面时初始化一次 + OnScrollEnd(); + } + + private void OnScrollUpdate() + { + if (LiveConfig == null || LiveConfig.Count == 0) return; + var firstVisibleIndex = ui.list_.GetFirstChildInView(); + var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_.numItems - 1); + + var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); + var endIndex = Mathf.Min(ui.list_.numItems - 1, lastVisibleIndex + PreloadCount); + + // 回收超出范围 loader + var keysToRemove = new List(); + foreach (var kv in activeLoaders) + { + var idx = kv.Key; + if (idx < startIndex || idx > endIndex) + { + GLoaderPool.Instance.ReturnLoader(kv.Value); + var oldItem = ui.list_.GetChildAt(idx) as item_live; + if (oldItem != null) { + (oldItem.img_cover as com_loaderMask_circlle).loader = null; + } + keysToRemove.Add(idx); + } + } + + foreach (var k in keysToRemove) activeLoaders.Remove(k); + + // 分配 loader 并加载图片 + for (var i = startIndex; i <= endIndex; i++) + { + if (activeLoaders.ContainsKey(i)) continue; + + var item = ui.list_.GetChildAt(i) as item_live; + if (item == null) continue; + + if ((item.img_cover as com_loaderMask_circlle).loader != null && !(item.img_cover as com_loaderMask_circlle).loader.isDisposed) + GLoaderPool.Instance.ReturnLoader((item.img_cover as com_loaderMask_circlle).loader); + + var loader = GLoaderPool.Instance.GetLoader(); + (item.img_cover as com_loaderMask_circlle).loader = loader; + item.img_cover.AddChild(loader); + loader.SetSize(item.img_cover.width, item.img_cover.height); + item.img_cover.visible = true; + + _fileIsExist.TryGetValue(i, out var value); + if (!value) + { + var localPath = Path.Combine(TextureHelper.getResPath(), "LiveVideoCovers", LiveConfig[i].Name + "_cover" + ".jpg"); + if (File.Exists(localPath)) + { + _fileIsExist[i] = true; + Debug.Log($"[SetImgLoader] 本地存在,直接加载 {LiveConfig[i].Name + "_cover"}"); + CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LiveConfig[i].Name + "_cover", loader, null, + "LiveVideoCovers/")); + } + else + { + _fileIsExist[i] = false; + CrazyAsyKit.StartCoroutine(LiveVideoManager.Instance.LoadCover(LiveConfig[i].Name + "_cover", tex => + { + if (tex != null) + { + if (loader != null) + { + loader.texture = new NTexture(tex); + loader.visible = true; + } + } + else + { + Debug.LogWarning("封面获取失败"); + } + })); + } + } + else + { + CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(LiveConfig[i].Name + "_cover", loader, null, + "LiveVideoCovers/")); + } + + activeLoaders[i] = loader; + } + } + + + private HashSet lastVisibleItems = new(); + + private void OnScrollEnd() + { + var tasks = new List<(GLoader loader, string fileName, Action callback, string folder, string localFolder)>(); + var firstVisibleIndex = ui.list_.GetFirstChildInView(); + var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.list_.numItems - 1); + + var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); + var endIndex = Mathf.Min(ui.list_.numItems - 1, lastVisibleIndex + PreloadCount); + for (var i = startIndex; i <= endIndex; i++) + { + _fileIsExist.TryGetValue(i, out var value); + + if (value) continue; + if (ui.list_.GetChildAt(i) is item_live item) + { + if ((item.img_cover as com_loaderMask_circlle).loader != null && !(item.img_cover as com_loaderMask_circlle).loader.isDisposed) + GLoaderPool.Instance.ReturnLoader((item.img_cover as com_loaderMask_circlle).loader); + var loader = GLoaderPool.Instance.GetLoader(); + (item.img_cover as com_loaderMask_circlle).loader = loader; + item.img_cover.AddChild(loader); + loader.SetSize(item.img_cover.width, item.img_cover.height); + + var idx = i; + tasks.Add((loader, LiveConfig[i].Name + "_cover", texture => + { + if (texture != null) _fileIsExist[idx] = true; + }, "LiveAlbums/", FolderNames.VideoCoversName)); + + activeLoaders[i] = loader; + } + } + + TextureHelper.SetImgLoaders(tasks); + + Debug.Log($"[OnScrollEnd]==lastVisibleItems=== {lastVisibleItems.Count}"); + VideoLoadScheduler.ClearAll(); + // 1️⃣ 回收上一次的可见播放器 + foreach (var oldItem in lastVisibleItems) + if (dictionary_.TryGetValue(oldItem, out var player)) + { + player.Pause(); + player.targetTexture?.Release(); + VideoPlayerPool.Instance.ReturnPlayer(player); + dictionary_.Remove(oldItem); + oldItem.com_loader.visible = false; + oldItem.img_cover.visible = true; + } + + lastVisibleItems.Clear(); + + + // 2️⃣ 获取当前可见项 + var firstIndex = ui.list_.GetFirstChildInView(); + var lastIndex = Mathf.Min(firstIndex + MaxVisibleCount, ui.list_.numItems); + + HashSet newVisibleItems = new(); + for (var i = firstIndex; i < lastIndex; i++) + { + if (ui.list_.GetChildAt(i) is item_live item) + { + // 分配播放器 + newVisibleItems.Add(item); + if (!dictionary_.ContainsKey(item)) + { + var player = VideoPlayerPool.Instance.GetPlayer(); + if (player != null) + { + dictionary_[item] = player; + BindPlayerToItem(item, i); + } + } + } + } + + // 3️⃣ 保存为“上一次可见项” + lastVisibleItems = newVisibleItems; + } + + private void BindPlayerToItem(item_live item, int index) + { + var data = PreDownloadManager.GetLiveDataByIndex(LiveConfig[index], index); + + Debug.Log($"[绑定播放器 进度] progress==1=== {data.progress}"); + if (data.progress < 100) return; + + var player = dictionary_[item]; + var loader = item.com_loader.GetChild("loader") as GLoader; + item.com_loader.visible = true; + + if (!loader_list.Contains(loader)) loader_list.Add(loader); + + TextureHelper.SetVideoLoader(player, loader, LiveConfig[index].Name, vp => + { + if (vp != null && !item.isDisposed) + { + if (data.progress >= 100) + { + item.img_cover.visible = false; + GameDispatcher.Instance.Dispatch(GameMsg.liveVideoLoaded); + } + } + }); + } + + + private void RendererList(int index, GObject obj) + { + var livedata_ = PreDownloadManager.GetLiveDataByIndex(LiveConfig[index], index); + + var item = (item_live)obj; + + // UI状态显示 + item.state.selectedIndex = livedata_.progress < 100 ? 1 : 0; + + if (LiveConfig[index].SubscribeUnlock == 1) + { + if (livedata_.progress < 100) item.vip.selectedIndex = 1; + else item.vip.selectedIndex = 2; + } + else item.vip.selectedIndex = 0; + + item.img_mask.fillAmount = (float)(100 - livedata_.progress) / 100; + + // 点击事件 + item.SetClick(() => + { + if (GameHelper.GetLevel() < GameHelper.GetCommonModel().UnlockLive[1]) + { + if (DataMgr.IsUnlockLive.Value < 0 && !GameHelper.GetVipPrivilege(Subscription.UnlockLive.As())) + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretUnlockUI_Open, 2); + else if (DataMgr.IsUnlockLive.Value == 0) + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.UnlockTipsUI_Open, 2); + else + HandleDetailOpen(item, index); + } + else + { + HandleDetailOpen(item, index); + } + }); + } + + private void HandleDetailOpen(item_live item, int index) + { + dictionary_.TryGetValue(item, out var player); + // if (dictionary_.TryGetValue(item, out var player)) + uiCtrlDispatcher.Dispatch(UICtrlMsg.LiveDetailUI_Open, (index, player)); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.LiveChange, Refresh); + HallManager.Instance.UpdateEvent += UpdateEvent; + } + + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.LiveChange, Refresh); + HallManager.Instance.UpdateEvent -= UpdateEvent; + } + + #endregion + } + + public class LiveData + { + public int AD_num; + public int progress; + public int Singleprogress; + public long LiveADTime; + } } \ No newline at end of file diff --git a/Assets/Scripts/ModuleUI/LiveDetail/LiveDetailUI.cs b/Assets/Scripts/ModuleUI/LiveDetail/LiveDetailUI.cs index 2db4a7ed..d167d8e6 100644 --- a/Assets/Scripts/ModuleUI/LiveDetail/LiveDetailUI.cs +++ b/Assets/Scripts/ModuleUI/LiveDetail/LiveDetailUI.cs @@ -262,7 +262,7 @@ namespace RedHotRoast player.audioOutputMode = VideoAudioOutputMode.None; // 从配置表取配置(这里还是 List,如果有 Id 字段可改成字典) - LiveConfig = ConfigSystem.GetConfig()[index]; + LiveConfig = ConfigSystem.GetLiveConfig()[index]; livedata_ = PreDownloadManager.GetLiveDataByIndex(LiveConfig, index); diff --git a/Assets/Scripts/ModuleUI/NewEnd/NewEndUI.cs b/Assets/Scripts/ModuleUI/NewEnd/NewEndUI.cs index ae597c65..450b3a26 100644 --- a/Assets/Scripts/ModuleUI/NewEnd/NewEndUI.cs +++ b/Assets/Scripts/ModuleUI/NewEnd/NewEndUI.cs @@ -1,674 +1,674 @@ -using System; -using System.Collections.Generic; -using DG.Tweening; -using FairyGUI; -using FGUI.LG_Common; -using FGUI.LG_End; -using FGUI.ZM_Common_01; -using Newtonsoft.Json; -using Spine.Unity; -using UnityEngine; -using btn_claim = FGUI.LG_Common.btn_claim; -using SGModule.Common.Extensions; -using System.Linq; -using SGModule.NetKit; -namespace RedHotRoast -{ - public class NewEndUI : BaseUI - { - private readonly List loader_list = new(); - private readonly List rate_list = new(); - private Action closeCallback; - private NewEndUICtrl ctrl; - - - private List list_1; - private NewEndModel model; - private int next_level; - private int rate_idnex = 3; - private int scroll_number; - private int scroll_type = 1; - private com_newend ui; - - public NewEndUI(NewEndUICtrl ctrl) : base(ctrl) - { - uiName = UIConst.NewEndUI; - this.ctrl = ctrl; - } - - protected override void SetUIInfo(UIInfo uiInfo) - { - uiInfo.packageName = "LG_End"; - uiInfo.assetName = "com_newend"; - uiInfo.layerType = UILayerType.Popup; - uiInfo.isNeedOpenAnim = false; - uiInfo.isNeedCloseAnim = false; - uiInfo.isNeedUIMask = true; - } - - private void UnlockLevelsuccess(object a = null) - { - CtrlCloseUI(); - } - - private void endClose() - { - var lv = GameHelper.GetCommonModel().MultiModal; - if (GameHelper.GetLevel() >= GameHelper.GetCommonModel().MultiModal) - { - uiCtrlDispatcher.Dispatch(UICtrlMsg.UnlockLevelNewUI_Open); - is_unlock_level = true; - } - CtrlCloseUI(); - } - - //初始化页面逻辑 - private void InitView() - { - if (GameHelper.IsGiftSwitch()) - { - if (!loader_list.Contains(ui.loader_bgimg)) loader_list.Add(ui.loader_bgimg); - - // TextureHelper.SetImgLoader(ui.loader_bgimg, LevelData.Name, null, "LevelAlbums/"); - if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal) - { - int level_ = GameHelper.GetLevel() - 1; - if (level_ < 0) level_ = 0; - if (level_ >= ConfigSystem.GetConfig().Count) level_ = ConfigSystem.GetConfig().Count - 1; - TextureHelper.SetImgLoader(ui.loader_bgimg, ConfigSystem.GetConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); - } - else - { - Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel()); - if (levelunlock_ != null) - { - if (levelunlock_.type == 0) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - FreeImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - } - else if (levelunlock_.type == 1) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - ADImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - } - else if (levelunlock_.type == 2) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - SpecialImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - } - else if (levelunlock_.type == 3) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - VIPImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - } - } - else - { - int level_ = GameHelper.GetLevel() - 1; - if (level_ < 0) level_ = 0; - if (level_ >= ConfigSystem.GetConfig().Count) level_ = ConfigSystem.GetConfig().Count - 1; - TextureHelper.SetImgLoader(ui.loader_bgimg, ConfigSystem.GetConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); - } - } - } - - ui.tetx_level.text = Language.GetContentParams("level", successData_.level); - ui.text_award.text = successData_.ch_number.ToString(); - Debug.Log(JsonConvert.SerializeObject(successData_) + "/////////////////"); - Debug.Log("/////////////////4"); - - // if (!successData_.IsWin) ui.text_award.text = DataMgr.Coin.Value.ToString(); - Debug.Log(GetNextSpecialLevel()); - next_level = GetNextSpecialLevel(); - - var levelUnlock_ = ConfigSystem.GetConfig()[next_level]; - if (levelUnlock_.LeveType == 1) - ui.text_levelType.text = "Special level"; - else if (levelUnlock_.LeveType == 2) ui.text_levelType.text = "VIP level"; - ui.progress_level.max = next_level; - ui.progress_level.value = successData_.level; - // if (successData_.IsLevelSuccess && successData_.level == next_level) - // //打开解锁界面 - // ui.btn_continue.SetClick(() => - // { - // uiCtrlDispatcher.Dispatch(UICtrlMsg.UnlockLevelUI_Open, next_level); - // }); - // else - ui.btn_continue.SetClick(() => - { - endClose(); - }); - ((btn_claim4)ui.btn_claim).title = $"{successData_.ch_number}"; - - var delayTime = successData_.IsLevelSuccess ? 1f : 0f; - if (!successData_.IsWin) - { - delayTime = 0f; - ui.win_lose.selectedIndex = 0; - } - else - { - ui.win_lose.selectedIndex = 1; - } - if (!GameHelper.IsGiftSwitch()) delayTime = 0; - ui.step.selectedIndex = !successData_.IsLevelSuccess || !successData_.IsWin ? 1 : 0; - Debug.Log("/////////////////5"); - DOVirtual.DelayedCall(delayTime, () => - { - Debug.Log(delayTime); - Debug.Log("/////////////////6"); - ui.step.selectedIndex = 1; - // var anim_bg = FXManager.Instance.SetFx(ui.GetChild("bg_parent") as GGraph, Fx_Type.fx_end_bg, ref closeCallback); - if (successData_.IsWin) - { - // anim_bg.state.SetAnimation(0, "win", false); - // anim_bg.state.Complete += (trackEntry) => - // { - // anim_bg.state.SetAnimation(0, "win_stop", true); - // }; - var fireworks = FXManager.Instance.SetFx(ui.GetChild("congra_parent") as GGraph, Fx_Type.fx_win, ref closeCallback); - fireworks.state.SetAnimation(0, "out", true); - - // var coin = FXManager.Instance.SetFx(ui.GetChild("coin_parent") as GGraph, Fx_Type.fx_wins, ref closeCallback); - // coin.state.SetAnimation(0, "animation", true); - // coin.state.Complete += (trackEntry) => - // { - // coin.state.SetAnimation(0, "animation2", true); - // }; - - if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetCommonConf().FreeClaims) - ((btn_claim3)ui.btn_mult).state.selectedIndex = 1; - else ((btn_claim3)ui.btn_mult).state.selectedIndex = 0; - ui.btn_mult.SetClick(() => - { - if (!GameHelper.GetCloseResult()) return; - if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetCommonConf().FreeClaims) - { - ui.btn_mult.touchable = ui.btn_claim.touchable = false; - SaveData.SaveDataFunc(); - StartScroll(); - } - else - { - GameHelper.ShowVideoAd("GameEnd", isSuccess => - { - if (isSuccess) - { - ui.btn_mult.touchable = ui.btn_claim.touchable = false; - StartScroll(); - } - }); - } - }); - ui.btn_claim.SetClick(() => - { - if (!GameHelper.GetCloseResult()) return; - ui.btn_mult.touchable = ui.btn_claim.touchable = false; - DOVirtual.DelayedCall(2f, () => { GameHelper.addInterAdnumber(); }); - GetReward(successData_.ch_number); - }); - - AudioManager.Instance.PlayDynamicEffect(AudioConst.Victoriously); - } - else - { - // anim_bg.state.SetAnimation(0, "lose", false); - // anim_bg.state.Complete += (trackEntry) => - // { - // anim_bg.state.SetAnimation(0, "lose_stop", true); - // }; - - ui.btn_restart.SetClick(() => - { - if (!GameHelper.GetCloseResult()) return; - - GameHelper.addInterAdnumber(); - if (!successData_.IsWin) GameHelper.SetLevelstate(3); - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Close); - }); - } - }); - if (GameHelper.GetVipPrivilege(Subscription.DoubleLevelReward.As())) ((wheel)ui.wheel).have_vip.selectedIndex = 1; - if (successData_.boost_array != null) - { - ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll); - ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() => - { - rate_idnex++; - ui.btn_mult.title = - GameHelper.Get101Str((decimal)successData_.ch_number * - successData_.boost_array[rate_idnex % 5]); - }); - ui.btn_mult.title = - GameHelper.Get101Str((decimal)successData_.ch_number * successData_.boost_array[rate_idnex]); - - list_1 = new List - { - ((wheel_)ui.wheel.GetChild("wheel_")).item_0, ((wheel_)ui.wheel.GetChild("wheel_")).item_1, - (ui.wheel.GetChild("wheel_") as wheel_).item_2, (ui.wheel.GetChild("wheel_") as wheel_).item_3, - (ui.wheel.GetChild("wheel_") as wheel_).item_4, (ui.wheel.GetChild("wheel_") as wheel_).item_5, - (ui.wheel.GetChild("wheel_") as wheel_).item_6, (ui.wheel.GetChild("wheel_") as wheel_).item_7 - }; - // list_1[2].img_light.visible = true; - - for (var i = 0; i < list_1.Count; i++) - { - list_1[i].type.selectedIndex = (i + scroll_number) % 3; - list_1[i].text_rate.text = "X" + successData_.boost_array[i % successData_.boost_array.Length]; - } - } - } - - private void StartScroll() - { - ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = - ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = 5.0f; - scroll_type = 2; - } - - private void Scroll() - { - if (scroll_type == 1) - { - scroll_number++; - rate_list.Clear(); - for (var i = 0; i < 8; i++) - rate_list.Add(successData_.boost_array[(scroll_number + i) % successData_.boost_array.Length]); - for (var i = 0; i < list_1.Count; i++) - { - list_1[i].type.selectedIndex = (i + scroll_number) % 3; - list_1[i].text_rate.text = "X" + rate_list[i]; - } - - ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() => - { - rate_idnex++; - ui.btn_mult.title = GameHelper.Get101Str((decimal)successData_.ch_number * - successData_.boost_array[ - rate_idnex % successData_.boost_array.Length]); - }); - - ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll); - } - else - { - scroll_number++; - - rate_list.Clear(); - for (var i = 0; i < 8; i++) - rate_list.Add(successData_.boost_array[(scroll_number + i) % successData_.boost_array.Length]); - - // bool need_return = false; - if (((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale < 2.2f && - list_1[4].text_rate.text == "X" + successData_.rate) - { - //开始领取 - var reward = successData_.ch_number * successData_.rate; - if (GameHelper.GetVipPrivilege(Subscription.DoubleLevelReward.As())) reward *= 2; - GetReward(reward); - - GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); - SaveData.GetSaveObject().LargeRewardNum++; - SaveData.SaveDataFunc(); - return; - } - - for (var i = 0; i < list_1.Count; i++) - { - list_1[i].type.selectedIndex = (i + scroll_number) % 3; - list_1[i].text_rate.text = "X" + rate_list[i]; - } - - // if (need_return) - // { - // (ui.wheel.GetChild("wheel_") as wheel_).t0.timeScale = 0; - // return; - // } - - ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() => - { - rate_idnex++; - ui.btn_mult.title = GameHelper.Get101Str((decimal)successData_.ch_number * - successData_.boost_array[ - rate_idnex % successData_.boost_array.Length]); - }); - - ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll); - ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = - ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale - 0.3f; - } - } - - private void GetReward(float awardNum) - { - var startObj = ui.btn_mult; - var endObj = ui.btn_gold; - - var pos = GameHelper.GetUICenterPosition(endObj); - - var rewardData = new RewardData(); - var rewardSingleData = new RewardSingleData(101, (decimal)awardNum, RewardOrigin.Play) - { - startPosition = GameHelper.GetUICenterPosition(startObj), - endPosition = new Vector2(pos.x, pos.y) - }; - - rewardData.AddReward(rewardSingleData); - rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; - rewardData.AddCompleted(success => - { - if (success) - { - RefreshAwardNum((decimal)awardNum, 101); - - if (successData_.IsLevelSuccess) - { - if (!loader_list.Contains(ui.com_loader.GetChild("loader") as GLoader)) - loader_list.Add(ui.com_loader.GetChild("loader") as GLoader); - - GameDispatcher.Instance.Dispatch(GameMsg.reset_game); - - - if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal) - { - TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null, "LevelAlbums/", FolderNames.AlbumName); - var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; - ui.btn_download_coin.SetClick(() => - { - if (GameHelper.Get101() >= downloadCoinNum) - { - GameHelper.AddGold(-downloadCoinNum); - ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}"; - TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName); - TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); - endClose(); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - } - }); - - ui.btn_download.SetClick(() => - { - if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) - { - TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName); - endClose(); - } - else - GameHelper.ShowVideoAd("DownloadImage", isSuccess => - { - if (isSuccess) - { - TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName); - endClose(); - } - }); - }); - - } - else - { - Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel()); - string file_name = ""; - if (levelunlock_ != null) - { - if (levelunlock_.type == 0) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - FreeImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - else if (levelunlock_.type == 1) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - ADImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - else if (levelunlock_.type == 2) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - SpecialImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - else if (levelunlock_.type == 3) - { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - VIPImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; - TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); - file_name = _leveldata.Name; - } - } - else - { - TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null, - "LevelAlbums/", FolderNames.AlbumName); - } - var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; - ui.btn_download_coin.SetClick(() => - { - if (GameHelper.Get101() >= downloadCoinNum) - { - GameHelper.AddGold(-downloadCoinNum); - ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}"; - TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); - TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); - endClose(); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - } - }); - - ui.btn_download.SetClick(() => - { - if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) - { - TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); - endClose(); - } - else - GameHelper.ShowVideoAd("DownloadImage", isSuccess => - { - if (isSuccess) - { - TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); - endClose(); - } - }); - }); - } - // TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null, - // "LevelAlbums/"); - - - GameHelper.SetLevel(GameHelper.GetLevel() + 1); - DOVirtual.DelayedCall(1.5f, () => - { - if (GameHelper.IsGiftSwitch()) - { - ui.step.selectedIndex = 2; - } - else - { - CtrlCloseUI(); - } - - - }); - } - else - { - CtrlCloseUI(); - } - } - }); - - GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); - } - - private void RefreshAwardNum(decimal num = -1, int id = 102) - { - if (num < 0) num = DataMgr.Coin.Value; - var btnCoin = ui.btn_gold as com_gold; - - - var gTextField = btnCoin.text_gold; - CommonHelper.ShowNumAnim(gTextField, num, id); - } - - #region 生命周期 - - protected override void OnInit() - { - //model = ModuleManager.Instance.GetModel(ModelConst.NewEndModel) as NewEndModel; - } - private bool is_unlock_level = false; - protected override void OnClose() - { - GameHelper.SetCloseResult(false); - closeCallback?.Invoke(); - if (!is_unlock_level) - { - if (successData_.IsLevelSuccess && !GameHelper.is_first_login) - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, successData_.IsWin); - else - GameDispatcher.Instance.Dispatch(GameMsg.CheckEnd); - } - - - foreach (var t in loader_list) - if (t != null && !t.isDisposed && t.texture != null) - { - t.texture.Dispose(); - t.texture = null; - } - - loader_list.Clear(); - - MemoryManager.CleanMemoryMonitor(); - } - - protected override void OnBind() - { - ui = baseUI as com_newend; - } - - private LevelUnlock LevelData; - - protected override void OnOpenBefore(object args) - { - if (Screen.safeArea.y != 0) ui.btn_gold.y += 68; - - Debug.Log("//////////////////////0"); - Debug.Log(JsonConvert.SerializeObject(args)); - successData_ = (SuccessData)args; - successData_.ch_number = (int)successData_.ch_number; - - // 修改后的代码 - var levelDataList = ConfigSystem.GetConfig(); - var levelIndex = successData_.level - 1; - - // 确保索引不超出范围,如果超出则使用最后一个元素 - if (levelDataList is { Count: > 0 }) - { - if (levelIndex >= 0 && levelIndex < levelDataList.Count) - LevelData = levelDataList[levelIndex]; - else - // 超出范围后,使用最后一个元素 - LevelData = levelDataList[^1]; - } - else - { - Debug.LogError("LevelUnlockModel DataList is null or empty"); - } - var btnDownCoin = ((btn_unlock_1)ui.btn_download_coin); - var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; - btnDownCoin.title = downloadCoinNum.ToString(); - ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}"; - if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) - { - ((btn_claim)ui.btn_download).have_vip.selectedIndex = 1; - ui.is_vip.selectedIndex = 1; - } - else - { - ui.is_vip.selectedIndex = 0; - btnDownCoin.down_load.selectedIndex = 1; - } - - - if (GameHelper.IsGiftSwitch() && successData_.IsLevelSuccess) - { - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Open); - - GameHelper.PlayGameTimeEvent(1, () => { GameHelper.RequestGameConfig(); }); - } - else - { - GameHelper.SetCloseResult(true); - } - - Debug.Log("//////////////////////3"); - InitView(); - } - - private int GetNextSpecialLevel() - { - var now_level = successData_.level; - var list_ = ConfigSystem.GetConfig(); - for (var i = now_level; i < list_.Count; i++) - if (list_[i].LeveType != 0) - return i; - return 0; - } - - private SuccessData successData_; - - protected override void OnOpen(object args) - { - } - - protected override void OnHide() - { - } - - protected override void OnDisplay(object args) - { - } - - #endregion - - #region 消息 - public void OnUpdate101(object a = null) - { - com_gold btn_gold = ui.btn_gold as com_gold; - btn_gold.text_gold.text = $"{DataMgr.Coin.Value:N0}"; - } - protected override void AddListener() - { - GameDispatcher.Instance.AddListener(GameMsg.UnlockLevelsuccess, UnlockLevelsuccess); - GameDispatcher.Instance.AddListener(GameMsg.Update101, OnUpdate101); - } - - protected override void RemoveListener() - { - GameDispatcher.Instance.RemoveListener(GameMsg.UnlockLevelsuccess, UnlockLevelsuccess); - GameDispatcher.Instance.RemoveListener(GameMsg.Update101, OnUpdate101); - } - - #endregion - } +using System; +using System.Collections.Generic; +using DG.Tweening; +using FairyGUI; +using FGUI.LG_Common; +using FGUI.LG_End; +using FGUI.ZM_Common_01; +using Newtonsoft.Json; +using Spine.Unity; +using UnityEngine; +using btn_claim = FGUI.LG_Common.btn_claim; +using SGModule.Common.Extensions; +using System.Linq; +using SGModule.NetKit; +namespace RedHotRoast +{ + public class NewEndUI : BaseUI + { + private readonly List loader_list = new(); + private readonly List rate_list = new(); + private Action closeCallback; + private NewEndUICtrl ctrl; + + + private List list_1; + private NewEndModel model; + private int next_level; + private int rate_idnex = 3; + private int scroll_number; + private int scroll_type = 1; + private com_newend ui; + + public NewEndUI(NewEndUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.NewEndUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "LG_End"; + uiInfo.assetName = "com_newend"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + private void UnlockLevelsuccess(object a = null) + { + CtrlCloseUI(); + } + + private void endClose() + { + var lv = GameHelper.GetCommonModel().MultiModal; + if (GameHelper.GetLevel() >= GameHelper.GetCommonModel().MultiModal) + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.UnlockLevelNewUI_Open); + is_unlock_level = true; + } + CtrlCloseUI(); + } + + //初始化页面逻辑 + private void InitView() + { + if (GameHelper.IsGiftSwitch()) + { + if (!loader_list.Contains(ui.loader_bgimg)) loader_list.Add(ui.loader_bgimg); + + // TextureHelper.SetImgLoader(ui.loader_bgimg, LevelData.Name, null, "LevelAlbums/"); + if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal) + { + int level_ = GameHelper.GetLevel() - 1; + if (level_ < 0) level_ = 0; + if (level_ >= ConfigSystem.GetLevelUnlockConfig().Count) level_ = ConfigSystem.GetLevelUnlockConfig().Count - 1; + TextureHelper.SetImgLoader(ui.loader_bgimg, ConfigSystem.GetLevelUnlockConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); + } + else + { + Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel()); + if (levelunlock_ != null) + { + if (levelunlock_.type == 0) + { + if (levelunlock_.config_index >= ConfigSystem.GetFreeImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetFreeImageConfig().Count - 1; + FreeImageLibrary _leveldata = ConfigSystem.GetFreeImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + } + else if (levelunlock_.type == 1) + { + if (levelunlock_.config_index >= ConfigSystem.GetADImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetADImageConfig().Count - 1; + ADImageLibrary _leveldata = ConfigSystem.GetADImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + } + else if (levelunlock_.type == 2) + { + if (levelunlock_.config_index >= ConfigSystem.GetSpecialImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetSpecialImageConfig().Count - 1; + SpecialImageLibrary _leveldata = ConfigSystem.GetSpecialImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + } + else if (levelunlock_.type == 3) + { + if (levelunlock_.config_index >= ConfigSystem.GetVIPImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetVIPImageConfig().Count - 1; + VIPImageLibrary _leveldata = ConfigSystem.GetVIPImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.loader_bgimg, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + } + } + else + { + int level_ = GameHelper.GetLevel() - 1; + if (level_ < 0) level_ = 0; + if (level_ >= ConfigSystem.GetLevelUnlockConfig().Count) level_ = ConfigSystem.GetLevelUnlockConfig().Count - 1; + TextureHelper.SetImgLoader(ui.loader_bgimg, ConfigSystem.GetLevelUnlockConfig()[level_].Name, null, "LevelAlbums/", FolderNames.AlbumName); + } + } + } + + ui.tetx_level.text = Language.GetContentParams("level", successData_.level); + ui.text_award.text = successData_.ch_number.ToString(); + Debug.Log(JsonConvert.SerializeObject(successData_) + "/////////////////"); + Debug.Log("/////////////////4"); + + // if (!successData_.IsWin) ui.text_award.text = DataMgr.Coin.Value.ToString(); + Debug.Log(GetNextSpecialLevel()); + next_level = GetNextSpecialLevel(); + + var levelUnlock_ = ConfigSystem.GetLevelUnlockConfig()[next_level]; + if (levelUnlock_.LeveType == 1) + ui.text_levelType.text = "Special level"; + else if (levelUnlock_.LeveType == 2) ui.text_levelType.text = "VIP level"; + ui.progress_level.max = next_level; + ui.progress_level.value = successData_.level; + // if (successData_.IsLevelSuccess && successData_.level == next_level) + // //打开解锁界面 + // ui.btn_continue.SetClick(() => + // { + // uiCtrlDispatcher.Dispatch(UICtrlMsg.UnlockLevelUI_Open, next_level); + // }); + // else + ui.btn_continue.SetClick(() => + { + endClose(); + }); + ((btn_claim4)ui.btn_claim).title = $"{successData_.ch_number}"; + + var delayTime = successData_.IsLevelSuccess ? 1f : 0f; + if (!successData_.IsWin) + { + delayTime = 0f; + ui.win_lose.selectedIndex = 0; + } + else + { + ui.win_lose.selectedIndex = 1; + } + if (!GameHelper.IsGiftSwitch()) delayTime = 0; + ui.step.selectedIndex = !successData_.IsLevelSuccess || !successData_.IsWin ? 1 : 0; + Debug.Log("/////////////////5"); + DOVirtual.DelayedCall(delayTime, () => + { + Debug.Log(delayTime); + Debug.Log("/////////////////6"); + ui.step.selectedIndex = 1; + // var anim_bg = FXManager.Instance.SetFx(ui.GetChild("bg_parent") as GGraph, Fx_Type.fx_end_bg, ref closeCallback); + if (successData_.IsWin) + { + // anim_bg.state.SetAnimation(0, "win", false); + // anim_bg.state.Complete += (trackEntry) => + // { + // anim_bg.state.SetAnimation(0, "win_stop", true); + // }; + var fireworks = FXManager.Instance.SetFx(ui.GetChild("congra_parent") as GGraph, Fx_Type.fx_win, ref closeCallback); + fireworks.state.SetAnimation(0, "out", true); + + // var coin = FXManager.Instance.SetFx(ui.GetChild("coin_parent") as GGraph, Fx_Type.fx_wins, ref closeCallback); + // coin.state.SetAnimation(0, "animation", true); + // coin.state.Complete += (trackEntry) => + // { + // coin.state.SetAnimation(0, "animation2", true); + // }; + + if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetCommonConf().FreeClaims) + ((btn_claim3)ui.btn_mult).state.selectedIndex = 1; + else ((btn_claim3)ui.btn_mult).state.selectedIndex = 0; + ui.btn_mult.SetClick(() => + { + if (!GameHelper.GetCloseResult()) return; + if (SaveData.GetSaveObject().LargeRewardNum < ConfigSystem.GetCommonConf().FreeClaims) + { + ui.btn_mult.touchable = ui.btn_claim.touchable = false; + SaveData.SaveDataFunc(); + StartScroll(); + } + else + { + GameHelper.ShowVideoAd("GameEnd", isSuccess => + { + if (isSuccess) + { + ui.btn_mult.touchable = ui.btn_claim.touchable = false; + StartScroll(); + } + }); + } + }); + ui.btn_claim.SetClick(() => + { + if (!GameHelper.GetCloseResult()) return; + ui.btn_mult.touchable = ui.btn_claim.touchable = false; + DOVirtual.DelayedCall(2f, () => { GameHelper.addInterAdnumber(); }); + GetReward(successData_.ch_number); + }); + + AudioManager.Instance.PlayDynamicEffect(AudioConst.Victoriously); + } + else + { + // anim_bg.state.SetAnimation(0, "lose", false); + // anim_bg.state.Complete += (trackEntry) => + // { + // anim_bg.state.SetAnimation(0, "lose_stop", true); + // }; + + ui.btn_restart.SetClick(() => + { + if (!GameHelper.GetCloseResult()) return; + + GameHelper.addInterAdnumber(); + if (!successData_.IsWin) GameHelper.SetLevelstate(3); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Close); + }); + } + }); + if (GameHelper.GetVipPrivilege(Subscription.DoubleLevelReward.As())) ((wheel)ui.wheel).have_vip.selectedIndex = 1; + if (successData_.boost_array != null) + { + ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll); + ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() => + { + rate_idnex++; + ui.btn_mult.title = + GameHelper.Get101Str((decimal)successData_.ch_number * + successData_.boost_array[rate_idnex % 5]); + }); + ui.btn_mult.title = + GameHelper.Get101Str((decimal)successData_.ch_number * successData_.boost_array[rate_idnex]); + + list_1 = new List + { + ((wheel_)ui.wheel.GetChild("wheel_")).item_0, ((wheel_)ui.wheel.GetChild("wheel_")).item_1, + (ui.wheel.GetChild("wheel_") as wheel_).item_2, (ui.wheel.GetChild("wheel_") as wheel_).item_3, + (ui.wheel.GetChild("wheel_") as wheel_).item_4, (ui.wheel.GetChild("wheel_") as wheel_).item_5, + (ui.wheel.GetChild("wheel_") as wheel_).item_6, (ui.wheel.GetChild("wheel_") as wheel_).item_7 + }; + // list_1[2].img_light.visible = true; + + for (var i = 0; i < list_1.Count; i++) + { + list_1[i].type.selectedIndex = (i + scroll_number) % 3; + list_1[i].text_rate.text = "X" + successData_.boost_array[i % successData_.boost_array.Length]; + } + } + } + + private void StartScroll() + { + ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = + ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = 5.0f; + scroll_type = 2; + } + + private void Scroll() + { + if (scroll_type == 1) + { + scroll_number++; + rate_list.Clear(); + for (var i = 0; i < 8; i++) + rate_list.Add(successData_.boost_array[(scroll_number + i) % successData_.boost_array.Length]); + for (var i = 0; i < list_1.Count; i++) + { + list_1[i].type.selectedIndex = (i + scroll_number) % 3; + list_1[i].text_rate.text = "X" + rate_list[i]; + } + + ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() => + { + rate_idnex++; + ui.btn_mult.title = GameHelper.Get101Str((decimal)successData_.ch_number * + successData_.boost_array[ + rate_idnex % successData_.boost_array.Length]); + }); + + ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll); + } + else + { + scroll_number++; + + rate_list.Clear(); + for (var i = 0; i < 8; i++) + rate_list.Add(successData_.boost_array[(scroll_number + i) % successData_.boost_array.Length]); + + // bool need_return = false; + if (((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale < 2.2f && + list_1[4].text_rate.text == "X" + successData_.rate) + { + //开始领取 + var reward = successData_.ch_number * successData_.rate; + if (GameHelper.GetVipPrivilege(Subscription.DoubleLevelReward.As())) reward *= 2; + GetReward(reward); + + GameDispatcher.Instance.Dispatch(GameMsg.RefreshMakeupData); + SaveData.GetSaveObject().LargeRewardNum++; + SaveData.SaveDataFunc(); + return; + } + + for (var i = 0; i < list_1.Count; i++) + { + list_1[i].type.selectedIndex = (i + scroll_number) % 3; + list_1[i].text_rate.text = "X" + rate_list[i]; + } + + // if (need_return) + // { + // (ui.wheel.GetChild("wheel_") as wheel_).t0.timeScale = 0; + // return; + // } + + ((wheel_)ui.wheel.GetChild("wheel_")).t1.Play(() => + { + rate_idnex++; + ui.btn_mult.title = GameHelper.Get101Str((decimal)successData_.ch_number * + successData_.boost_array[ + rate_idnex % successData_.boost_array.Length]); + }); + + ((wheel_)ui.wheel.GetChild("wheel_")).t0.Play(Scroll); + ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale = + ((wheel_)ui.wheel.GetChild("wheel_")).t0.timeScale - 0.3f; + } + } + + private void GetReward(float awardNum) + { + var startObj = ui.btn_mult; + var endObj = ui.btn_gold; + + var pos = GameHelper.GetUICenterPosition(endObj); + + var rewardData = new RewardData(); + var rewardSingleData = new RewardSingleData(101, (decimal)awardNum, RewardOrigin.Play) + { + startPosition = GameHelper.GetUICenterPosition(startObj), + endPosition = new Vector2(pos.x, pos.y) + }; + + rewardData.AddReward(rewardSingleData); + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + rewardData.AddCompleted(success => + { + if (success) + { + RefreshAwardNum((decimal)awardNum, 101); + + if (successData_.IsLevelSuccess) + { + if (!loader_list.Contains(ui.com_loader.GetChild("loader") as GLoader)) + loader_list.Add(ui.com_loader.GetChild("loader") as GLoader); + + GameDispatcher.Instance.Dispatch(GameMsg.reset_game); + + + if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal) + { + TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null, "LevelAlbums/", FolderNames.AlbumName); + var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; + ui.btn_download_coin.SetClick(() => + { + if (GameHelper.Get101() >= downloadCoinNum) + { + GameHelper.AddGold(-downloadCoinNum); + ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}"; + TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName); + TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); + endClose(); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + } + }); + + ui.btn_download.SetClick(() => + { + if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) + { + TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName); + endClose(); + } + else + GameHelper.ShowVideoAd("DownloadImage", isSuccess => + { + if (isSuccess) + { + TextureHelper.SaveImageToAlbum(LevelData.Name, FolderNames.AlbumName); + endClose(); + } + }); + }); + + } + else + { + Levelunlock levelunlock_ = DataMgr.LevelUnlockListNew.Value.FirstOrDefault(x => x.level_ == GameHelper.GetLevel()); + string file_name = ""; + if (levelunlock_ != null) + { + if (levelunlock_.type == 0) + { + if (levelunlock_.config_index >= ConfigSystem.GetFreeImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetFreeImageConfig().Count - 1; + FreeImageLibrary _leveldata = ConfigSystem.GetFreeImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + else if (levelunlock_.type == 1) + { + if (levelunlock_.config_index >= ConfigSystem.GetADImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetADImageConfig().Count - 1; + ADImageLibrary _leveldata = ConfigSystem.GetADImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + else if (levelunlock_.type == 2) + { + if (levelunlock_.config_index >= ConfigSystem.GetSpecialImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetSpecialImageConfig().Count - 1; + SpecialImageLibrary _leveldata = ConfigSystem.GetSpecialImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + else if (levelunlock_.type == 3) + { + if (levelunlock_.config_index >= ConfigSystem.GetVIPImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetVIPImageConfig().Count - 1; + VIPImageLibrary _leveldata = ConfigSystem.GetVIPImageConfig()[levelunlock_.config_index]; + TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, _leveldata.Name, null, "LevelAlbums/", FolderNames.AlbumName); + file_name = _leveldata.Name; + } + } + else + { + TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null, + "LevelAlbums/", FolderNames.AlbumName); + } + var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; + ui.btn_download_coin.SetClick(() => + { + if (GameHelper.Get101() >= downloadCoinNum) + { + GameHelper.AddGold(-downloadCoinNum); + ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}"; + TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); + TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.download); + endClose(); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + } + }); + + ui.btn_download.SetClick(() => + { + if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) + { + TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); + endClose(); + } + else + GameHelper.ShowVideoAd("DownloadImage", isSuccess => + { + if (isSuccess) + { + TextureHelper.SaveImageToAlbum(file_name, FolderNames.AlbumName); + endClose(); + } + }); + }); + } + // TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, LevelData.Name, null, + // "LevelAlbums/"); + + + GameHelper.SetLevel(GameHelper.GetLevel() + 1); + DOVirtual.DelayedCall(1.5f, () => + { + if (GameHelper.IsGiftSwitch()) + { + ui.step.selectedIndex = 2; + } + else + { + CtrlCloseUI(); + } + + + }); + } + else + { + CtrlCloseUI(); + } + } + }); + + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + } + + private void RefreshAwardNum(decimal num = -1, int id = 102) + { + if (num < 0) num = DataMgr.Coin.Value; + var btnCoin = ui.btn_gold as com_gold; + + + var gTextField = btnCoin.text_gold; + CommonHelper.ShowNumAnim(gTextField, num, id); + } + + #region 生命周期 + + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.NewEndModel) as NewEndModel; + } + private bool is_unlock_level = false; + protected override void OnClose() + { + GameHelper.SetCloseResult(false); + closeCallback?.Invoke(); + if (!is_unlock_level) + { + if (successData_.IsLevelSuccess && !GameHelper.is_first_login) + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, successData_.IsWin); + else + GameDispatcher.Instance.Dispatch(GameMsg.CheckEnd); + } + + + foreach (var t in loader_list) + if (t != null && !t.isDisposed && t.texture != null) + { + t.texture.Dispose(); + t.texture = null; + } + + loader_list.Clear(); + + MemoryManager.CleanMemoryMonitor(); + } + + protected override void OnBind() + { + ui = baseUI as com_newend; + } + + private LevelUnlock LevelData; + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) ui.btn_gold.y += 68; + + Debug.Log("//////////////////////0"); + Debug.Log(JsonConvert.SerializeObject(args)); + successData_ = (SuccessData)args; + successData_.ch_number = (int)successData_.ch_number; + + // 修改后的代码 + var levelDataList = ConfigSystem.GetLevelUnlockConfig(); + var levelIndex = successData_.level - 1; + + // 确保索引不超出范围,如果超出则使用最后一个元素 + if (levelDataList is { Count: > 0 }) + { + if (levelIndex >= 0 && levelIndex < levelDataList.Count) + LevelData = levelDataList[levelIndex]; + else + // 超出范围后,使用最后一个元素 + LevelData = levelDataList[^1]; + } + else + { + Debug.LogError("LevelUnlockModel DataList is null or empty"); + } + var btnDownCoin = ((btn_unlock_1)ui.btn_download_coin); + var downloadCoinNum = ConfigSystem.GetCommonConf().CoinsDownload; + btnDownCoin.title = downloadCoinNum.ToString(); + ui.btn_gold.GetChild("text_gold").text = $"{DataMgr.Coin.Value:N0}"; + if (GameHelper.GetVipPrivilege(Subscription.FreeDownImage.As())) + { + ((btn_claim)ui.btn_download).have_vip.selectedIndex = 1; + ui.is_vip.selectedIndex = 1; + } + else + { + ui.is_vip.selectedIndex = 0; + btnDownCoin.down_load.selectedIndex = 1; + } + + + if (GameHelper.IsGiftSwitch() && successData_.IsLevelSuccess) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Open); + + GameHelper.PlayGameTimeEvent(1, () => { GameHelper.RequestGameConfig(); }); + } + else + { + GameHelper.SetCloseResult(true); + } + + Debug.Log("//////////////////////3"); + InitView(); + } + + private int GetNextSpecialLevel() + { + var now_level = successData_.level; + var list_ = ConfigSystem.GetLevelUnlockConfig(); + for (var i = now_level; i < list_.Count; i++) + if (list_[i].LeveType != 0) + return i; + return 0; + } + + private SuccessData successData_; + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + public void OnUpdate101(object a = null) + { + com_gold btn_gold = ui.btn_gold as com_gold; + btn_gold.text_gold.text = $"{DataMgr.Coin.Value:N0}"; + } + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.UnlockLevelsuccess, UnlockLevelsuccess); + GameDispatcher.Instance.AddListener(GameMsg.Update101, OnUpdate101); + } + + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.UnlockLevelsuccess, UnlockLevelsuccess); + GameDispatcher.Instance.RemoveListener(GameMsg.Update101, OnUpdate101); + } + + #endregion + } } \ No newline at end of file diff --git a/Assets/Scripts/ModuleUI/OpenGame/OpenGameUI.cs b/Assets/Scripts/ModuleUI/OpenGame/OpenGameUI.cs index 22e2025e..a297ea81 100644 --- a/Assets/Scripts/ModuleUI/OpenGame/OpenGameUI.cs +++ b/Assets/Scripts/ModuleUI/OpenGame/OpenGameUI.cs @@ -51,9 +51,9 @@ namespace RedHotRoast InitView(); // DOVirtual.DelayedCall(0.2f, () => // { - // if (GameHelper.GetLevel() - 1 < ConfigSystem.GetConfig().Count&&GameHelper.IsGiftSwitch()) + // if (GameHelper.GetLevel() - 1 < ConfigSystem.GetLevelUnlockConfig().Count&&GameHelper.IsGiftSwitch()) // { - // LevelUnlock levelUnlock_ = ConfigSystem.GetConfig()[GameHelper.GetLevel() - 1]; + // LevelUnlock levelUnlock_ = ConfigSystem.GetLevelUnlockConfig()[GameHelper.GetLevel() - 1]; // if (levelUnlock_.LeveType != 0) // { // if (!DataMgr.LevelUnlockList.Value.Contains(GameHelper.GetLevel() - 1)) diff --git a/Assets/Scripts/ModuleUI/Play/RainPlayUI.cs b/Assets/Scripts/ModuleUI/Play/RainPlayUI.cs index 29813d8c..3b23c563 100644 --- a/Assets/Scripts/ModuleUI/Play/RainPlayUI.cs +++ b/Assets/Scripts/ModuleUI/Play/RainPlayUI.cs @@ -593,7 +593,7 @@ namespace RedHotRoast { if (GameHelper.GetLevel() < GameHelper.GetCommonModel().MultiModal) { - TextureHelper.setGamebg(ConfigSystem.GetConfig()[GameHelper.GetLevel() - 1].Name); + TextureHelper.setGamebg(ConfigSystem.GetLevelUnlockConfig()[GameHelper.GetLevel() - 1].Name); } else { @@ -603,27 +603,27 @@ namespace RedHotRoast { if (levelunlock_.type == 0) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - FreeImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetFreeImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetFreeImageConfig().Count - 1; + FreeImageLibrary _leveldata = ConfigSystem.GetFreeImageConfig()[levelunlock_.config_index]; TextureHelper.setGamebg(_leveldata.Name); } else if (levelunlock_.type == 1) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - ADImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetADImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetADImageConfig().Count - 1; + ADImageLibrary _leveldata = ConfigSystem.GetADImageConfig()[levelunlock_.config_index]; TextureHelper.setGamebg(_leveldata.Name); } else if (levelunlock_.type == 2) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - SpecialImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetSpecialImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetSpecialImageConfig().Count - 1; + SpecialImageLibrary _leveldata = ConfigSystem.GetSpecialImageConfig()[levelunlock_.config_index]; TextureHelper.setGamebg(_leveldata.Name); } else if (levelunlock_.type == 3) { - if (levelunlock_.config_index >= ConfigSystem.GetConfig().Count) levelunlock_.config_index = ConfigSystem.GetConfig().Count - 1; - VIPImageLibrary _leveldata = ConfigSystem.GetConfig()[levelunlock_.config_index]; + if (levelunlock_.config_index >= ConfigSystem.GetVIPImageConfig().Count) levelunlock_.config_index = ConfigSystem.GetVIPImageConfig().Count - 1; + VIPImageLibrary _leveldata = ConfigSystem.GetVIPImageConfig()[levelunlock_.config_index]; TextureHelper.setGamebg(_leveldata.Name); } } @@ -633,13 +633,13 @@ namespace RedHotRoast { return; } - if (GameHelper.GetLevel() - 1 < ConfigSystem.GetConfig().Count) + if (GameHelper.GetLevel() - 1 < ConfigSystem.GetLevelUnlockConfig().Count) { - TextureHelper.setGamebg(ConfigSystem.GetConfig()[GameHelper.GetLevel() - 1].Name); + TextureHelper.setGamebg(ConfigSystem.GetLevelUnlockConfig()[GameHelper.GetLevel() - 1].Name); } else { - TextureHelper.setGamebg(ConfigSystem.GetConfig()[ConfigSystem.GetConfig().Count - 1].Name); + TextureHelper.setGamebg(ConfigSystem.GetLevelUnlockConfig()[ConfigSystem.GetLevelUnlockConfig().Count - 1].Name); } } } diff --git a/Assets/Scripts/ModuleUI/Play/RainPlayUICtrl.cs b/Assets/Scripts/ModuleUI/Play/RainPlayUICtrl.cs index 1406a6bb..9239b135 100644 --- a/Assets/Scripts/ModuleUI/Play/RainPlayUICtrl.cs +++ b/Assets/Scripts/ModuleUI/Play/RainPlayUICtrl.cs @@ -1,308 +1,308 @@ -using System.Collections.Generic; -using System.Globalization; -using AppsFlyerSDK; -using IgnoreOPS; -using SGModule.Common.Extensions; -using SGModule.Net; -using SGModule.NetKit; -using UnityEngine; - -namespace RedHotRoast -{ - public class RainPlayUICtrl : BaseUICtrl - { - private RainPlayUI ui; - private RainPlayModel model; - - private uint openUIMsg = UICtrlMsg.RainPlayUI_Open; - private uint closeUIMsg = UICtrlMsg.RainPlayUI_Close; - - #region 生命周期 - protected override void OnInit() - { - //model = ModuleManager.Instance.GetModel(ModelConst.RainPlayModel) as RainPlayModel; - } - - protected override void OnDispose() - { - } - - public override void OpenUI(object args = null) - { - if (ui == null) - { - ui = new RainPlayUI(this); - ui.Open(args); - } - } - - public override void CloseUI(object args = null) - { - if (ui != null && !ui.isClose) - { - ui.Close(); - } - ui = null; - } - #endregion - - #region 消息 - public override uint GetOpenUIMsg(string uiName) - { - return openUIMsg; - } - public override uint GetCloseUIMsg(string uiName) - { - return closeUIMsg; - } - - protected override void AddListener() - { - uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); - uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); - GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); - - } - protected override void RemoveListener() - { - uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); - uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); - GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); - - } - - protected override void AddServerListener() - { - - } - protected override void RemoveServerListener() - { - - } - - private void GetPayReward(decimal goldNum) - { - if (goldNum == 0) return; - - var start = new Vector2(540, 960); - var end = new Vector2(236, 62); - var rewardData = new RewardData(); - var rewardSingleData = new RewardSingleData(101, goldNum, RewardOrigin.AdTask) - { - startPosition = start, - }; - rewardData.AddReward(rewardSingleData); - rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; - - GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); - } - - void pay_success(object str) - { - bool is_maxPay = false; // 第三方支付 - string type = (string)str; - string purch_number = ""; - if (type.Contains("buy_gold")) - { - if (type.StartsWith("buy_gold")) - { - int startIndex = "buy_gold".Length; - string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 - int suffix_num = int.Parse(suffix); - - purch_number = ConfigSystem.GetConfig()[suffix_num].Payment_amount2.ToString(); - - if (!UIManager.Instance.IsExistUI(UIConst.BuygoldUI)) - { - List list = ConfigSystem.GetConfig(); - // GameHelper.AddGoldNumber(list[suffix_num].Actual_coins); - int gold_num = list[suffix_num].Actual_coins; - GetPayReward(gold_num); - SaveData.GetSaveObject()._goldtime[suffix_num] = (int)GameHelper.GetNowTime(); - SaveData.SaveDataFunc(); - GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); - } - } - - } - else if (type == PurchasingManager.GetPaySku(PayType.battle_pass)) - { - SaveData.GetSaveObject().is_get_battlepass = true; - int gold = 0; - int out_ = 0; - int back_ = 0; - int refresh_ = 0; - List Passportrewards_list = ConfigSystem.GetConfig(); - for (int i = 0; i < Passportrewards_list.Count; i++) - { - if (GameHelper.GetBattleLv() > i || (GameHelper.GetGameExp() >= Passportrewards_list[Passportrewards_list.Count - 1].Eliminating_quantity)) - { - if (Passportrewards_list[i].Paid_rewards_type == 0) gold += Passportrewards_list[i].Paid_rewards_num; - else if (Passportrewards_list[i].Paid_rewards_type == 1) out_ += Passportrewards_list[i].Paid_rewards_num; - else if (Passportrewards_list[i].Paid_rewards_type == 2) back_ += Passportrewards_list[i].Paid_rewards_num; - else if (Passportrewards_list[i].Paid_rewards_type == 3) refresh_ += Passportrewards_list[i].Paid_rewards_num; - SaveData.GetSaveObject().battle_pass_paylist.Add(i + 1); - } - else break; - } - var purch = ConfigSystem.GetCommonConf().Passportgift2; - purch_number = purch.ToString(); - if (UIManager.Instance.IsExistUI(UIConst.PassViewUI)) - { - GameHelper.AddItemNumber(0, out_); - GameHelper.AddItemNumber(1, back_); - GameHelper.AddItemNumber(2, refresh_); - GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); - // DataMgr.Coin.Value += gold; - GetPayReward(gold); - GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); - } - } - else if (type == PurchasingManager.GetPaySku(PayType.buy_one)) - { - SaveData.GetSaveObject().have_slot = true; - SaveData.SaveDataFunc(); - GameDispatcher.Instance.Dispatch(GameMsg.Slot_refresh); - GameHelper.ShowTips("purchase_succ", true); - - purch_number = GameHelper.GetCommonModel().addspace2.ToString(); - } - else if (type == PurchasingManager.GetPaySku(PayType.remove_ad)) - { - SaveData.GetSaveObject().remove_ad_time = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().RemoveADsPackDuration * 3600; - SaveData.GetSaveObject().is_get_removead = true; - SaveData.SaveDataFunc(); - // GameHelper.AddGoldNumber(ConfigSystem.GetConfig().DataList[1].coins_quantity); - // GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); - ui?.setBtnAds(); - GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads); - GameHelper.ShowTips("purchase_succ", true); - purch_number = ConfigSystem.GetConfig()[1].Paid_price2.ToString(); - } - else if (type == PurchasingManager.GetPaySku(PayType.pack_reward)) - { - List list = ConfigSystem.GetConfig(); - int gold_num = list[0].coins_quantity; - int back_num = list[0].props_quantity[1]; - int out_num = list[0].props_quantity[0]; - int refresh_num = list[0].props_quantity[2]; - - GameHelper.AddItemNumber(0, out_num); - GameHelper.AddItemNumber(1, back_num); - GameHelper.AddItemNumber(2, refresh_num); - SaveData.GetSaveObject().is_get_packreward = true; - SaveData.SaveDataFunc(); - GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); - GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); - ui?.setBtnAds(); - GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads); - GameHelper.ShowTips("purchase_succ", true); - purch_number = ConfigSystem.GetConfig()[0].Paid_price2.ToString(); - } - else if (type == PurchasingManager.GetPaySku(PayType.fail_pack)) - { - List list = ConfigSystem.GetConfig(); - purch_number = ConfigSystem.GetConfig()[2].Paid_price2.ToString(); - //ui?.setBtnAds(); - GameDispatcher.Instance.Dispatch(GameMsg.resurgence); - - // DataMgr.Coin.Value += ConfigSystem.GetConfig().DataList[1].coins_quantity; - // GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); - int back_num = list[2].props_quantity[1]; - int out_num = list[2].props_quantity[0]; - int refresh_num = list[2].props_quantity[2]; - //GameHelper.addGoldNumber(gold_num); - int gold_num = list[2].coins_quantity; - if (!UIManager.Instance.IsExistUI(UIConst.ResurgenceUI)) DataMgr.Coin.Value += gold_num; - GameHelper.AddItemNumber(0, out_num); - GameHelper.AddItemNumber(1, back_num); - GameHelper.AddItemNumber(2, refresh_num); - GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); - SaveData.SaveDataFunc(); - - } - else if (type == PurchasingManager.GetPaySku(PayType.three_days_gift)) - { - SaveData.GetSaveObject().is_get_ThreeDaysGift = true; - SaveData.SaveDataFunc(); - purch_number = ConfigSystem.GetConfig()[0].Paid_price2.ToString(); - } - else if (type.StartsWith("vip_club")) - { - is_maxPay = true; - int startIndex = "vip_club".Length; - string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 - int suffixNum = int.Parse(suffix); - - if (!MaxPayManager.isIOSPay) - { - var days = 0; - switch (suffixNum) - { - case 0: - days = (int)VipDay.Week; - break; - case 1: - days = (int)VipDay.Month; - break; - case 2: - days = (int)VipDay.Year; - break; - } - - if (days > 0) - { - // 设置 VIP 到期时间(当前时间戳 + VIP 天数对应的秒数) - if (DataMgr.VipExpirationTime.Value > ServerClock.GetCurrentServerTime()) - { - DataMgr.VipExpirationTime.Value = DataMgr.VipExpirationTime.Value + days * 24 * 60 * 60; - } - else DataMgr.VipExpirationTime.Value = ServerClock.GetCurrentServerTime() + days * 24 * 60 * 60; - } - DataMgr.VipLevel.Value = suffixNum + 1; - } - purch_number = ConfigSystem.GetConfig()[suffixNum].DiscountPrice.ToString(); - GameDispatcher.Instance.Dispatch(GameMsg.BuyVip); - } - else if (type.StartsWith("secret_albnums")) - { - is_maxPay = true; - int startIndex = "secret_albnums".Length; - string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 - int suffix_num = int.Parse(suffix); - var model = ConfigSystem.GetConfig()[suffix_num]; - if (model.PayType == (int)UnlockPayType.Pay && !GameHelper.isVipUnlock) - { - purch_number = ConfigSystem.GetConfig()[suffix_num].DiscountPrice.ToString(); - } - GameHelper.isVipUnlock = false; - } - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close); - - if ((!GameHelper.IsAdModelOfPay() || is_maxPay) && !string.IsNullOrEmpty(purch_number) && decimal.TryParse(purch_number, out decimal revenue)) - { - var revenueNum = (int)(purch_number.As() * 10000); - var payType = MaxPayManager.isIOSPay ? 0 : 1; - - // 付费上报BI - BIManager.Instance.TrackPurchase(purch_number.As(), "USD", payType.ToString(), type, "paid"); - - Debug.Log("付费收益上报AF----------- " + revenue); - adCallbackInfo.Clear(); - adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId()); - adCallbackInfo.Add("customer_user_id", GameHelper.GetLoginModel().Uid.ToString()); - adCallbackInfo.Add("af_currency", "USD"); - adCallbackInfo.Add("af_revenue", revenue.ToString(CultureInfo.InvariantCulture)); - AppsFlyer.sendEvent("af_purchase", adCallbackInfo); - - TrackKit.SendEvent(AfPurchaseTrack.Event, AfPurchaseTrack.Property.af_revenue, (int)(purch_number.As() * 10000)); - - } - } - - #endregion - - public static Dictionary adCallbackInfo = new Dictionary(); - - } +using System.Collections.Generic; +using System.Globalization; +using AppsFlyerSDK; +using IgnoreOPS; +using SGModule.Common.Extensions; +using SGModule.Net; +using SGModule.NetKit; +using UnityEngine; + +namespace RedHotRoast +{ + public class RainPlayUICtrl : BaseUICtrl + { + private RainPlayUI ui; + private RainPlayModel model; + + private uint openUIMsg = UICtrlMsg.RainPlayUI_Open; + private uint closeUIMsg = UICtrlMsg.RainPlayUI_Close; + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.RainPlayModel) as RainPlayModel; + } + + protected override void OnDispose() + { + } + + public override void OpenUI(object args = null) + { + if (ui == null) + { + ui = new RainPlayUI(this); + ui.Open(args); + } + } + + public override void CloseUI(object args = null) + { + if (ui != null && !ui.isClose) + { + ui.Close(); + } + ui = null; + } + #endregion + + #region 消息 + public override uint GetOpenUIMsg(string uiName) + { + return openUIMsg; + } + public override uint GetCloseUIMsg(string uiName) + { + return closeUIMsg; + } + + protected override void AddListener() + { + uiCtrlDispatcher.AddListener(openUIMsg, OpenUI); + uiCtrlDispatcher.AddListener(closeUIMsg, CloseUI); + GameDispatcher.Instance.AddListener(GameMsg.apple_pay_success, pay_success); + + } + protected override void RemoveListener() + { + uiCtrlDispatcher.RemoveListener(openUIMsg, OpenUI); + uiCtrlDispatcher.RemoveListener(closeUIMsg, CloseUI); + GameDispatcher.Instance.RemoveListener(GameMsg.apple_pay_success, pay_success); + + } + + protected override void AddServerListener() + { + + } + protected override void RemoveServerListener() + { + + } + + private void GetPayReward(decimal goldNum) + { + if (goldNum == 0) return; + + var start = new Vector2(540, 960); + var end = new Vector2(236, 62); + var rewardData = new RewardData(); + var rewardSingleData = new RewardSingleData(101, goldNum, RewardOrigin.AdTask) + { + startPosition = start, + }; + rewardData.AddReward(rewardSingleData); + rewardData.displayType = RewardDisplayType.RewardFly | RewardDisplayType.ValueChange; + + GameDispatcher.Instance.Dispatch(GameMsg.GetReward, rewardData); + } + + void pay_success(object str) + { + bool is_maxPay = false; // 第三方支付 + string type = (string)str; + string purch_number = ""; + if (type.Contains("buy_gold")) + { + if (type.StartsWith("buy_gold")) + { + int startIndex = "buy_gold".Length; + string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 + int suffix_num = int.Parse(suffix); + + purch_number = ConfigSystem.GetConfig()[suffix_num].Payment_amount2.ToString(); + + if (!UIManager.Instance.IsExistUI(UIConst.BuygoldUI)) + { + List list = ConfigSystem.GetConfig(); + // GameHelper.AddGoldNumber(list[suffix_num].Actual_coins); + int gold_num = list[suffix_num].Actual_coins; + GetPayReward(gold_num); + SaveData.GetSaveObject()._goldtime[suffix_num] = (int)GameHelper.GetNowTime(); + SaveData.SaveDataFunc(); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + } + } + + } + else if (type == PurchasingManager.GetPaySku(PayType.battle_pass)) + { + SaveData.GetSaveObject().is_get_battlepass = true; + int gold = 0; + int out_ = 0; + int back_ = 0; + int refresh_ = 0; + List Passportrewards_list = ConfigSystem.GetConfig(); + for (int i = 0; i < Passportrewards_list.Count; i++) + { + if (GameHelper.GetBattleLv() > i || (GameHelper.GetGameExp() >= Passportrewards_list[Passportrewards_list.Count - 1].Eliminating_quantity)) + { + if (Passportrewards_list[i].Paid_rewards_type == 0) gold += Passportrewards_list[i].Paid_rewards_num; + else if (Passportrewards_list[i].Paid_rewards_type == 1) out_ += Passportrewards_list[i].Paid_rewards_num; + else if (Passportrewards_list[i].Paid_rewards_type == 2) back_ += Passportrewards_list[i].Paid_rewards_num; + else if (Passportrewards_list[i].Paid_rewards_type == 3) refresh_ += Passportrewards_list[i].Paid_rewards_num; + SaveData.GetSaveObject().battle_pass_paylist.Add(i + 1); + } + else break; + } + var purch = ConfigSystem.GetCommonConf().Passportgift2; + purch_number = purch.ToString(); + if (UIManager.Instance.IsExistUI(UIConst.PassViewUI)) + { + GameHelper.AddItemNumber(0, out_); + GameHelper.AddItemNumber(1, back_); + GameHelper.AddItemNumber(2, refresh_); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + // DataMgr.Coin.Value += gold; + GetPayReward(gold); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + } + } + else if (type == PurchasingManager.GetPaySku(PayType.buy_one)) + { + SaveData.GetSaveObject().have_slot = true; + SaveData.SaveDataFunc(); + GameDispatcher.Instance.Dispatch(GameMsg.Slot_refresh); + GameHelper.ShowTips("purchase_succ", true); + + purch_number = GameHelper.GetCommonModel().addspace2.ToString(); + } + else if (type == PurchasingManager.GetPaySku(PayType.remove_ad)) + { + SaveData.GetSaveObject().remove_ad_time = (int)GameHelper.GetNowTime() + GameHelper.GetCommonModel().RemoveADsPackDuration * 3600; + SaveData.GetSaveObject().is_get_removead = true; + SaveData.SaveDataFunc(); + // GameHelper.AddGoldNumber(ConfigSystem.GetConfig().DataList[1].coins_quantity); + // GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + ui?.setBtnAds(); + GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads); + GameHelper.ShowTips("purchase_succ", true); + purch_number = ConfigSystem.GetConfig()[1].Paid_price2.ToString(); + } + else if (type == PurchasingManager.GetPaySku(PayType.pack_reward)) + { + List list = ConfigSystem.GetConfig(); + int gold_num = list[0].coins_quantity; + int back_num = list[0].props_quantity[1]; + int out_num = list[0].props_quantity[0]; + int refresh_num = list[0].props_quantity[2]; + + GameHelper.AddItemNumber(0, out_num); + GameHelper.AddItemNumber(1, back_num); + GameHelper.AddItemNumber(2, refresh_num); + SaveData.GetSaveObject().is_get_packreward = true; + SaveData.SaveDataFunc(); + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + ui?.setBtnAds(); + GameDispatcher.Instance.Dispatch(GameMsg.UpdateNoads); + GameHelper.ShowTips("purchase_succ", true); + purch_number = ConfigSystem.GetConfig()[0].Paid_price2.ToString(); + } + else if (type == PurchasingManager.GetPaySku(PayType.fail_pack)) + { + List list = ConfigSystem.GetConfig(); + purch_number = ConfigSystem.GetConfig()[2].Paid_price2.ToString(); + //ui?.setBtnAds(); + GameDispatcher.Instance.Dispatch(GameMsg.resurgence); + + // DataMgr.Coin.Value += ConfigSystem.GetConfig().DataList[1].coins_quantity; + // GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + int back_num = list[2].props_quantity[1]; + int out_num = list[2].props_quantity[0]; + int refresh_num = list[2].props_quantity[2]; + //GameHelper.addGoldNumber(gold_num); + int gold_num = list[2].coins_quantity; + if (!UIManager.Instance.IsExistUI(UIConst.ResurgenceUI)) DataMgr.Coin.Value += gold_num; + GameHelper.AddItemNumber(0, out_num); + GameHelper.AddItemNumber(1, back_num); + GameHelper.AddItemNumber(2, refresh_num); + GameDispatcher.Instance.Dispatch(GameMsg.Sheep_item_refresh); + SaveData.SaveDataFunc(); + + } + else if (type == PurchasingManager.GetPaySku(PayType.three_days_gift)) + { + SaveData.GetSaveObject().is_get_ThreeDaysGift = true; + SaveData.SaveDataFunc(); + purch_number = ConfigSystem.GetConfig()[0].Paid_price2.ToString(); + } + else if (type.StartsWith("vip_club")) + { + is_maxPay = true; + int startIndex = "vip_club".Length; + string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 + int suffixNum = int.Parse(suffix); + + if (!MaxPayManager.isIOSPay) + { + var days = 0; + switch (suffixNum) + { + case 0: + days = (int)VipDay.Week; + break; + case 1: + days = (int)VipDay.Month; + break; + case 2: + days = (int)VipDay.Year; + break; + } + + if (days > 0) + { + // 设置 VIP 到期时间(当前时间戳 + VIP 天数对应的秒数) + if (DataMgr.VipExpirationTime.Value > ServerClock.GetCurrentServerTime()) + { + DataMgr.VipExpirationTime.Value = DataMgr.VipExpirationTime.Value + days * 24 * 60 * 60; + } + else DataMgr.VipExpirationTime.Value = ServerClock.GetCurrentServerTime() + days * 24 * 60 * 60; + } + DataMgr.VipLevel.Value = suffixNum + 1; + } + purch_number = ConfigSystem.GetConfig()[suffixNum].DiscountPrice.ToString(); + GameDispatcher.Instance.Dispatch(GameMsg.BuyVip); + } + else if (type.StartsWith("secret_albnums")) + { + is_maxPay = true; + int startIndex = "secret_albnums".Length; + string suffix = type[startIndex..]; // 截取 "gold" 后的所有字符 + int suffix_num = int.Parse(suffix); + var model = ConfigSystem.GetSecretAlbumsConfig()[suffix_num]; + if (model.PayType == (int)UnlockPayType.Pay && !GameHelper.isVipUnlock) + { + purch_number = ConfigSystem.GetSecretAlbumsConfig()[suffix_num].DiscountPrice.ToString(); + } + GameHelper.isVipUnlock = false; + } + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.PayloadingUI_Close); + + if ((!GameHelper.IsAdModelOfPay() || is_maxPay) && !string.IsNullOrEmpty(purch_number) && decimal.TryParse(purch_number, out decimal revenue)) + { + var revenueNum = (int)(purch_number.As() * 10000); + var payType = MaxPayManager.isIOSPay ? 0 : 1; + + // 付费上报BI + BIManager.Instance.TrackPurchase(purch_number.As(), "USD", payType.ToString(), type, "paid"); + + Debug.Log("付费收益上报AF----------- " + revenue); + adCallbackInfo.Clear(); + adCallbackInfo.Add("appsflyer_id", AppsFlyer.getAppsFlyerId()); + adCallbackInfo.Add("customer_user_id", GameHelper.GetLoginModel().Uid.ToString()); + adCallbackInfo.Add("af_currency", "USD"); + adCallbackInfo.Add("af_revenue", revenue.ToString(CultureInfo.InvariantCulture)); + AppsFlyer.sendEvent("af_purchase", adCallbackInfo); + + TrackKit.SendEvent(AfPurchaseTrack.Event, AfPurchaseTrack.Property.af_revenue, (int)(purch_number.As() * 10000)); + + } + } + + #endregion + + public static Dictionary adCallbackInfo = new Dictionary(); + + } } \ No newline at end of file diff --git a/Assets/Scripts/ModuleUI/SecretAlbums/SecretAlbumsUI.cs b/Assets/Scripts/ModuleUI/SecretAlbums/SecretAlbumsUI.cs index 719dd0ed..7548a85c 100644 --- a/Assets/Scripts/ModuleUI/SecretAlbums/SecretAlbumsUI.cs +++ b/Assets/Scripts/ModuleUI/SecretAlbums/SecretAlbumsUI.cs @@ -1,378 +1,378 @@ -using System; -using System.Collections.Generic; -using System.IO; -using FairyGUI; -using FGUI.LG_secretAlbums; -using SGModule.NetKit; -using UnityEngine; - -namespace RedHotRoast -{ - public class SecretAlbumsUI : BaseUI - { - private const int MaxVisibleCount = 6; // 一屏显示6个 - private const int PreloadCount = 2; // 上下各预加载一屏 - - private readonly Dictionary _fileIsExist = new(); - private readonly Dictionary activeLoaders = new(); - private SecretAlbumsUICtrl ctrl; - private SecretAlbumsModel model; - private com_scAlbums ui; - - public SecretAlbumsUI(SecretAlbumsUICtrl ctrl) : base(ctrl) - { - uiName = UIConst.SecretAlbumsUI; - this.ctrl = ctrl; - } - - protected override void SetUIInfo(UIInfo uiInfo) - { - uiInfo.packageName = "LG_secretAlbums"; - uiInfo.assetName = "com_scAlbums"; - uiInfo.layerType = UILayerType.Popup; - uiInfo.isNeedOpenAnim = false; - uiInfo.isNeedCloseAnim = false; - uiInfo.isNeedUIMask = true; - } - - private void UnlockSuccess(object str = null) - { - ui.sc_list.itemRenderer = ItemRender; - ui.sc_list.numItems = _secretData.Count; - } - - - // 初始化页面逻辑 - private void InitView() - { - ui.btn_gold.GetChild("text_gold").text = GameHelper.Get101Str(); - ui.btn_close.SetClick(CtrlCloseUI); - - UnlockSuccess(); - - - // 滚动过程中实时刷新可见播放器 - // ui.sc_list.scrollPane.onScrollEnd.Add(OnScrollEnd); - - // 打开页面时初始化一次 - // OnScrollEnd(); - InitScroll(); - } - - private void InitScroll() - { - ui.sc_list.scrollPane.onScroll.Add(OnScrollUpdate); - ui.sc_list.scrollPane.onScrollEnd.Add(OnScrollEnd); // 保留结束时的整理 - - OnScrollEnd(); - } - - // 滑动过程中实时更新 - private void OnScrollUpdate() - { - UpdateVisibleAndPreload(); - } - - // 核心刷新逻辑 - private void UpdateVisibleAndPreload() - { - if (_secretData == null || _secretData.Count == 0) return; - - var firstVisibleIndex = ui.sc_list.GetFirstChildInView(); - var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.sc_list.numItems - 1); - - var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); - var endIndex = Mathf.Min(ui.sc_list.numItems - 1, lastVisibleIndex + PreloadCount); - - // 回收超出范围 loader - var keysToRemove = new List(); - foreach (var kv in activeLoaders) - { - var idx = kv.Key; - if (idx < startIndex || idx > endIndex) - { - GLoaderPool.Instance.ReturnLoader(kv.Value); - var oldItem = ui.sc_list.GetChildAt(idx) as item_scalnums; - if (oldItem != null) oldItem.com_pic.picture = null; - keysToRemove.Add(idx); - } - } - - foreach (var k in keysToRemove) activeLoaders.Remove(k); - - - // 分配 loader 并加载图片 - for (var i = startIndex; i <= endIndex; i++) - { - if (activeLoaders.ContainsKey(i)) continue; - - var item = ui.sc_list.GetChildAt(i) as item_scalnums; - if (item == null) continue; - - if (item.com_pic.picture != null && !item.com_pic.picture.isDisposed) - GLoaderPool.Instance.ReturnLoader(item.com_pic.picture); - - var loader = GLoaderPool.Instance.GetLoader(); - item.com_pic.picture = loader; - item.com_pic.AddChild(loader); - loader.SetSize(item.com_pic.width, item.com_pic.height); - - _fileIsExist.TryGetValue(i, out var value); - if (!value) - { - var localPath = Path.Combine(TextureHelper.getResPath(), _secretData[i].Name + ".jpg"); - - if (File.Exists(localPath)) - { - _fileIsExist[i] = true; - Debug.Log($"[SetImgLoader] 本地存在,直接加载 {_secretData[i].Name}"); - CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(_secretData[i].Name, loader, null, - "SecretAlbums/")); - } - else - { - _fileIsExist[i] = false; - } - } - else - { - CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(_secretData[i].Name, loader, null, - "SecretAlbums/")); - } - - activeLoaders[i] = loader; - } - - // Debug.Log($"[ScrollUpdate] active loaders={activeLoaders.Count}, pool={GLoaderPool.Instance.GetPoolCount()}, inUse={GLoaderPool.Instance.GetInUseCount()}"); - } - - private void OnScrollEnd() - { - if (_secretData == null || _secretData.Count == 0) return; - - var firstVisibleIndex = ui.sc_list.GetFirstChildInView(); - var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.sc_list.numItems - 1); - - var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); - var endIndex = Mathf.Min(ui.sc_list.numItems - 1, lastVisibleIndex + PreloadCount); - - // Debug.Log($"[ScrollEnd] start index={startIndex} end index={endIndex}"); - - - var tasks = new List<(GLoader loader, string fileName, Action callback, string folder, string localFolder)>(); - // 分配 loader 并加载图片 - for (var i = startIndex; i <= endIndex; i++) - { - _fileIsExist.TryGetValue(i, out var value); - - if (value) continue; - var item = ui.sc_list.GetChildAt(i) as item_scalnums; - if (item == null) continue; - if (item.com_pic.picture != null && !item.com_pic.picture.isDisposed) - GLoaderPool.Instance.ReturnLoader(item.com_pic.picture); - var loader = GLoaderPool.Instance.GetLoader(); - item.com_pic.picture = loader; - item.com_pic.AddChild(loader); - loader.SetSize(item.com_pic.width, item.com_pic.height); - - var idx = i; - tasks.Add((loader, _secretData[i].Name, texture => - { - if (texture != null) _fileIsExist[idx] = true; - }, "SecretAlbums/", FolderNames.SecretName)); - - activeLoaders[i] = loader; - } - - TextureHelper.SetImgLoaders(tasks); - } - - - private void ItemRender(int index, GObject obj) - { - var item = (item_scalnums)obj; - - item.text_id.text = _secretData[index].id.ToString(); - - var isUnlock = DataMgr.SecretUnlockList.Value.Contains(index); - - item.btn_unlock.pay_type.selectedIndex = _secretData[index].PayType; - - if (_secretData[index].PayType == 0) - item.btn_unlock.title = GameHelper.getPrice((decimal)_secretData[index].DiscountPrice); - else if (_secretData[index].PayType == 1) - item.btn_unlock.title = _secretData[index].GoldCoins.ToString(); - else if (_secretData[index].PayType == 2) item.btn_unlock.title = _secretData[index].AD + "AD"; - - if (isUnlock) - { - item.btn_unlock.pay_type.selectedIndex = 3; - if (_secretData[index].SubscribeUnlock == 1) - { - item.vip.selectedIndex = 1; - item.btn_unlock.pay_type.selectedIndex = 5; - } - item.btn_unlock.title = Language.GetContent("go"); - } - else - { - if (_secretData[index].SubscribeUnlock == 1) - { - item.vip.selectedIndex = 1; - item.btn_unlock.pay_type.selectedIndex = 4; - } - } - - item.btn_null.SetClick(GotoNext); - - item.un_lock.selectedIndex = isUnlock ? 1 : 0; - - item.btn_unlock.SetClick(GotoNext); - - item.peple_num.text = GetPepleNum(_secretData[index].Quantity).ToString(); - - item.hot.selectedIndex = _secretData[index].HotType; - - void GotoNext() - { - var data = new AlbumPreviewData - { - Index = index, - State = _secretData[index].State, - Price = _secretData[index].Price, - PayType = _secretData[index].PayType, - SubscribeUnlock = _secretData[index].SubscribeUnlock, - DiscountPrice = _secretData[index].DiscountPrice, - Name = _secretData[index].Name, - Name2 = _secretData[index].Name2, - GoldCoins = _secretData[index].GoldCoins, - AD = _secretData[index].AD, - CD = _secretData[index].CD - }; - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretAlbumsNextUI_Open, data); - } - } - - private int GetPepleNum(float quantity) - { - // 获取当前时间 - var now = DateTime.Now; - - // 计算当天已经过去的分钟数(从凌晨 0 点开始算) - var minutesPassedToday = now.Hour * 60 + now.Minute; - - // 计算人数 - var num = Mathf.FloorToInt(quantity * minutesPassedToday); - - return num; - } - - #region 生命周期 - - protected override void OnInit() - { - // 初始化GLoader池,设置最大缓存数 - GLoaderPool.Instance.Init(null, 10, 464, 642); - } - - protected override void OnClose() - { - // 1. 解除 UI 对 Loader 的引用 - for (var i = 0; i < ui.sc_list.numChildren; i++) - { - var item = ui.sc_list.GetChildAt(i) as item_scalnums; - if (item != null && item.com_pic.picture != null) item.com_pic.picture = null; // 清掉 GLoader 引用 - } - - activeLoaders.Clear(); - _fileIsExist.Clear(); - - GLoaderPool.Instance.DisposeAll(); - - TextureHelper.ClearMaterialPool(); - - // 强制卸载未使用的资源 - Resources.UnloadUnusedAssets(); - MemoryManager.CleanMemoryMonitor(); - } - - protected override void OnBind() - { - ui = baseUI as com_scAlbums; - } - - private List _secretData = new(); - - protected override void OnOpenBefore(object args) - { - if (Screen.safeArea.y != 0) - { - ui.btn_gold.y += 68; - ui.btn_close.y += 68; - ui.sc_list.y += 68; - } - - var eventName = GameHelper.IsAdModelOfPay() ? ADEventTrack.Event : ADEventTrack.MaxPayEvent; - TrackKit.SendEvent(eventName, ADEventTrack.Property.shop_show); - - _secretData = ConfigSystem.GetConfig(); - InitView(); - } - - protected override void OnOpen(object args) - { - } - - protected override void OnHide() - { - } - - protected override void OnDisplay(object args) - { - } - - #endregion - - #region 消息 - public void SetTopCurr(object a = null) - { - ui.btn_gold.GetChild("text_gold").text = GameHelper.Get101Str(); - } - protected override void AddListener() - { - GameDispatcher.Instance.AddListener(GameMsg.UnlockSecretSuccess, UnlockSuccess); - GameDispatcher.Instance.AddListener(GameMsg.Update101, SetTopCurr); - } - - protected override void RemoveListener() - { - GameDispatcher.Instance.RemoveListener(GameMsg.UnlockSecretSuccess, UnlockSuccess); - GameDispatcher.Instance.RemoveListener(GameMsg.Update101, SetTopCurr); - } - - #endregion - } - - public class AlbumPreviewData - { - public int AD; - public int CD; - public float DiscountPrice; - public int GoldCoins; - public int Index; - public string Name; - public string Name2; - public int PayType; - public float Price; - public int[] State; - public int SubscribeUnlock; - } - - public enum UnlockPayType - { - Pay = 0, - Coin = 1, - Ad = 2, - None = 3 - } +using System; +using System.Collections.Generic; +using System.IO; +using FairyGUI; +using FGUI.LG_secretAlbums; +using SGModule.NetKit; +using UnityEngine; + +namespace RedHotRoast +{ + public class SecretAlbumsUI : BaseUI + { + private const int MaxVisibleCount = 6; // 一屏显示6个 + private const int PreloadCount = 2; // 上下各预加载一屏 + + private readonly Dictionary _fileIsExist = new(); + private readonly Dictionary activeLoaders = new(); + private SecretAlbumsUICtrl ctrl; + private SecretAlbumsModel model; + private com_scAlbums ui; + + public SecretAlbumsUI(SecretAlbumsUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.SecretAlbumsUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "LG_secretAlbums"; + uiInfo.assetName = "com_scAlbums"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + private void UnlockSuccess(object str = null) + { + ui.sc_list.itemRenderer = ItemRender; + ui.sc_list.numItems = _secretData.Count; + } + + + // 初始化页面逻辑 + private void InitView() + { + ui.btn_gold.GetChild("text_gold").text = GameHelper.Get101Str(); + ui.btn_close.SetClick(CtrlCloseUI); + + UnlockSuccess(); + + + // 滚动过程中实时刷新可见播放器 + // ui.sc_list.scrollPane.onScrollEnd.Add(OnScrollEnd); + + // 打开页面时初始化一次 + // OnScrollEnd(); + InitScroll(); + } + + private void InitScroll() + { + ui.sc_list.scrollPane.onScroll.Add(OnScrollUpdate); + ui.sc_list.scrollPane.onScrollEnd.Add(OnScrollEnd); // 保留结束时的整理 + + OnScrollEnd(); + } + + // 滑动过程中实时更新 + private void OnScrollUpdate() + { + UpdateVisibleAndPreload(); + } + + // 核心刷新逻辑 + private void UpdateVisibleAndPreload() + { + if (_secretData == null || _secretData.Count == 0) return; + + var firstVisibleIndex = ui.sc_list.GetFirstChildInView(); + var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.sc_list.numItems - 1); + + var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); + var endIndex = Mathf.Min(ui.sc_list.numItems - 1, lastVisibleIndex + PreloadCount); + + // 回收超出范围 loader + var keysToRemove = new List(); + foreach (var kv in activeLoaders) + { + var idx = kv.Key; + if (idx < startIndex || idx > endIndex) + { + GLoaderPool.Instance.ReturnLoader(kv.Value); + var oldItem = ui.sc_list.GetChildAt(idx) as item_scalnums; + if (oldItem != null) oldItem.com_pic.picture = null; + keysToRemove.Add(idx); + } + } + + foreach (var k in keysToRemove) activeLoaders.Remove(k); + + + // 分配 loader 并加载图片 + for (var i = startIndex; i <= endIndex; i++) + { + if (activeLoaders.ContainsKey(i)) continue; + + var item = ui.sc_list.GetChildAt(i) as item_scalnums; + if (item == null) continue; + + if (item.com_pic.picture != null && !item.com_pic.picture.isDisposed) + GLoaderPool.Instance.ReturnLoader(item.com_pic.picture); + + var loader = GLoaderPool.Instance.GetLoader(); + item.com_pic.picture = loader; + item.com_pic.AddChild(loader); + loader.SetSize(item.com_pic.width, item.com_pic.height); + + _fileIsExist.TryGetValue(i, out var value); + if (!value) + { + var localPath = Path.Combine(TextureHelper.getResPath(), _secretData[i].Name + ".jpg"); + + if (File.Exists(localPath)) + { + _fileIsExist[i] = true; + Debug.Log($"[SetImgLoader] 本地存在,直接加载 {_secretData[i].Name}"); + CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(_secretData[i].Name, loader, null, + "SecretAlbums/")); + } + else + { + _fileIsExist[i] = false; + } + } + else + { + CrazyAsyKit.StartCoroutine(TextureHelper.LoadTexture(_secretData[i].Name, loader, null, + "SecretAlbums/")); + } + + activeLoaders[i] = loader; + } + + // Debug.Log($"[ScrollUpdate] active loaders={activeLoaders.Count}, pool={GLoaderPool.Instance.GetPoolCount()}, inUse={GLoaderPool.Instance.GetInUseCount()}"); + } + + private void OnScrollEnd() + { + if (_secretData == null || _secretData.Count == 0) return; + + var firstVisibleIndex = ui.sc_list.GetFirstChildInView(); + var lastVisibleIndex = Mathf.Min(firstVisibleIndex + MaxVisibleCount - 1, ui.sc_list.numItems - 1); + + var startIndex = Mathf.Max(0, firstVisibleIndex - PreloadCount); + var endIndex = Mathf.Min(ui.sc_list.numItems - 1, lastVisibleIndex + PreloadCount); + + // Debug.Log($"[ScrollEnd] start index={startIndex} end index={endIndex}"); + + + var tasks = new List<(GLoader loader, string fileName, Action callback, string folder, string localFolder)>(); + // 分配 loader 并加载图片 + for (var i = startIndex; i <= endIndex; i++) + { + _fileIsExist.TryGetValue(i, out var value); + + if (value) continue; + var item = ui.sc_list.GetChildAt(i) as item_scalnums; + if (item == null) continue; + if (item.com_pic.picture != null && !item.com_pic.picture.isDisposed) + GLoaderPool.Instance.ReturnLoader(item.com_pic.picture); + var loader = GLoaderPool.Instance.GetLoader(); + item.com_pic.picture = loader; + item.com_pic.AddChild(loader); + loader.SetSize(item.com_pic.width, item.com_pic.height); + + var idx = i; + tasks.Add((loader, _secretData[i].Name, texture => + { + if (texture != null) _fileIsExist[idx] = true; + }, "SecretAlbums/", FolderNames.SecretName)); + + activeLoaders[i] = loader; + } + + TextureHelper.SetImgLoaders(tasks); + } + + + private void ItemRender(int index, GObject obj) + { + var item = (item_scalnums)obj; + + item.text_id.text = _secretData[index].id.ToString(); + + var isUnlock = DataMgr.SecretUnlockList.Value.Contains(index); + + item.btn_unlock.pay_type.selectedIndex = _secretData[index].PayType; + + if (_secretData[index].PayType == 0) + item.btn_unlock.title = GameHelper.getPrice((decimal)_secretData[index].DiscountPrice); + else if (_secretData[index].PayType == 1) + item.btn_unlock.title = _secretData[index].GoldCoins.ToString(); + else if (_secretData[index].PayType == 2) item.btn_unlock.title = _secretData[index].AD + "AD"; + + if (isUnlock) + { + item.btn_unlock.pay_type.selectedIndex = 3; + if (_secretData[index].SubscribeUnlock == 1) + { + item.vip.selectedIndex = 1; + item.btn_unlock.pay_type.selectedIndex = 5; + } + item.btn_unlock.title = Language.GetContent("go"); + } + else + { + if (_secretData[index].SubscribeUnlock == 1) + { + item.vip.selectedIndex = 1; + item.btn_unlock.pay_type.selectedIndex = 4; + } + } + + item.btn_null.SetClick(GotoNext); + + item.un_lock.selectedIndex = isUnlock ? 1 : 0; + + item.btn_unlock.SetClick(GotoNext); + + item.peple_num.text = GetPepleNum(_secretData[index].Quantity).ToString(); + + item.hot.selectedIndex = _secretData[index].HotType; + + void GotoNext() + { + var data = new AlbumPreviewData + { + Index = index, + State = _secretData[index].State, + Price = _secretData[index].Price, + PayType = _secretData[index].PayType, + SubscribeUnlock = _secretData[index].SubscribeUnlock, + DiscountPrice = _secretData[index].DiscountPrice, + Name = _secretData[index].Name, + Name2 = _secretData[index].Name2, + GoldCoins = _secretData[index].GoldCoins, + AD = _secretData[index].AD, + CD = _secretData[index].CD + }; + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.SecretAlbumsNextUI_Open, data); + } + } + + private int GetPepleNum(float quantity) + { + // 获取当前时间 + var now = DateTime.Now; + + // 计算当天已经过去的分钟数(从凌晨 0 点开始算) + var minutesPassedToday = now.Hour * 60 + now.Minute; + + // 计算人数 + var num = Mathf.FloorToInt(quantity * minutesPassedToday); + + return num; + } + + #region 生命周期 + + protected override void OnInit() + { + // 初始化GLoader池,设置最大缓存数 + GLoaderPool.Instance.Init(null, 10, 464, 642); + } + + protected override void OnClose() + { + // 1. 解除 UI 对 Loader 的引用 + for (var i = 0; i < ui.sc_list.numChildren; i++) + { + var item = ui.sc_list.GetChildAt(i) as item_scalnums; + if (item != null && item.com_pic.picture != null) item.com_pic.picture = null; // 清掉 GLoader 引用 + } + + activeLoaders.Clear(); + _fileIsExist.Clear(); + + GLoaderPool.Instance.DisposeAll(); + + TextureHelper.ClearMaterialPool(); + + // 强制卸载未使用的资源 + Resources.UnloadUnusedAssets(); + MemoryManager.CleanMemoryMonitor(); + } + + protected override void OnBind() + { + ui = baseUI as com_scAlbums; + } + + private List _secretData = new(); + + protected override void OnOpenBefore(object args) + { + if (Screen.safeArea.y != 0) + { + ui.btn_gold.y += 68; + ui.btn_close.y += 68; + ui.sc_list.y += 68; + } + + var eventName = GameHelper.IsAdModelOfPay() ? ADEventTrack.Event : ADEventTrack.MaxPayEvent; + TrackKit.SendEvent(eventName, ADEventTrack.Property.shop_show); + + _secretData = ConfigSystem.GetSecretAlbumsConfig(); + InitView(); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + + #endregion + + #region 消息 + public void SetTopCurr(object a = null) + { + ui.btn_gold.GetChild("text_gold").text = GameHelper.Get101Str(); + } + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.UnlockSecretSuccess, UnlockSuccess); + GameDispatcher.Instance.AddListener(GameMsg.Update101, SetTopCurr); + } + + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.UnlockSecretSuccess, UnlockSuccess); + GameDispatcher.Instance.RemoveListener(GameMsg.Update101, SetTopCurr); + } + + #endregion + } + + public class AlbumPreviewData + { + public int AD; + public int CD; + public float DiscountPrice; + public int GoldCoins; + public int Index; + public string Name; + public string Name2; + public int PayType; + public float Price; + public int[] State; + public int SubscribeUnlock; + } + + public enum UnlockPayType + { + Pay = 0, + Coin = 1, + Ad = 2, + None = 3 + } } \ No newline at end of file diff --git a/Assets/Scripts/ModuleUI/UnlockLevel/UnlockLevelUI.cs b/Assets/Scripts/ModuleUI/UnlockLevel/UnlockLevelUI.cs index 628e68fc..2320eeed 100644 --- a/Assets/Scripts/ModuleUI/UnlockLevel/UnlockLevelUI.cs +++ b/Assets/Scripts/ModuleUI/UnlockLevel/UnlockLevelUI.cs @@ -1,248 +1,248 @@ - -using FGUI.ZM_Common_01; -using UnityEngine; -using FairyGUI; -using FGUI.LG_Common; -using DG.Tweening; -using SGModule.NetKit; -using System.Collections.Generic; -using SGModule.Common.Extensions; - -namespace RedHotRoast -{ - public class UnlockLevelUI : BaseUI - { - private UnlockLevelUICtrl ctrl; - private UnlockLevelModel model; - private FGUI.LG_End.com_unlockLevel ui; - - public UnlockLevelUI(UnlockLevelUICtrl ctrl) : base(ctrl) - { - uiName = UIConst.UnlockLevelUI; - this.ctrl = ctrl; - } - - protected override void SetUIInfo(UIInfo uiInfo) - { - uiInfo.packageName = "LG_End"; - uiInfo.assetName = "com_unlockLevel"; - uiInfo.layerType = UILayerType.Popup; - uiInfo.isNeedOpenAnim = false; - uiInfo.isNeedCloseAnim = false; - uiInfo.isNeedUIMask = true; - } - - #region 生命周期 - protected override void OnInit() - { - //model = ModuleManager.Instance.GetModel(ModelConst.UnlockLevelModel) as UnlockLevelModel; - } - - protected override void OnClose() - { - for (int i = 0; i < loader_list.Count; i++) - { - if (loader_list[i] != null && !loader_list[i].isDisposed && loader_list[i].texture != null) - { - loader_list[i].texture.Dispose(); - loader_list[i].texture = null; - } - } - loader_list.Clear(); - } - - protected override void OnBind() - { - ui = baseUI as FGUI.LG_End.com_unlockLevel; - } - private LevelUnlock levelUnlock_; - private int level_; - protected override void OnOpenBefore(object args) - { - level_ = (int)args; - Debug.Log(level_); - - if (!loader_list.Contains(ui.com_loader.GetChild("loader") as GLoader)) - { - loader_list.Add(ui.com_loader.GetChild("loader") as GLoader); - } - - levelUnlock_ = ConfigSystem.GetConfig()[level_]; - TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, levelUnlock_.Name, (s) => - { - TextureHelper.SetImageBlur(ui.com_loader.GetChild("loader") as GLoader); - }, "LevelAlbums/", FolderNames.AlbumName); - InitView(); - if (levelUnlock_.LeveType == 1) - { - TrackKit.SendEvent(ADEventTrack.Special, ADEventTrack.Property.speciallevel); - } - else if (levelUnlock_.LeveType == 2) - { - TrackKit.SendEvent(ADEventTrack.VipLevel, ADEventTrack.Property.viplevel); - } - - } - private List loader_list = new List(); - protected override void OnOpen(object args) - { - } - - protected override void OnHide() - { - } - - protected override void OnDisplay(object args) - { - } - #endregion - - #region 消息 - protected override void AddListener() - { - GameDispatcher.Instance.AddListener(GameMsg.BuyVip, refrsh); - } - protected override void RemoveListener() - { - GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, refrsh); - } - #endregion - private void refrsh(object a = null) - { - DOVirtual.DelayedCall(0.5f, () => - { - InitView(); - }); - - } - //初始化页面逻辑 - private void InitView() - { - - - if (GameHelper.GetVipPrivilege(Subscription.VipLevel.As())) - { - (ui.btn_vip as btn_claim_2).have_vip.selectedIndex = 1; - } - if (GameHelper.GetVipPrivilege(Subscription.SLVLevel.As())) - { - (ui.btn_watch as btn_claim_1).have_vip.selectedIndex = 1; - } - - if (levelUnlock_.LeveType == 1) //特殊关 - { - ui.type.selectedIndex = 0; - ui.btn_pay.title = levelUnlock_.GoldCoins.ToString(); - - ui.btn_pay.SetClick(() => - { - if (DataMgr.Coin.Value >= levelUnlock_.GoldCoins) - { - DataMgr.Coin.Value -= levelUnlock_.GoldCoins; - GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); - DataMgr.LevelUnlockList.Value.Add(level_); - GameHelper.ShowTips("unlocked", true); - DataMgr.LevelUnlockList.Save(); - GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); - CtrlCloseUI(); - TrackKit.SendEvent(ADEventTrack.Special, ADEventTrack.Property.speciallevelcoin); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open); - } - }); - - ui.btn_watch.SetClick(() => //7天都不包含。30天包含特殊,365全部包含 - { - if (GameHelper.GetVipPrivilege(Subscription.SLVLevel.As())) - { - DataMgr.LevelUnlockList.Value.Add(level_); - GameHelper.ShowTips("unlocked", true); - DataMgr.LevelUnlockList.Save(); - GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); - CtrlCloseUI(); - - } - else - { - GameHelper.ShowVideoAd("UnlockSpecialLevel", isSuccess => - { - if (isSuccess) - { - DataMgr.LevelUnlockList.Value.Add(level_); - GameHelper.ShowTips("unlocked", true); - DataMgr.LevelUnlockList.Save(); - GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); - CtrlCloseUI(); - } - TrackKit.SendEvent(ADEventTrack.Special, ADEventTrack.Property.speciallevelvideo); - }); - } - - }); - } - else if (levelUnlock_.LeveType == 2)//vip关 - { - ui.type.selectedIndex = 1; - ui.btn_pay.title = levelUnlock_.GoldCoins.ToString(); - - ui.btn_pay.SetClick(() => - { - if (DataMgr.Coin.Value >= levelUnlock_.GoldCoins) - { - DataMgr.Coin.Value -= levelUnlock_.GoldCoins; - GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); - DataMgr.LevelUnlockList.Value.Add(level_); - GameHelper.ShowTips("unlocked", true); - DataMgr.LevelUnlockList.Save(); - GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); - TrackKit.SendEvent(ADEventTrack.VipLevel, ADEventTrack.Property.viplevelcoin); - CtrlCloseUI(); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open); - } - }); - ui.btn_vip.SetClick(() => - { - if (GameHelper.GetVipPrivilege(Subscription.VipLevel.As())) - { - DataMgr.LevelUnlockList.Value.Add(level_); - GameHelper.ShowTips("unlocked", true); - DataMgr.LevelUnlockList.Save(); - GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); - CtrlCloseUI(); - } - else - { - uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open, 2); - TrackKit.SendEvent(ADEventTrack.VipLevel, ADEventTrack.Property.viplevelsub); - } - - - }); - - - } - ui.btn_close.SetClick(() => - { - GameHelper.SetLevel(GameHelper.GetLevel() + 1); - if (UIManager.Instance.IsExistUI(UIConst.NewEndUI)) - { - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Close); - } - else - { - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open); - } - - CtrlCloseUI(); - }); - - } - } -} + +using FGUI.ZM_Common_01; +using UnityEngine; +using FairyGUI; +using FGUI.LG_Common; +using DG.Tweening; +using SGModule.NetKit; +using System.Collections.Generic; +using SGModule.Common.Extensions; + +namespace RedHotRoast +{ + public class UnlockLevelUI : BaseUI + { + private UnlockLevelUICtrl ctrl; + private UnlockLevelModel model; + private FGUI.LG_End.com_unlockLevel ui; + + public UnlockLevelUI(UnlockLevelUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.UnlockLevelUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "LG_End"; + uiInfo.assetName = "com_unlockLevel"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.UnlockLevelModel) as UnlockLevelModel; + } + + protected override void OnClose() + { + for (int i = 0; i < loader_list.Count; i++) + { + if (loader_list[i] != null && !loader_list[i].isDisposed && loader_list[i].texture != null) + { + loader_list[i].texture.Dispose(); + loader_list[i].texture = null; + } + } + loader_list.Clear(); + } + + protected override void OnBind() + { + ui = baseUI as FGUI.LG_End.com_unlockLevel; + } + private LevelUnlock levelUnlock_; + private int level_; + protected override void OnOpenBefore(object args) + { + level_ = (int)args; + Debug.Log(level_); + + if (!loader_list.Contains(ui.com_loader.GetChild("loader") as GLoader)) + { + loader_list.Add(ui.com_loader.GetChild("loader") as GLoader); + } + + levelUnlock_ = ConfigSystem.GetLevelUnlockConfig()[level_]; + TextureHelper.SetImgLoader(ui.com_loader.GetChild("loader") as GLoader, levelUnlock_.Name, (s) => + { + TextureHelper.SetImageBlur(ui.com_loader.GetChild("loader") as GLoader); + }, "LevelAlbums/", FolderNames.AlbumName); + InitView(); + if (levelUnlock_.LeveType == 1) + { + TrackKit.SendEvent(ADEventTrack.Special, ADEventTrack.Property.speciallevel); + } + else if (levelUnlock_.LeveType == 2) + { + TrackKit.SendEvent(ADEventTrack.VipLevel, ADEventTrack.Property.viplevel); + } + + } + private List loader_list = new List(); + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.BuyVip, refrsh); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, refrsh); + } + #endregion + private void refrsh(object a = null) + { + DOVirtual.DelayedCall(0.5f, () => + { + InitView(); + }); + + } + //初始化页面逻辑 + private void InitView() + { + + + if (GameHelper.GetVipPrivilege(Subscription.VipLevel.As())) + { + (ui.btn_vip as btn_claim_2).have_vip.selectedIndex = 1; + } + if (GameHelper.GetVipPrivilege(Subscription.SLVLevel.As())) + { + (ui.btn_watch as btn_claim_1).have_vip.selectedIndex = 1; + } + + if (levelUnlock_.LeveType == 1) //特殊关 + { + ui.type.selectedIndex = 0; + ui.btn_pay.title = levelUnlock_.GoldCoins.ToString(); + + ui.btn_pay.SetClick(() => + { + if (DataMgr.Coin.Value >= levelUnlock_.GoldCoins) + { + DataMgr.Coin.Value -= levelUnlock_.GoldCoins; + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + DataMgr.LevelUnlockList.Value.Add(level_); + GameHelper.ShowTips("unlocked", true); + DataMgr.LevelUnlockList.Save(); + GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); + CtrlCloseUI(); + TrackKit.SendEvent(ADEventTrack.Special, ADEventTrack.Property.speciallevelcoin); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open); + } + }); + + ui.btn_watch.SetClick(() => //7天都不包含。30天包含特殊,365全部包含 + { + if (GameHelper.GetVipPrivilege(Subscription.SLVLevel.As())) + { + DataMgr.LevelUnlockList.Value.Add(level_); + GameHelper.ShowTips("unlocked", true); + DataMgr.LevelUnlockList.Save(); + GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); + CtrlCloseUI(); + + } + else + { + GameHelper.ShowVideoAd("UnlockSpecialLevel", isSuccess => + { + if (isSuccess) + { + DataMgr.LevelUnlockList.Value.Add(level_); + GameHelper.ShowTips("unlocked", true); + DataMgr.LevelUnlockList.Save(); + GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); + CtrlCloseUI(); + } + TrackKit.SendEvent(ADEventTrack.Special, ADEventTrack.Property.speciallevelvideo); + }); + } + + }); + } + else if (levelUnlock_.LeveType == 2)//vip关 + { + ui.type.selectedIndex = 1; + ui.btn_pay.title = levelUnlock_.GoldCoins.ToString(); + + ui.btn_pay.SetClick(() => + { + if (DataMgr.Coin.Value >= levelUnlock_.GoldCoins) + { + DataMgr.Coin.Value -= levelUnlock_.GoldCoins; + GameDispatcher.Instance.Dispatch(GameMsg.Gold_refresh); + DataMgr.LevelUnlockList.Value.Add(level_); + GameHelper.ShowTips("unlocked", true); + DataMgr.LevelUnlockList.Save(); + GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); + TrackKit.SendEvent(ADEventTrack.VipLevel, ADEventTrack.Property.viplevelcoin); + CtrlCloseUI(); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.BuygoldUI_Open); + } + }); + ui.btn_vip.SetClick(() => + { + if (GameHelper.GetVipPrivilege(Subscription.VipLevel.As())) + { + DataMgr.LevelUnlockList.Value.Add(level_); + GameHelper.ShowTips("unlocked", true); + DataMgr.LevelUnlockList.Save(); + GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); + CtrlCloseUI(); + } + else + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open, 2); + TrackKit.SendEvent(ADEventTrack.VipLevel, ADEventTrack.Property.viplevelsub); + } + + + }); + + + } + ui.btn_close.SetClick(() => + { + GameHelper.SetLevel(GameHelper.GetLevel() + 1); + if (UIManager.Instance.IsExistUI(UIConst.NewEndUI)) + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NewEndUI_Close); + } + else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open); + } + + CtrlCloseUI(); + }); + + } + } +} diff --git a/Assets/Scripts/ModuleUI/UnlockLevelNew/UnlockLevelNewUI.cs b/Assets/Scripts/ModuleUI/UnlockLevelNew/UnlockLevelNewUI.cs index f084768e..f6d793bc 100644 --- a/Assets/Scripts/ModuleUI/UnlockLevelNew/UnlockLevelNewUI.cs +++ b/Assets/Scripts/ModuleUI/UnlockLevelNew/UnlockLevelNewUI.cs @@ -1,490 +1,490 @@ - -using FGUI.ZM_Common_01; -using UnityEngine; -using FairyGUI; -using Newtonsoft.Json; -using System.Collections.Generic; -using System.Linq; -using SGModule.Common.Extensions; -using DG.Tweening; -using UnityEngine.UIElements; -using SGModule.NetKit; - -namespace RedHotRoast -{ - public class UnlockLevelNewUI : BaseUI - { - private UnlockLevelNewUICtrl ctrl; - private UnlockLevelNewModel model; - private FGUI.LG_End.com_unlockLevelNew ui; - - public UnlockLevelNewUI(UnlockLevelNewUICtrl ctrl) : base(ctrl) - { - uiName = UIConst.UnlockLevelNewUI; - this.ctrl = ctrl; - } - - protected override void SetUIInfo(UIInfo uiInfo) - { - uiInfo.packageName = "LG_End"; - uiInfo.assetName = "com_unlockLevelNew"; - uiInfo.layerType = UILayerType.Popup; - uiInfo.isNeedOpenAnim = false; - uiInfo.isNeedCloseAnim = false; - uiInfo.isNeedUIMask = true; - } - - #region 生命周期 - protected override void OnInit() - { - //model = ModuleManager.Instance.GetModel(ModelConst.UnlockLevelNewModel) as UnlockLevelNewModel; - } - - protected override void OnClose() - { - // for (int i = 0; i < loader_list.Count; i++) - // { - // if (loader_list[i] != null && !loader_list[i].isDisposed && loader_list[i].texture != null) - // { - // loader_list[i].texture = null; - // } - // } - // loader_list.Clear(); - foreach (var loader in loader_list) - { - if (loader == null || loader.isDisposed) continue; - - // 释放材质到材质池 - if (loader.material != null) - { - TextureHelper.CancelImageBlur(loader); // 自动返回材质池 - loader.material = null; - } - - // 清理 NTexture - if (loader.texture != null) - { - loader.texture.Dispose(); // 销毁 NTexture 对象 - loader.texture = null; - } - } - loader_list.Clear(); - } - private List loader_list = new List(); - protected override void OnBind() - { - ui = baseUI as FGUI.LG_End.com_unlockLevelNew; - } - - private bool isHallEnter = false; - protected override void OnOpenBefore(object args) - { - if (args != null) - { - isHallEnter = (bool)args; - } - InitView(); - ui.btn_close.SetClick(() => - { - GameDispatcher.Instance.Dispatch(GameMsg.ExitGame); - uiCtrlDispatcher.Dispatch(UICtrlMsg.NewEndUI_Close); - CtrlCloseUI(); - }); - } - - protected override void OnOpen(object args) - { - } - - protected override void OnHide() - { - } - - protected override void OnDisplay(object args) - { - } - #endregion - - #region 消息 - protected override void AddListener() - { - GameDispatcher.Instance.AddListener(GameMsg.BuyVip, RefreshVip); - } - protected override void RemoveListener() - { - GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, RefreshVip); - } - #endregion - private void RefreshVip(object a = null) - { - bool have_special = GameHelper.GetVipPrivilege(Subscription.SLVLevel.As()); - SpecialImageLibrary special_ImageLibrary = ConfigSystem.GetConfig()[DataMgr.LevelUnlockSpecial.Value]; - if (special_ImageLibrary.State == 1 && !have_special) TextureHelper.SetImageBlur(ui.item_2.com_pic.picture); - else TextureHelper.CancelImageBlur(ui.item_2.com_pic.picture); - - if (have_special) - { - ui.item_2.btn_unlock.visible = false; - ui.item_2.type.selectedIndex = 0; - ui.item_2.btn_skip.SetClick(() => - { - SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); - }); - } - else - { - ui.item_2.type.selectedIndex = 2; - ui.item_2.btn_unlock.visible = true; - ui.item_2.btn_skip.SetClick(() => - { - uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); - }); - - if (special_ImageLibrary.GoldCoins > 0) - { - ui.item_2.btn_unlock.pay_type.selectedIndex = 1; - ui.item_2.btn_unlock.title = special_ImageLibrary.GoldCoins.ToString(); - ui.item_2.btn_unlock.SetClick(() => - { - if (DataMgr.Coin.Value >= special_ImageLibrary.GoldCoins) - { - GameHelper.AddGold(-special_ImageLibrary.GoldCoins); - SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); - Debug.Log("///////金币解锁"); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - - } - }); - } - else - { - ui.item_2.btn_unlock.visible = false; - } - } - - bool have_vip = GameHelper.GetVipPrivilege(Subscription.VipLevel.As()); - VIPImageLibrary vip_ImageLibrary = ConfigSystem.GetConfig()[DataMgr.LevelUnlockVIP.Value]; - if (vip_ImageLibrary.State == 1 && !have_vip) TextureHelper.SetImageBlur(ui.item_3.com_pic.picture); - else TextureHelper.CancelImageBlur(ui.item_3.com_pic.picture); - if (have_vip) - { - ui.item_3.btn_unlock.visible = false; - ui.item_3.type.selectedIndex = 0; - ui.item_3.btn_skip.SetClick(() => - { - SelectLevel(3, DataMgr.LevelUnlockVIP.Value); - }); - } - else - { - ui.item_3.type.selectedIndex = 3; - ui.item_3.btn_unlock.visible = true; - ui.item_3.btn_skip.SetClick(() => - { - uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); - }); - - if (vip_ImageLibrary.GoldCoins > 0) - { - ui.item_3.btn_unlock.pay_type.selectedIndex = 1; - ui.item_3.btn_unlock.title = vip_ImageLibrary.GoldCoins.ToString(); - ui.item_3.btn_unlock.SetClick(() => - { - if (DataMgr.Coin.Value >= vip_ImageLibrary.GoldCoins) - { - GameHelper.AddGold(-vip_ImageLibrary.GoldCoins); - SelectLevel(3, DataMgr.LevelUnlockVIP.Value); - Debug.Log("///////金币解锁"); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - - } - }); - } - else - { - ui.item_3.btn_unlock.visible = false; - } - } - } - - //初始化页面逻辑 - private void InitView() - { - Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); - Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); - Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); - Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); - - ConfigSystem.GetConfig(); - - loader_list.Add(ui.item_0.com_pic.picture); - loader_list.Add(ui.item_1.com_pic.picture); - loader_list.Add(ui.item_2.com_pic.picture); - loader_list.Add(ui.item_3.com_pic.picture); - - // List free_level_list = new List(); - // List ad_level_list = new List(); - // List special_level_list = new List(); - // List vip_level_list = new List(); - // for (int i = 0; i < DataMgr.LevelUnlockListNew.Value.Count; i++) - // { - // if (DataMgr.LevelUnlockListNew.Value[i].type == 0) free_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - // else if (DataMgr.LevelUnlockListNew.Value[i].type == 1) ad_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - // else if (DataMgr.LevelUnlockListNew.Value[i].type == 2) special_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - // else if (DataMgr.LevelUnlockListNew.Value[i].type == 3) vip_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - // } - int Free_Alubum_0 = PlayerPrefs.GetInt("Free_Alubum_0", -1); - - int AD_Alubum = PlayerPrefs.GetInt("AD_Alubum", -1); - int Spec_Alubum = PlayerPrefs.GetInt("Spec_Alubum", -1); - int Vip_Alubum = PlayerPrefs.GetInt("Vip_Alubum", -1); - - if (DataMgr.LevelUnlockFree.Value < 0) - { - DataMgr.LevelUnlockFree.Value = Free_Alubum_0; - } - - if (DataMgr.LevelUnlockAD.Value < 0) - { - DataMgr.LevelUnlockAD.Value = AD_Alubum; - } - - if (DataMgr.LevelUnlockSpecial.Value < 0) - { - DataMgr.LevelUnlockSpecial.Value = Spec_Alubum; - } - - if (DataMgr.LevelUnlockVIP.Value < 0) - { - DataMgr.LevelUnlockVIP.Value = Vip_Alubum; - } - - - FreeImageLibrary free_ImageLibrary = ConfigSystem.GetConfig()[DataMgr.LevelUnlockFree.Value]; - ui.item_0.btn_unlock.pay_type.selectedIndex = 2; - ui.item_0_re.btn_unlock.visible = false; - TextureHelper.SetImgLoader(ui.item_0.com_pic.picture, free_ImageLibrary.Name, (s) => - { - if (free_ImageLibrary.State == 1) TextureHelper.SetImageBlur(ui.item_0.com_pic.picture); - }, "LevelAlbums/", FolderNames.AlbumName); - - int Free_Alubum_1 = PlayerPrefs.GetInt("Free_Alubum_1", -1); - FreeImageLibrary free_ImageLibrary_re = ConfigSystem.GetConfig()[Free_Alubum_1]; - TextureHelper.SetImgLoader(ui.item_0_re.com_pic.picture, free_ImageLibrary_re.Name, (s) => - { - if (free_ImageLibrary_re.State == 1) TextureHelper.SetImageBlur(ui.item_0_re.com_pic.picture); - }, "LevelAlbums/", FolderNames.AlbumName); - - ui.item_0.btn_unlock.SetClick(() => - { - PlayerPrefs.SetInt("unlock_refresh", 0); - DataMgr.LevelUnlockFree.Value = Free_Alubum_1; - ui.item_0.visible = false; - ui.item_0_re.visible = true; - }); - - if (PlayerPrefs.GetInt("unlock_refresh", 1) == 1) - { - ui.item_0.visible = true; - ui.item_0_re.visible = false; - } - else - { - ui.item_0.visible = false; - ui.item_0_re.visible = true; - } - - ui.item_0.btn_skip.SetClick(() => - { - SelectLevel(0, DataMgr.LevelUnlockFree.Value); - }); - ui.item_0_re.btn_skip.SetClick(() => - { - SelectLevel(0, DataMgr.LevelUnlockFree.Value); - }); - - - - ADImageLibrary ad_ImageLibrary = ConfigSystem.GetConfig()[DataMgr.LevelUnlockAD.Value]; - TextureHelper.SetImgLoader(ui.item_1.com_pic.picture, ad_ImageLibrary.Name, (s) => - { - if (ad_ImageLibrary.State == 1) TextureHelper.SetImageBlur(ui.item_1.com_pic.picture); - }, "LevelAlbums/", FolderNames.AlbumName); - - ui.item_1.btn_unlock.pay_type.selectedIndex = 3; - - ui.item_1.btn_skip.SetClick(() => - { - Debug.Log("///////播放广告解锁"); - GameHelper.ShowVideoAd("UnlockLevel", isSuccess => - { - if (isSuccess) - { - SelectLevel(1, DataMgr.LevelUnlockAD.Value); - } - }); - }); - - - bool have_special = GameHelper.GetVipPrivilege(Subscription.SLVLevel.As()); - SpecialImageLibrary special_ImageLibrary = ConfigSystem.GetConfig()[DataMgr.LevelUnlockSpecial.Value]; - TextureHelper.SetImgLoader(ui.item_2.com_pic.picture, special_ImageLibrary.Name, (s) => - { - if (special_ImageLibrary.State == 1 && !have_special) TextureHelper.SetImageBlur(ui.item_2.com_pic.picture); - }, "LevelAlbums/", FolderNames.AlbumName); - if (have_special) - { - ui.item_2.btn_unlock.visible = false; - ui.item_2.type.selectedIndex = 0; - ui.item_2.btn_skip.SetClick(() => - { - SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); - }); - } - else - { - ui.item_2.type.selectedIndex = 2; - ui.item_2.btn_unlock.visible = true; - ui.item_2.btn_skip.SetClick(() => - { - uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); - }); - - if (special_ImageLibrary.GoldCoins > 0) - { - ui.item_2.btn_unlock.pay_type.selectedIndex = 1; - ui.item_2.btn_unlock.title = special_ImageLibrary.GoldCoins.ToString(); - ui.item_2.btn_unlock.SetClick(() => - { - if (DataMgr.Coin.Value >= special_ImageLibrary.GoldCoins) - { - GameHelper.AddGold(-special_ImageLibrary.GoldCoins); - SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); - TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.unlock_svip); - Debug.Log("///////金币解锁"); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - - } - }); - } - else - { - ui.item_2.btn_unlock.visible = false; - } - } - - bool have_vip = GameHelper.GetVipPrivilege(Subscription.VipLevel.As()); - VIPImageLibrary vip_ImageLibrary = ConfigSystem.GetConfig()[DataMgr.LevelUnlockVIP.Value]; - - TextureHelper.SetImgLoader(ui.item_3.com_pic.picture, vip_ImageLibrary.Name, (s) => - { - if (vip_ImageLibrary.State == 1 && !have_vip) TextureHelper.SetImageBlur(ui.item_3.com_pic.picture); - }, "LevelAlbums/", FolderNames.AlbumName); - if (have_vip) - { - ui.item_3.btn_unlock.visible = false; - ui.item_3.type.selectedIndex = 0; - ui.item_3.btn_skip.SetClick(() => - { - SelectLevel(3, DataMgr.LevelUnlockVIP.Value); - }); - } - else - { - ui.item_3.type.selectedIndex = 3; - ui.item_3.btn_unlock.visible = true; - ui.item_3.btn_skip.SetClick(() => - { - uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); - }); - - if (vip_ImageLibrary.GoldCoins > 0) - { - ui.item_3.btn_unlock.pay_type.selectedIndex = 1; - ui.item_3.btn_unlock.title = vip_ImageLibrary.GoldCoins.ToString(); - ui.item_3.btn_unlock.SetClick(() => - { - if (DataMgr.Coin.Value >= vip_ImageLibrary.GoldCoins) - { - GameHelper.AddGold(-vip_ImageLibrary.GoldCoins); - SelectLevel(3, DataMgr.LevelUnlockVIP.Value); - Debug.Log("///////金币解锁"); - TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.unlock_vip); - } - else - { - GameHelper.ShowTips("no_enough_gold", true); - - uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); - - } - }); - } - else - { - ui.item_3.btn_unlock.visible = false; - } - } - - - } - - public void SelectLevel(int type_, int id) - { - - DataMgr.LevelUnlockListNew.Value.Add(new Levelunlock() - { - level_ = GameHelper.GetLevel(), - type = type_, - config_index = id - }); - DataMgr.LevelUnlockListNew.Save(); - DataMgr.LevelUnlockFree.Value = -1; - DataMgr.LevelUnlockAD.Value = -1; - DataMgr.LevelUnlockSpecial.Value = -1; - DataMgr.LevelUnlockVIP.Value = -1; - - PlayerPrefs.SetInt("Free_Alubum_0", -1); - PlayerPrefs.SetInt("Free_Alubum_1", -1); - PlayerPrefs.SetInt("AD_Alubum", -1); - PlayerPrefs.SetInt("Spec_Alubum", -1); - PlayerPrefs.SetInt("Vip_Alubum", -1); - - PlayerPrefs.SetInt("unlock_refresh", 1); - GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); - CtrlCloseUI(); - PreDownloadManager.StartDownloadAlbumsPicture(); - - if (isHallEnter) - { - GameHelper.gameType = 0; - GameDispatcher.Instance.Dispatch(GameMsg.OpenGame, false); - } else - { - UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, true); - } - - } - } - public class Levelunlock - { - public int level_; - public int type; - public int config_index; - } -} + +using FGUI.ZM_Common_01; +using UnityEngine; +using FairyGUI; +using Newtonsoft.Json; +using System.Collections.Generic; +using System.Linq; +using SGModule.Common.Extensions; +using DG.Tweening; +using UnityEngine.UIElements; +using SGModule.NetKit; + +namespace RedHotRoast +{ + public class UnlockLevelNewUI : BaseUI + { + private UnlockLevelNewUICtrl ctrl; + private UnlockLevelNewModel model; + private FGUI.LG_End.com_unlockLevelNew ui; + + public UnlockLevelNewUI(UnlockLevelNewUICtrl ctrl) : base(ctrl) + { + uiName = UIConst.UnlockLevelNewUI; + this.ctrl = ctrl; + } + + protected override void SetUIInfo(UIInfo uiInfo) + { + uiInfo.packageName = "LG_End"; + uiInfo.assetName = "com_unlockLevelNew"; + uiInfo.layerType = UILayerType.Popup; + uiInfo.isNeedOpenAnim = false; + uiInfo.isNeedCloseAnim = false; + uiInfo.isNeedUIMask = true; + } + + #region 生命周期 + protected override void OnInit() + { + //model = ModuleManager.Instance.GetModel(ModelConst.UnlockLevelNewModel) as UnlockLevelNewModel; + } + + protected override void OnClose() + { + // for (int i = 0; i < loader_list.Count; i++) + // { + // if (loader_list[i] != null && !loader_list[i].isDisposed && loader_list[i].texture != null) + // { + // loader_list[i].texture = null; + // } + // } + // loader_list.Clear(); + foreach (var loader in loader_list) + { + if (loader == null || loader.isDisposed) continue; + + // 释放材质到材质池 + if (loader.material != null) + { + TextureHelper.CancelImageBlur(loader); // 自动返回材质池 + loader.material = null; + } + + // 清理 NTexture + if (loader.texture != null) + { + loader.texture.Dispose(); // 销毁 NTexture 对象 + loader.texture = null; + } + } + loader_list.Clear(); + } + private List loader_list = new List(); + protected override void OnBind() + { + ui = baseUI as FGUI.LG_End.com_unlockLevelNew; + } + + private bool isHallEnter = false; + protected override void OnOpenBefore(object args) + { + if (args != null) + { + isHallEnter = (bool)args; + } + InitView(); + ui.btn_close.SetClick(() => + { + GameDispatcher.Instance.Dispatch(GameMsg.ExitGame); + uiCtrlDispatcher.Dispatch(UICtrlMsg.NewEndUI_Close); + CtrlCloseUI(); + }); + } + + protected override void OnOpen(object args) + { + } + + protected override void OnHide() + { + } + + protected override void OnDisplay(object args) + { + } + #endregion + + #region 消息 + protected override void AddListener() + { + GameDispatcher.Instance.AddListener(GameMsg.BuyVip, RefreshVip); + } + protected override void RemoveListener() + { + GameDispatcher.Instance.RemoveListener(GameMsg.BuyVip, RefreshVip); + } + #endregion + private void RefreshVip(object a = null) + { + bool have_special = GameHelper.GetVipPrivilege(Subscription.SLVLevel.As()); + SpecialImageLibrary special_ImageLibrary = ConfigSystem.GetSpecialImageConfig()[DataMgr.LevelUnlockSpecial.Value]; + if (special_ImageLibrary.State == 1 && !have_special) TextureHelper.SetImageBlur(ui.item_2.com_pic.picture); + else TextureHelper.CancelImageBlur(ui.item_2.com_pic.picture); + + if (have_special) + { + ui.item_2.btn_unlock.visible = false; + ui.item_2.type.selectedIndex = 0; + ui.item_2.btn_skip.SetClick(() => + { + SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); + }); + } + else + { + ui.item_2.type.selectedIndex = 2; + ui.item_2.btn_unlock.visible = true; + ui.item_2.btn_skip.SetClick(() => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); + }); + + if (special_ImageLibrary.GoldCoins > 0) + { + ui.item_2.btn_unlock.pay_type.selectedIndex = 1; + ui.item_2.btn_unlock.title = special_ImageLibrary.GoldCoins.ToString(); + ui.item_2.btn_unlock.SetClick(() => + { + if (DataMgr.Coin.Value >= special_ImageLibrary.GoldCoins) + { + GameHelper.AddGold(-special_ImageLibrary.GoldCoins); + SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); + Debug.Log("///////金币解锁"); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + + } + }); + } + else + { + ui.item_2.btn_unlock.visible = false; + } + } + + bool have_vip = GameHelper.GetVipPrivilege(Subscription.VipLevel.As()); + VIPImageLibrary vip_ImageLibrary = ConfigSystem.GetVIPImageConfig()[DataMgr.LevelUnlockVIP.Value]; + if (vip_ImageLibrary.State == 1 && !have_vip) TextureHelper.SetImageBlur(ui.item_3.com_pic.picture); + else TextureHelper.CancelImageBlur(ui.item_3.com_pic.picture); + if (have_vip) + { + ui.item_3.btn_unlock.visible = false; + ui.item_3.type.selectedIndex = 0; + ui.item_3.btn_skip.SetClick(() => + { + SelectLevel(3, DataMgr.LevelUnlockVIP.Value); + }); + } + else + { + ui.item_3.type.selectedIndex = 3; + ui.item_3.btn_unlock.visible = true; + ui.item_3.btn_skip.SetClick(() => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); + }); + + if (vip_ImageLibrary.GoldCoins > 0) + { + ui.item_3.btn_unlock.pay_type.selectedIndex = 1; + ui.item_3.btn_unlock.title = vip_ImageLibrary.GoldCoins.ToString(); + ui.item_3.btn_unlock.SetClick(() => + { + if (DataMgr.Coin.Value >= vip_ImageLibrary.GoldCoins) + { + GameHelper.AddGold(-vip_ImageLibrary.GoldCoins); + SelectLevel(3, DataMgr.LevelUnlockVIP.Value); + Debug.Log("///////金币解锁"); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + + } + }); + } + else + { + ui.item_3.btn_unlock.visible = false; + } + } + } + + //初始化页面逻辑 + private void InitView() + { + Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); + Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); + Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); + Debug.Log(JsonConvert.SerializeObject(ConfigSystem.GetConfig()) + ".................."); + + ConfigSystem.GetVIPImageConfig(); + + loader_list.Add(ui.item_0.com_pic.picture); + loader_list.Add(ui.item_1.com_pic.picture); + loader_list.Add(ui.item_2.com_pic.picture); + loader_list.Add(ui.item_3.com_pic.picture); + + // List free_level_list = new List(); + // List ad_level_list = new List(); + // List special_level_list = new List(); + // List vip_level_list = new List(); + // for (int i = 0; i < DataMgr.LevelUnlockListNew.Value.Count; i++) + // { + // if (DataMgr.LevelUnlockListNew.Value[i].type == 0) free_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + // else if (DataMgr.LevelUnlockListNew.Value[i].type == 1) ad_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + // else if (DataMgr.LevelUnlockListNew.Value[i].type == 2) special_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + // else if (DataMgr.LevelUnlockListNew.Value[i].type == 3) vip_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + // } + int Free_Alubum_0 = PlayerPrefs.GetInt("Free_Alubum_0", -1); + + int AD_Alubum = PlayerPrefs.GetInt("AD_Alubum", -1); + int Spec_Alubum = PlayerPrefs.GetInt("Spec_Alubum", -1); + int Vip_Alubum = PlayerPrefs.GetInt("Vip_Alubum", -1); + + if (DataMgr.LevelUnlockFree.Value < 0) + { + DataMgr.LevelUnlockFree.Value = Free_Alubum_0; + } + + if (DataMgr.LevelUnlockAD.Value < 0) + { + DataMgr.LevelUnlockAD.Value = AD_Alubum; + } + + if (DataMgr.LevelUnlockSpecial.Value < 0) + { + DataMgr.LevelUnlockSpecial.Value = Spec_Alubum; + } + + if (DataMgr.LevelUnlockVIP.Value < 0) + { + DataMgr.LevelUnlockVIP.Value = Vip_Alubum; + } + + + FreeImageLibrary free_ImageLibrary = ConfigSystem.GetFreeImageConfig()[DataMgr.LevelUnlockFree.Value]; + ui.item_0.btn_unlock.pay_type.selectedIndex = 2; + ui.item_0_re.btn_unlock.visible = false; + TextureHelper.SetImgLoader(ui.item_0.com_pic.picture, free_ImageLibrary.Name, (s) => + { + if (free_ImageLibrary.State == 1) TextureHelper.SetImageBlur(ui.item_0.com_pic.picture); + }, "LevelAlbums/", FolderNames.AlbumName); + + int Free_Alubum_1 = PlayerPrefs.GetInt("Free_Alubum_1", -1); + FreeImageLibrary free_ImageLibrary_re = ConfigSystem.GetFreeImageConfig()[Free_Alubum_1]; + TextureHelper.SetImgLoader(ui.item_0_re.com_pic.picture, free_ImageLibrary_re.Name, (s) => + { + if (free_ImageLibrary_re.State == 1) TextureHelper.SetImageBlur(ui.item_0_re.com_pic.picture); + }, "LevelAlbums/", FolderNames.AlbumName); + + ui.item_0.btn_unlock.SetClick(() => + { + PlayerPrefs.SetInt("unlock_refresh", 0); + DataMgr.LevelUnlockFree.Value = Free_Alubum_1; + ui.item_0.visible = false; + ui.item_0_re.visible = true; + }); + + if (PlayerPrefs.GetInt("unlock_refresh", 1) == 1) + { + ui.item_0.visible = true; + ui.item_0_re.visible = false; + } + else + { + ui.item_0.visible = false; + ui.item_0_re.visible = true; + } + + ui.item_0.btn_skip.SetClick(() => + { + SelectLevel(0, DataMgr.LevelUnlockFree.Value); + }); + ui.item_0_re.btn_skip.SetClick(() => + { + SelectLevel(0, DataMgr.LevelUnlockFree.Value); + }); + + + + ADImageLibrary ad_ImageLibrary = ConfigSystem.GetADImageConfig()[DataMgr.LevelUnlockAD.Value]; + TextureHelper.SetImgLoader(ui.item_1.com_pic.picture, ad_ImageLibrary.Name, (s) => + { + if (ad_ImageLibrary.State == 1) TextureHelper.SetImageBlur(ui.item_1.com_pic.picture); + }, "LevelAlbums/", FolderNames.AlbumName); + + ui.item_1.btn_unlock.pay_type.selectedIndex = 3; + + ui.item_1.btn_skip.SetClick(() => + { + Debug.Log("///////播放广告解锁"); + GameHelper.ShowVideoAd("UnlockLevel", isSuccess => + { + if (isSuccess) + { + SelectLevel(1, DataMgr.LevelUnlockAD.Value); + } + }); + }); + + + bool have_special = GameHelper.GetVipPrivilege(Subscription.SLVLevel.As()); + SpecialImageLibrary special_ImageLibrary = ConfigSystem.GetSpecialImageConfig()[DataMgr.LevelUnlockSpecial.Value]; + TextureHelper.SetImgLoader(ui.item_2.com_pic.picture, special_ImageLibrary.Name, (s) => + { + if (special_ImageLibrary.State == 1 && !have_special) TextureHelper.SetImageBlur(ui.item_2.com_pic.picture); + }, "LevelAlbums/", FolderNames.AlbumName); + if (have_special) + { + ui.item_2.btn_unlock.visible = false; + ui.item_2.type.selectedIndex = 0; + ui.item_2.btn_skip.SetClick(() => + { + SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); + }); + } + else + { + ui.item_2.type.selectedIndex = 2; + ui.item_2.btn_unlock.visible = true; + ui.item_2.btn_skip.SetClick(() => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); + }); + + if (special_ImageLibrary.GoldCoins > 0) + { + ui.item_2.btn_unlock.pay_type.selectedIndex = 1; + ui.item_2.btn_unlock.title = special_ImageLibrary.GoldCoins.ToString(); + ui.item_2.btn_unlock.SetClick(() => + { + if (DataMgr.Coin.Value >= special_ImageLibrary.GoldCoins) + { + GameHelper.AddGold(-special_ImageLibrary.GoldCoins); + SelectLevel(2, DataMgr.LevelUnlockSpecial.Value); + TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.unlock_svip); + Debug.Log("///////金币解锁"); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + + } + }); + } + else + { + ui.item_2.btn_unlock.visible = false; + } + } + + bool have_vip = GameHelper.GetVipPrivilege(Subscription.VipLevel.As()); + VIPImageLibrary vip_ImageLibrary = ConfigSystem.GetVIPImageConfig()[DataMgr.LevelUnlockVIP.Value]; + + TextureHelper.SetImgLoader(ui.item_3.com_pic.picture, vip_ImageLibrary.Name, (s) => + { + if (vip_ImageLibrary.State == 1 && !have_vip) TextureHelper.SetImageBlur(ui.item_3.com_pic.picture); + }, "LevelAlbums/", FolderNames.AlbumName); + if (have_vip) + { + ui.item_3.btn_unlock.visible = false; + ui.item_3.type.selectedIndex = 0; + ui.item_3.btn_skip.SetClick(() => + { + SelectLevel(3, DataMgr.LevelUnlockVIP.Value); + }); + } + else + { + ui.item_3.type.selectedIndex = 3; + ui.item_3.btn_unlock.visible = true; + ui.item_3.btn_skip.SetClick(() => + { + uiCtrlDispatcher.Dispatch(UICtrlMsg.VipClubViewUI_Open); + }); + + if (vip_ImageLibrary.GoldCoins > 0) + { + ui.item_3.btn_unlock.pay_type.selectedIndex = 1; + ui.item_3.btn_unlock.title = vip_ImageLibrary.GoldCoins.ToString(); + ui.item_3.btn_unlock.SetClick(() => + { + if (DataMgr.Coin.Value >= vip_ImageLibrary.GoldCoins) + { + GameHelper.AddGold(-vip_ImageLibrary.GoldCoins); + SelectLevel(3, DataMgr.LevelUnlockVIP.Value); + Debug.Log("///////金币解锁"); + TrackKit.SendEvent(ADEventTrack.Coinsbuy, ADEventTrack.Property.unlock_vip); + } + else + { + GameHelper.ShowTips("no_enough_gold", true); + + uiCtrlDispatcher.Dispatch(UICtrlMsg.BuygoldUI_Open); + + } + }); + } + else + { + ui.item_3.btn_unlock.visible = false; + } + } + + + } + + public void SelectLevel(int type_, int id) + { + + DataMgr.LevelUnlockListNew.Value.Add(new Levelunlock() + { + level_ = GameHelper.GetLevel(), + type = type_, + config_index = id + }); + DataMgr.LevelUnlockListNew.Save(); + DataMgr.LevelUnlockFree.Value = -1; + DataMgr.LevelUnlockAD.Value = -1; + DataMgr.LevelUnlockSpecial.Value = -1; + DataMgr.LevelUnlockVIP.Value = -1; + + PlayerPrefs.SetInt("Free_Alubum_0", -1); + PlayerPrefs.SetInt("Free_Alubum_1", -1); + PlayerPrefs.SetInt("AD_Alubum", -1); + PlayerPrefs.SetInt("Spec_Alubum", -1); + PlayerPrefs.SetInt("Vip_Alubum", -1); + + PlayerPrefs.SetInt("unlock_refresh", 1); + GameDispatcher.Instance.Dispatch(GameMsg.UnlockLevelsuccess); + CtrlCloseUI(); + PreDownloadManager.StartDownloadAlbumsPicture(); + + if (isHallEnter) + { + GameHelper.gameType = 0; + GameDispatcher.Instance.Dispatch(GameMsg.OpenGame, false); + } else + { + UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.OpenGameUI_Open, true); + } + + } + } + public class Levelunlock + { + public int level_; + public int type; + public int config_index; + } +} diff --git a/Assets/Scripts/System/Network/ConfigSystem.cs b/Assets/Scripts/System/Network/ConfigSystem.cs index 6f86c8e1..522a2e78 100644 --- a/Assets/Scripts/System/Network/ConfigSystem.cs +++ b/Assets/Scripts/System/Network/ConfigSystem.cs @@ -59,8 +59,8 @@ namespace RedHotRoast { TrackKit.TrackLoginFunnel(LoginFunnelEventType.LoadFinish); //加载完成打点 - TextureHelper.imgUrl = CdnURL + "/" + ConfigSystem.GetCommonConf().ResVersion + "/"; - LiveVideoManager.videoBaseUrl = CdnURL + "/" + ConfigSystem.GetCommonConf().ResVersion + "/"; + TextureHelper.imgUrl = CdnURL + "/" + (IsOrganic() ? GetCommonConf().ResVersion : GetCommonConf().ResVersion1) + "/"; + LiveVideoManager.videoBaseUrl = CdnURL + "/" + (IsOrganic() ? GetCommonConf().ResVersion : GetCommonConf().ResVersion1) + "/"; // ParseGameConfig(); UICtrlDispatcher.Instance.Dispatch(UICtrlMsg.NetLoadingUI_Close); @@ -116,6 +116,66 @@ namespace RedHotRoast { return ConfigLoader.Instance.GetConfig>() ?? new List(); } + private static bool IsOrganic() + { + bool b = false; + + if (GameHelper.IsGiftSwitch() && SuperApplication.Instance.attribution == "organic") + { + b = GetCommonConf().IsOrganic == 1; + } + return b; + } + + private static List GetConfigWithOrganicFallback() where T : class + { + if (IsOrganic()) + { + var organicConfig = ConfigLoader.Instance.GetConfig>(); + if (organicConfig != null) + { + var json = Newtonsoft.Json.JsonConvert.SerializeObject(organicConfig); + return Newtonsoft.Json.JsonConvert.DeserializeObject>(json); + } + } + + return GetConfig(); + } + + public static List GetLiveConfig() + { + return GetConfigWithOrganicFallback(); + } + + public static List GetSecretAlbumsConfig() + { + return GetConfigWithOrganicFallback(); + } + public static List GetFreeImageConfig() + { + return GetConfigWithOrganicFallback(); + } + public static List GetADImageConfig() + { + return GetConfigWithOrganicFallback(); + } + + public static List GetSpecialImageConfig() + { + return GetConfigWithOrganicFallback(); + } + + public static List GetVIPImageConfig() + { + return GetConfigWithOrganicFallback(); + } + + public static List GetLevelUnlockConfig() + { + return GetConfigWithOrganicFallback(); + } + + public override void Dispose() { base.Dispose(); RemoveListener(); diff --git a/Assets/Scripts/ToolKit/PreDownloadManager.cs b/Assets/Scripts/ToolKit/PreDownloadManager.cs index b53e3265..de90aded 100644 --- a/Assets/Scripts/ToolKit/PreDownloadManager.cs +++ b/Assets/Scripts/ToolKit/PreDownloadManager.cs @@ -1,382 +1,382 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using Newtonsoft.Json; -using UnityEngine; - -namespace RedHotRoast -{ - public static class PreDownloadManager - { - #region Live - - public static void InitializeLiveData() - { - var liveConfigList = ConfigSystem.GetConfig(); - - Debug.Log($"[预下载视频 数据初始化]-0-----{DataMgr.LiveDataDic.Value.Count}"); - - var newData = new Dictionary(); - - for (var i = 0; i < liveConfigList.Count; i++) - { - var oldData = GetLiveDataByIndex(liveConfigList[i], i); - - if (oldData.progress > 0) newData[i] = oldData; - } - - Debug.Log($"[预下载视频 数据初始化]--1----- {newData.Count}"); - DataMgr.LiveDataDic.Value = newData; - } - - public static LiveData GetLiveDataByIndex(Live liveConfig, int i) - { - DataMgr.LiveDataDic.Value.TryGetValue(i, out var oldData); - - oldData ??= new LiveData - { - progress = liveConfig.Progress, - AD_num = 0, - Singleprogress = (100 - liveConfig.Progress) / liveConfig.AD - }; - - if (oldData.progress < liveConfig.Progress) oldData.progress = liveConfig.Progress; - - return oldData; - } - - // 最大同时下载数量 - private const int MaxConcurrentDownloads = 1; - - public static void StartDownload() - { - CrazyAsyKit.StartCoroutine(DownloadVideosCoroutine()); - } - - private static IEnumerator DownloadVideosCoroutine() - { - var liveConfigList = ConfigSystem.GetConfig(); - var liveDic = DataMgr.LiveDataDic.Value; - - var downloadNameList = new List(); - - // 先加入已有进度的视频 - foreach (var kvp in liveDic) - { - var index = kvp.Key; - var data = kvp.Value; - - if (data.progress > 0 && index < liveConfigList.Count) downloadNameList.Add(liveConfigList[index].Name); - } - - Debug.Log($"[init down video]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - // 添加不在downloadNameList中的项,最多添加6个 - var addedCount = 0; - for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++) - if (!downloadNameList.Contains(liveConfigList[i].Name)) - { - downloadNameList.Add(liveConfigList[i].Name); - addedCount++; - } - - Debug.Log($"[init down video]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - // 当前正在下载的协程数量 - var runningCount = 0; - var currentIndex = 0; - - if (downloadNameList.Count > 0) - { - var name = downloadNameList[currentIndex]; - - var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.VideoName, name + ".enc"); - Debug.Log($"[预下载 视频 路径]-------localPath===={localPath}"); - - if (!File.Exists(localPath)) - { - Debug.Log("[开始预下载 视频 ]---------------"); - runningCount++; - CrazyAsyKit.StartCoroutine(DownloadSingleVideoCoroutine(name, () => { runningCount--; })); - } - } - - // 等待下一帧再检查 - yield return null; - Debug.Log("[init down video]---All downloads finished---"); - } - - - private static IEnumerator DownloadSingleVideoCoroutine(string name, Action onComplete) - { - var isDone = false; - - LiveVideoManager.Instance.GetVideoLocalPath(name, tex => - { - Debug.Log($"[init down video]----------------{name}"); - isDone = true; - }, false); - - // 等待下载完成 - while (!isDone) yield return null; - - onComplete?.Invoke(); - } - - #endregion - - - #region Picture - - public static void StartDownloadSecretPicture() - { - var liveConfigList = ConfigSystem.GetConfig(); - var liveList = DataMgr.SecretUnlockList.Value; - - var downloadNameList = new List(); - - // 先加入所有可用的图片 - for (var i = 0; i < liveList.Count; i++) - if (liveConfigList[i] != null && !downloadNameList.Contains(liveConfigList[i].Name)) - downloadNameList.Add(liveConfigList[i].Name); - - Debug.Log( - $"[init down picture Secret]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - // 添加不在downloadNameList中的项,最多添加6个 - var addedCount = 0; - for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++) - if (!downloadNameList.Contains(liveConfigList[i].Name)) - { - downloadNameList.Add(liveConfigList[i].Name); - addedCount++; - } - - Debug.Log( - $"[init down picture Secret]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - foreach (var name in downloadNameList) - { - var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.SecretName, name + ".jpg"); - Debug.Log($"[预下载 Secret 路径]-------localPath===={localPath}"); - if (!File.Exists(localPath)) - { - Debug.Log("[开始预下载 Secret ]---------------"); - TextureHelper.SetImgLoader(null, name, - s => - { - Debug.Log($"[init down Secret picture]----------------{name}"); - }, "SecretAlbums/", FolderNames.SecretName, false); - } - } - } - - public static void StartDownloadAlbumsPicture() - { - int Free_Alubum_0 = PlayerPrefs.GetInt("Free_Alubum_0", -1); - int Free_Alubum_1 = PlayerPrefs.GetInt("Free_Alubum_1", -1); - int AD_Alubum = PlayerPrefs.GetInt("AD_Alubum", -1); - int Spec_Alubum = PlayerPrefs.GetInt("Spec_Alubum", -1); - int Vip_Alubum = PlayerPrefs.GetInt("Vip_Alubum", -1); - - if (Free_Alubum_0 >= 0) return; - - var FreeImageLibrary_ = ConfigSystem.GetConfig(); - var ADImageLibrary_ = ConfigSystem.GetConfig(); - var SpecialImageLibrary_ = ConfigSystem.GetConfig(); - var VIPImageLibrary_ = ConfigSystem.GetConfig(); - - List free_level_list = new List(); - List ad_level_list = new List(); - List special_level_list = new List(); - List vip_level_list = new List(); - for (int i = 0; i < DataMgr.LevelUnlockListNew.Value.Count; i++) - { - if (DataMgr.LevelUnlockListNew.Value[i].type == 0) free_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - else if (DataMgr.LevelUnlockListNew.Value[i].type == 1) ad_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - else if (DataMgr.LevelUnlockListNew.Value[i].type == 2) special_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - else if (DataMgr.LevelUnlockListNew.Value[i].type == 3) vip_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); - } - - - if (Free_Alubum_0 < 0) - { - HashSet levelIds = new HashSet(free_level_list); - List filtered = ConfigSystem.GetConfig().Where(x => !levelIds.Contains(x.id)).ToList(); - if (filtered.Count > 0) - { - Free_Alubum_0 = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; - } - else - { - Free_Alubum_0 = ConfigSystem.GetConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig().Count)].id; - } - free_level_list.Add(Free_Alubum_0); - Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); - } - if (Free_Alubum_1 < 0) - { - HashSet levelIds = new HashSet(free_level_list); - List filtered = ConfigSystem.GetConfig().Where(x => !levelIds.Contains(x.id)).ToList(); - if (filtered.Count > 0) - { - Free_Alubum_1 = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; - } - else - { - Free_Alubum_1 = ConfigSystem.GetConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig().Count)].id; - } - Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); - } - - - if (AD_Alubum < 0) - { - HashSet levelIds = new HashSet(ad_level_list); - List filtered = ConfigSystem.GetConfig().Where(x => !levelIds.Contains(x.id)).ToList(); - if (filtered.Count > 0) - { - AD_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; - } - else - { - AD_Alubum = ConfigSystem.GetConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig().Count)].id; - } - Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); - } - - if (Spec_Alubum < 0) - { - HashSet levelIds = new HashSet(special_level_list); - List filtered = ConfigSystem.GetConfig().Where(x => !levelIds.Contains(x.id)).ToList(); - if (filtered.Count > 0) - { - Spec_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; - } - else - { - Spec_Alubum = ConfigSystem.GetConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig().Count)].id; - } - Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); - } - - if (Vip_Alubum < 0) - { - HashSet levelIds = new HashSet(vip_level_list); - List filtered = ConfigSystem.GetConfig().Where(x => !levelIds.Contains(x.id)).ToList(); - if (filtered.Count > 0) - { - Vip_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; - } - else - { - Vip_Alubum = ConfigSystem.GetConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetConfig().Count)].id; - } - Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); - } - PlayerPrefs.SetInt("Free_Alubum_0", Free_Alubum_0); - PlayerPrefs.SetInt("Free_Alubum_1", Free_Alubum_1); - PlayerPrefs.SetInt("AD_Alubum", AD_Alubum); - PlayerPrefs.SetInt("Spec_Alubum", Spec_Alubum); - PlayerPrefs.SetInt("Vip_Alubum", Vip_Alubum); - - var downloadNameList = new List - { - FreeImageLibrary_[Free_Alubum_0].Name, - FreeImageLibrary_[Free_Alubum_1].Name, - ADImageLibrary_[AD_Alubum].Name, - SpecialImageLibrary_[Spec_Alubum].Name, - VIPImageLibrary_[Vip_Alubum].Name - }; - - Debug.Log( - $"[init down picture Album]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - // 添加不在downloadNameList中的项,最多添加12个 - // var addedCount = 0; - // for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++) - // if (!downloadNameList.Contains(liveConfigList[i].Name)) - // { - // downloadNameList.Add(liveConfigList[i].Name); - // addedCount++; - // } - - Debug.Log( - $"[init down picture Album]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - // int centerIndex = GameHelper.GetLevel(); - // int totalCount = downloadNameList.Count; - - // // 计算起始索引和实际要取的数量 - // int rangeStart = Math.Max(0, centerIndex - 5); - // int rangeEnd = Math.Min(totalCount, centerIndex + 5); - // int rangeCount = rangeEnd - rangeStart; - - // // 获取范围内元素并反转 - // var segment = downloadNameList.GetRange(rangeStart, rangeCount); - // segment.Reverse(); - - // // 移除原始位置的元素 - // downloadNameList.RemoveRange(rangeStart, rangeCount); - - // // 插入反转后的元素到最前面 - // downloadNameList.InsertRange(0, segment); - - - Debug.Log( - $"[init down picture Album]---3---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - foreach (var name in downloadNameList) - { - var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.AlbumName, name + ".jpg"); - Debug.Log($"[预下载 Albums 路径]-------localPath===={localPath}"); - if (!File.Exists(localPath)) - { - Debug.Log($"[开始预下载 Albums ]--------------name-{name}"); - TextureHelper.SetImgLoader(null, name, - s => - { - Debug.Log($"[init down Album picture]----------------{name}"); - }, "LevelAlbums/", FolderNames.AlbumName, false); - } - } - } - - public static void StartDownloadLivePicture() - { - var liveConfigList = ConfigSystem.GetConfig(); - var liveList = DataMgr.SecretUnlockList.Value; - - var downloadNameList = new List(); - - // 先加入所有可用的图片 - for (var i = 0; i < liveConfigList.Count; i++) - if (liveConfigList[i] != null && !downloadNameList.Contains(liveConfigList[i].Name)) - downloadNameList.Add(liveConfigList[i].Name); - - Debug.Log( - $"[init down picture LiveCover]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); - - // 添加不在downloadNameList中的项,最多添加6个 - - foreach (var name in downloadNameList) - { - var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.VideoCoversName, name + "_cover" + ".jpg"); - Debug.Log($"[预下载 Secret 路径]-------localPath===={localPath}"); - if (!File.Exists(localPath)) - { - Debug.Log("[开始预下载 Secret ]---------------"); - TextureHelper.SetImgLoader(null, name + "_cover", - s => - { - Debug.Log($"[init down VideoCovers picture]----------------{name}"); - }, "LiveAlbums/", FolderNames.VideoCoversName, false); - } - } - } - - #endregion - } +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using Newtonsoft.Json; +using UnityEngine; + +namespace RedHotRoast +{ + public static class PreDownloadManager + { + #region Live + + public static void InitializeLiveData() + { + var liveConfigList = ConfigSystem.GetLiveConfig(); + + Debug.Log($"[预下载视频 数据初始化]-0-----{DataMgr.LiveDataDic.Value.Count}"); + + var newData = new Dictionary(); + + for (var i = 0; i < liveConfigList.Count; i++) + { + var oldData = GetLiveDataByIndex(liveConfigList[i], i); + + if (oldData.progress > 0) newData[i] = oldData; + } + + Debug.Log($"[预下载视频 数据初始化]--1----- {newData.Count}"); + DataMgr.LiveDataDic.Value = newData; + } + + public static LiveData GetLiveDataByIndex(Live liveConfig, int i) + { + DataMgr.LiveDataDic.Value.TryGetValue(i, out var oldData); + + oldData ??= new LiveData + { + progress = liveConfig.Progress, + AD_num = 0, + Singleprogress = (100 - liveConfig.Progress) / liveConfig.AD + }; + + if (oldData.progress < liveConfig.Progress) oldData.progress = liveConfig.Progress; + + return oldData; + } + + // 最大同时下载数量 + private const int MaxConcurrentDownloads = 1; + + public static void StartDownload() + { + CrazyAsyKit.StartCoroutine(DownloadVideosCoroutine()); + } + + private static IEnumerator DownloadVideosCoroutine() + { + var liveConfigList = ConfigSystem.GetLiveConfig(); + var liveDic = DataMgr.LiveDataDic.Value; + + var downloadNameList = new List(); + + // 先加入已有进度的视频 + foreach (var kvp in liveDic) + { + var index = kvp.Key; + var data = kvp.Value; + + if (data.progress > 0 && index < liveConfigList.Count) downloadNameList.Add(liveConfigList[index].Name); + } + + Debug.Log($"[init down video]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + // 添加不在downloadNameList中的项,最多添加6个 + var addedCount = 0; + for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++) + if (!downloadNameList.Contains(liveConfigList[i].Name)) + { + downloadNameList.Add(liveConfigList[i].Name); + addedCount++; + } + + Debug.Log($"[init down video]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + // 当前正在下载的协程数量 + var runningCount = 0; + var currentIndex = 0; + + if (downloadNameList.Count > 0) + { + var name = downloadNameList[currentIndex]; + + var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.VideoName, name + ".enc"); + Debug.Log($"[预下载 视频 路径]-------localPath===={localPath}"); + + if (!File.Exists(localPath)) + { + Debug.Log("[开始预下载 视频 ]---------------"); + runningCount++; + CrazyAsyKit.StartCoroutine(DownloadSingleVideoCoroutine(name, () => { runningCount--; })); + } + } + + // 等待下一帧再检查 + yield return null; + Debug.Log("[init down video]---All downloads finished---"); + } + + + private static IEnumerator DownloadSingleVideoCoroutine(string name, Action onComplete) + { + var isDone = false; + + LiveVideoManager.Instance.GetVideoLocalPath(name, tex => + { + Debug.Log($"[init down video]----------------{name}"); + isDone = true; + }, false); + + // 等待下载完成 + while (!isDone) yield return null; + + onComplete?.Invoke(); + } + + #endregion + + + #region Picture + + public static void StartDownloadSecretPicture() + { + var liveConfigList = ConfigSystem.GetSecretAlbumsConfig(); + var liveList = DataMgr.SecretUnlockList.Value; + + var downloadNameList = new List(); + + // 先加入所有可用的图片 + for (var i = 0; i < liveList.Count; i++) + if (liveConfigList[i] != null && !downloadNameList.Contains(liveConfigList[i].Name)) + downloadNameList.Add(liveConfigList[i].Name); + + Debug.Log( + $"[init down picture Secret]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + // 添加不在downloadNameList中的项,最多添加6个 + var addedCount = 0; + for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++) + if (!downloadNameList.Contains(liveConfigList[i].Name)) + { + downloadNameList.Add(liveConfigList[i].Name); + addedCount++; + } + + Debug.Log( + $"[init down picture Secret]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + foreach (var name in downloadNameList) + { + var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.SecretName, name + ".jpg"); + Debug.Log($"[预下载 Secret 路径]-------localPath===={localPath}"); + if (!File.Exists(localPath)) + { + Debug.Log("[开始预下载 Secret ]---------------"); + TextureHelper.SetImgLoader(null, name, + s => + { + Debug.Log($"[init down Secret picture]----------------{name}"); + }, "SecretAlbums/", FolderNames.SecretName, false); + } + } + } + + public static void StartDownloadAlbumsPicture() + { + int Free_Alubum_0 = PlayerPrefs.GetInt("Free_Alubum_0", -1); + int Free_Alubum_1 = PlayerPrefs.GetInt("Free_Alubum_1", -1); + int AD_Alubum = PlayerPrefs.GetInt("AD_Alubum", -1); + int Spec_Alubum = PlayerPrefs.GetInt("Spec_Alubum", -1); + int Vip_Alubum = PlayerPrefs.GetInt("Vip_Alubum", -1); + + if (Free_Alubum_0 >= 0) return; + + var FreeImageLibrary_ = ConfigSystem.GetFreeImageConfig(); + var ADImageLibrary_ = ConfigSystem.GetADImageConfig(); + var SpecialImageLibrary_ = ConfigSystem.GetSpecialImageConfig(); + var VIPImageLibrary_ = ConfigSystem.GetVIPImageConfig(); + + List free_level_list = new List(); + List ad_level_list = new List(); + List special_level_list = new List(); + List vip_level_list = new List(); + for (int i = 0; i < DataMgr.LevelUnlockListNew.Value.Count; i++) + { + if (DataMgr.LevelUnlockListNew.Value[i].type == 0) free_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + else if (DataMgr.LevelUnlockListNew.Value[i].type == 1) ad_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + else if (DataMgr.LevelUnlockListNew.Value[i].type == 2) special_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + else if (DataMgr.LevelUnlockListNew.Value[i].type == 3) vip_level_list.Add(DataMgr.LevelUnlockListNew.Value[i].config_index); + } + + + if (Free_Alubum_0 < 0) + { + HashSet levelIds = new HashSet(free_level_list); + List filtered = ConfigSystem.GetFreeImageConfig().Where(x => !levelIds.Contains(x.id)).ToList(); + if (filtered.Count > 0) + { + Free_Alubum_0 = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; + } + else + { + Free_Alubum_0 = ConfigSystem.GetFreeImageConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetFreeImageConfig().Count)].id; + } + free_level_list.Add(Free_Alubum_0); + Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); + } + if (Free_Alubum_1 < 0) + { + HashSet levelIds = new HashSet(free_level_list); + List filtered = ConfigSystem.GetFreeImageConfig().Where(x => !levelIds.Contains(x.id)).ToList(); + if (filtered.Count > 0) + { + Free_Alubum_1 = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; + } + else + { + Free_Alubum_1 = ConfigSystem.GetFreeImageConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetFreeImageConfig().Count)].id; + } + Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); + } + + + if (AD_Alubum < 0) + { + HashSet levelIds = new HashSet(ad_level_list); + List filtered = ConfigSystem.GetADImageConfig().Where(x => !levelIds.Contains(x.id)).ToList(); + if (filtered.Count > 0) + { + AD_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; + } + else + { + AD_Alubum = ConfigSystem.GetADImageConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetADImageConfig().Count)].id; + } + Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); + } + + if (Spec_Alubum < 0) + { + HashSet levelIds = new HashSet(special_level_list); + List filtered = ConfigSystem.GetSpecialImageConfig().Where(x => !levelIds.Contains(x.id)).ToList(); + if (filtered.Count > 0) + { + Spec_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; + } + else + { + Spec_Alubum = ConfigSystem.GetSpecialImageConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetSpecialImageConfig().Count)].id; + } + Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); + } + + if (Vip_Alubum < 0) + { + HashSet levelIds = new HashSet(vip_level_list); + List filtered = ConfigSystem.GetVIPImageConfig().Where(x => !levelIds.Contains(x.id)).ToList(); + if (filtered.Count > 0) + { + Vip_Alubum = filtered[UnityEngine.Random.Range(0, filtered.Count)].id; + } + else + { + Vip_Alubum = ConfigSystem.GetVIPImageConfig()[UnityEngine.Random.Range(0, ConfigSystem.GetVIPImageConfig().Count)].id; + } + Debug.Log(JsonConvert.SerializeObject(filtered) + ",,,,,,,,,,,,,,,,,,,,"); + } + PlayerPrefs.SetInt("Free_Alubum_0", Free_Alubum_0); + PlayerPrefs.SetInt("Free_Alubum_1", Free_Alubum_1); + PlayerPrefs.SetInt("AD_Alubum", AD_Alubum); + PlayerPrefs.SetInt("Spec_Alubum", Spec_Alubum); + PlayerPrefs.SetInt("Vip_Alubum", Vip_Alubum); + + var downloadNameList = new List + { + FreeImageLibrary_[Free_Alubum_0].Name, + FreeImageLibrary_[Free_Alubum_1].Name, + ADImageLibrary_[AD_Alubum].Name, + SpecialImageLibrary_[Spec_Alubum].Name, + VIPImageLibrary_[Vip_Alubum].Name + }; + + Debug.Log( + $"[init down picture Album]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + // 添加不在downloadNameList中的项,最多添加12个 + // var addedCount = 0; + // for (var i = 0; i < liveConfigList.Count && addedCount < 6; i++) + // if (!downloadNameList.Contains(liveConfigList[i].Name)) + // { + // downloadNameList.Add(liveConfigList[i].Name); + // addedCount++; + // } + + Debug.Log( + $"[init down picture Album]---2---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + // int centerIndex = GameHelper.GetLevel(); + // int totalCount = downloadNameList.Count; + + // // 计算起始索引和实际要取的数量 + // int rangeStart = Math.Max(0, centerIndex - 5); + // int rangeEnd = Math.Min(totalCount, centerIndex + 5); + // int rangeCount = rangeEnd - rangeStart; + + // // 获取范围内元素并反转 + // var segment = downloadNameList.GetRange(rangeStart, rangeCount); + // segment.Reverse(); + + // // 移除原始位置的元素 + // downloadNameList.RemoveRange(rangeStart, rangeCount); + + // // 插入反转后的元素到最前面 + // downloadNameList.InsertRange(0, segment); + + + Debug.Log( + $"[init down picture Album]---3---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + foreach (var name in downloadNameList) + { + var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.AlbumName, name + ".jpg"); + Debug.Log($"[预下载 Albums 路径]-------localPath===={localPath}"); + if (!File.Exists(localPath)) + { + Debug.Log($"[开始预下载 Albums ]--------------name-{name}"); + TextureHelper.SetImgLoader(null, name, + s => + { + Debug.Log($"[init down Album picture]----------------{name}"); + }, "LevelAlbums/", FolderNames.AlbumName, false); + } + } + } + + public static void StartDownloadLivePicture() + { + var liveConfigList = ConfigSystem.GetLiveConfig(); + var liveList = DataMgr.SecretUnlockList.Value; + + var downloadNameList = new List(); + + // 先加入所有可用的图片 + for (var i = 0; i < liveConfigList.Count; i++) + if (liveConfigList[i] != null && !downloadNameList.Contains(liveConfigList[i].Name)) + downloadNameList.Add(liveConfigList[i].Name); + + Debug.Log( + $"[init down picture LiveCover]---1---nameList----------{JsonConvert.SerializeObject(downloadNameList)}"); + + // 添加不在downloadNameList中的项,最多添加6个 + + foreach (var name in downloadNameList) + { + var localPath = Path.Combine(TextureHelper.getResPath(), FolderNames.VideoCoversName, name + "_cover" + ".jpg"); + Debug.Log($"[预下载 Secret 路径]-------localPath===={localPath}"); + if (!File.Exists(localPath)) + { + Debug.Log("[开始预下载 Secret ]---------------"); + TextureHelper.SetImgLoader(null, name + "_cover", + s => + { + Debug.Log($"[init down VideoCovers picture]----------------{name}"); + }, "LiveAlbums/", FolderNames.VideoCoversName, false); + } + } + } + + #endregion + } } \ No newline at end of file