Exemple #1
0
    public void DoLoadModel(string modelPath, string texturePath, object userData, OnLoadModelOverHandler callback, bool instantiate)
    {
        if (string.IsNullOrEmpty(modelPath))
        {
            return;
        }

        if (callback == null)
        {
            Debug.LogError("Empty Callback when LoadResource");
            return;
        }

#if UNITY_EDITOR || UNITY_ANDROID
        // editor模式下可以优先加载Resources目录下的资源,方便测试。发布版本时要清掉不需要的资源
        GameObject obj = Resources.Load <GameObject>("model/" + modelPath);

        if (obj != null)
        {
            GameObject goModel;
            if (instantiate)
            {
                goModel = Instantiate(obj) as GameObject;
            }
            else
            {
                goModel = obj;
            }

            if (!string.IsNullOrEmpty(texturePath))
            {
                // 额外加载纹理
                Texture tex = Resources.Load <Texture>("model/" + texturePath);
                callback(goModel, null, userData);
            }
            else
            {
                // 没有纹理,直接使用
                callback(goModel, null, userData);
            }
            return;
        }
#endif

        ModelTaskInfo taskInfo = new ModelTaskInfo();
        taskInfo.instantiate = instantiate;
        taskInfo.userData    = userData;

        // 模型
        taskInfo.task = CreateWWW("model/" + modelPath);

        // 纹理
        if (!string.IsNullOrEmpty(texturePath))
        {
            taskInfo.subTask = CreateWWW("texture/" + texturePath);
        }

        // 依赖项
        List <string> deps = new List <string>();
        string        key  = "model/" + modelPath + GameConfig.ASSETBUNDLE;
        CollectDependencies(key, ref deps);
        if (deps.Count > 0)
        {
            foreach (var dep in deps)
            {
                WWWInfo depTask = CreateWWW(dep);
                if (depTask != null)
                {
                    taskInfo.depTask.Add(depTask);
                }
            }
        }

        // 设置回调
        taskInfo.callback = callback;

        _taskQueue.Add(taskInfo);
    }
Exemple #2
0
    private WWWInfo CreateWWW(string resPath, bool isText = false, bool forceNew = false)
    {
        string path = GetAssetBundlePath(resPath);

        if (string.IsNullOrEmpty(path))
        {
            // 没有这个文件
            return(null);
        }

        WWWInfo task = new WWWInfo();

        task.name   = resPath;
        task.isText = isText;

        if (!task.name.EndsWith(GameConfig.ASSETBUNDLE))
        {
            task.name += GameConfig.ASSETBUNDLE;
        }

        BundleInfo bundleInfo;

        if (_loadedBundle.TryGetValue(task.name, out bundleInfo))
        {
            // 此包已经加载过了,可以直接使用
            bundleInfo.lastUseTime = Time.time;
            ++bundleInfo.referenceCount;
            task.assetBundle = bundleInfo.assetBundle;
            task.complete    = true;
            task.www         = null;
        }
        else
        {
            List <WWWInfo> list;
            if (!_loadingQueue.TryGetValue(task.name, out list))
            {
                // 没有加载
                list = new List <WWWInfo>();
                _loadingQueue[task.name] = list;

                // TODO 检验两种方式的速度和内存占用 WWW.LoadFromCacheOrDownload("", Hash128.Parse(""));
                if (isText || forceNew)
                {
                    // 文本只能用这种方式加载
                    task.www = new WWW(GetFileURL(path));
                }
                else
                {
                    task.www = WWW.LoadFromCacheOrDownload(GetFileURL(path), Hash128.Parse(GetBundleHash(task.name)));
                }
            }
            else
            {
                // 正在加载中
                task.www = null;
                list.Add(task);
            }
        }

        return(task);
    }
    private IEnumerator Request_Impl <T>(string path, WWWForm form, Action <T> call_back, Action call_fatal, string get_param = "", string token = "") where T : BaseModel, new()
    {
        SetPreload(false);
        if (form == null)
        {
            form = new WWWForm();
        }
        form.AddField("app", "rob");
        if (!string.IsNullOrEmpty(token))
        {
            form.AddField("rcToken", token);
        }
        string url = GetUrl(path, get_param);

        CrashlyticsReporter.SetAPIRequest(url);
        CrashlyticsReporter.SetAPIRequestStatus(true);
        byte[] data = form.get_data();
        Dictionary <string, string> headers = GetHeader(form);
        string msg = GenerateErrorMsg(Error.Unknown);

        AccountManager.Account account = MonoBehaviourSingleton <AccountManager> .I.account;
        lastRequestTime = Time.get_time();
        WWW www = new WWW(url, data, headers);

        try
        {
            WWWInfo wwwinfo = new WWWInfo(www, false, false);
            wwwInfos.Add(wwwinfo);
            DateTime timeBegin = DateTime.Now;
            while (true)
            {
                yield return((object)new WaitForEndOfFrame());

                if ((DateTime.Now - timeBegin).TotalSeconds > 15.0)
                {
                    msg = GenerateErrorMsg(Error.TimeOut);
                    break;
                }
                if (!string.IsNullOrEmpty(www.get_error()))
                {
                    string txt       = www.get_error();
                    int    httpError = 0;
                    msg = ((!int.TryParse(txt.Substring(0, 3), out httpError)) ? GenerateErrorMsg(Error.DetectHttpError) : GenerateErrorMsg((Error)(200000 + httpError)));
                    break;
                }
                if (www.get_isDone())
                {
                    www.get_text();
                    string signature = null;
                    foreach (KeyValuePair <string, string> responseHeader in www.get_responseHeaders())
                    {
                        string headerName = responseHeader.Key.ToLower();
                        if (string.IsNullOrEmpty(tokenTemp) && headerName == "set-cookie")
                        {
                            List <string> values = new List <string>((IEnumerable <string>)responseHeader.Value.Split(';'));
                            foreach (string item in values)
                            {
                                if (item.Contains("robpt"))
                                {
                                    tokenTemp = item;
                                }
                            }
                        }
                        else if (headerName == "x-compress-encrypt")
                        {
                            if (!(responseHeader.Value.Trim() == "cipher"))
                            {
                                continue;
                            }
                        }
                        else if (headerName == "x-signature")
                        {
                            signature = responseHeader.Value.Trim();
                        }
                    }
                    bool   isDecryptSuccess2 = true;
                    byte[] gzippedResponse   = null;
                    try
                    {
                        string key = (!string.IsNullOrEmpty(account.userHash)) ? account.userHash : "ELqdT/y.pM#8+J##x7|3/tLb7jZhmqJ,";
                        gzippedResponse = Cipher.DecryptRJ128Byte(key, "yCNBH$$rCNGvC+#f", www.get_text());
                    }
                    catch (Exception exc4)
                    {
                        Debug.LogException(exc4);
                        Debug.LogError((object)("Decrypt fail: " + www.get_url() + " data " + www.get_text()));
                        Debug.LogError((object)("Key Decrypt : " + ((!string.IsNullOrEmpty(account.userHash)) ? account.userHash : "ELqdT/y.pM#8+J##x7|3/tLb7jZhmqJ,")));
                        isDecryptSuccess2 = false;
                    }
                    if (!isDecryptSuccess2)
                    {
                        if (string.IsNullOrEmpty(account.userHash))
                        {
                            msg = GenerateErrorMsg(Error.DecryptResponceIsNull);
                            Log.Error(LOG.NETWORK, "Decrypt failed!!!");
                            break;
                        }
                        isDecryptSuccess2 = true;
                        try
                        {
                            gzippedResponse = Cipher.DecryptRJ128Byte("ELqdT/y.pM#8+J##x7|3/tLb7jZhmqJ,", "yCNBH$$rCNGvC+#f", www.get_text());
                        }
                        catch (Exception exc3)
                        {
                            Log.Exception(exc3);
                            isDecryptSuccess2 = false;
                        }
                        if (!isDecryptSuccess2)
                        {
                            msg = GenerateErrorMsg(Error.DecryptFailed);
                            Log.Error(LOG.NETWORK, "Decrypt failed");
                            break;
                        }
                    }
                    if (gzippedResponse == null)
                    {
                        msg = GenerateErrorMsg(Error.DecryptResponceIsNull);
                        Log.Error(LOG.NETWORK, "Decrypt responce is null");
                    }
                    else
                    {
                        bool isUncompressSuccess = true;
                        try
                        {
                            msg = GzUncompress(gzippedResponse);
                        }
                        catch (Exception ex)
                        {
                            Exception exc2 = ex;
                            Log.Exception(exc2);
                            isUncompressSuccess = false;
                        }
                        if (!isUncompressSuccess)
                        {
                            msg = GenerateErrorMsg(Error.UncompressFailed);
                        }
                        else if (signature == null)
                        {
                            msg = GenerateErrorMsg(Error.SignatureIsNull);
                            Log.Error(LOG.NETWORK, "Signature is null");
                        }
                        else
                        {
                            bool isVerifySignatureSuccess = true;
                            bool isValidSignature         = true;
                            try
                            {
                                isValidSignature = Cipher.verify(msg, signature);
                            }
                            catch (Exception ex2)
                            {
                                Exception exc = ex2;
                                Log.Exception(exc);
                                isVerifySignatureSuccess = false;
                            }
                            if (!isVerifySignatureSuccess)
                            {
                                msg = GenerateErrorMsg(Error.VerifySignatureFailed);
                            }
                            else if (!isValidSignature)
                            {
                                msg = GenerateErrorMsg(Error.InvalidSignature);
                            }
                            else
                            {
                                msg = Regex.Unescape(msg);
                                if (msg == "{\"error\":0,\"result\":[]}")
                                {
                                    msg = GenerateErrorMsg(Error.EmptyRecord);
                                }
                                if (msg.Contains("\"result\":[]"))
                                {
                                    msg = msg.Replace("\"result\":[]", "\"dummy\":[]");
                                }
                            }
                        }
                    }
                    break;
                }
            }
            wwwInfos.Remove(wwwinfo);
        }
        finally
        {
            ((IDisposable)www)?.Dispose();
        }
        yield return((object)new WaitForEndOfFrame());

        yield return((object)new WaitForEndOfFrame());

        yield return((object)new WaitForEndOfFrame());

        try
        {
            if (call_back != null)
            {
                new T();
                try
                {
                    JSONSerializer.Deserialize <T>(msg);
                }
                catch (Exception ex3)
                {
                    Exception exp2 = ex3;
                    string    decode_failed_msg = GenerateErrorMsg(Error.DecodeFailed);
                    JSONSerializer.Deserialize <T>(decode_failed_msg);
                    Debug.LogException(exp2);
                }
                finally
                {
                    ((_003CRequest_Impl_003Ec__Iterator1E7 <T>) /*Error near IL_08b6: stateMachine*/)._003C_003E__Finally0();
                }
            }
        }
        catch (Exception exp)
        {
            Debug.LogException(exp);
            CrashlyticsReporter.SetAPIRequestStatus(false);
            call_fatal();
        }
    }