ResourceMgr

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System;
using System.Net;
using UnityEngine;
using UnityEngine.UI;
using System.Text;
using System.Threading;
using System.Security.Cryptography;
using Application = UnityEngine.Application;

public class ResourceMgr
{
public const string NEEDDOWNLOADTITLE = “需要下载的资源:{0}/{1}”;
private const string HDMD5_NAME = “HDmd5.txt”;
private const string IMG_FILE_SUFFIX1 = “.png”;
private const string IMG_FILE_SUFFIX2 = “.jpg”;
private const string MODEL_FILE_SUFFIX1 = “.unity3d”;
private const string VEDIO_FILE_SUFFIX1 = “.mp4”;
private const string VEDIO_FILE_SUFFIX2 = “.avi”;

private const string IMGDIRECTORYNAME = "/Images/";
public const string MODELDIRECTORYNAME = "/Models/";
private const string VEDIOSDIRECTORYNAME = "/Video/";

private string streamingPath = "";
private static ResourceMgr _instance;

public static ResourceMgr instance
{
    get
    {
        if (_instance == null)
        {
            _instance = new ResourceMgr();
            _instance.streamingPath = Application.streamingAssetsPath;
        }
        return _instance;
    }
}

//加载本地资源线程
private Thread loadImgThread = null;

/// <summary>
/// 处理多线程的sleep
/// </summary>
private AutoResetEvent loadImgThreadEvent = new AutoResetEvent(false);
private int errorCount = 0;
struct LoadImgData
{
    public string fileName;
    public Action<byte[]> action;

    public LoadImgData(string _fileName, Action<byte[]> _action)
    {
        fileName = _fileName;
        action = _action;
    }
}

private List<LoadImgData> needLoadImgs = new List<LoadImgData>();

public void StopAllThread()
{
    if (loadImgThread != null)
    {
        loadImgThread.Abort();
        loadImgThread = null;
    }
    if (loadImgThreadEvent != null)
    {
        loadImgThreadEvent.Close();
        loadImgThreadEvent = null;
    }
}

private string GetAllPath(string fileName)
{
    string path = "";
    if (fileName.EndsWith(IMG_FILE_SUFFIX1) || fileName.EndsWith(IMG_FILE_SUFFIX2))
    {
        path = streamingPath + IMGDIRECTORYNAME + fileName;
    }
    else if (fileName.EndsWith(VEDIO_FILE_SUFFIX1) || fileName.EndsWith(VEDIO_FILE_SUFFIX2))
    {
        path = streamingPath + VEDIOSDIRECTORYNAME + fileName;
    }
    else
    {
        path = streamingPath + MODELDIRECTORYNAME + fileName;
    }
    return path;
}

/// <summary>
/// 加载图片
/// </summary>
/// <param name="fileName"></param>
/// <param name="action"></param>
public void LoadImageResource(string fileName, Action<Texture2D> action, MonoBehaviour mono)
{
    string path = streamingPath + IMGDIRECTORYNAME + fileName;
    string fullPath = path + ".png";
    if (!File.Exists(fullPath))
    {
        fullPath = path + ".jpg";
    }
    if (File.Exists(fullPath))
    {
        mono.StartCoroutine(LoadWWWTexture("file://" + fullPath, action));
        //ReadFile(fullPath, action);
    }
    else
    {
        LogError("1", fileName + " 资源不存在");
        if (action != null)
            action(null);
    }
}

public void LoadImageData1(string fileName, Action<byte[]> action)
{
    if (loadImgThread == null)
    {
        loadImgThread = new Thread(LoadImg);
        loadImgThread.IsBackground = true;
        loadImgThread.Start();
    }
    //bool needSet = true;
    if (needLoadImgs.Count > 0)
    {
        SetLoadImgThreadEvent(true);
    }
    needLoadImgs.Add(new LoadImgData(fileName, action));
}

void LoadImg()
{
    while (true)
    {
        //loadImgThreadEvent.WaitOne();
        lock (needLoadImgs)
        {
            if (needLoadImgs.Count > 0)
            {
                LoadImageData(needLoadImgs[0].fileName, needLoadImgs[0].action);
                needLoadImgs.RemoveAt(0);
                //SetLoadImgThreadEvent(false);
            }
            else
            {
                SetLoadImgThreadEvent(false);
            }
        }
    }
}

void SetLoadImgThreadEvent(bool needCheckState)
{
    if (needCheckState)
    {
        ThreadState state = (ThreadState)((int)loadImgThread.ThreadState - (int)ThreadState.Background);
        if (state != ThreadState.WaitSleepJoin)
        {
            return;
        }
    }
    if (loadImgThreadEvent != null)
        loadImgThreadEvent.Set();
}

public void LoadImageData(string fileName, Action<Texture2D> action)
{
    string path = streamingPath + IMGDIRECTORYNAME + fileName;
    string fullPath = path;
    if (!File.Exists(fullPath))
    {
        fullPath = path + ".jpg";
        if (!File.Exists(fullPath))
        {
            fullPath = path + ".png";
        }
    }
    if (File.Exists(fullPath))
    {
        byte[] data = File.ReadAllBytes(fullPath);
        if (data != null && action != null)
        {
            // data = DecryptFile(data);
            Texture2D texture = new Texture2D(1024, 1024);
            texture.LoadImage(data);
            action(texture);
        }
        else
        {
            LogError("2", path + " 资源损坏 ");
            if (action != null)
                action(null);
        }
    }
    else
    {
        LogError("1", fileName + " 资源不存在");
        if (action != null)
            action(null);
    }
}

public void LoadImageData(string fileName, Action<byte[]> action, bool isBackground = true)
{
    string path = streamingPath + IMGDIRECTORYNAME + fileName;
    string fullPath = path;
    if (!File.Exists(fullPath))
    {
        fullPath = path + ".jpg";
        if (!File.Exists(fullPath))
        {
            fullPath = path + ".png";
        }
    }
    if (File.Exists(fullPath))
    {
        ReadFile(fullPath, action);
    }
    else
    {
        LogError("1", fileName + " 资源不存在");
        if (action != null)
            action(null);
    }
    if (isBackground)
        SetLoadImgThreadEvent(true);
}

void ReadFile(string path, Action<byte[]> action)
{
    try
    {
        //using (FileStream fs = File.Open(path))
        byte[] data = File.ReadAllBytes(path);
        if (data != null && action != null)
        {
            //data = DecryptFile(data);
            //Texture2D texture = new Texture2D(1024, 1024);
            //texture.LoadImage(data);
            action(data);
        }
        else
        {
            LogError("2", path + " 资源损坏 ");
            if (action != null)
                action(null);
        }
    }
    catch (Exception ex)
    {
        LogError("2", path + " 资源损坏 " + ex.ToString());
        if (action != null)
            action(null);
    }
}

IEnumerator LoadWWWTexture(string path, Action<Texture2D> action)
{
    WWW www = new WWW(path);
    yield return null;
    while (true)
    {
        if (www.progress >= 0.9f && www.isDone)
        {
            if (www.error == null)
            {
                if (action != null)
                {
                    byte[] data = DecryptFile(www.bytes);
                    Texture2D texture = new Texture2D(1024, 1024);
                    texture.LoadImage(data);
                    action(texture);
                }
            }
            else
            {
                LogError("2", path + " 资源损坏 " + www.error);
                if (action != null)
                    action(null);
            }
        }
        break;
    }
}

/// <summary>
/// 加载模型
/// </summary>
/// <param name="fileName"></param>
/// <param name="action"></param>
public void LoadModelResource(string fileName, Action<UnityEngine.Object> action)
{
    if (AssetBundleLoader.instance != null)
    {
        AssetBundleLoader.instance.LoadAsset(fileName, delegate (string assetName)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                LogError("2", fileName + " 资源损坏 ");
                if (action != null)
                {
                    action(null);
                }
            }
            else
            {
                if (action != null)
                {
                    action(AssetBundleLoader.assets[assetName]);
                }
            }
        });
    }
}

private void LogError(string type, string error)
{
    Debug.Log(error);

#if _TEST
if (Main.HasNetwork)
{
//发送状态检测日志
RQSyslog rq = new RQSyslog(type, error);
errorList.Add(rq);
//HttpService.instance.DoSendData(rq, delegate (RPMessage msg) { });
}
#endif
}

#region
private const string HASHKEY = "BBHD455KSDLJLLSDKJFOSLNV";
private byte[] EncryptFile(byte[] inputByteArray)
{
    //通过des加密
    DESCryptoServiceProvider des = new DESCryptoServiceProvider();

    //获得加密字符串二进制字符
    byte[] keyByteArray = Encoding.Default.GetBytes(HASHKEY);

    //计算指定字节组指定区域哈希值
    SHA1 ha = new SHA1Managed();
    byte[] hb = ha.ComputeHash(keyByteArray);
    //加密密钥数组
    byte[] sKey = new byte[8];
    //加密变量
    byte[] sIV = new byte[8];
    for (int i = 0; i < 8; i++)
        sKey[i] = hb[i];
    for (int i = 8; i < 16; i++)
        sIV[i - 8] = hb[i];

    //获取加密密钥
    des.Key = sKey;
    //设置加密初始化向量
    des.IV = sIV;
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
    cs.Write(inputByteArray, 0, inputByteArray.Length);
    cs.FlushFinalBlock();
    byte[] data = ms.ToArray();
    cs.Close();
    ms.Close();
    return data;
}

private byte[] DecryptFile(byte[] inputByteArray)
{
    try
    {

        //通过des解密
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();

        //密钥数组
        byte[] keyByteArray = Encoding.Default.GetBytes(HASHKEY);
        //定义哈希变量
        SHA1 ha = new SHA1Managed();
        //计算指定字节组指定区域哈希值
        byte[] hb = ha.ComputeHash(keyByteArray);
        //加密密钥数组
        byte[] sKey = new byte[8];
        //加密变量
        byte[] sIV = new byte[8];
        for (int i = 0; i < 8; i++)
            sKey[i] = hb[i];
        for (int i = 8; i < 16; i++)
            sIV[i - 8] = hb[i];
        //获取加密密钥
        des.Key = sKey;
        //加密变量
        des.IV = sIV;
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        byte[] data = ms.ToArray();
        cs.Close();
        ms.Close();
        return data;
    }
    catch (Exception ex)
    {
        Debug.LogError(ex.ToString());
        return inputByteArray;
    }

}
#endregion

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值