Exemplo n.º 1
0
 public TestGame(string roomId, Caching.RoomCacheBase parent, int emptyRoomTTL, IPluginManager eManager, string pluginName)
     : base(roomId, parent, new TestGameStateFactory(), emptyRoomTTL, eManager, pluginName)
 {
     //this.IsOpen = true;
     //this.IsVisible = true;
     //this.EventCache.SetGameAppCounters(NullHiveGameAppCounters.Instance);
     //this.EventCache.AddSlice(0);
 }
Exemplo n.º 2
0
	public void UpdateNodeMaterials(IEnumerable<GameObject> scene_nodes)
	{
		m_cache = new Caching();

		foreach(var n in scene_nodes)
		{
			UpdateNodeMaterials(n);
		}
	}
Exemplo n.º 3
0
        /*  http://developer.yahoo.com/performance/rules.html
            http://24x7aspnet.blogspot.com/2009/06/using-cache-methods-httpcacheability-in.html

            Redirects should have caching headers.
            Expires: is good
            Remove ETags, bad server implementation
         */
        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            int mins = c.get("clientcache.minutes", -1);
            //Set the expires value if present
            if (mins > 0)
                e.ResponseHeaders.Expires = DateTime.UtcNow.AddMinutes(mins);

            //NDJ Jan-16-2013. The last modified date sent in the headers should NOT match the source modified date when using DiskCaching.
            //Setting this will prevent 304s from being sent properly.
            // (Moved to NoCache)

            //Authenticated requests only allow caching on the client.
            //Anonymous requests get caching on the server, proxy and client
            if (context.Request.IsAuthenticated)
                e.ResponseHeaders.CacheControl = System.Web.HttpCacheability.Private;
            else
                e.ResponseHeaders.CacheControl = System.Web.HttpCacheability.Public;
        }
Exemplo n.º 4
0
        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            string info = e.RewrittenQuerystring["getinfo"];
            if (string.IsNullOrEmpty(info)) return;

            ResponseArgs ra = e as ResponseArgs;
            e.ResponseHeaders.ContentType = "application/json; charset=utf-8";

            NameValueCollection d = new NameValueCollection();
            ra.ResizeImageToStream = new ResizeImageDelegate(delegate(Stream s) {
                try {
                    using (Stream src = ra.GetSourceImage()) {

                        bool attemptFastMode = src.CanSeek;
                        long orig = attemptFastMode ? src.Position : 0;
                        bool trySlowMode = !attemptFastMode;
                        if (attemptFastMode) {
                            try {
                                using (Image i = System.Drawing.Image.FromStream(src, false, false)) {
                                    d["width"] = i.Width.ToString();
                                    d["height"] = i.Height.ToString();
                                }
                            } catch {
                                trySlowMode = true;

                            }
                        }
                        if (trySlowMode){
                            if (attemptFastMode) src.Seek(orig, SeekOrigin.Begin);
                            using (Bitmap b = c.CurrentImageBuilder.LoadImage(src,new ResizeSettings(ra.RewrittenQuerystring))){
                                d["width"] = b.Width.ToString();
                                d["height"] = b.Height.ToString();
                            }
                        }
                        SimpleJson(s, d, e.RewrittenQuerystring["jsonp"]);
                    }
                } catch (FileNotFoundException) {
                    d["result"] = "404";
                    SimpleJson(s,d,e.RewrittenQuerystring["jsonp"]);
                }
            });
        }
Exemplo n.º 5
0
        public object Create(object parent, object configContext, XmlNode section)
        {
            Caching c = new Caching();
            c.StaticHost = section.Attributes["staticHost"] != null ? section.Attributes["staticHost"].Value : c.StaticHost;

            if (section.Attributes["enableOutputCaching"] != null)
            {
                bool enabled = c.EnableOutputCaching;

                bool.TryParse(section.Attributes["enableOutputCaching"].Value, out enabled);
                c.EnableOutputCaching = enabled;
            }

            if (section.Attributes["sharedObjectCacheTime"] != null)
            {
                int time = c.SharedObjectCacheTime;

                int.TryParse(section.Attributes["sharedObjectCacheTime"].Value, out time);
                c.SharedObjectCacheTime = time;
            }

            return c;
        }
Exemplo n.º 6
0
    /// <summary>
    /// 下载服务器的ABConfig.json与本地ABConfig.json对比差异,有差异则下载更新
    /// </summary>
    /// <returns></returns>
    private IEnumerator DoCheckUpdate(Action <Dictionary <string, SingleBundleInfo> > onFinished)
    {
        string abConfigUrl = _baseURL + "ABConfig.json";

        UnityWebRequest request = UnityWebRequest.Get(abConfigUrl);

        yield return(request.SendWebRequest());

        if (request.error != null)
        {
            LogUtil.LogError($"下载AssetBundle版本文件时发生错误,url:{abConfigUrl},error:{request.error}");
            yield break;
        }

        _serverABConfig = request.downloadHandler.text;
        request.Dispose();

        Debug.Log("下载AssetBundle的版本文件:\n" + _serverABConfig);
        var serverAllBundleInfo = JsonConvert.DeserializeObject <AllBundleInfo>(_serverABConfig);

        if (serverAllBundleInfo == null)
        {
            LogUtil.LogError("下载AssetBundle版本文件解析出来是空值!");
            yield break;
        }

        string streamingAssetsABconfigPath = Application.streamingAssetsPath + "/ABconfig.json";//本地路径

        if (!File.Exists(streamingAssetsABconfigPath))
        {
            LogUtil.LogError("streamingAssetsPath文件夹没有ABconfig.json文件!");
            yield break;
        }

        //缓存文件夹没有 ABconfig.json ,则从 streamingAssetsPath 文件下拷贝过去
        string persistentABconfigPath = Application.persistentDataPath + "/ABconfig.json";//缓存路径

        if (!File.Exists(persistentABconfigPath))
        {
            FileInfo fileInfo = new FileInfo(streamingAssetsABconfigPath);
            fileInfo.CopyTo(persistentABconfigPath);
            Debug.Log("成功从“streamingAssetsPath”拷贝ABconfig.json到“persistentDataPath”!");
        }
        else
        {
            Debug.Log("“persistentDataPath”路径下存在ABconfig.json文件!");
        }

        //打开缓存的 ABconfig.json,比较差别,检测是否需要更新
        string abConfig           = FileHelper.ReadStrFromFile(persistentABconfigPath, false);
        var    localAllBundleInfo = JsonConvert.DeserializeObject <AllBundleInfo>(abConfig);

        if (localAllBundleInfo == null)
        {
            LogUtil.LogError("缓存文件夹下ABconfig.json文件格式错误!");
            yield break;
        }

        Debug.Log("本地AssetBundle版本文件:\n" + JsonConvert.SerializeObject(localAllBundleInfo, Formatting.Indented));

        //获取需要更新的assetbundle。
        Dictionary <string, SingleBundleInfo> changedDic = GetChangedBundleInfo(serverAllBundleInfo.BundleInfoList, localAllBundleInfo.BundleInfoList);

        foreach (var item in changedDic)
        {
            List <Hash128> lis = new List <Hash128>();
            Caching.GetCachedVersions(item.Value.bundleName, lis);
            foreach (var hash128 in lis)
            {
                Debug.Log(string.Format("AssetBundle:{0},hash128:{1}", item.Value.bundleName, hash128));
            }
        }

        Debug.Log(string.Format("需要更新的资源有{0}个,列表如下:", changedDic.Count));
        foreach (var item in changedDic)
        {
            Debug.Log(item.Value.bundleName);
        }

        //没有资源更新的情况
        if (changedDic.Count == 0)
        {
            InitBasicData();
        }

        onFinished?.Invoke(changedDic);
    }
Exemplo n.º 7
0
    public IEnumerator CheckVersion(string cdnURL)
    {
        yield return(LoadServerPatchXML());

        if (m_CurState == eVCstate.FAIL_LOAD_SERVER_XML)
        {
            if (CDN_CONNECT_FAIL_CALLBACK != null)
            {
                CDN_CONNECT_FAIL_CALLBACK();
            }

            while (CDN_CONNECT_FAIL_FORCE_END == false)
            {
                yield return(null);
            }

            yield break;
        }

        CheckAPKstep();         // apk ���� ��?

        var havDict    = m_CurHavingInfo.AssetDict;
        var serverDict = m_LoadedServerInfo.AssetDict;

        NEED_DOWNLOAD = 0;
        foreach (var kvPair in serverDict)
        {
            m_FullAssetSize += kvPair.Value.FileSize;

            if (Caching.IsVersionCached(kvPair.Key, (int)kvPair.Value.Version) == true)
            {
                m_HavingAssetSize += kvPair.Value.FileSize;
                m_CurHavingInfo.AssetDict[kvPair.Key] = kvPair.Value;
                Caching.MarkAsUsed(kvPair.Key, (int)kvPair.Value.Version);
                continue;
            }

            // cdn 주소가 streaming-> cdn으로가져옴
            if (havDict.ContainsKey(kvPair.Key) == true)
            {
                // stremaing asset patch 랑 cdn patch랑 겹치는데, streaming 버전이 같거나 작으면 pass.
                if (havDict[kvPair.Key].Version >= (int)kvPair.Value.Version)
                {
                    continue;
                }
            }

            NEED_SIZE += kvPair.Value.FileSize;
            NEED_DOWNLOAD++;
        }

        Debug.Log("Total Need Size : " + NEED_SIZE.ToString());



        //NEED_SIZE = 0;
        //DOWNLOADED_SIZE = 0;
        //m_FullAssetSize = 0.0f;
        //m_HavingAssetSize = 0.0f;
        //NEED_DOWNLOAD = int.MaxValue;	// ���ǰ� �ʱ�ȭ



        //yield return LoadServerPatchXML(CachedBaseURL);

        //if (m_CurState == eVCstate.FAIL_LOAD_SERVER_XML)
        //{
        //	if (CDN_CONNECT_FAIL_CALLBACK != null)
        //		CDN_CONNECT_FAIL_CALLBACK();

        //	while (CDN_CONNECT_FAIL_FORCE_END == false)
        //		yield return null;

        //	yield break;
        //}

        //CheckAPKstep();         // apk ���� ��?

        //var havDict = m_CurHavingInfo.AssetDict;
        //var serverDict = m_LoadedServerInfo.AssetDict;


        //NEED_DOWNLOAD = 0;
        //foreach (var kvPair in serverDict)
        //{
        //	m_FullAssetSize += kvPair.Value.FileSize;

        //          if (Caching.IsVersionCached(kvPair.Key, (int)kvPair.Value.Version) == true)
        //          {
        //              m_HavingAssetSize += kvPair.Value.FileSize;
        //              m_CurHavingInfo.AssetDict[kvPair.Key] = kvPair.Value;
        //              Caching.MarkAsUsed(kvPair.Key, (int)kvPair.Value.Version);
        //              continue;
        //          }
        //          NEED_SIZE += kvPair.Value.FileSize;
        //	NEED_DOWNLOAD++;
        //}

        //Debug.Log("Total Need Size : " + NEED_SIZE.ToString());
    }
Exemplo n.º 8
0
    public static void ExecuteEncryption(UnityEditor.BuildTarget target)
    {
        //清空一下缓存
        Caching.CleanCache();

        string platfrom = AssetBundleController.GetPlatformName(target);
        string dir      = System.IO.Path.Combine(Application.dataPath, "StreamingAssets/AssetBundle/" + platfrom);

        foreach (string filePath in Directory.GetFiles(dir))
        {
            if (filePath.Contains(".meta") || filePath.Contains("VersionMD5") || filePath.Contains(".xml") || filePath.Contains(".enc") || filePath.Contains(".lua"))
            {
                continue;
            }
            string key = filePath.Substring(dir.Length + 1, filePath.Length - dir.Length - 1);

            FileStream file      = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
            byte[]     fileData  = new byte[file.Length];
            byte[]     NewHeader = System.Text.Encoding.UTF8.GetBytes("DreamfactionGame");
            byte[]     NewEnd    = System.Text.Encoding.UTF8.GetBytes("zmy");
            byte[]     buff      = new byte[(int)file.Length + NewHeader.Length + NewEnd.Length];
            file.Read(fileData, 0, (int)file.Length);

            //对二进制文件添加固定头尾,中端修改内容
            for (int i = 0; i < buff.Length; i++)
            {
                if (i >= 0 && i < NewHeader.Length)
                {
                    buff[i] = NewHeader[i];
                    //buff[i] += (byte)i;
                }
                else if (i >= NewHeader.Length && i < fileData.Length + NewHeader.Length)
                {
                    buff[i]  = fileData[i - NewHeader.Length];
                    buff[i] += 1;
                }
                else if (i >= fileData.Length + NewHeader.Length && i < buff.Length)
                {
                    int randomNum = Random.Range(97, 123);
                    buff[i] = (byte)randomNum;
                }
            }
            file.Flush();
            file.Close();
            fileData = null;

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            key  = key.Substring(0, key.LastIndexOf('.'));
            key += ".enc";

            string newFilePath = filePath.Substring(0, filePath.LastIndexOf('.'));
            newFilePath += ".enc";
            if (File.Exists(newFilePath))
            {
//                 string nMessage = key + "资源有重名,是否覆盖";
//                 if (EditorUtility.DisplayDialog("", nMessage, "是", "否") == false)
//                 {
//                     EditorUtility.DisplayDialog("", "资源加密已取消,请修改资源名称重新打包", "OK");
//                     return;
//                 }
//                 else
//                 {
//                     File.Delete(key);
//                 }
                File.Delete(key);
            }

            FileStream stream = new FileStream(dir + "/" + key, FileMode.Create);
            stream.Write(buff, 0, buff.Length);
            stream.Flush();
            stream.Close();
            buff = null;
        }

        AssetDatabase.Refresh();
        EditorUtility.DisplayDialog("", "资源加密完成", "OK");
    }
Exemplo n.º 9
0
    public async UniTask Initialize()
    {
        // Get built-in catalog first
        BundleCatalog builtInCatalog;

        using (var request = UnityWebRequest.Get(BuiltInCatalogPath))
        {
            await request.SendWebRequest();

            var text = Encoding.UTF8.GetString(request.downloadHandler.data);
            builtInCatalog = new BundleCatalog(JObject.Parse(text));
        }

        // Then the cached catalog
        if (File.Exists(CachedCatalogPath))
        {
            Debug.Log($"[BundleManager] Reading cached catalog from {CachedCatalogPath}");
            using (var request = UnityWebRequest.Get("file://" + CachedCatalogPath))
            {
                var valid = true;
                try
                {
                    await request.SendWebRequest();

                    if (request.isHttpError || request.isNetworkError)
                    {
                        throw new Exception(request.error);
                    }
                    var text = Encoding.UTF8.GetString(request.downloadHandler.data);
                    Catalog = new BundleCatalog(JObject.Parse(text));
                    foreach (var bundleName in builtInCatalog.GetEntryNames())
                    {
                        if (!Catalog.ContainsEntry(bundleName))
                        {
                            valid = false;
                            break;
                        }

                        var cachedVersion  = Catalog.GetEntry(bundleName).version;
                        var builtInVersion = builtInCatalog.GetEntry(bundleName).version;
                        if (builtInVersion > cachedVersion)
                        {
                            Debug.Log($"[BundleManager] Bumping {bundleName} from {cachedVersion} to {builtInVersion}");
                            Catalog.SetEntry(bundleName, Catalog.GetEntry(bundleName).JsonDeepCopy().Also(it => it.version = builtInVersion));
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.LogWarning(e);
                    valid = false;
                }

                if (!valid)
                {
                    Debug.Log($"[BundleManager] Invalid cached catalog! Using built-in catalog");
                    Catalog = builtInCatalog;
                }
            }
        }
        else
        {
            Catalog = builtInCatalog;
        }

        var cachePaths = new List <string>();

        Caching.GetAllCachePaths(cachePaths);
        cachePaths.ForEach(it => Debug.Log($"[BundleManager] Cache path: {it}"));

        // Always cache built in bundles
        foreach (var bundle in builtInCatalog.GetEntryNames())
        {
            if (IsCached(bundle) && IsUpToDate(bundle))
            {
                Debug.Log($"[BundleManager] Built-in bundle {bundle} is cached and up-to-date (version {Catalog.GetEntry(bundle).version})");
                continue;
            }
            await LoadBundle(bundle, true, false);

            Release(bundle);
        }
    }
Exemplo n.º 10
0
Arquivo: CLogo.cs Projeto: zlbsy/sh109
 public void ClearCacher()
 {
     Caching.ClearCache();
     PlayerPrefs.DeleteAll();
 }
Exemplo n.º 11
0
 public bool Contains(Microsoft.Xna.Framework.Vector2 point, Caching.IResourceCache<Microsoft.Xna.Framework.Graphics.Texture2D> cache, Microsoft.Xna.Framework.Matrix globalTransform)
 {
     return false;
 }
 public CriteriaCacheSettings(Caching.ICacheProvider provider)
 {
     Provider = provider;
 }
Exemplo n.º 13
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="bundleInfo"></param>
 /// <returns></returns>
 public static bool ExistsInCache(BundleInfo bundleInfo)
 {
     if (Caching.IsVersionCached(bundleInfo.Filename, bundleInfo.Hash))
         return true;
     return false;
 }
Exemplo n.º 14
0
    //-------------------------------------------------------------------------
    void _packAssetBundleCompress()
    {
        EditorUserBuildSettings.SwitchActiveBuildTarget(mCurrentBuildTarget);

        _getCurrentTargetPath();
        _checkPatchData();

        _deleteFile(mTargetPlatformRootPath);

        Caching.CleanCache();

        _getAllFiles(mAssetBundleResourcesPath);

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

        foreach (var obj in mListAllABFile)
        {
            if (File.Exists(obj))
            {
                string path = Path.GetFullPath(obj);
                path = path.Replace(@"\", "/");
                path = path.Replace(mAssetPath, "");
                path = mTargetPath + "/" + path;
                string obj_dir = path.Replace(Path.GetFileName(obj), "");
                if (!Directory.Exists(obj_dir))
                {
                    Directory.CreateDirectory(obj_dir);
                }
                var names = AssetDatabase.GetDependencies(obj);

                AssetBundleBuild abb;
                abb.assetBundleName    = Path.GetFileNameWithoutExtension(obj) + ".ab";
                abb.assetBundleVariant = "";
                int           asset_index             = 0;
                List <string> list_needbuildassetname = new List <string>();
                //list_needbuildassetname.Add(obj.Replace(mAssetPath, "Assets/"));
                foreach (var j in names)
                {
                    //Debug.Log("Asset: " + j);
                    if (j.EndsWith(".cs") || j.EndsWith(".ttf"))
                    {
                        continue;
                    }
                    if (list_needbuildassetname.Contains(j))
                    {
                        continue;
                    }
                    list_needbuildassetname.Add(j);
                }
                abb.assetNames = new string[list_needbuildassetname.Count];

                foreach (var i in list_needbuildassetname)
                {
                    abb.assetNames[asset_index++] = i;
                }

                AssetBundleBuild[] arr_abb = new AssetBundleBuild[1];
                arr_abb[0] = abb;

                _buildAssetBundleCompressed(arr_abb, obj_dir, mCurrentBuildTarget, false);
                //#if UNITY_STANDALONE_WIN
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.StandaloneWindows64, false);
                //#elif UNITY_IOS||UNITY_IPHONE
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.iOS, false);
                //#elif UNITY_ANDROID
                //                _buildAssetBundleCompressed(arr_abb, obj_dir, BuildTarget.Android, false);
                //#endif
            }
        }

        if (Directory.Exists(mRowAssetPath))
        {
            copyFile(mRowAssetPath, mTargetPath, "Assets/");
        }

        Debug.Log("裸资源复制完毕!");

        _packResources(mTargetPath);
    }
Exemplo n.º 15
0
    private void OnGUI()
    {
        if (GUILayout.Button("CheckCatalogUpdate"))
        {
            Debug.Log("CheckCatalogUpdate");

            var opChecklist = Addressables.CheckForCatalogUpdates();
            opChecklist.Completed += handle =>
            {
                var checkList = handle.Result;
                Debug.LogFormat("CheckForCatalogUpdates: {0}, Status: {1}", checkList.Count, handle.Status);
                for (int i = 0; i < checkList.Count; i++)
                {
                    Debug.LogFormat("[{0}] Check Catalog: {1}", i, checkList[i]);
                }

                if (checkList.Count > 0)
                {
                    var opUpdate = Addressables.UpdateCatalogs(checkList);
                    opUpdate.Completed += operationHandle =>
                    {
                        Debug.LogFormat("UpdateCatalogs Status: {0}", operationHandle.Status);
                        if (operationHandle.Status == AsyncOperationStatus.Succeeded)
                        {
                            var locations = operationHandle.Result;
                            Debug.LogFormat("UpdateCatalogs: {0}", locations?.Count ?? 0);
                            for (int i = 0; i < checkList.Count; i++)
                            {
                                Debug.LogFormat("[{0}] Resource Locator: {1}", i, checkList[i]);
                            }
                        }
                    };
                }
            };
        }

        if (GUILayout.Button("Download"))
        {
            var opInit = Addressables.InitializeAsync();
            opInit.Completed += opInitHandle =>
            {
                var resLocator = opInitHandle.Result;
                Debug.Log("Download:" + resLocator.Keys);
                var opGetDownloadSize = Addressables.GetDownloadSizeAsync(resLocator.Keys);

                opGetDownloadSize.Completed += handle =>
                {
                    Debug.LogFormat("GetDownloadSizeAsync Status: {0} Size: {1} bytes", handle.GetDownloadStatus(), handle.Result);

                    var allLocations = new List <IResourceLocation>();
                    foreach (var key in resLocator.Keys)
                    {
                        IList <IResourceLocation> locations;
                        if (resLocator.Locate(key, typeof(object), out locations))
                        {
                            foreach (var loc in locations)
                            {
                                if (loc.HasDependencies)
                                {
                                    allLocations.AddRange(loc.Dependencies);
                                }
                            }
                        }
                    }


                    var allPrimaryKeys = allLocations.Distinct().ToList();
                    for (int i = 0; i < allPrimaryKeys.Count; i++)
                    {
                        Debug.LogFormat("[{0}]DownloadDependency PrimaryKey: {1}", i, allPrimaryKeys[i]);
                    }

                    var opDownload = Addressables.DownloadDependenciesAsync(allPrimaryKeys);

                    opDownload.Completed += operationHandle =>
                    {
                        Debug.LogFormat("DownloadDependenciesAsync: {0}", operationHandle.Result);
                    };
                };
            };
        }

        if (GUILayout.Button("ClearDependencyCache"))
        {
            var opInit = Addressables.InitializeAsync();
            opInit.Completed += opInitHandle =>
            {
                var resLocator = opInitHandle.Result;

                var allLocations = new List <IResourceLocation>();
                foreach (var key in resLocator.Keys)
                {
                    IList <IResourceLocation> locations;
                    if (resLocator.Locate(key, typeof(object), out locations))
                    {
                        foreach (var loc in locations)
                        {
                            if (loc.HasDependencies)
                            {
                                allLocations.AddRange(loc.Dependencies);
                            }
                        }
                    }
                }

                Debug.LogFormat("ClearDependencyCacheAsync: {0}", allLocations.Count);

                var opClear = Addressables.ClearDependencyCacheAsync(allLocations, false);
                opClear.Completed += handle =>
                {
                    Debug.LogFormat("ClearDependencyCacheAsync Completed: {0}", handle.Result);
                    Addressables.Release(handle);
                };
            };
        }

        if (GUILayout.Button("Caching.ClearCache"))
        {
            var seconds = 1;
            var result  = Caching.ClearCache(seconds);
            Debug.LogFormat("Caching.ClearCache: {0}", result);
        }

        if (GUILayout.Button("Load"))
        {
            Debug.Log("Load");

            var handle = Addressables.LoadAssetAsync <GameObject>("Assets/CanNotChangePost/A_1.prefab");
            handle.Completed += onLoadDone;

            handles.Add(handle);
        }
        if (GUILayout.Button("UnLoad"))
        {
            if (handles.Count > 0)
            {
                var handle = handles[handles.Count - 1];

                if (handle.IsValid())
                {
                    Debug.Log("UnLoad OK");

                    Addressables.Release(handle);
                }
                else
                {
                    Debug.Log("UnLoad Fail");
                }
            }


            if (instances.Count > 0)
            {
                Destroy(instances[instances.Count - 1]);
                instances.RemoveAt(instances.Count - 1);
            }
        }
    }
Exemplo n.º 16
0
        //------------------------------------------------------
        // Settings
        //------------------------------------------------------

        public void OnClearCacheDown()
        {
            Caching.ClearCache();

            m_clearCache.interactable = false;
        }
    public override void OnXGUI()
    {
        //TODO List
        if (Selection.objects != null && Selection.objects.Length > 0)
        {
            selectedObject = Selection.objects[0];
        }

        if (CreateSpaceButton("Packing Selected Objects"))
        {
            Object[] objects = Selection.objects;

            string path = EditorUtility.SaveFilePanel("Create A Bundle", AssetDatabase.GetAssetPath(objects[0]), "newbundle.assetbundle", "assetbundle");
            if (path == "")
            {
                return;
            }


            CreateXMLWithDependencies(objects, path);

            BuildPipeline.BuildAssetBundle(
                null, objects,
                path,
                BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.UncompressedAssetBundle
                | BuildAssetBundleOptions.DeterministicAssetBundle, BuildTarget.Android);
        }

        if (CreateSpaceButton("GetObject"))
        {
            string path = EditorUtility.OpenFilePanel("Open A Bundle", Application.streamingAssetsPath, "");
            if (path == "")
            {
                return;
            }
            _bundlepath   = "file://" + path;
            LoadingConfig = true;
            asset         = null;
//			AssetDatabase.Refresh();
            if (currBundle != null)
            {
                currBundle.Unload(true);
            }
        }

        if (CreateSpaceButton("Clean Cache"))
        {
            currentBundleObjects = null;
            Caching.CleanCache();
        }

        if (LoadingConfig)
        {
            XLogger.Log("start loading");
            if (null == asset)
            {
                asset = new WWW(_bundlepath);
            }
            LoadingConfig = false;
        }
//		Logger.Log(string.Format("asset == null is {0}" , asset == null));
        if (asset != null)
        {
//			Logger.Log("asset.isDone is " + asset.isDone);
//			if(asset.isDone){

            XLogger.Log("end loading");
            currBundle = asset.assetBundle;
            if (currBundle == null)
            {
                CreateNotification("Selected the asset bundle 's format is error.");
                LoadingConfig = false;
                asset         = null;
                return;
            }
                        #if UNITY_5_0
            currentBundleObjects = currBundle.LoadAllAssets();
                        #endif
                        #if UNITY_4_6
            currentBundleObjects = currBundle.LoadAll();
                        #endif
            LoadingConfig = false;
            asset         = null;
//			}
        }



        if (null != currentBundleObjects)
        {
            for (int pos = 0; pos < currentBundleObjects.Length; pos++)
            {
                CreateObjectField(currentBundleObjects[pos].GetType().ToString(), currentBundleObjects[pos]);
            }
        }

        if (CreateSpaceButton("Add A AssetBundle"))
        {
            allAssets.Add(new AssetBundleModel());
        }
        if (CreateSpaceButton("Clean All AssetBundle"))
        {
            allAssets.Clear();
        }
        if (CreateSpaceButton("Collect") && allAssets.Count > 0)
        {
            List <AssetBundleModel> AllChilds = new List <AssetBundleModel>();
            sortAssets.Clear();

            BundlePath = EditorUtility.SaveFolderPanel("Save Bundles", Application.streamingAssetsPath, "");
            if (BundlePath == null)
            {
                return;
            }
            BundlePath += "/";
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement  root   = xmlDoc.CreateElement("root");
            for (int pos = 0; pos < allAssets.Count; pos++)
            {
                if (allAssets[pos].ParentName.Equals(""))
                {
                    sortAssets.Add(allAssets[pos].ModelName, allAssets[pos]);
                    XmlElement child = xmlDoc.CreateElement(allAssets[pos].ModelName);
                    root.AppendChild(child);
                }
                else
                {
                    AllChilds.Add(allAssets[pos]);
                }
//				allAssets.Remove(allAssets[pos]);
            }
            for (int pos = 0; pos < AllChilds.Count; pos++)
            {
                sortAssets[AllChilds[pos].ParentName].Childs.Add(AllChilds[pos]);
                XmlElement child = xmlDoc.CreateElement(AllChilds[pos].ModelName);
                root.SelectSingleNode(AllChilds[pos].ParentName).AppendChild(child);
//				allAssets.Remove(allAssets[pos]);
            }
            xmlDoc.AppendChild(root);
            xmlDoc.Save(BundlePath + "bundle.xml");
            foreach (var bundle in sortAssets)
            {
                bundle.Value.PackingSelf();
            }
//			allAssets.Clear();
            AssetDatabase.Refresh();
            CreateNotification("Create asset bundle success!");
        }

        for (int pos = 0; pos < allAssets.Count; pos++)
        {
            AssetBundleModel Item = allAssets[pos];
            BeginHorizontal();
            Item.ModelName  = CreateStringField("Name", allAssets[pos].ModelName);
            Item.ParentName = CreateStringField("Dependencies", allAssets[pos].ParentName);
            if (CreateSpaceButton("Add Asset") && null != selectedObject)
            {
                Item.Assets.AddRange(Selection.objects);
            }
            if (CreateSpaceButton("Remove Bundle"))
            {
                allAssets.RemoveAt(pos);
            }
            EndHorizontal();
            CreateSpaceBox();

            for (int idx = 0; idx < Item.Assets.Count; idx++)
            {
                BeginHorizontal();
                CreateObjectField("child_" + idx, Item.Assets[idx]);
                if (CreateSpaceButton("Remove"))
                {
                    Item.Assets.RemoveAt(idx);
                }
                EndHorizontal();
            }

            CreateSpaceBox();
        }
    }
Exemplo n.º 18
0
        /// <summary>
        /// Search for local GLTFs in "_Downloaded" and use those hashes to find their corresponding
        /// Asset Bundle files, then instantiate those ABs in the Unity scene
        /// </summary>
        public static GameObject[] LoadAndInstantiateAllAssetBundles()
        {
            Caching.ClearCache();

            string workingFolderName = "_Downloaded";

            var pathList = Directory.GetDirectories(Application.dataPath + "/" + workingFolderName);

            List <string> dependencyAbs = new List <string>();
            List <string> mainAbs       = new List <string>();

            foreach (var paths in pathList)
            {
                var hash  = new DirectoryInfo(paths).Name;
                var path  = "Assets/" + workingFolderName + "/" + hash;
                var guids = AssetDatabase.FindAssets("t:GameObject", new[] { path });

                // NOTE(Brian): If no gameObjects are found, we assume they are dependency assets (textures, etc).
                if (guids.Length == 0)
                {
                    // We need to avoid adding dependencies that are NOT converted to ABs (like .bin files)
                    if (AssetDatabase.FindAssets("t:Texture", new[] { path }).Length != 0)
                    {
                        dependencyAbs.Add(hash);
                    }
                }
                else
                {
                    // Otherwise we assume they are gltfs.
                    mainAbs.Add(hash);
                }
            }

            // NOTE(Brian): We need to store the asset bundles so they can be unloaded later.
            List <AssetBundle> loadedAbs = new List <AssetBundle>();

            foreach (var hash in dependencyAbs)
            {
                string path = abPath + hash;
                var    req  = UnityWebRequestAssetBundle.GetAssetBundle(path);

                if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
                {
                    req.url = req.url.Replace("http://localhost", "file:///");
                }

                req.SendWebRequest();

                while (!req.isDone)
                {
                }

                if (!req.WebRequestSucceded())
                {
                    Debug.Log("Visual Test Detection: Failed to download dependency asset: " + hash);
                    continue;
                }

                var assetBundle = DownloadHandlerAssetBundle.GetContent(req);
                assetBundle.LoadAllAssets();
                loadedAbs.Add(assetBundle);
            }

            List <GameObject> results = new List <GameObject>();

            foreach (var hash in mainAbs)
            {
                string path = abPath + hash;
                var    req  = UnityWebRequestAssetBundle.GetAssetBundle(path);

                if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX)
                {
                    req.url = req.url.Replace("http://localhost", "file:///");
                }

                req.SendWebRequest();

                while (!req.isDone)
                {
                }

                if (!req.WebRequestSucceded())
                {
                    Debug.Log("Visual Test Detection: Failed to instantiate AB, missing source file for : " + hash);
                    skippedAssets++;
                    continue;
                }

                var      assetBundle = DownloadHandlerAssetBundle.GetContent(req);
                Object[] assets      = assetBundle.LoadAllAssets();

                foreach (Object asset in assets)
                {
                    if (asset is Material material)
                    {
                        material.shader = Shader.Find("DCL/Universal Render Pipeline/Lit");
                    }

                    if (asset is GameObject assetAsGameObject)
                    {
                        GameObject instance = Object.Instantiate(assetAsGameObject);

                        PatchSkeletonlessSkinnedMeshRenderer(instance.GetComponentInChildren <SkinnedMeshRenderer>());

                        results.Add(instance);
                        instance.name = instance.name.Replace("(Clone)", "");
                    }
                }

                loadedAbs.Add(assetBundle);
            }

            foreach (var ab in loadedAbs)
            {
                ab.Unload(false);
            }

            return(results.ToArray());
        }
Exemplo n.º 19
0
 static void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
 {
     if (!Config.Current.Plugins.Has<Trial>()) new Trial().Install(Config.Current);
 }
Exemplo n.º 20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="VertexBuffer" /> class.
        /// </summary>
        /// <param name="attributes">The vertex attributes.</param>
        /// <param name="caching">The data caching policy.</param>
        public VertexBuffer(Attrib attributes, Caching caching = Caching.Static)
        {
            this.attributes = attributes;
            this.caching = caching;
            this.stride = 12;

            if (this.Has(Attrib.Normal))
            {
                this.stride += 12;
            }

            if (this.Has(Attrib.Tangent))
            {
                this.stride += 16;
            }

            if (this.Has(Attrib.Color))
            {
                this.stride += 4;
            }

            if (this.Has(Attrib.UV))
            {
                this.stride += 8;
            }
        }
Exemplo n.º 21
0
 /// <summary>
 /// Specifies the type of distributed program that should be used.  If this is
 /// not declared on the Program class, the program will not be distributed.
 /// </summary>
 /// <param name="network">The type of network architecture.</param>
 /// <param name="cache">The type of caching to use.</param>
 public DistributedAttribute(Architecture network, Caching cache)
 {
     this.Architecture = network;
     this.Caching = cache;
 }
Exemplo n.º 22
0
    static void CreateSceneALL()
    {
        //清空一下缓存
        Caching.CleanCache();

        string path = EditorUtility.OpenFilePanel("请选择要打包的场景", "Assets", "unity");

        if (path == null || path.Length == 0)
        {
            Debug.LogError("请选择打包的场景");
            return;
        }
        if (!Directory.Exists(System.Environment.CurrentDirectory + "\\SceneResources"))
        {
            Directory.CreateDirectory(System.Environment.CurrentDirectory + "\\SceneResources");
        }

        string[] strPath = path.Split('/');
        string   SceneName;

        if (strPath != null && strPath.Length > 0)
        {
            SceneName = strPath[strPath.Length - 1].Split('.')[0];
        }
        else
        {
            SceneName = null;
        }

        //获得用户选择的路径的方法,可以打开保存面板(推荐)
        string Path;

        if (SceneName != null || SceneName.Length > 0)
        {
            Path = EditorUtility.SaveFilePanel("设置场景打包后的文件名和保存路径", "SceneResources", "" + SceneName, "zxy");
        }
        else
        {
            Path = EditorUtility.SaveFilePanel("设置场景打包后的文件名和保存路径", "SceneResources", "" + "SceneName", "zxy");
        }


        if (Path == null || Path.Length == 0)
        {
            Debug.LogError("请选择保存的路径");
            return;
        }

        //另一种获得用户选择的路径,默认把打包后的文件放在Assets目录下
        //string Path = Application.dataPath + "/MyScene.unity3d";



        //选择的要保存的对象
        string[] levels = { path };

        //打包场景
        // BuildPipeline.BuildPlayer(levels, Path, BuildTarget.StandaloneWindows64, BuildOptions.BuildAdditionalStreamedScenes);

        BuildPipeline.BuildStreamedSceneAssetBundle(levels, Path, BuildTarget.StandaloneWindows64, BuildOptions.BuildAdditionalStreamedScenes);


        // 刷新,可以直接在Unity工程中看见打包后的文件
        AssetDatabase.Refresh();
    }
Exemplo n.º 23
0
 internal ResolutionIterator(DomainResolver resolver, DnsClient.DNS.QTYPE question, Caching.AddressCache addressCache)
     : base(resolver, question, addressCache)
 {
     NestingLevel = 0;
 }
        /// <summary>
        /// OnGUI
        /// </summary>
        // -----------------------------------------------------------------------------------------------
        protected virtual void OnGUI()
        {
            this.m_scrollPos = EditorGUILayout.BeginScrollView(this.m_scrollPos);

            bool dummy = true;

            //
            {
                EditorGUIUtility.labelWidth = 250;

                GUILayout.Label("AssetBundle Options", EditorStyles.boldLabel);

                // m_encryptionInfo
                {
                    this.m_encryptionInfo.useEncryption = EditorGUILayout.BeginToggleGroup("Encryption", this.m_encryptionInfo.useEncryption);

                    this.m_encryptionInfo.cryptoVersion = (CryptoVersion)EditorGUILayout.EnumPopup(
                        "Crypto Version",
                        this.m_encryptionInfo.cryptoVersion
                        );

                    this.m_encryptionInfo.encryptedAssetBundlePrefix = EditorGUILayout.TextField(
                        new GUIContent("Prefix of encrypted AssetBundles Name", "prefix"),
                        this.m_encryptionInfo.encryptedAssetBundlePrefix
                        );

                    this.m_encryptionInfo.tempAssetBundlesFolderPath = EditorGUILayout.TextField(
                        new GUIContent("Temp AssetBundles Folder", "Starts with Assets/"),
                        this.m_encryptionInfo.tempAssetBundlesFolderPath
                        );

                    this.m_encryptionInfo.tempEncryptedFolderPath = EditorGUILayout.TextField(
                        new GUIContent("Temp encrypted Folder", "Starts with Assets/"),
                        this.m_encryptionInfo.tempEncryptedFolderPath
                        );

                    if (this.m_encryptionInfo.cryptoVersion == CryptoVersion.Ver1_depricated)
                    {
                        this.m_encryptionInfo.password = EditorGUILayout.TextField(
                            new GUIContent("Password (Length = 16, 24, or 32)", "Password length must be 16, 24, or 32"),
                            this.m_encryptionInfo.password
                            );
                    }

                    else
                    {
                        this.m_encryptionInfo.password = EditorGUILayout.TextField(
                            new GUIContent("Password", "Password"),
                            this.m_encryptionInfo.password
                            );
                    }

                    EditorGUILayout.EndToggleGroup();
                }

                GUILayout.Space(30.0f);

                // m_buildPlatforms
                {
                    GUILayout.Label("Select Platforms", EditorStyles.boldLabel);

                    // buildWindows
                    {
                        this.m_buildPlatforms.buildWindows = EditorGUILayout.BeginToggleGroup("Windows", this.m_buildPlatforms.buildWindows);

                        if (this.m_encryptionInfo.useEncryption)
                        {
                            this.m_buildPlatforms.windowsEncryptedManifestName = EditorGUILayout.TextField(
                                new GUIContent("Windows Encrypted Manifest Name", "Windows Encrypted Manifest Name"),
                                this.m_buildPlatforms.windowsEncryptedManifestName
                                );
                        }

                        else
                        {
                            this.m_buildPlatforms.windowsManifestName = EditorGUILayout.TextField(
                                new GUIContent("Windows Manifest Name", "Windows Manifest Name"),
                                this.m_buildPlatforms.windowsManifestName
                                );
                        }

                        EditorGUILayout.EndToggleGroup();
                    }

                    // builAndroid
                    {
                        this.m_buildPlatforms.builAndroid = EditorGUILayout.BeginToggleGroup("Android", this.m_buildPlatforms.builAndroid);

                        if (this.m_encryptionInfo.useEncryption)
                        {
                            this.m_buildPlatforms.androidEncryptedManifestName = EditorGUILayout.TextField(
                                new GUIContent("Android Encrypted Manifest Name", "Android Encrypted Manifest Name"),
                                this.m_buildPlatforms.androidEncryptedManifestName
                                );
                        }

                        else
                        {
                            this.m_buildPlatforms.androidManifestName = EditorGUILayout.TextField(
                                new GUIContent("Android Manifest Name", "Android Manifest Name"),
                                this.m_buildPlatforms.androidManifestName
                                );
                        }

                        EditorGUILayout.EndToggleGroup();
                    }

                    // buildWindows
                    {
                        this.m_buildPlatforms.buildIos = EditorGUILayout.BeginToggleGroup("iOS", this.m_buildPlatforms.buildIos);

                        if (this.m_encryptionInfo.useEncryption)
                        {
                            this.m_buildPlatforms.iosEncryptedManifestName = EditorGUILayout.TextField(
                                new GUIContent("iOS Encrypted Manifest Name", "iOS Encrypted Manifest Name"),
                                this.m_buildPlatforms.iosEncryptedManifestName
                                );
                        }

                        else
                        {
                            this.m_buildPlatforms.iosManifestName = EditorGUILayout.TextField(
                                new GUIContent("iOS Manifest Name", "iOS Manifest Name"),
                                this.m_buildPlatforms.iosManifestName
                                );
                        }

                        EditorGUILayout.EndToggleGroup();
                    }
                }

                GUILayout.Space(30.0f);

                // m_otherInfo
                {
                    GUILayout.Label("Other Options", EditorStyles.boldLabel);

                    this.m_otherInfo.forceRebuild = EditorGUILayout.Toggle(
                        new GUIContent("Force rebuild AssetBundles", "Force rebuild AssetBundles"),
                        this.m_otherInfo.forceRebuild
                        );

                    this.m_otherInfo.useFakeAssetBundleNames = EditorGUILayout.Toggle(
                        new GUIContent("(Convert variant to name)", "If you got an error 'already loaded' in LoadFromMemoryAsync, try this"),
                        this.m_otherInfo.useFakeAssetBundleNames
                        );
                }

                // button
                {
                    GUILayout.Space(30.0f);

                    EditorGUILayout.BeginHorizontal();

                    GUILayout.Space(250.0f);

                    if (GUILayout.Button("Reset Settings", GUILayout.MinHeight(30)))
                    {
                        GUI.FocusControl("");

                        if (EditorUtility.DisplayDialog("Reset Settings", "Reset ?", "Yes", "No"))
                        {
                            this.resetSettings();
                        }
                    }

                    EditorGUILayout.EndHorizontal();
                }
            }

            // validate
            {
                this.m_encryptionInfo.validate();
            }

            // build
            {
                GUILayout.FlexibleSpace();

                EditorGUILayout.BeginHorizontal(GUI.skin.box);

                if (GUILayout.Button("Clear Editor Cache", GUILayout.MinHeight(30), GUILayout.MaxWidth(150)))
                {
                    if (EditorUtility.DisplayDialog("Clear Editor AssetBundle Cache", "Clear Editor Cache ?", "Yes", "No"))
                    {
#if UNITY_2017_2_OR_NEWER
                        EditorUtility.DisplayDialog("Clear Editor AssetBundle Cache", Caching.ClearCache() ? "Success" : "Failed", "Ok");
#else
                        EditorUtility.DisplayDialog("Clear Editor AssetBundle Cache", Caching.CleanCache() ? "Success" : "Failed", "Ok");
#endif
                    }
                }

                GUILayout.Space(150.0f);

                if (GUILayout.Button("Build AssetBundles", GUILayout.MinHeight(30)))
                {
                    this.build();
                    dummy = false;
                }

                EditorGUILayout.EndHorizontal();
            }

            if (dummy)
            {
                EditorGUILayout.EndScrollView();
            }
        }
Exemplo n.º 25
0
 public NonAxisAlignedBoundingBox GetNonAxisAlignedBoundingBox(Caching.IResourceCache<Microsoft.Xna.Framework.Graphics.Texture2D> cache, Microsoft.Xna.Framework.Matrix globalTransform)
 {
     throw new NotImplementedException();
 }
        private static IEnumerator DownloadCoroutine(int threadNumber)
        {
            Debug.Log(string.Format("DownloadCoroutine #{0} - Started", threadNumber));

            // wait for a frame - to allow functions in call stack
            // (invoked this coroutine) finish their current work
            yield return(null);

            // process entire downloads list
            int idx = 0;

            while (idx < m_downloads.Count)
            {
                // pick only unresolved downloads, i.e. marked as NotStarted
                Download download = m_downloads[idx];
                Debug.Log(string.Format("DownloadCoroutine #{0} - Processing download with state {1}", threadNumber, download.state));
                if (download.state == Download.State.NotStarted)
                {
                    Debug.Log(string.Format("DownloadCoroutine #{0} - Found new task, GUID = \"{1}\"", threadNumber, download.GUID));

                    bool downloaded     = false;
                    bool cacheBreakdown = false;
                    int  urlIndex       = 0;
                    for (urlIndex = 0; urlIndex < download.Urls.Length; ++urlIndex)
                    {
                        Debug.Log(string.Format("DownloadCoroutine #{0} - Got URL #{1}: \"{2}\" (ver. {3})", threadNumber, urlIndex, download.Urls[urlIndex], download.version));
                        if (download.Urls[urlIndex].Contains("http"))
                        {
                            download.CurDownloadSource = Download.DownloadSource.Online;
                        }
                        else
                        {
                            download.CurDownloadSource = Download.DownloadSource.Cache;
                        }
                        int attempt = 0;
                        for (attempt = 0; attempt < TriesCount; ++attempt) // attempt to get required file
                        {
                            // if we're going to request the same file twice, lets make a pause
                            if (/*(urlIndex > 0) || */ (attempt > 0))
                            {
                                Debug.Log(string.Format("DownloadCoroutine #{0} - Waiting for the delay ({1} seconds), because previous attempt has failed", threadNumber, DelayBeforeRetry));
                                yield return(new WaitForSeconds(DelayBeforeRetry));
                            }

                            if (RTUtils.UncompressedAssetBundlesAllowed)
                            {
                                // try to catch asset bundle out from the StreamingAssets
                                try
                                {
                                    string filename = download.Urls[urlIndex].Substring(download.Urls[urlIndex].IndexOf("://") + 3);
                                    if ((download.version >= 0) && File.Exists(filename) && ShouldAssetBundleBeTriedAsUncompressed(filename))
                                    {
                                        download.OfflineAssetBundle = AssetBundle.CreateFromFile(filename);
                                        downloaded = (download.OfflineAssetBundle != null);
                                        Debug.Log(string.Format("DownloadCoroutine #{0} - CreateFromFile - Created from the StreamingAssets with result: {1}", threadNumber, downloaded));
                                        if (downloaded)
                                        {
                                            download.cacheStatus = Download.CacheStatus.NotCached;
                                            break;
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    Debug.Log(string.Format("DownloadCoroutine #{0} - CreateFromFile - Caught exception: {1}", threadNumber, e.ToString()));
                                }
                            }

                            // try to download. Check, whether version has been specified
                            Debug.Log(string.Format("DownloadCoroutine #{0} - Trying to download (attempt #{1})", threadNumber, attempt));
                            if (download.version >= 0)
                            {
                                // file could be downloaded from server as well as from cache
                                Debug.Log(string.Format("DownloadCoroutine #{0} - LoadFromCacheOrDownload", threadNumber));
                                download.state = Download.State.Loading;

                                bool warned = false;
#if UNITY_EDITOR
                                // wait until cache would be cleaned
                                warned = false;
                                while (!m_isCacheCleaned)
                                {
                                    if (!warned)
                                    {
                                        Debug.Log(string.Format("DownloadCoroutine #{0} - Waiting until cache would be cleaned", threadNumber));
                                        warned = true;
                                    }
                                    yield return(null);
                                }
#endif

                                // cache could be in invalid state, wait until it would be validated
                                warned = false;
                                while (!Caching.ready)
                                {
                                    if (!warned)
                                    {
                                        Debug.Log(string.Format("DownloadCoroutine #{0} - Waiting until Caching.ready would be true", threadNumber));
                                        warned = true;
                                    }
                                    yield return(null);
                                }

                                bool alreadyCached = Caching.IsVersionCached(download.Urls[urlIndex], download.version);
                                download.www = WWW.LoadFromCacheOrDownload(SpecializeURL(download.Urls[urlIndex]), download.version);
                                yield return(UnityEntity.Instance.StartCoroutine(WWWCoroutine(download.www)));

                                if (WWWSucceeded(download.www))
                                {
                                    Debug.Log(string.Format("DownloadCoroutine #{0} - Downloaded successfully", threadNumber));
                                    if (Caching.IsVersionCached(download.Urls[urlIndex], download.version))
                                    {
                                        Debug.Log(string.Format("DownloadCoroutine #{0} - Cached successfully", threadNumber));
                                        download.cacheStatus = alreadyCached ? Download.CacheStatus.AlreadyCached : Download.CacheStatus.JustCached;
                                        downloaded           = true;
                                        break;
                                    }
                                    else
                                    {
                                        // most likely this means, no free space on HDD
                                        Debug.LogWarning(string.Format("DownloadCoroutine #{0} - Failed to cache", threadNumber));
                                        download.cacheStatus = Download.CacheStatus.Breakdown;
                                        cacheBreakdown       = true;
                                    }
                                }
                                else
                                {
                                    download.cacheStatus = Download.CacheStatus.NotCached;
                                }

                                Assertion.Check(!downloaded); // SANITY CHECK
                                Debug.Log(string.Format("DownloadCoroutine #{0} - Failed to download and cache", threadNumber));
                                Debug.Log(string.Format("DownloadCoroutine #{0} - WWW properties are URL:\"{1}\", isDone:{2}, error:\"{3}\", progress sent/received:{4}/{5}", threadNumber, download.www.url, download.www.isDone, download.www.error, download.www.uploadProgress, download.www.progress));
                                Debug.Log(string.Format("DownloadCoroutine #{0} - IsVersionCached:{1}", threadNumber, Caching.IsVersionCached(download.Urls[urlIndex], download.version)));
                                Debug.Log(string.Format("DownloadCoroutine #{0} - Caching enabled:{1}, ready:{2}, expirationDelay:{3}", threadNumber, Caching.enabled, Caching.ready, Caching.expirationDelay));


                                //patch
                                if (!String.IsNullOrEmpty(download.www.error) && download.www.error.Contains("Cannot load cached AssetBundle."))
                                {
                                    PlayerPrefs.SetInt("ForceCleanCache", 1);
                                    PlayerPrefs.Save();
                                }

#if !UNITY_EDITOR
                                // FIXME: this doesn't help. Remove it later
                                // HACK: to try to catch unbelievable www.error, to be exact:
                                // "Cannot load cached AssetBundle. A file of the same name is already loaded from another AssetBundle."
                                try
                                {
                                    AssetBundle assetBundle = download.www.assetBundle;
                                    if (assetBundle != null)
                                    {
                                        Debug.LogWarning(string.Format("DownloadCoroutine #{0} - Asset bundle failed to load was instantiated! Unloading it immediately!", threadNumber));
                                        assetBundle.Unload(true);
                                    }
                                    else
                                    {
                                        Debug.Log(string.Format("DownloadCoroutine #{0} - AssetBundle is null", threadNumber));
                                    }
                                }
                                catch (Exception e)
                                {
                                    Debug.LogWarning(string.Format("DownloadCoroutine #{0} - Caught exception: {1}", threadNumber, e.ToString()));
                                }
#endif
                            }
                            else if (download.version == VERSION_FORCE_REDOWNLOAD)
                            {
                                // file should be downloaded from server
                                Debug.Log(string.Format("DownloadCoroutine #{0} - Download", threadNumber));
                                download.state = Download.State.Loading;
                                download.www   = new WWW(SpecializeURL(HackUrl(download.Urls[urlIndex])));
                                yield return(UnityEntity.Instance.StartCoroutine(WWWCoroutine(download.www)));

                                if (WWWSucceeded(download.www))
                                {
                                    Debug.Log(string.Format("DownloadCoroutine #{0} - Downloaded successfully", threadNumber));
                                    downloaded = true;
                                    break;
                                }

                                Assertion.Check(!downloaded); // SANITY CHECK
                                Debug.Log(string.Format("DownloadCoroutine #{0} - Failed to download", threadNumber));
                                Debug.Log(string.Format("DownloadCoroutine #{0} - WWW properties are URL:\"{1}\", isDone:{2}, error:\"{3}\", progress sent/received:{4}/{5}", threadNumber, download.www.url, download.www.isDone, download.www.error, download.www.uploadProgress, download.www.progress));
                            }
                            else
                            {
                                // do nothing, and download will be just failed
                                Debug.LogWarning(string.Format("DownloadCoroutine #{0} - Not implemented", threadNumber));
                            }

                            Assertion.Check(!downloaded); // SANITY CHECK
                            if (download.www != null)
                            {
                                try
                                {
                                    // HACK: to try to dismiss connection failed because of fired timeout
                                    download.www.Dispose();
                                }
                                catch (Exception e)
                                {
                                    Debug.LogWarning(string.Format("DownloadCoroutine #{0} - Caught exception: {1}", threadNumber, e.ToString()));
                                }
                                finally
                                {
                                    Debug.Log(string.Format("DownloadCoroutine #{0} - Reseting WWW to null", threadNumber));
                                    download.www = null;
                                }
                            }

                            // at this point attempt failed
                            download.state = Download.State.WaitingBeforeRetry;
                            Debug.Log(string.Format("DownloadCoroutine #{0} - Failed to download", threadNumber));

                            if (cacheBreakdown)
                            {
                                ++attempt; // just to match actual count on leave
                                break;
                            }
                        }

                        if (downloaded) // succeeded to download a file
                        {
                            // mark download as finished (successfully finished)
                            download.state = Download.State.Downloaded;
                            Debug.Log(string.Format("DownloadCoroutine #{0} - Downloaded successfully", threadNumber));

                            // let postprocess delegate know result
                            if (download.onDownloadCallback != null)
                            {
                                try
                                {
                                    Debug.Log(string.Format("DownloadCoroutine #{0} - Invoking OnDownloadCallback", threadNumber));
                                    downloaded = download.onDownloadCallback(Info.Retrieve(download.GUID));
                                }
                                catch (Exception e)
                                {
                                    Debug.LogError(string.Format("DownloadCoroutine #{0} - Caught exception, thrown by callback: {1}", threadNumber, e.ToString()));
                                    downloaded = false;
                                }
                            }

                            if (downloaded) // succeeded to download a file
                            {
                                break;
                            }
                            else
                            {
                                Debug.LogWarning(string.Format("DownloadCoroutine #{0} - Forced to fail download", threadNumber));
                            }
                        }

                        if (!downloaded) // all our attempts to download from current URL were without effect
                        {
                            download.state = Download.State.WaitingBeforeRetry;
                            Debug.Log(string.Format("DownloadCoroutine #{0} - Tried URL up to {1} times with no success", threadNumber, attempt));
                        }

                        if (cacheBreakdown)
                        {
                            ++urlIndex; // just to match actual count on leave
                            break;
                        }
                    }

                    if (!downloaded) // all our attempts to download from all URLS were without effect
                    {
                        // mark download as finished (failed)
                        download.state = Download.State.Abandoned;
                        Debug.Log(string.Format("DownloadCoroutine #{0} - Tried {1} links and failed in the end", threadNumber, urlIndex));

                        // let postprocess delegate know result
                        if (download.onDownloadCallback != null)
                        {
                            try
                            {
                                Debug.Log(string.Format("DownloadCoroutine #{0} - Invoking OnDownloadCallback", threadNumber));
                                download.onDownloadCallback(Info.Retrieve(download.GUID));
                            }
                            catch (Exception e)
                            {
                                Debug.LogError(string.Format("DownloadCoroutine #{0} - Caught exception, thrown by callback: {1}", threadNumber, e.ToString()));
                            }
                        }
                    }

                    // remove resolved download from list
                    Debug.Log(string.Format("DownloadCoroutine #{0} - Remove task from the list, GUID = \"{1}\"", threadNumber, download.GUID));
                    m_downloads.Remove(download);
                    idx = 0;
                }
                else if (download.state == Download.State.DoNotDownload)
                {
                    // remove skipped download from list
                    m_downloads.RemoveAt(idx);
                    Debug.Log(string.Format("DownloadCoroutine #{0} - Removed skipped task, GUID = \"{1}\"", threadNumber, download.GUID));
                }
                else
                {
                    // look for next download in list
                    Debug.Log(string.Format("DownloadCoroutine #{0} - Look for next download", threadNumber));
                    ++idx;
                }

                // if suddenly granted limit of threads was decreased during downloading, lets finish freed coroutine
                // TODO: choose the coroutine to be stopped in more flexible way
                if (threadNumber >= ThreadCount)
                {
                    Debug.Log(string.Format("DownloadCoroutine #{0} - Allowed thread count has decreased (actually, {1}). Exitting", threadNumber, ThreadCount));
                    break;
                }

                // following pause is required for the reasons
                // 1) downloads list could contain a lot of files,
                // make a pause to allow Unity to process its tasks;
                // 2) more important, uncompressed asset bundles
                // must not be loaded all in one frame.
                yield return(null);
            }

            // mark, that coroutine is going to finish its work
            m_downloadCoroutines.Remove(threadNumber);
            Debug.Log(string.Format("DownloadCoroutine #{0} - Finished", threadNumber));
        }
Exemplo n.º 27
0
        /// <summary>
        /// This is where we hijack the resizing process, interrupt it, and send
        /// back the json data we created.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="context"></param>
        /// <param name="e"></param>
        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            if (!this.IsDiagnosticRequest(e.RewrittenQuerystring)) return;

            AlternateResponseException.InjectExceptionHandler(e as ImageResizer.Caching.ResponseArgs);
        }
Exemplo n.º 28
0
        /// <summary>
        /// load assetbundle manifest, check hash, load actual bundle with hash parameter to use caching
        /// instantiate gameobject
        /// </summary>
        /// <param name="bundleURL">full url to assetbundle file</param>
        /// <param name="assetName">optional parameter to access specific asset from assetbundle</param>
        /// <returns></returns>
        IEnumerator DownloadAndCache(string bundleURL, string assetName = "")
        {
            // Wait for the Caching system to be ready
            while (!Caching.ready)
            {
                yield return(null);
            }

            // if you want to always load from server, can clear cache first
            //        Caching.CleanCache();

            // get current bundle hash from server, random value added to avoid caching
            UnityWebRequest www = UnityWebRequest.Get(bundleURL + ".manifest?r=" + (Random.value * 9999999));

            Debug.Log("Loading manifest:" + bundleURL + ".manifest");

            // wait for load to finish
            yield return(www.Send());

            // if received error, exit
            if (www.isNetworkError == true)
            {
                Debug.LogError("www error: " + www.error);
                www.Dispose();
                www = null;
                yield break;
            }

            // create empty hash string
            Hash128 hashString = (default(Hash128));// new Hash128(0, 0, 0, 0);

            // check if received data contains 'ManifestFileVersion'
            if (www.downloadHandler.text.Contains("ManifestFileVersion"))
            {
                // extract hash string from the received data, TODO should add some error checking here
                var hashRow = www.downloadHandler.text.ToString().Split("\n".ToCharArray())[5];
                hashString = Hash128.Parse(hashRow.Split(':')[1].Trim());

                if (hashString.isValid == true)
                {
                    // we can check if there is cached version or not
                    if (Caching.IsVersionCached(bundleURL, hashString) == true)
                    {
                        Debug.Log("Bundle with this hash is already cached!");
                    }
                    else
                    {
                        Debug.Log("No cached version founded for this hash..");
                    }
                }
                else
                {
                    // invalid loaded hash, just try loading latest bundle
                    Debug.LogError("Invalid hash:" + hashString);
                    yield break;
                }
            }
            else
            {
                Debug.LogError("Manifest doesn't contain string 'ManifestFileVersion': " + bundleURL + ".manifest");
                yield break;
            }

            // now download the actual bundle, with hashString parameter it uses cached version if available
            www = UnityWebRequest.GetAssetBundle(bundleURL + "?r=" + (Random.value * 9999999), hashString, 0);

            // wait for load to finish
            yield return(www.Send());

            if (www.error != null)
            {
                Debug.LogError("www error: " + www.error);
                www.Dispose();
                www = null;
                yield break;
            }

            // get bundle from downloadhandler
            AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;

            GameObject bundlePrefab = null;

            // if no asset name is given, take the first/main asset
            if (assetName == "")
            {
                bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]);
            }
            else
            { // use asset name to access inside bundle
                bundlePrefab = (GameObject)bundle.LoadAsset(assetName);
            }

            // if we got something out
            if (bundlePrefab != null)
            {
                // instantiate at 0,0,0 and without rotation
                Instantiate(bundlePrefab, Vector3.zero, Quaternion.identity);

                /*
                 * // fix pink shaders, NOTE: not always needed..
                 * foreach (Renderer r in go.GetComponentsInChildren<Renderer>(includeInactive: true))
                 * {
                 *  // FIXME: creates multiple materials, not good
                 *  var material = Shader.Find(r.material.shader.name);
                 *  r.material.shader = null;
                 *  r.material.shader = material;
                 * }*/
            }

            www.Dispose();
            www = null;

            // try to cleanup memory
            Resources.UnloadUnusedAssets();
            bundle.Unload(false);
            bundle = null;
        }
Exemplo n.º 29
0
 [MenuItem("Window/Autoya/Clean Cached AssetBundles")] public static void CleanCache()
 {
     Caching.CleanCache();
 }
        /**
         *              load assetBundle on memory.
         */
        private IEnumerator LoadAssetBundleOnMemory <T>(
            string bundleName,
            string assetName,
            uint crc,
            Hash128 hash,
            Action <string, T> loadSucceeded,
            Action <string, AssetBundleLoadError, string, AutoyaStatus> loadFailed,
            long timeoutTick,
            bool isDependency = false,
            List <string> loadingDependentBundleNames = null
            ) where T : UnityEngine.Object
        {
            while (!Caching.ready)
            {
                yield return(null);
            }

            var assetBundleInfo = bundleListStorage.AssetBundleInfoFromBundleName(bundleName);


            if (AssetBundleInfo.IsEmpty(assetBundleInfo))
            {
                // no assetBundleInfo found.
                loadFailed(assetName, AssetBundleLoadError.NoAssetBundleFoundInList, "no assetBundle found:" + bundleName + " in list.", new AutoyaStatus());
                yield break;
            }

            var dependentBundleNames = assetBundleInfo.dependsBundleNames;

            var dependentBundleLoadErrors = new List <DependentBundleError>();

            /*
             *                  resolve dependencies.
             */
            {
                if (dependentBundleNames.Any())
                {
                    var coroutines = new Dictionary <string, IEnumerator>();

                    foreach (var dependentBundleName in dependentBundleNames)
                    {
                        if (loadingDependentBundleNames != null)
                        {
                            if (loadingDependentBundleNames.Contains(dependentBundleName))
                            {
                                continue;
                            }
                        }

                        // skip if assetBundle is already loaded on memory.
                        if (onMemoryCache.ContainsKey(dependentBundleName) && onMemoryCache[dependentBundleName] != null)
                        {
                            continue;
                        }

                        var dependedBundleInfo = bundleListStorage.AssetBundleInfoFromBundleName(dependentBundleName);
                        if (AssetBundleInfo.IsEmpty(dependedBundleInfo))
                        {
                            // skip empty info.
                            continue;
                        }

                        var dependentBundleCrc  = dependedBundleInfo.crc;
                        var dependentBundleHash = Hash128.Parse(dependedBundleInfo.hash);

                        // set UnityEngine.Object for request. this asset will never use directory.
                        var loadCoroutine = LoadAssetBundleOnMemory <UnityEngine.Object>(
                            dependentBundleName,
                            string.Empty,// bundleName not required.
                            dependentBundleCrc,
                            dependentBundleHash,
                            (depBundleName, depObj) =>
                        {
                            // do nothing. this bundle is currently on memory.
                        },
                            (depBundleName, depErr, depReason, autoyaStatus) =>
                        {
                            // collect error for this dependent bundle loading.
                            dependentBundleLoadErrors.Add(new DependentBundleError(depBundleName, depErr, depReason, autoyaStatus));
                        },
                            timeoutTick,
                            true, // this loading is for resolve dependency of root asset. no need to return any instances.
                            loadingDependentBundleNames
                            );

                        if (loadingDependentBundleNames != null)
                        {
                            loadingDependentBundleNames.Add(dependentBundleName);
                        }
                        coroutines[dependentBundleName] = loadCoroutine;
                    }

                    if (coroutines.Count != 0)
                    {
                        while (true)
                        {
                            if (!coroutines.Where(c => c.Value != null).Any())
                            {
                                // load done.
                                break;
                            }

                            for (var i = 0; i < coroutines.Count; i++)
                            {
                                var loadingAssetBundleName = coroutines.Keys.ToArray()[i];
                                var coroutine = coroutines[loadingAssetBundleName];
                                if (coroutine == null)
                                {
                                    continue;
                                }

                                if (!coroutine.MoveNext())
                                {
                                    coroutines[loadingAssetBundleName] = null;
                                }
                            }
                            yield return(null);
                        }

                        // all dependencies are loaded on memory.
                    }
                }
            }

            var url = GetAssetBundleDownloadUrl(bundleName);

            // check now loading or not. if same bundle is already under loading, wait it here.
            if (loadingAssetBundleNames.Contains(bundleName))
            {
                while (loadingAssetBundleNames.Contains(bundleName))
                {
                    yield return(null);
                }

                // check downloaded bundle is correctly cached or not.
                var isCached = Caching.IsVersionCached(url, hash);
                if (!isCached)
                {
                    loadFailed(assetName, AssetBundleLoadError.DownloadFailed, "caching failed.", new AutoyaStatus());
                    yield break;
                }
            }

            // assetBundle is already allocated on memory.
            if (onMemoryCache.ContainsKey(bundleName))
            {
                var isCached = Caching.IsVersionCached(url, hash);

                if (isCached)
                {
                    // if current target is dependency, dependent assetBundle is already on memory. and no need to load it.
                    if (isDependency)
                    {
                        yield break;
                    }

                    // start loading assetBundle on memory.
                    var loadOnMemoryCachedAssetCoroutine = LoadOnMemoryAssetAsync(bundleName, assetName, loadSucceeded, loadFailed);
                    while (loadOnMemoryCachedAssetCoroutine.MoveNext())
                    {
                        yield return(null);
                    }

                    // loading asset from on memory cache is done.
                    yield break;
                }

                // assetBundle is cached on memory but it's not target hashed bundle. need to download other one.
                var oldOnMemoryAssetBundle = onMemoryCache[bundleName];

                // remove from on memory cache.
                UnloadOnMemoryAssetBundle(bundleName);
            }

            /*
             *                  assetBundle is..
             *                          not yet cached (or) already cached.
             *                          not allocated on memory.
             *
             *                  assetBundle is not on memory yet. start downloading.
             */

            // binded block.
            using (var loadingConstraint = new AssetBundleLoadingConstraint(bundleName, loadingAssetBundleNames))
            {
                /*
                 *                      download bundle or load donwloaded bundle from cache.
                 *                      load to memory.
                 */
                {
                    var downloadCoroutine = DownloadAssetThenCacheAndLoadToMemory(bundleName, assetName, url, crc, hash, loadFailed, timeoutTick);
                    while (downloadCoroutine.MoveNext())
                    {
                        yield return(null);
                    }

                    if (!onMemoryCache.ContainsKey(bundleName))
                    {
                        // error is already fired in above.
                        yield break;
                    }

                    if (!isDependency)
                    {
                        /*
                         *                              break if dependent bundle has load error.
                         */
                        if (dependentBundleLoadErrors.Any())
                        {
                            var loadErrorBundleMessages = new StringBuilder();
                            loadErrorBundleMessages.Append("failed to load/download dependent bundle:");
                            foreach (var dependentBundleLoadError in dependentBundleLoadErrors)
                            {
                                loadErrorBundleMessages.Append("bundleName:");
                                loadErrorBundleMessages.Append(dependentBundleLoadError.bundleName);
                                loadErrorBundleMessages.Append(" error:");
                                loadErrorBundleMessages.Append(dependentBundleLoadError.err);
                                loadErrorBundleMessages.Append(" reason:");
                                loadErrorBundleMessages.Append(dependentBundleLoadError.reason);
                                loadErrorBundleMessages.Append(" autoyaStatus:");
                                loadErrorBundleMessages.Append("  inMaintenance:" + dependentBundleLoadError.status.inMaintenance);
                                loadErrorBundleMessages.Append("  isAuthFailed:" + dependentBundleLoadError.status.isAuthFailed);
                            }
                            loadFailed(assetName, AssetBundleLoadError.FailedToLoadDependentBundles, loadErrorBundleMessages.ToString(), new AutoyaStatus());

                            yield break;
                        }

                        /*
                         *                              load asset from on memory AssetBundle.
                         */
                        var loadAssetCoroutine = LoadOnMemoryAssetAsync(bundleName, assetName, loadSucceeded, loadFailed);
                        while (loadAssetCoroutine.MoveNext())
                        {
                            yield return(null);
                        }
                    }
                }
            }
        }
Exemplo n.º 31
0
 static void CleanCache()
 {
     Caching.ClearCache();
 }
        /**
         *  Downloads the asset bundle.
         */
        public IEnumerator DownloadAssetBundle(
            string bundleName,
            string connectionId,
            Dictionary <string, string> requestHeader,
            string url,
            uint crc,
            Hash128 hash,
            Action <string, int, Dictionary <string, string>, AssetBundle> succeeded,
            Action <string, int, string, Dictionary <string, string> > failed,
            long limitTick
            )
        {
            var alreadyStorageCached = false;

            if (Caching.IsVersionCached(url, hash))
            {
                alreadyStorageCached = true;
            }

            using (var request = UnityWebRequest.GetAssetBundle(url, hash, crc))
            {
                if (requestHeader != null)
                {
                    foreach (var kv in requestHeader)
                    {
                        request.SetRequestHeader(kv.Key, kv.Value);
                    }
                }

                var p = request.SendWebRequest();

                while (!p.isDone)
                {
                    yield return(null);

                    // check timeout.
                    if (limitTick != 0 && limitTick < DateTime.UtcNow.Ticks)
                    {
                        request.Abort();
                        failed(connectionId, BackyardSettings.HTTP_TIMEOUT_CODE, "timeout to download bundle:" + bundleName, new Dictionary <string, string>());
                        yield break;
                    }
                }

                while (!request.isDone)
                {
                    yield return(null);
                }

                var responseCode    = (int)request.responseCode;
                var responseHeaders = request.GetResponseHeaders();

                if (request.isNetworkError)
                {
                    failed(connectionId, responseCode, request.error, responseHeaders);
                    yield break;
                }

                if (alreadyStorageCached)
                {
                    // set response code to 200 manually if already cached and succeeded to load from cache.
                    // sadly, in this case, the code is not 200 by default.
                    responseCode    = 200;
                    responseHeaders = new Dictionary <string, string>();
                }
                else
                {
                    if (200 <= responseCode && responseCode <= 299)
                    {
                        // do nothing.
                    }
                    else
                    {
                        failed(connectionId, responseCode, "failed to load assetBundle. downloaded bundle:" + bundleName + " was not downloaded.", responseHeaders);
                        yield break;
                    }
                }

                var dataHandler = (DownloadHandlerAssetBundle)request.downloadHandler;

                var assetBundle = dataHandler.assetBundle;

                if (assetBundle == null)
                {
                    responseCode = CODE_CRC_MISMATCHED;
                    failed(connectionId, responseCode, "failed to load assetBundle. downloaded bundle:" + bundleName + ", requested crc was not matched.", responseHeaders);
                    yield break;
                }

                // wait for cache.
                while (!Caching.IsVersionCached(url, hash))
                {
                    yield return(null);
                }

                succeeded(connectionId, responseCode, responseHeaders, assetBundle);
            }
        }
Exemplo n.º 33
0
    public IEnumerator LoadAssets(Action onDisconnectMethod = null)
    {
        m_CurState      = eVCstate.ASSET_DOWNLOADING;
        DOWNLOADED_SIZE = 0;

        OnDisconnectNetwork = onDisconnectMethod;
        var havDict    = m_CurHavingInfo.AssetDict;
        var serverDict = m_LoadedServerInfo.AssetDict;

        foreach (var kvPair in serverDict)
        {
            string assetName = kvPair.Key;

            bool isNewDownload = true;

            if (Caching.IsVersionCached(kvPair.Key, (int)kvPair.Value.Version) == true)
            {
                isNewDownload = false;
            }

            if (havDict.ContainsKey(kvPair.Key))
            {
                if (havDict[kvPair.Key].Version >= kvPair.Value.Version)
                {
                    continue;
                }
            }

            bool isPlatformManifest = false;
            if (assetName.Equals(AssetBundleManager.strPlatformManifestName) == true)
            {
                isPlatformManifest = true;
            }

            string assetURL = "datapath";

            double startFileSize       = m_HavingAssetSize;
            double startDownloadedSize = DOWNLOADED_SIZE;

            using (UnityWebRequest loadAsset_u = UnityWebRequestAssetBundle.GetAssetBundle(assetURL, (uint)kvPair.Value.Version, 0))
            {
                loadAsset_u.SendWebRequest();

                while (loadAsset_u.isDone == false)
                {
                    double increasedSize = kvPair.Value.FileSize * (double)loadAsset_u.downloadProgress;
                    m_HavingAssetSize = startFileSize + increasedSize;

                    if (isNewDownload == true)
                    {
                        DOWNLOADED_SIZE = startDownloadedSize + increasedSize;
                    }

                    if (Application.internetReachability == NetworkReachability.NotReachable)
                    {
                        _OnDisconnectNetwork();
                        m_CurState = eVCstate.ASSET_DOWN_FAILED;
                        yield break;
                    }

                    if (loadAsset_u.error != null)
                    {
                        if (!loadAsset_u.error.Contains("another AssetBundle with the same files is already loaded"))
                        {
                            Debug.LogError("WWW Error : " + loadAsset_u.error);
                            m_CurState = eVCstate.ASSET_DOWN_FAILED;
                            yield break;
                        }
                    }

                    yield return(null);
                }

                if (loadAsset_u.error != null)
                {
                    if (!loadAsset_u.error.Contains("another AssetBundle with the same files is already loaded"))
                    {
                        Debug.LogError("WWW Error : " + loadAsset_u.error);
                        m_CurState = eVCstate.ASSET_DOWN_FAILED;
                        yield break;
                    }
                }

                m_HavingAssetSize = startFileSize + kvPair.Value.FileSize;

                if (isNewDownload == true)
                {
                    DOWNLOADED_SIZE = startDownloadedSize + kvPair.Value.FileSize;
                    NEED_DOWNLOAD--;
                    if (NEED_DOWNLOAD <= 0)
                    {
                        NEED_DOWNLOAD = 0;
                    }
                }

                m_CurHavingInfo.AssetDict[kvPair.Key] = kvPair.Value;


                if (isPlatformManifest == false)
                {
                    AssetBundle loadedBundle = DownloadHandlerAssetBundle.GetContent(loadAsset_u);

                    if (loadedBundle != null)
                    {
                        loadedBundle.Unload(true);
                    }
                }
            }

            SaveCurVerInfo();
        }

        OnFinishDownAsset();



        //      m_CurState = eVCstate.ASSET_DOWNLOADING;
        //      DOWNLOADED_SIZE = 0;

        //      OnDisconnectNetwork = onDisconnectMethod;
        //var havDict = m_CurHavingInfo.AssetDict;
        //var serverDict = m_LoadedServerInfo.AssetDict;
        //      foreach (var kvPair in serverDict)
        //{
        //	string assetName = kvPair.Key;

        //          bool isNewDownload = true;

        //          if (Caching.IsVersionCached(kvPair.Key, (int)kvPair.Value.Version) == true)
        //              isNewDownload = false;

        //          bool isPlatformManifest = false;
        //          if (assetName.Equals(AssetBundleManager.strPlatformManifestName) == true)
        //          {
        //              isPlatformManifest = true;
        //          }

        //	string assetURL = CachedBaseURL + assetName;

        //	double startFileSize = m_HavingAssetSize;
        //	double startDownloadedSize = DOWNLOADED_SIZE;

        //          using (UnityWebRequest loadAsset_u = UnityWebRequest.GetAssetBundle(assetURL, (uint)kvPair.Value.Version, 0))
        //	{
        //              loadAsset_u.SendWebRequest();

        //		while (loadAsset_u.isDone == false)
        //		{
        //			double increasedSize = kvPair.Value.FileSize * (double)loadAsset_u.downloadProgress;
        //			m_HavingAssetSize = startFileSize + increasedSize; // ���� ��� ������ ����

        //			if (isNewDownload == true)
        //				DOWNLOADED_SIZE = startDownloadedSize + increasedSize;

        //                  //Debug.Log(Application.internetReachability.ToString());
        //                  if( Application.internetReachability == NetworkReachability.NotReachable)
        //                  {
        //                      _OnDisconnectNetwork();
        //                      m_CurState = eVCstate.ASSET_DOWN_FAILED;
        //                      yield break;
        //                  }

        //                  if (loadAsset_u.error != null)
        //                  {
        //                      if (!loadAsset_u.error.Contains("another AssetBundle with the same files is already loaded"))
        //                      {
        //                          Debug.LogError("WWW Error : " + loadAsset_u.error);
        //                          m_CurState = eVCstate.ASSET_DOWN_FAILED;
        //                          yield break;
        //                      }
        //                  }

        //                  yield return null;
        //		}

        //		if (loadAsset_u.error != null)
        //		{
        //			if (!loadAsset_u.error.Contains("another AssetBundle with the same files is already loaded"))
        //			{
        //				Debug.LogError("WWW Error : " + loadAsset_u.error);
        //				m_CurState = eVCstate.ASSET_DOWN_FAILED;
        //				yield break;
        //			}
        //		}

        //		m_HavingAssetSize = startFileSize + kvPair.Value.FileSize;

        //		if (isNewDownload == true)
        //		{
        //			DOWNLOADED_SIZE = startDownloadedSize + kvPair.Value.FileSize;
        //			//Debug.Log("Cur Downloaded Size : " + DOWNLOADED_SIZE.ToString());
        //			NEED_DOWNLOAD--;
        //		}

        //		m_CurHavingInfo.AssetDict[kvPair.Key] = kvPair.Value;

        //              if (isPlatformManifest == false)
        //              {
        //                  AssetBundle loadedBundle = DownloadHandlerAssetBundle.GetContent(loadAsset_u);

        //                  if (loadedBundle != null)
        //                      loadedBundle.Unload(true);
        //              }
        //	}

        //          SaveCurVerInfo();
        //      }

        //      OnFinishDownAsset();
    }
 internal PublicationSettings(IPublicationPackage publicationPackage, Caching caching = Caching.Enabled) : base(caching)
 {
     PublicationPackage = publicationPackage;
     RetrieveFunc       = GetPublicationSettings;
 }
Exemplo n.º 35
0
        internal UnityWebRequest CreateWebRequest(IResourceLocation loc)
        {
            var             url        = m_ProvideHandle.ResourceManager.TransformInternalId(loc);
            UnityWebRequest webRequest = null;

            if (m_dataProc == null)
            {
                if (m_Options == null)
                {
                    return(UnityWebRequestAssetBundle.GetAssetBundle(url));
                }

                if (!string.IsNullOrEmpty(m_Options.Hash))
                {
                    CachedAssetBundle cachedBundle = new CachedAssetBundle(m_Options.BundleName, Hash128.Parse(m_Options.Hash));
#if ENABLE_CACHING
                    if (m_Options.UseCrcForCachedBundle || !Caching.IsVersionCached(cachedBundle))
                    {
                        webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle, m_Options.Crc);
                    }
                    else
                    {
                        webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle);
                    }
#else
                    webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, cachedBundle, m_Options.Crc);
#endif
                }
                else
                {
                    webRequest = UnityWebRequestAssetBundle.GetAssetBundle(url, m_Options.Crc);
                }
            }
            else
            {
                webRequest = new UnityWebRequest(loc.InternalId);
                DownloadHandlerBuffer dH = new DownloadHandlerBuffer();
                webRequest.downloadHandler = dH;
            }

            if (webRequest == null)
            {
                return(webRequest);
            }

            if (m_Options != null)
            {
                if (m_Options.Timeout > 0)
                {
                    webRequest.timeout = m_Options.Timeout;
                }
                if (m_Options.RedirectLimit > 0)
                {
                    webRequest.redirectLimit = m_Options.RedirectLimit;
                }
#if !UNITY_2019_3_OR_NEWER
                webRequest.chunkedTransfer = m_Options.ChunkedTransfer;
#endif
            }
            if (m_ProvideHandle.ResourceManager.CertificateHandlerInstance != null)
            {
                webRequest.certificateHandler = m_ProvideHandle.ResourceManager.CertificateHandlerInstance;
                webRequest.disposeCertificateHandlerOnDispose = false;
            }
            return(webRequest);
        }
Exemplo n.º 36
0
        public IEnumerator Preload(AssetBundleLoader loader, PreloadList preloadList, Action <string[], Action, Action> onBeforePreloading, Action <double> progress, Action done, Action <int, string, AutoyaStatus> preloadFailed, Action <string, AssetBundleLoadError, string, AutoyaStatus> bundlePreloadFailed, int maxParallelCount = 1)
        {
            if (0 < maxParallelCount)
            {
                // pass.
            }
            else
            {
                yield return(null);

                preloadFailed(-1, "maxParallelCount is negative or 0. unable to start preload.", new AutoyaStatus());
                yield break;
            }

            if (loader != null)
            {
                // pass.
            }
            else
            {
                yield return(null);

                preloadFailed(-1, "attached AssetBundleLoader is null. unable to start preload.", new AutoyaStatus());
                yield break;
            }

            if (preloadList != null)
            {
                // pass.
            }
            else
            {
                yield return(null);

                preloadFailed(-1, "preloadList is null. unable to start preload.", new AutoyaStatus());
                yield break;
            }

            /*
             *                  check if preloadList's assetBundleNames are contained by assetBundleList.
             */
            var targetAssetBundleNames = preloadList.bundleNames;
            var assetBundleListContainedAssetBundleNames = loader.GetWholeBundleNames();

            // start preload assetBundles.
            var loadingCoroutines = new Queue <IEnumerator>();

            var currentDownloadCount = 0;

            // define.
            var totalLoadingCoroutinesCount = 0;

            /*
             *                  assetBundle downloaded actions.
             */
            Action <string> bundlePreloadSucceededAct = (bundleName) =>
            {
                currentDownloadCount++;
                // Debug.Log("bundleName:" + bundleName);

                var count = ((currentDownloadCount * 100.0) / totalLoadingCoroutinesCount) * 0.01;
                progress(count);
            };

            Action <string, AssetBundleLoadError, string, AutoyaStatus> bundlePreloadFailedAct = (bundleName, error, reason, autoyaStatus) =>
            {
                bundlePreloadFailed(bundleName, error, reason, autoyaStatus);
            };

            var wholeDownloadableAssetBundleNames = new List <string>();

            foreach (var targetAssetBundleName in targetAssetBundleNames)
            {
                // skip not contained bundle.
                if (!assetBundleListContainedAssetBundleNames.Contains(targetAssetBundleName))
                {
                    continue;
                }

                // reserve this assetBundle name.
                wholeDownloadableAssetBundleNames.Add(targetAssetBundleName);

                // add only 1st level dependent AsstBundle Names.
                var dependentBundleNames = loader.AssetBundleInfoFromBundleName(targetAssetBundleName).dependsBundleNames;
                wholeDownloadableAssetBundleNames.AddRange(dependentBundleNames);
            }

            var shouldDownloadAssetBundleNamesCandidate = wholeDownloadableAssetBundleNames.Distinct().ToArray();
            var shouldDownloadAssetBundleNames          = new List <string>();

            foreach (var shouldDownloadAssetBundleName in shouldDownloadAssetBundleNamesCandidate)
            {
                var bundleUrl        = loader.GetAssetBundleDownloadUrl(shouldDownloadAssetBundleName);
                var targetBundleInfo = loader.AssetBundleInfoFromBundleName(shouldDownloadAssetBundleName);
                var hash             = Hash128.Parse(targetBundleInfo.hash);

                // ignore cached one.
                if (Caching.IsVersionCached(bundleUrl, hash))
                {
                    continue;
                }

                // ignore loaded one.
                if (loader.IsAssetBundleCachedOnMemory(shouldDownloadAssetBundleName))
                {
                    continue;
                }

                shouldDownloadAssetBundleNames.Add(shouldDownloadAssetBundleName);
            }

            // ここまでで、DLする対象のAssetBundleと、そのAssetBundleが依存しているAssetBundleまでが確保できている。

            /*
             *                  ask should continue or not before downloading target assetBundles.
             *  estimation is not considered about duplication of download same AssetBundle at same time.
             *  this is max case.
             */
            var shouldContinueCor = shouldContinuePreloading(shouldDownloadAssetBundleNames.ToArray(), onBeforePreloading);

            while (shouldContinueCor.MoveNext())
            {
                yield return(null);
            }

            var shouldContinue = shouldContinueCor.Current;

            if (!shouldContinue)
            {
                done();
                yield break;
            }

            /*
             *                  bundles are not cached on storage. should start download.
             */
            foreach (var shouldDownloadAssetBundleName in shouldDownloadAssetBundleNames)
            {
                var targetBundleInfo = loader.AssetBundleInfoFromBundleName(shouldDownloadAssetBundleName);
                var crc = targetBundleInfo.crc;

                var hash = Hash128.Parse(targetBundleInfo.hash);

                if (loader.IsAssetBundleCachedOnMemory(shouldDownloadAssetBundleName))
                {
                    // bundle is not cached on storage, but old bundle is no memory. need to unload it.
                    loader.UnloadOnMemoryAssetBundle(shouldDownloadAssetBundleName);
                }

                var bundlePreloadTimeoutTick = 0;// preloader does not have limit now.

                /*
                 *  AssetBundleのダウンロードを行う。
                 *  依存取得はoffで、ハンドリングはAssetBundleLoaderのものを使用する。
                 */
                var cor = loader.LoadAssetBundleThenNotUse(
                    shouldDownloadAssetBundleName,
                    crc,
                    hash,
                    false,// not download more dependency.
                    downloadedBundleName =>
                {
                    bundlePreloadSucceededAct(downloadedBundleName);
                },
                    (downloadedBundleName, error, reason, autoyaStatus) =>
                {
                    bundlePreloadFailedAct(downloadedBundleName, error, reason, autoyaStatus);
                },
                    bundlePreloadTimeoutTick
                    );

                loadingCoroutines.Enqueue(cor);
            }

            // update total count to actual.
            totalLoadingCoroutinesCount = loadingCoroutines.Count;

            /*
             *                  execute loading.
             */
            var currentLoadingCoroutines = new IEnumerator[maxParallelCount];

            while (true)
            {
                for (var j = 0; j < currentLoadingCoroutines.Length; j++)
                {
                    var currentLoadingCoroutine = currentLoadingCoroutines[j];
                    if (currentLoadingCoroutine == null)
                    {
                        // set next coroutine to currentLoadingCoroutines.
                        if (0 < loadingCoroutines.Count)
                        {
                            var next = loadingCoroutines.Dequeue();
                            currentLoadingCoroutines[j] = next;
                        }
                        else
                        {
                            // no coroutine exists.
                            continue;
                        }
                    }
                }

                var loading = false;
                for (var j = 0; j < currentLoadingCoroutines.Length; j++)
                {
                    var cor = currentLoadingCoroutines[j];
                    if (cor == null)
                    {
                        continue;
                    }

                    var result = cor.MoveNext();

                    // just finished.
                    if (!result)
                    {
                        currentLoadingCoroutines[j] = null;
                    }
                    else
                    {
                        loading = true;
                    }
                }

                if (0 < loadingCoroutines.Count)
                {
                    loading = true;
                }

                if (loading)
                {
                    yield return(null);
                }
                else
                {
                    // nothing loading.
                    break;
                }
            }

            // every bundle downloading is done.
            done();
        }
Exemplo n.º 37
0
        /// <summary>
        /// This is where we hijack the resizing process, interrupt it, and send back the json data we created.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="context"></param>
        /// <param name="e"></param>
        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            bool detect = NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "f.detect", false);
            bool getlayout = NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "f.getlayout", false);
            if (!detect && !getlayout) return;

            DetectionResponse<Face>.InjectExceptionHandler(e as ResponseArgs);
        }
Exemplo n.º 38
0
    private IEnumerator DoDownloadBundles(string databaseId)
    {
        ResetUpdateError();


        Console_WriteLine("Downloading database " + databaseId + "...");


        if (DownloadingStart != null)
        {
            DownloadingStart();
        }

        if (DownloadingBundleStart != null)
        {
            DownloadingBundleStart();
        }


        if (DownloadingDatabase != null)
        {
            DownloadingDatabase(databaseId);
        }

        AssetBundlesDatabase database = _shippedDatabase;

        if (databaseId != _shippedDatabase.Id)
        {
            if (!Caching.IsVersionCached("index", CachingUtils.GetVersionFromId(databaseId)))
            {
                if (Application.internetReachability == NetworkReachability.NotReachable)
                {
                    ThrowUpdateError(UpdateErrorType.NoInternetAvailable);
                    yield break;
                }
            }


            // Download requested database
            int version = CachingUtils.GetVersionFromId(databaseId);



            // This do-while: workaround of unity bug of caching startup delay
            do
            {
                using (WWW www = WWW.LoadFromCacheOrDownload(UpdateUrl + "/" + databaseId + "/index", version))
                {
                    yield return(StartCoroutine(WwwDone(www)));

                    if (WwwHasBundleError(www))
                    {
                    }
                    else
                    {
                        database = www.assetBundle.mainAsset as AssetBundlesDatabase;
                        www.assetBundle.Unload(false);
                    }
                }
            } while (!Caching.IsVersionCached("index", version));
        }
        else
        {
            database = _shippedDatabase;
        }

        int totalDownloadSize = 0;

        var bundlesToDownload = new List <AssetBundlesDatabase.BundleData>();

        // Check which bundles must be downloaded/cached
        foreach (var bundleData in EnumerateUncachedBundles(database))
        {
            totalDownloadSize += bundleData.Size;
            bundlesToDownload.Add(bundleData);
        }

        if (bundlesToDownload.Count == 0)
        {
            yield break;
        }

        if (DownloadStart != null)
        {
            DownloadStart(database, bundlesToDownload, totalDownloadSize);
        }

        int totalDownloadedBytes = 0;

        if (bundlesToDownload.Count > 0)
        {
            Console_WriteLine("Will download " + bundlesToDownload.Count + " bundles, with a total of " + totalDownloadSize + " bytes");


            string url = UpdateUrl + "/" + databaseId + "/";

            //foreach (var bundleData in bundlesToDownload)
            for (int i = 0; i < bundlesToDownload.Count;)
            {
                var bundleData = bundlesToDownload.ElementAt(i);

                Console_WriteLine("Downloading bundle " + bundleData.Name + "...");

                using (var www = WWW.LoadFromCacheOrDownload(url + bundleData.Filename,
                                                             CachingUtils.GetVersionFromHash(bundleData.Hash)))
                {
                    int previousDownloadedBytes = totalDownloadedBytes;

                    yield return(StartCoroutine(WwwDone(www, () => {
                        totalDownloadedBytes = previousDownloadedBytes + (int)(www.progress * (float)bundleData.Size);

                        if (DownloadProgress != null)
                        {
                            DownloadProgress(bundlesToDownload.IndexOf(bundleData), totalDownloadedBytes);
                        }
                    })));

                    if (WwwHasBundleError(www))
                    {
                    }
                    else
                    {
                        www.assetBundle.Unload(false);
                        totalDownloadedBytes = previousDownloadedBytes + bundleData.Size;
                    }
                }

                i++;
            }
        }

        Console_WriteLine("Database downloaded");
        if (DownloadingBundleEnd != null)
        {
            DownloadingBundleEnd("success", "url");
        }

        if (DownloadingFinish != null)
        {
            DownloadingFinish();
        }
    }
Exemplo n.º 39
0
 public bool Contains(Vector2 point, Caching.IResourceCache<Microsoft.Xna.Framework.Graphics.Texture2D> cache, Matrix globalTransform)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 40
0
    private IEnumerator DoLoadBundles(string databaseId)
    {
        Console_WriteLine("Loading database " + databaseId + "...");


        if (LoadingStart != null)
        {
            LoadingStart();
        }

        var database = LoadAssetBundlesDatabaseFromId(databaseId);

        if (LoadStart != null)
        {
            LoadStart(database);
        }

        //Console.WriteLine("==== Current language: " + LanguageTextManager.CurSystemLang);

        float       lastYieldTime    = Time.realtimeSinceStartup;
        const float maximumYieldTime = 1.0f / 5.0f;

        int i = 0;

        foreach (var bundleData in database.Bundles)
        {
            BundleInfo bundleInfo = new BundleInfo(bundleData);

            Console_WriteLine("Loading bundle " + bundleData.Name + "...");


            string url = UpdateUrl + "/" + databaseId + "/";

            int version = CachingUtils.GetVersionFromHash(bundleData.Hash);

            if (!Caching.IsVersionCached(bundleData.Filename, version) &&
                IsBundleInShippedDatabase(bundleData.Name, version))
            {
                if (_buildInfo.BundlesCacheIncluded)
                {
                    // Uncompressed cache copy (faster)

                    Console_WriteLine("Caching " + bundleData.Name);

                    CopyToCache(_shippedDatabase[bundleData.Name].CacheName);
                }
                else
                {
                    Console_WriteLine("Caching decompressing " + bundleData.Name);

                    url = StreamingAssetsUrl + "/Bundles/";
                }
            }

            if (LoadProgress != null)
            {
                LoadProgress(database.Bundles.IndexOf(bundleData));
            }

            using (var www = WWW.LoadFromCacheOrDownload(url + bundleData.Filename,
                                                         version))
            {
                yield return(www);

                lastYieldTime     = Time.realtimeSinceStartup;
                bundleInfo.Bundle = www.assetBundle;
            }
            yield return(null);

            foreach (var sceneName in bundleData.SceneNames)
            {
                _scenesMap.Add(sceneName, bundleInfo);
            }

            foreach (var assetId in bundleData.AssetsIds)
            {
                _assetIdMap[assetId] = bundleInfo;
            }

            _bundlesMap.Add(bundleData.Name, bundleInfo);

            // Allow some processing if hanging for too much long
            if (Time.realtimeSinceStartup - lastYieldTime > maximumYieldTime)
            {
                yield return(null);

                lastYieldTime = Time.realtimeSinceStartup;
            }

            i++;
            if (i % 30 == 0)
            {
                yield return(new WaitForSeconds(0.5f));
            }
        }


        Console_WriteLine("Database loaded");


        if (LoadingFinish != null)
        {
            LoadingFinish();
        }
    }
 public CriteriaCacheSettings(Caching.ICacheProvider provider, int duration)
 {
     Provider = provider;
     Duration = duration; 
 }
 /// <summary>
 /// 释放当前程序中所有 www 对象缓存到本地的资源
 /// </summary>
 public static void CleanCache()
 {
     Caching.CleanCache();
 }
Exemplo n.º 43
0
 // sub iterators: Address / CName
 protected ResolutionIterator(DomainResolver resolver, DnsClient.DNS.QTYPE question, Caching.AddressCache addressCache, int nestingLevel)
     : base(resolver, question, addressCache)
 {
     this.NestingLevel = nestingLevel;
 }
Exemplo n.º 44
0
 /// <summary>
 /// This is where we hijack the resizing process, interrupt it, and send back the json data we created.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="context"></param>
 /// <param name="e"></param>
 void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
 {
     if (NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "r.detecteyes", false) ||
         NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "r.getlayout", false)) {
         DetectionResponse<ObjRect>.InjectExceptionHandler(e as ResponseArgs);
     }
 }
Exemplo n.º 45
0
 public Microsoft.Xna.Framework.Vector2 GetCenter(Caching.IResourceCache<Microsoft.Xna.Framework.Graphics.Texture2D> cache, Microsoft.Xna.Framework.Matrix globalTransform)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 46
0
 protected override bool TryCreateRoom(string gameId, out Caching.RoomReference roomReference, params object[] args)
 {
     return TestGameCache.Instance.TryCreateRoom(gameId, this, out roomReference, args);
 }
Exemplo n.º 47
0
        internal static async Task <RuntimeComposition> TryCreateRuntimeCompositionFromCache(Caching caching)
        {
            CachedComposition cacheManager = new CachedComposition();

            try {
                using (Counters.CompositionCache.BeginTiming())
                    using (var cacheStream = caching.OpenCacheStream()) {
                        return(await cacheManager.LoadRuntimeCompositionAsync(cacheStream, StandardResolver));
                    }
            } catch (Exception ex) {
                LoggingService.LogError("Could not deserialize MEF cache", ex);
                caching.DeleteFiles();
            }
            return(null);
        }
Exemplo n.º 48
0
 internal MultiLinkConnections(ILinkElement element, Caching caching)
     : base(element, caching)
 {
 }
Exemplo n.º 49
0
 internal AssetManagerFiles(IAssetManagerFolder folder, Caching caching) : base(folder, caching)
 {
     RetrieveFunc = GetFiles;
 }
Exemplo n.º 50
0
        internal static async Task <RuntimeComposition> CreateRuntimeCompositionFromDiscovery(Caching caching)
        {
            using (var timer = Counters.CompositionDiscovery.BeginTiming()) {
                var parts = await Discovery.CreatePartsAsync(caching.Assemblies);

                timer.Trace("Composition parts discovered");

                ComposableCatalog catalog = ComposableCatalog.Create(StandardResolver)
                                            .WithCompositionService()
                                            .AddParts(parts);

                var discoveryErrors = catalog.DiscoveredParts.DiscoveryErrors;
                if (!discoveryErrors.IsEmpty)
                {
                    foreach (var error in discoveryErrors)
                    {
                        LoggingService.LogInfo("MEF discovery error", error);
                    }

                    // throw new ApplicationException ("MEF discovery errors");
                }

                CompositionConfiguration configuration = CompositionConfiguration.Create(catalog);

                if (!configuration.CompositionErrors.IsEmpty)
                {
                    // capture the errors in an array for easier debugging
                    var errors = configuration.CompositionErrors.SelectMany(e => e).ToArray();
                    foreach (var error in errors)
                    {
                        LoggingService.LogInfo("MEF composition error: " + error.Message);
                    }

                    // For now while we're still transitioning to VSMEF it's useful to work
                    // even if the composition has some errors. TODO: re-enable this.
                    //configuration.ThrowOnErrors ();
                }

                timer.Trace("Composition configured");

                var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration);
                return(runtimeComposition);
            }
        }
Exemplo n.º 51
0
 protected override bool TryGetRoomReference(string gameId, out Caching.RoomReference roomReference)
 {
     return TestGameCache.Instance.TryGetRoomReference(gameId, this, out roomReference);
 }
 internal ContentClassElements(ContentClass contentClass, Caching caching) : base(caching)
 {
     _contentClass = contentClass;
     RetrieveFunc  = GetContentClassElements;
 }
Exemplo n.º 53
0
        void OnGUI()
        {
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, true);
            EditorGUILayout.BeginVertical(GUILayout.Width(EditorGUIUtility.currentViewWidth - 20f));
            EditorGUILayout.Space();
            GUILayout.Label("UMA AssetBundle Manager", EditorStyles.boldLabel);

            BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f));

            GUILayout.Label("AssetBundle Options", EditorStyles.boldLabel);

            //Asset Bundle Encryption
            //defined here so we can modify the message if encryption settings change
            string      buildBundlesMsg     = "";
            MessageType buildBundlesMsgType = MessageType.Info;

            EditorGUI.BeginChangeCheck();
            encryptionKeysEnabled = EditorGUILayout.ToggleLeft("Enable AssetBundle Encryption", encryptionKeysEnabled);
            if (EditorGUI.EndChangeCheck())
            {
                //If encryption was turned ON generate the encryption password if necessary
                if (encryptionKeysEnabled)
                {
                    if (currentEncryptionPassword == "")
                    {
                        if (UMAABMSettings.GetEncryptionPassword() != "")
                        {
                            currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword();
                        }
                        else
                        {
                            currentEncryptionPassword = EncryptionUtil.GenerateRandomPW();
                        }
                    }
                    UMAABMSettings.SetEncryptionPassword(currentEncryptionPassword);
                    buildBundlesMsg     = "You have turned on encryption and need to Rebuild your bundles to encrypt them.";
                    buildBundlesMsgType = MessageType.Warning;
                }
                else
                {
                    UMAABMSettings.DisableEncryption();
                    currentEncryptionPassword = "";
                }
            }
            if (encryptionKeysEnabled)
            {
                BeginVerticalIndented(10, new Color(0.75f, 0.875f, 1f));
                //tip
                EditorGUILayout.HelpBox("Make sure you turn on 'Use Encrypted Bundles' in the 'DynamicAssetLoader' components in your scenes.", MessageType.Info);
                //Encryption key
                //If we can work out a way for people to download a key we can use this tip and the 'EncryptionKeyURL' field
                //string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt. If you use the 'Encryption Key URL' field below you MUST ensure this field is set to the same key the url will return.";
                string encryptionKeyToolTip = "This key is used to generate the required encryption keys used when encrypting your bundles. If you change this key you will need to rebuild your bundles otherwise they wont decrypt.";
                EditorGUILayout.LabelField(new GUIContent("Bundle Encryption Password", encryptionKeyToolTip));
                EditorGUILayout.BeginHorizontal();
                if (!manualEditEncryptionKey)
                {
                    if (GUILayout.Button(new GUIContent("Edit", encryptionKeyToolTip)))
                    {
                        manualEditEncryptionKey = true;
                    }
                    EditorGUI.BeginDisabledGroup(!manualEditEncryptionKey);
                    EditorGUILayout.TextField("", UMAABMSettings.GetEncryptionPassword());                    //THis bloody field WILL NOT update when you click edit, then canel, the value stays
                    EditorGUI.EndDisabledGroup();
                }
                else
                {
                    EditorGUI.BeginChangeCheck();
                    newEncryptionPassword = EditorGUILayout.TextArea(newEncryptionPassword);
                    if (EditorGUI.EndChangeCheck())
                    {
                        encryptionSaveButEnabled = EncryptionUtil.PasswordValid(newEncryptionPassword);
                    }
                    if (encryptionSaveButEnabled)
                    {
                        if (GUILayout.Button(new GUIContent("Save"), GUILayout.MaxWidth(60)))
                        {
                            currentEncryptionPassword = newEncryptionPassword;
                            UMAABMSettings.SetEncryptionPassword(newEncryptionPassword);
                            EditorGUIUtility.keyboardControl = 0;
                            manualEditEncryptionKey          = false;
                        }
                    }
                    else
                    {
                        GUI.enabled = false;
                        if (GUILayout.Button(new GUIContent("Save", "Your Encryptiom Password should be at least 16 characters long"), GUILayout.MaxWidth(60)))
                        {
                            //Do nothing
                        }
                        GUI.enabled = true;
                    }
                    if (GUILayout.Button(new GUIContent("Cancel", "Reset to previous value: " + currentEncryptionPassword), GUILayout.MaxWidth(60)))
                    {
                        manualEditEncryptionKey          = false;
                        newEncryptionPassword            = currentEncryptionPassword = UMAABMSettings.GetEncryptionPassword();
                        encryptionSaveButEnabled         = false;
                        EditorGUIUtility.keyboardControl = 0;
                    }
                }
                EditorGUILayout.EndHorizontal();
                //EncryptionKey URL
                //not sure how this would work- the delivered key would itself need to be encrypted probably
                //Encrypted bundle suffix
                string encryptionSuffixToolTip = "This suffix is appled to the end of your encrypted bundle names when they are built. Must be lower case and alphaNumeric. Cannot be empty. Defaults to " + DEFAULT_ENCRYPTION_SUFFIX;
                EditorGUILayout.LabelField(new GUIContent("Encrypted Bundle Suffix", encryptionSuffixToolTip));
                EditorGUILayout.BeginHorizontal();
                if (!manualEditEncryptionSuffix)
                {
                    if (GUILayout.Button(new GUIContent("Edit", encryptionSuffixToolTip)))
                    {
                        manualEditEncryptionSuffix = true;
                    }
                    EditorGUI.BeginDisabledGroup(!manualEditEncryptionSuffix);
                    EditorGUILayout.TextField(new GUIContent("", encryptionSuffixToolTip), currentEncryptionSuffix);
                    EditorGUI.EndDisabledGroup();
                }
                else
                {
                    newEncryptionSuffix = EditorGUILayout.TextArea(newEncryptionSuffix);
                    if (GUILayout.Button(new GUIContent("Save")))
                    {
                        if (newEncryptionSuffix != "")
                        {
                            Regex rgx          = new Regex("[^a-zA-Z0-9 -]");
                            var   suffixToSend = rgx.Replace(newEncryptionSuffix, "");
                            currentEncryptionSuffix = suffixToSend;
                            UMAABMSettings.SetEncryptionSuffix(suffixToSend.ToLower());
                            EditorGUIUtility.keyboardControl = 0;
                            manualEditEncryptionSuffix       = false;
                        }
                    }
                }
                EditorGUILayout.EndHorizontal();

                //Encode Bundle Names
                string encodeBundleNamesTooltip = "If true encrypted bundle names will be base64 encoded";
                EditorGUI.BeginChangeCheck();
                newEncodeNamesSetting = EditorGUILayout.ToggleLeft(new GUIContent("Encode Bundle Names", encodeBundleNamesTooltip), currentEncodeNamesSetting);
                if (EditorGUI.EndChangeCheck())
                {
                    currentEncodeNamesSetting = newEncodeNamesSetting;
                    UMAABMSettings.SetEncodeNames(newEncodeNamesSetting);
                }

                EndVerticalIndented();
            }
#if ENABLE_IOS_APP_SLICING
            string AppSlicingTooltip = "If true will build bundles uncompressed for use with iOS Resources Catalogs";
            EditorGUI.BeginChangeCheck();
            bool newAppSlicingSetting = EditorGUILayout.ToggleLeft(new GUIContent("Build for iOS App Slicing", AppSlicingTooltip), currentAppSlicingSetting);
            if (EditorGUI.EndChangeCheck())
            {
                currentAppSlicingSetting = newAppSlicingSetting;
                UMAABMSettings.SetBuildForSlicing(newAppSlicingSetting);
            }
#endif

            //Asset Bundle Building
            EditorGUILayout.Space();
            string buttonBuildAssetBundlesText = "Build AssetBundles";
            //Now defined above the encryption
            //string buildBundlesText = "Click the button below to build your bundles if you have not done so already.";
            string fullPathToBundles         = Path.Combine(Directory.GetParent(Application.dataPath).FullName, Utility.AssetBundlesOutputPath);
            string fullPathToPlatformBundles = Path.Combine(fullPathToBundles, Utility.GetPlatformName());

            //if we have not built any asset bundles there wont be anything in the cache to clear
            bool showClearCache = false;

            if (Directory.Exists(fullPathToPlatformBundles))
            {
                buttonBuildAssetBundlesText = "Rebuild AssetBundles";
                buildBundlesMsg             = buildBundlesMsg == "" ? "Rebuild your assetBundles to reflect your latest changes" : buildBundlesMsg;
                showClearCache = true;
            }
            else
            {
                buildBundlesMsg     = "You have not built your asset bundles for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " yet. Click this button to build them.";
                buildBundlesMsgType = MessageType.Warning;
                showClearCache      = false;
            }
            EditorGUILayout.HelpBox(buildBundlesMsg, buildBundlesMsgType);
            if (GUILayout.Button(buttonBuildAssetBundlesText))
            {
                BuildScript.BuildAssetBundles();
                Caching.CleanCache();
                return;
            }
            EndVerticalPadded(5);
            EditorGUILayout.Space();

            //Local AssetBundleServer
            BeginVerticalPadded(5f, new Color(0.75f, 0.875f, 1f));
            GUILayout.Label("AssetBundle Testing Server", EditorStyles.boldLabel);
            EditorGUILayout.HelpBox("Once you have built your bundles this local Testing Server can be enabled and it will load those AssetBundles rather than the files inside the project.", MessageType.Info);

            if (!BuildScript.CanRunLocally(EditorUserBuildSettings.activeBuildTarget))
            {
                EditorGUILayout.HelpBox("Builds for " + EditorUserBuildSettings.activeBuildTarget.ToString() + " cannot access this local server, but you can still use it in the editor.", MessageType.Warning);
            }

            bool updateURL = false;
            EnableLocalAssetBundleServer = EditorGUILayout.Toggle("Start Server", EnableLocalAssetBundleServer);

            //If the server is off we need to show the user a message telling them that they will have to have uploaded their bundles to an external server
            //and that they need to set the address of that server in DynamicAssetLoader
            int newPort = Port;
            EditorGUI.BeginChangeCheck();
            newPort = EditorGUILayout.IntField("Port", Port);
            if (EditorGUI.EndChangeCheck())
            {
                if (newPort != Port)
                {
                    if (_activeHost != null && _activeHost != "")
                    {
                        ActiveHost = _activeHost.Replace(":" + Port.ToString(), ":" + newPort.ToString());
                    }
                    Port = newPort;
                    UpdateHosts();
                    //we need to start the server to see if it works with this port- regardless of whether it is turned on or not.
                    if (!EnableLocalAssetBundleServer)
                    {
                        UpdateServer(true);
                    }
                    else
                    {
                        UpdateServer();
                    }
                    if (serverException == false)
                    {
                        //We can use the set IP with this port so update it
                        if (EnableLocalAssetBundleServer)
                        {
                            SimpleWebServer.ServerURL = ActiveHost;
                        }
                    }
                    else
                    {
                        //We CANT use the set IP with this port so set the saved URL to "" and tell the user the Port is in use elsewhere
                        SimpleWebServer.ServerURL    = "";
                        EnableLocalAssetBundleServer = false;
                        portError = true;
                    }
                }
            }
            if (!EnableLocalAssetBundleServer)
            {
                if (portError)
                {
                    EditorGUILayout.HelpBox("There are no hosts available for that port. Its probably in use by another application. Try another.", MessageType.Warning);
                }
                else
                {
                    EditorGUILayout.HelpBox("When the local server is not running the game will play in Simulation Mode OR if you have set the 'RemoteServerURL' for each DynamicAssetLoader, bundles will be downloaded from that location.", MessageType.Warning);
                    if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebGL)
                    {
                        EditorGUILayout.HelpBox("WARNING: AssetBundles in WebGL builds that you run locally WILL NOT WORK unless the local server is turned on, and you build using the button below!", MessageType.Warning);
                    }
                }
            }

            EditorGUILayout.Space();

            if (_hosts != null && _hosts.Length > 0 && EnableLocalAssetBundleServer)
            {
                if (_activeHost == null || _activeHost == "")
                {
                    ActiveHost = _hosts[0];
                }
                int      activeHostInt = 0;
                string[] hostsStrings  = new string[_hosts.Length];
                for (int i = 0; i < _hosts.Length; i++)
                {
                    hostsStrings[i] = _hosts[i].Replace("http://", "").TrimEnd(new char[] { '/' });
                    if (_hosts[i] == _activeHost)
                    {
                        activeHostInt = i;
                    }
                }
                EditorGUI.BeginChangeCheck();
                int newActiveHostInt = EditorGUILayout.Popup("Host Address:  http://", activeHostInt, hostsStrings);
                if (EditorGUI.EndChangeCheck())
                {
                    if (newActiveHostInt != activeHostInt)
                    {
                        ActiveHost = _hosts[newActiveHostInt];
                        updateURL  = true;
                    }
                }
            }
            EditorGUILayout.Space();

            if (showClearCache)            //no point in showing a button for bundles that dont exist - or is there? The user might be using a remote url to download assetbundles without the localserver?
            {
                EditorGUILayout.HelpBox("You can clear the cache to force asset bundles to be redownloaded.", MessageType.Info);

                if (GUILayout.Button("Clean the Cache"))
                {
                    _statusMessage = Caching.CleanCache() ? "Cache Cleared." : "Error clearing cache.";
                }
                EditorGUILayout.Space();
            }

            EditorGUILayout.Space();
            GUILayout.Label("Server Status");
            if (_statusMessage != null)
            {
                EditorGUILayout.HelpBox(_statusMessage, MessageType.None);
            }

            if (SimpleWebServer.Instance != null)
            {
                //GUILayout.Label("Server Request Log");
                serverRequestLogOpen = EditorGUILayout.Foldout(serverRequestLogOpen, "Server Request Log");
                if (serverRequestLogOpen)
                {
                    EditorGUILayout.HelpBox(SimpleWebServer.Instance.GetLog(), MessageType.Info);
                }
            }
            if (updateURL)
            {
                SimpleWebServer.ServerURL = ActiveHost;
            }

            EndVerticalPadded(5);
            EditorGUILayout.Space();

            //Testing Build- only show this if we can run a build for the current platform (i.e. if its not iOS or Android)
            if (BuildScript.CanRunLocally(EditorUserBuildSettings.activeBuildTarget))
            {
                BeginVerticalPadded(5, new Color(0.75f, 0.875f, 1f));
                GUILayout.Label("Local Testing Build", EditorStyles.boldLabel);
                //if the bundles are built and the server is turned on then the user can use this option otherwise there is no point
                //But we will show them that this option is available even if this is not the case
                if (!showClearCache || !EnableLocalAssetBundleServer)
                {
                    EditorGUI.BeginDisabledGroup(true);
                }
                EditorGUILayout.HelpBox("Make a testing Build that uses the Local Server using the button below.", MessageType.Info);

                developmentBuild = EditorGUILayout.Toggle("Development Build", developmentBuild);
                if (GUILayout.Button("Build and Run!"))
                {
                    BuildScript.BuildAndRunPlayer(developmentBuild);
                }
                if (!showClearCache || !EnableLocalAssetBundleServer)                  //
                {
                    EditorGUI.EndDisabledGroup();
                }
                EditorGUILayout.Space();
                EndVerticalPadded(5);

                EditorGUILayout.Space();
            }
            //END SCROLL VIEW
            //for some reason when we build or build assetbundles when this window is open we get an error
            //InvalidOperationException: Operation is not valid due to the current state of the object
            //so try catch is here as a nasty hack to get rid of it
            try
            {
                EditorGUILayout.EndVertical();
                EditorGUILayout.EndScrollView();
            }
            catch { }
        }
Exemplo n.º 54
0
    static int _CreateCaching(IntPtr L)
    {
        int count = LuaDLL.lua_gettop(L);

        if (count == 0)
        {
            Caching obj = new Caching();
            LuaScriptMgr.PushObject(L, obj);
            return 1;
        }
        else
        {
            LuaDLL.luaL_error(L, "invalid arguments to method: Caching.New");
        }

        return 0;
    }