void OnAssetBundleLoaded(string url, AssetBundle assetBundle, params object[] args)
    {
        Object asset = null;

        System.DateTime beginTime = System.DateTime.Now;
        if (AssetInBundleName == null)
        {
            // 经过AddWatch调试,.mainAsset这个getter第一次执行时特别久,要做序列化
            try
            {
                asset = assetBundle.mainAsset;
            }
            catch
            {
                CBase.LogError("[OnAssetBundleLoaded:mainAsset]{0}", url);
            }
        }
        else
        {
            AssetBundleRequest request = assetBundle.LoadAsync(AssetInBundleName, typeof(Object));
            asset = request.asset;
        }

        CResourceManager.LogLoadTime("AssetFileBridge", url, beginTime);

        if (asset == null)
        {
            CBase.LogError("Asset is NULL: {0}", url);
        }

        AssetFileLoadedCallback(asset, CallbackArgs);
    }
Exemple #2
0
    public T GetInfo <T>(string id) where T : CBaseInfo
    {
        EnsureLoad <T>();

        Dictionary <string, CBaseInfo> dict;

        if (SettingInfos.TryGetValue(typeof(T), out dict))
        {
            CBaseInfo tabInfo;
            if (dict.TryGetValue(id, out tabInfo))
            {
                return((T)tabInfo);
            }
            else
            {
                CBase.LogError("找不到类型{0} Id为{1}的配置对象, 类型表里共有对象{2}", typeof(T).Name, id, dict.Count);
            }
        }
        else
        {
            CBase.LogError("嘗試Id {0}, 找不到类型配置{1}, 总类型数{2}", id, typeof(T).Name, SettingInfos.Count);
        }

        return(null);
    }
Exemple #3
0
    public object GetControl(Type type, string uri, Transform findTrans = null, bool isLog = true)
    {
        if (findTrans == null)
        {
            findTrans = transform;
        }

        Transform trans = findTrans.Find(uri);

        if (trans == null)
        {
            if (isLog)
            {
                CBase.LogError("Get UI Control Error: " + uri);
            }
            return(null);
        }

        if (type == typeof(GameObject))
        {
            return(trans.gameObject);
        }

        return(trans.GetComponent(type));
    }
    IEnumerator StartDownload(string fullUrl)
    {
        float startTime = Time.time;

        while (!WWWLoader.IsFinished)
        {
            if (WWWLoader.Progress == 0 && Time.time - startTime > TIME_OUT_DEF)
            {
                CBase.LogError("超時卻無下載 Timeout: {0}", fullUrl);
                break;
            }

            yield return(null);
        }
        if (WWWLoader.IsError || !WWWLoader.IsFinished)
        {
            CBase.LogError("Download WWW Error: {0}", fullUrl);
            ForceFinished = true;
            ForceError    = true;
            yield break;
        }

        string dir = Path.GetDirectoryName(_SavePath);

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
        }

        System.IO.File.WriteAllBytes(_SavePath, WWWLoader.Www.bytes);
    }
Exemple #5
0
    private void Awake()
    {
        if (EngineInstance != null)
        {
            CBase.LogError("Duplicated Instance CCosmosEngine!!!");
        }

        EngineInstance = this;

        Init();
    }
Exemple #6
0
    public Action InitAction; // Init時調用的委託、函數指針

    public IEnumerator Init()
    {
        if (this.InitAction == null)
        {
            CBase.LogError("GameSettings沒有定義初始化行為!!!");
        }
        else
        {
            this.InitAction();
        }
        yield break;
    }
Exemple #7
0
    /// <summary>
    /// Get Config from the CEngineConfig file through key
    /// </summary>
    public static string GetConfig(string key)
    {
        EnsureConfigTab();

        string getValue;

        if (!ConfigMap.TryGetValue(key, out getValue))
        {
            CBase.LogError("Cannot get CosmosConfig: {0}", key);
        }
        return(getValue);
    }
Exemple #8
0
    public GameObject FindGameObject(string name)
    {
        GameObject obj = DFSFindObject(transform, name);

        if (obj == null)
        {
            CBase.LogError("Find GemeObject Error: " + name);
            return(null);
        }

        return(obj);
    }
Exemple #9
0
    public T FindControl <T>(string name) where T : Component
    {
        GameObject obj = DFSFindObject(transform, name);

        if (obj == null)
        {
            CBase.LogError("Find UI Control Error: " + name);
            return(null);
        }

        return(obj.GetComponent <T>());
    }
    IEnumerator LoadAssetBundle(string relativeUrl)
    {
        XLoadCache loadCache;

        if (!AssetBundlesCache.TryGetValue(RelativeResourceUrl, out loadCache))
        {
            loadCache = new XLoadCache()
            {
                RelativeUrl = RelativeResourceUrl, Ab = null
            };
            AssetBundlesCache[RelativeResourceUrl] = loadCache;

            CWWWLoader wwwLoader = new CWWWLoader(FullUrl);
            while (!wwwLoader.IsFinished)
            {
                yield return(null);
            }

            // 解密
            CAssetBundleParser parser = new CAssetBundleParser(RelativeResourceUrl, wwwLoader.Www.bytes);
            while (!parser.IsFinished)
            {
                yield return(null);
            }

            if (parser.Bundle == null)
            {
                CBase.LogError("WWW.assetBundle is NULL: {0}", FullUrl);
            }

            loadCache.Ab = parser.Bundle;
        }
        else
        {
            if (loadCache.IsLoadedFinish)
            {
                yield return(null);  // 确保每一次异步都延迟一帧
            }

            while (!loadCache.IsLoadedFinish)
            {
                yield return(null); //Wait
            }
        }

        Bundle = loadCache.Ab;

        if (Callback != null)
        {
            Callback(FullUrl, Bundle, CallbackArgs);
        }
    }
Exemple #11
0
    string LoadSettingInPackage(string path)
    {
        string content;
        bool   result = GameSettings.TryGetValue(path, out content);

        if (!result)
        {
            CBase.LogError("Setting not fount, {0}", path);
            return(null);
        }

        return(content);
    }
Exemple #12
0
    public static bool TryGetInAppResourceUrl(string url, out string newUrl)
    {
        newUrl = ResourcesPath + url;

        // 注意,StreamingAssetsPath在Android平台時,壓縮在apk里面,不要做文件檢查了
        if (Application.platform != RuntimePlatform.Android && !File.Exists(ResourcesPathWithOutFileProtocol + url))
        {
            CBase.LogError("[GetResourcePath:InAppUrl]Not Exist File: {0}", newUrl);
            return(false);
        }

        return(true);
    }
    IEnumerator LoadInResourceFolder(string path)
    {
        yield return(null); // 延遲1幀

        string extension = System.IO.Path.GetExtension(path);

        path = path.Substring(0, path.Length - extension.Length);  // remove extensions

        UnityEngine.Object asset = Resources.Load <UnityEngine.Object>(path);
        if (asset == null)
        {
            CBase.LogError("Asset is NULL(from Resources Folder): {0}", path);
        }
        AssetFileLoadedCallback(asset, CallbackArgs);
    }
Exemple #14
0
    public static Shader FindShader(string shaderName)
    {
        Shader shader;

        if (!CacheShaders.TryGetValue(shaderName, out shader))
        {
            shader = Shader.Find(shaderName);
            CacheShaders[shaderName] = shader;
            if (shader == null)
            {
                CBase.LogError("缺少Shader:{0}  , 检查Graphics Settings的预置shader", shaderName);
            }
        }

        return(shader);
    }
Exemple #15
0
 public override void Export(string path)
 {
     if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.StandaloneWindows)
     {
         ExportPkg(path);
     }
     else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android ||
              EditorUserBuildSettings.activeBuildTarget == BuildTarget.iPhone)
     {
         //ExportMobile(path);
         ExportPkg(path);
     }
     else
     {
         CBase.LogError("Error Build Audio {0}", path);
     }
 }
Exemple #16
0
    public CAudioLoader(string url, System.Action <AudioClip> callback = null)
    {
        new CAssetFileBridge(url, (UnityEngine.Object obj, object[] args) =>
        {
            AudioClip clip = obj as AudioClip;

            if (clip == null)
            {
                CBase.LogError("Null Audio Clip!!!: {0}", url);
            }

            ResultAudioClip = clip;

            if (callback != null)
            {
                callback(ResultAudioClip);
            }
        });
    }
Exemple #17
0
    public List <T> GetInfos <T>() where T : CBaseInfo
    {
        Dictionary <string, CBaseInfo> dict;

        if (SettingInfos.TryGetValue(typeof(T), out dict))
        {
            //CBase.Log(dict.Count+"");
            List <T> list = new List <T>();
            foreach (CBaseInfo item in dict.Values)
            {
                list.Add((T)item);
            }
            return(list);
        }
        else
        {
            CBase.LogError("找不到类型配置{0}, 总类型数{1}", typeof(T).Name, SettingInfos.Count);
        }

        return(null);
    }
Exemple #18
0
    public static System.Func <string, string> CustomGetResourcesPath;                                              // 自定义资源路径。。。

    public static string GetResourcesPath(string url)
    {
        if (string.IsNullOrEmpty(url))
        {
            CBase.LogError("尝试获取一个空的资源路径!");
        }

        string docUrl;
        bool   hasDocUrl = TryGetDocumentResourceUrl(url, out docUrl);

        string inAppUrl;
        bool   hasInAppUrl = TryGetInAppResourceUrl(url, out inAppUrl);

        if (ResourcePathType == CResourceManagerPathType.PersistentDataPathPriority)  // 優先下載資源模式
        {
            if (hasDocUrl)
            {
                if (Application.isEditor)
                {
                    CBase.LogWarning("使用外部资源 {0}", docUrl);
                }
                return(docUrl);
            }
            else
            {
                return(inAppUrl);  // 優先下載資源,但又沒有下載資源文件!使用本地資源目錄
            }
        }
        else
        {
            if (!hasInAppUrl)
            {
                CBase.LogError("找不到InApp的資源: {0}", url);
            }
            return(inAppUrl);  // 直接使用本地資源!

            // ?? 沒有本地資源但又遠程資源?竟然!!?
        }
    }
Exemple #19
0
    public CUILoadState LoadWindow(string name, bool openWhenFinish, params object[] args)
    {
        if (UIWindows.ContainsKey(name))
        {
            CBase.LogError("[LoadWindow]多次重复LoadWindow: {0}", name);
        }
        CBase.Assert(!UIWindows.ContainsKey(name));

        string path = string.Format("UI/{0}_UI{1}", name, CCosmosEngine.GetConfig("AssetBundleExt"));

        CUILoadState openState = new CUILoadState(name);

        openState.IsStaticUI     = true;
        openState.OpenArgs       = args;
        openState.OpenWhenFinish = openWhenFinish;

        CResourceManager.Instance.StartCoroutine(LoadUIAssetBundle(path, name, openState));

        UIWindows.Add(name, openState);

        return(openState);
    }
Exemple #20
0
    public CStaticAssetLoader(string path, System.Action <UnityEngine.Object> callback = null)
    {
        if (string.IsNullOrEmpty(path))
        {
            CBase.LogError("XStaticAssetLoader 空资源路径!");
        }

        new CAssetFileBridge(path, (_obj, _args) =>
        {
            Object asset = null;
            if (!CachcedAssets.TryGetValue(path, out asset))
            {
                asset = Object.Instantiate(_obj);
                CachcedAssets[path] = asset;
            }

            if (callback != null)
            {
                callback(asset);
            }

            OnLoad(path, asset);
        });
    }
    public CStaticAssetLoader(string path, CResourceManager.ASyncLoadABAssetDelegate callback = null, params object[] args)
    {
        if (string.IsNullOrEmpty(path))
        {
            CBase.LogError("XStaticAssetLoader 空资源路径!");
        }

        new CAssetFileBridge(path, (_obj, _args) =>
        {
            Object asset = null;
            if (!CachcedAssets.TryGetValue(path, out asset))
            {
                asset = Object.Instantiate(_obj);
                CachcedAssets[path] = asset;
            }

            if (callback != null)
            {
                callback(asset, args);
            }

            OnLoad(path, asset);
        });
    }
Exemple #22
0
    /// <summary>
    /// 协和加载Assetbundle,加载完后执行callback
    /// </summary>
    /// <param name="url">资源的url</param>
    /// <param name="callback"></param>
    /// <param name="callbackArgs"></param>
    /// <returns></returns>
    IEnumerator CoLoad(string url, Action <WWW, object[]> callback = null, params object[] callbackArgs)
    {
        if (CResourceManager.LoadByQueue)
        {
            while (Loaded.Count != 0)
            {
                yield return(null);
            }
        }

        CResourceManager.LogRequest("WWW", url);

        CLoadingCache cache = null;

        if (!Loaded.TryGetValue(url, out cache))
        {
            cache = new CLoadingCache(url);
            Loaded.Add(url, cache);
            System.DateTime beginTime = System.DateTime.Now;
            WWW             www       = new WWW(url);

            //设置AssetBundle解压缩线程的优先级
            www.threadPriority = Application.backgroundLoadingPriority;  // 取用全局的加载优先速度
            while (!www.isDone)
            {
                Progress = www.progress;
                yield return(null);
            }

            yield return(www);

            if (!string.IsNullOrEmpty(www.error))
            {
                IsError = true;
                string fileProtocol = CResourceManager.GetFileProtocol();
                if (url.StartsWith(fileProtocol))
                {
                    string fileRealPath = url.Replace(fileProtocol, "");
                    CBase.LogError("File {0} Exist State: {1}", fileRealPath, System.IO.File.Exists(fileRealPath));
                }
                CBase.LogError(www.error + " " + url);
            }

            CResourceManager.LogLoadTime("WWW", url, beginTime);

            cache.Www = www;

            if (WWWFinishCallback != null)
            {
                WWWFinishCallback(url);
            }
        }
        else
        {
            if (cache.Www != null)
            {
                yield return(null);   // 确保每一次异步读取资源都延迟一帧
            }
            while (cache.Www == null) // 未加载完
            {
                yield return(null);
            }
        }

        Progress = cache.Www.progress;
        WwwCache = cache;
        if (callback != null)
        {
            callback(WwwCache.Www, callbackArgs);
        }
    }
Exemple #23
0
    static void RefreshProgramVersion()
    {
        string cmd = string.Format("{0}/GetSvnInfo.bat", Application.dataPath);

        var p    = new Process();
        var si   = new ProcessStartInfo();
        var path = Environment.SystemDirectory;

        if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iPhone)
        {
            path = Path.Combine(path, @"sh");
        }
        else
        {
            path = Path.Combine(path, @"cmd.exe");
        }

        si.FileName = path;
        if (!cmd.StartsWith(@"/"))
        {
            cmd = @"/c " + cmd;
        }
        si.Arguments              = cmd;
        si.UseShellExecute        = false;
        si.CreateNoWindow         = true;
        si.RedirectStandardOutput = true;
        si.RedirectStandardError  = true;
        p.StartInfo = si;

        p.Start();
        p.WaitForExit();

        var str = p.StandardOutput.ReadToEnd();

        if (!string.IsNullOrEmpty(str))
        {
            string programVersionFile = string.Format("{0}/Resources/ProgramVersion.txt", Application.dataPath);

            Regex regex = new Regex(@"Revision: (\d+)");  // 截取svn版本号
            Match match = regex.Match(str);

            string szRevision = match.Groups[1].ToString();
            int    nRevision  = szRevision.ToInt32();
            using (FileStream fs = new FileStream(programVersionFile, FileMode.Create))
            {
                using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8))
                {
                    sw.Write(nRevision.ToString());
                }
            }


            CBase.Log("Refresh ProgramVersion.txt!! SVN Version: {0}", nRevision);
        }
        else
        {
            CBase.LogError("Error Read svn Revision!");
        }


        str = p.StandardError.ReadToEnd();
        if (!string.IsNullOrEmpty(str))
        {
            CBase.LogError(str);
        }
    }
Exemple #24
0
    public static void LoadFromTab(Type type, ref CBaseInfo newT, ICTabReadble tabFile, int row)
    {
        CBase.Assert(typeof(CBaseInfo).IsAssignableFrom(type));

        FieldInfo[] fields = type.GetFields();
        foreach (FieldInfo field in fields)
        {
            if (!tabFile.HasColumn(field.Name))
            {
                CBase.LogError("表{0} 找不到表头{1}", type.Name, field.Name);
                continue;
            }
            object value;
            if (field.FieldType == typeof(int))
            {
                value = tabFile.GetInteger(row, field.Name);
            }
            else if (field.FieldType == typeof(long))
            {
                value = (long)tabFile.GetInteger(row, field.Name);
            }
            else if (field.FieldType == typeof(string))
            {
                value = tabFile.GetString(row, field.Name);
            }
            else if (field.FieldType == typeof(float))
            {
                value = tabFile.GetFloat(row, field.Name);
            }
            else if (field.FieldType == typeof(bool))
            {
                value = tabFile.GetBool(row, field.Name);
            }
            else if (field.FieldType == typeof(double))
            {
                value = tabFile.GetDouble(row, field.Name);
            }
            else if (field.FieldType == typeof(uint))
            {
                value = tabFile.GetUInteger(row, field.Name);
            }
            else if (field.FieldType == typeof(List <string>))
            {
                string sz = tabFile.GetString(row, field.Name);
                value = CTool.Split <string>(sz, '|');
            }
            else if (field.FieldType == typeof(List <int>))
            {
                List <int> retInt = new List <int>();
                string     szArr  = tabFile.GetString(row, field.Name);
                if (!string.IsNullOrEmpty(szArr))
                {
                    string[] szIntArr = szArr.Split('|');
                    foreach (string szInt in szIntArr)
                    {
                        float parseFloat;
                        float.TryParse(szInt, out parseFloat);
                        int parseInt_ = (int)parseFloat;
                        retInt.Add(parseInt_);
                    }
                    value = retInt;
                }
                else
                {
                    value = new List <int>();
                }
            }
            else if (field.FieldType == typeof(List <List <string> >))
            {
                string sz = tabFile.GetString(row, field.Name);
                if (!string.IsNullOrEmpty(sz))
                {
                    var      szOneList = new List <List <string> >();
                    string[] szArr     = sz.Split('|');
                    foreach (string szOne in szArr)
                    {
                        string[] szOneArr = szOne.Split('-');
                        szOneList.Add(new List <string>(szOneArr));
                    }
                    value = szOneList;
                }
                else
                {
                    value = new List <List <string> >();
                }
            }
            else if (field.FieldType == typeof(List <List <int> >))
            {
                string sz = tabFile.GetString(row, field.Name);
                if (!string.IsNullOrEmpty(sz))
                {
                    var      zsOneIntList = new List <List <int> >();
                    string[] szArr        = sz.Split('|');
                    foreach (string szOne in szArr)
                    {
                        List <int> retInts  = new List <int>();
                        string[]   szOneArr = szOne.Split('-');
                        foreach (string szOneInt in szOneArr)
                        {
                            float parseFloat;
                            float.TryParse(szOneInt, out parseFloat);
                            int parseInt_ = (int)parseFloat;
                            retInts.Add(parseInt_);
                        }
                        zsOneIntList.Add(retInts);
                    }
                    value = zsOneIntList;
                }
                else
                {
                    value = new List <List <int> >();
                }
            }
            else
            {
                CBase.LogWarning("未知类型: {0}", field.Name);
                value = null;
            }

            if (field.Name == "Id")  // 如果是Id主键,确保数字成整数!不是浮点数  因为excel转tab可能转成浮点
            {
                float fValue;
                if (float.TryParse((string)value, out fValue))
                {
                    try
                    {
                        value = ((int)fValue).ToString();
                    }
                    catch
                    {
                        CBase.LogError("转型错误...{0}", value.ToString());
                    }
                }
            }

            field.SetValue(newT, value);
        }
    }
Exemple #25
0
    // 将字符串转成指定类型的数组 , 单元测试在Test_StrBytesToArray
    public static T[] StrBytesToArray <T>(string str, int arraySize)
    {
        int typeSize = Marshal.SizeOf(typeof(T));

        byte[] strBytes = Encoding.Unicode.GetBytes(str);
        byte[] bytes    = new byte[typeSize * arraySize]; // 强制数组大小

        for (int k = 0; k < strBytes.Length; k++)
        {
            bytes[k] = strBytes[k];                  // copy
        }
        T[] tArray = new T[bytes.Length / typeSize]; // 总字节 除以 类型长度 = 有多少个类型对象

        int offset = 0;

        for (int i = 0; i < tArray.Length; i++)
        {
            object   convertedObj = null;
            TypeCode typeCode     = Type.GetTypeCode(typeof(T));
            switch (typeCode)
            {
            case TypeCode.Byte:
                convertedObj = bytes[offset];
                break;

            case TypeCode.Int16:
                convertedObj = BitConverter.ToInt16(bytes, offset);
                break;

            case TypeCode.Int32:
                convertedObj = BitConverter.ToInt32(bytes, offset);
                break;

            case TypeCode.Int64:
                convertedObj = BitConverter.ToInt64(bytes, offset);
                break;

            case TypeCode.UInt16:
                convertedObj = BitConverter.ToUInt16(bytes, offset);
                break;

            case TypeCode.UInt32:
                convertedObj = BitConverter.ToUInt32(bytes, offset);
                break;

            case TypeCode.UInt64:
                convertedObj = BitConverter.ToUInt64(bytes, offset);
                break;

            default:
                CBase.LogError("Unsupport Type {0} in StrBytesToArray(), You can custom this.", typeCode);
                CBase.Assert(false);
                break;
            }

            tArray[i] = (T)(convertedObj);
            offset   += typeSize;
        }

        return(tArray);
    }