Exemple #1
0
 private void OnConnectServer(SocketError error)
 {
     MotionLog.Log($"Server connect result : {error}");
     if (error == SocketError.Success)
     {
         States = ENetworkStates.Connected;
         NetworkEventDispatcher.SendConnectSuccessMsg();
     }
     else
     {
         States = ENetworkStates.Disconnect;
         NetworkEventDispatcher.SendConnectFailMsg(error.ToString());
     }
 }
Exemple #2
0
        public IEnumerator Download()
        {
            // 获取最新的游戏版本号
            {
                string url  = _patcher.GetWebServerIP();
                string post = _patcher.GetWebPostData();
                MotionLog.Log($"Beginning to request from web : {url} {post}");
                WebPostRequest download = new WebPostRequest(url, post);
                download.DownLoad();
                yield return(download);

                //Check fatal
                if (download.HasError())
                {
                    download.ReportError();
                    download.Dispose();
                    PatchEventDispatcher.SendGameVersionRequestFailedMsg();
                    yield break;
                }

                string response = download.GetResponse();
                MotionLog.Log($"Succeed get response from web : {url} {response}");
                _patcher.ParseWebResponseData(response);
                download.Dispose();
            }

            // 检测强更安装包
            if (_patcher.ForceInstall)
            {
                string requestedGameVersion = _patcher.RequestedGameVersion.ToString();
                MotionLog.Log($"Found new APP can be install : {requestedGameVersion}");
                PatchEventDispatcher.SendFoundForceInstallAPPMsg(requestedGameVersion, _patcher.AppURL);
                yield break;
            }

            // 检测资源版本是否变化
            int newResourceVersion = _patcher.RequestedResourceVersion;
            int oldResourceVersion = _patcher.LocalResourceVersion;

            if (newResourceVersion == oldResourceVersion)
            {
                MotionLog.Log($"Resource version is not change.");
                _patcher.Switch(EPatchStates.PatchDone.ToString());
            }
            else
            {
                MotionLog.Log($"Resource version is change : {oldResourceVersion} -> {newResourceVersion}");
                _patcher.SwitchNext();
            }
        }
        /// <summary>
        /// 启动状态机
        /// </summary>
        /// <param name="entryNode">入口节点</param>
        public void Run(string entryNode)
        {
            _curNode = GetNode(entryNode);
            _preNode = GetNode(entryNode);

            if (_curNode != null)
            {
                _curNode.OnEnter();
            }
            else
            {
                MotionLog.Error($"Not found entry node : {entryNode}");
            }
        }
Exemple #4
0
        public void UnLoad()
        {
            if (_handle != null)
            {
                MotionLog.Log($"Begin to unload scene : {Location}");
                _finishCallback    = null;
                _progressCallback  = null;
                _lastProgressValue = 0;

                // 异步卸载场景
                _handle.UnloadAsync();
                _handle = null;
            }
        }
        /// <summary>
        /// 获取配表
        /// </summary>
        public T GetConfig <T>() where T : AssetConfig
        {
            System.Type type = typeof(T);
            foreach (var pair in _configs)
            {
                if (pair.Value.GetType() == type)
                {
                    return(pair.Value as T);
                }
            }

            MotionLog.Log(ELogLevel.Error, $"Not found config {type}");
            return(null);
        }
Exemple #6
0
        private void TryAgainRequest()
        {
            _failedTryAgain--;

            // 报告错误
            ReportError();

            // 清除旧数据
            base.Dispose();

            // 重新请求下载
            SendRequest(_savePath, _failedTryAgain, _timeout);
            MotionLog.Warning($"Try again request : {_requestURL}");
        }
Exemple #7
0
        public void Load(bool isAdditive, bool activeOnLoad, System.Action <SceneOperationHandle> finishCallback, System.Action <int> progressCallbcak)
        {
            if (_handle != null)
            {
                return;
            }

            var _sceneMode = isAdditive ? LoadSceneMode.Additive : LoadSceneMode.Single;

            MotionLog.Log($"Begin to load scene : {Location}");
            _finishCallback    = finishCallback;
            _progressCallback  = progressCallbcak;
            _handle            = ResourceManager.Instance.LoadSceneAsync(Location, _sceneMode, activeOnLoad);
            _handle.Completed += Handle_Completed;
        }
Exemple #8
0
        public AssetConfig GetConfig(Type configType)
        {
            string configName = configType.FullName;

            foreach (var pair in _configs)
            {
                if (pair.Key == configName)
                {
                    return(pair.Value);
                }
            }

            MotionLog.Error($"Not found config {configName}");
            return(null);
        }
Exemple #9
0
        /// <summary>
        /// 检测转换关系
        /// </summary>
        public bool CanTransition(string from, string to)
        {
            if (_graph.ContainsKey(from) == false)
            {
                MotionLog.Warning($"Not found graph node {from}");
                return(false);
            }

            if (to == _globalNode)
            {
                return(true);
            }

            return(_graph[from].Contains(to));
        }
        /// <summary>
        /// 在当前主场景的基础上加载附加场景
        /// </summary>
        /// <param name="location">场景资源地址</param>
        /// <param name="activeOnLoad">加载完成时是否激活场景</param>
        /// <param name="callback">场景加载完毕的回调</param>
        public void LoadAdditionScene(string location, bool activeOnLoad, System.Action <SceneInstance> callback)
        {
            AssetScene scene = TryGetAdditionScene(location);

            if (scene != null)
            {
                MotionLog.Warning($"The addition scene {location} is already load.");
                return;
            }

            AssetScene newScene = new AssetScene(location);

            _additionScenes.Add(newScene);
            newScene.Load(true, activeOnLoad, callback);
        }
Exemple #11
0
        /// <summary>
        /// 添加转换关系
        /// </summary>
        /// <param name="nodeName">节点名称</param>
        /// <param name="transitionNodes">可以转换到的节点列表</param>
        public void AddTransition(string nodeName, List <string> transitionNodes)
        {
            if (transitionNodes == null)
            {
                throw new ArgumentNullException();
            }

            if (_graph.ContainsKey(nodeName))
            {
                MotionLog.Warning($"Graph node {nodeName} already existed.");
                return;
            }

            _graph.Add(nodeName, transitionNodes);
        }
 /// <summary>
 /// 获取文件的MD5值
 /// </summary>
 public static string FileMD5(string filePath)
 {
     try
     {
         using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
         {
             return(StreamMD5(fs));
         }
     }
     catch (Exception e)
     {
         MotionLog.Exception(e.ToString());
         return(string.Empty);
     }
 }
 AssetBundleInfo IBundleServices.GetAssetBundleInfo(string bundleName)
 {
     if (_patchManifest.Bundles.TryGetValue(bundleName, out PatchBundle patchBundle))
     {
         string          localPath  = AssetPathHelper.MakeStreamingLoadPath(patchBundle.Hash);
         AssetBundleInfo bundleInfo = new AssetBundleInfo(bundleName, localPath, patchBundle.Version, patchBundle.IsEncrypted);
         return(bundleInfo);
     }
     else
     {
         MotionLog.Warning($"Not found bundle in patch manifest : {bundleName}");
         AssetBundleInfo bundleInfo = new AssetBundleInfo(bundleName, string.Empty);
         return(bundleInfo);
     }
 }
Exemple #14
0
        public override void Update()
        {
            if (IsDone)
            {
                return;
            }

            if (_loader.CacheBundle == null)
            {
                States = EAssetStates.Fail;
                InvokeCompletion();
            }

            if (States == EAssetStates.None)
            {
                States = EAssetStates.Loading;
            }

            // 1. 加载资源对象
            if (States == EAssetStates.Loading)
            {
                if (AssetType == null)
                {
                    _cacheRequest = _loader.CacheBundle.LoadAssetAsync(AssetName);
                }
                else
                {
                    _cacheRequest = _loader.CacheBundle.LoadAssetAsync(AssetName, AssetType);
                }
                States = EAssetStates.Checking;
            }

            // 2. 检测加载结果
            if (States == EAssetStates.Checking)
            {
                if (_cacheRequest.isDone == false)
                {
                    return;
                }
                AssetObject = _cacheRequest.asset;
                States      = AssetObject == null ? EAssetStates.Fail : EAssetStates.Success;
                if (States == EAssetStates.Fail)
                {
                    MotionLog.Warning($"Failed to load asset object : {AssetName} from bundle : {_loader.BundleInfo.BundleName}");
                }
                InvokeCompletion();
            }
        }
		/// <summary>
		/// 检测是否超时
		/// </summary>
		private void CheckTimeout()
		{
			if (CacheRequest == null || AsyncOperationHandle == null)
				return;

			if(_latestDownloadBytes != DownloadedBytes)
			{
				_latestDownloadBytes = DownloadedBytes;
				_latestDownloadRealtime = Time.realtimeSinceStartup;
			}
			if ((Time.realtimeSinceStartup - _latestDownloadRealtime) > Timeout)
			{
				MotionLog.Warning($"Web request timeout : {URL}");
				CacheRequest.Abort();
			}
		}
Exemple #16
0
		/// <summary>
		/// 添加一个监听
		/// </summary>
		public void AddListener<TEvent>(System.Action<IEventMessage> listener) where TEvent : IEventMessage
		{
			System.Type eventType = typeof(TEvent);
			if (_cachedListener.ContainsKey(eventType) == false)
				_cachedListener.Add(eventType, new List<Action<IEventMessage>>());

			if (_cachedListener[eventType].Contains(listener) == false)
			{
				_cachedListener[eventType].Add(listener);
				EventManager.Instance.AddListener(eventType, listener);
			}
			else
			{
				MotionLog.Warning($"Event listener is exist : {eventType}");
			}
		}
Exemple #17
0
        private WebFileRequest CreateDownloader(PatchBundle element)
        {
            // 注意:资源版本号只用于确定下载路径
            string url      = _patcher.GetWebDownloadURL(element.Version.ToString(), element.Hash);
            string savePath = PatchHelper.MakeSandboxCacheFilePath(element.Hash);

            FileUtility.CreateFileDirectory(savePath);

            // 创建下载器
            MotionLog.Log($"Beginning to download web file : {url}");
            WebFileRequest download = new WebFileRequest(url, savePath);

            download.UserData = element;
            download.DownLoad();
            return(download);
        }
        /// <summary>
        /// 在当前主场景上加载附加场景
        /// </summary>
        /// <param name="location">场景资源地址</param>
        /// <param name="activeOnLoad">加载完成时是否激活附加场景</param>
        /// <param name="callback">场景加载完毕的回调</param>
        public void LoadAdditionScene(string location, bool activeOnLoad, System.Action <SceneOperationHandle> finishCallback = null,
                                      System.Action <int> progressCallback = null)
        {
            AssetScene scene = TryGetAdditionScene(location);

            if (scene != null)
            {
                MotionLog.Warning($"The addition scene {location} is already load.");
                return;
            }

            AssetScene newScene = new AssetScene(location);

            _additionScenes.Add(newScene);
            newScene.Load(true, activeOnLoad, finishCallback, progressCallback);
        }
Exemple #19
0
        /// <summary>
        /// 加入一个节点
        /// </summary>
        public void AddNode(IFsmNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException();
            }

            if (_nodes.Contains(node) == false)
            {
                _nodes.Add(node);
            }
            else
            {
                MotionLog.Warning($"Node {node.Name} already existed");
            }
        }
Exemple #20
0
        private WebFileRequest CreateDownloader(PatchBundle patchBundle)
        {
            // 注意:资源版本号只用于确定下载路径
            string mainURL     = _patcherMgr.GetPatchDownloadURL(patchBundle.Version, patchBundle.Hash);
            string fallbackURL = _patcherMgr.GetPatchDownloadFallbackURL(patchBundle.Version, patchBundle.Hash);
            string savePath    = PatchHelper.MakeSandboxCacheFilePath(patchBundle.Hash);

            FileUtility.CreateFileDirectory(savePath);

            // 创建下载器
            MotionLog.Log($"Beginning to download web file : {patchBundle.BundleName} URL : {mainURL}");
            WebFileRequest download = WebFileSystem.GetWebFileRequest(mainURL, fallbackURL, savePath, _failedTryAgain);

            download.UserData = patchBundle;
            return(download);
        }
        public IEnumerator Download()
        {
            // 获取最新的游戏版本号
            {
                string url  = _patcher.GetWebServerIP();
                string post = _patcher.GetWebPostData();
                MotionLog.Log($"Request game version : {url} : {post}");
                WebPostRequest download = new WebPostRequest(url, post);
                yield return(download.DownLoad());

                //Check fatal
                if (download.States != EWebRequestStates.Success)
                {
                    download.Dispose();
                    PatchEventDispatcher.SendGameVersionRequestFailedMsg();
                    yield break;
                }

                string response = download.GetResponse();
                _patcher.ParseResponseData(response);
                download.Dispose();
            }

            int newResourceVersion = _patcher.RequestedResourceVersion;
            int oldResourceVersion = _patcher.SandboxPatchManifest.Version;

            // 检测强更安装包
            if (_patcher.ForceInstall)
            {
                MotionLog.Log($"Found new APP can be install : {_patcher.GameVersion.ToString()}");
                PatchEventDispatcher.SendFoundForceInstallAPPMsg(_patcher.GameVersion.ToString(), _patcher.AppURL);
                yield break;
            }

            // 检测资源版本是否变化
            if (newResourceVersion == oldResourceVersion)
            {
                MotionLog.Log($"Resource version is not change.");
                _patcher.Switch(EPatchStates.DownloadOver.ToString());
            }
            else
            {
                MotionLog.Log($"Resource version is change : {oldResourceVersion} -> {newResourceVersion}");
                _patcher.SwitchNext();
            }
        }
        /// <summary>
        /// 同步加载接口
        /// 注意:仅支持无依赖关系的资源
        /// </summary>
        public T SyncLoad <T>(string location, string variant) where T : UnityEngine.Object
        {
            UnityEngine.Object result = null;

            if (AssetSystem.SimulationOnEditor)
            {
#if UNITY_EDITOR
                string loadPath = AssetPathHelper.FindDatabaseAssetPath(location);
                result = UnityEditor.AssetDatabase.LoadAssetAtPath <T>(loadPath);
                if (result == null)
                {
                    MotionLog.Log(ELogLevel.Error, $"Failed to load {loadPath}");
                }
#else
                throw new Exception($"AssetSystem virtual simulation only support unity editor.");
#endif
            }
            else
            {
                if (AssetSystem.BundleServices == null)
                {
                    throw new Exception($"{nameof(AssetSystem.BundleServices)} is null.");
                }

                string      manifestPath = AssetSystem.BundleServices.ConvertLocationToManifestPath(location, variant);
                string      loadPath     = AssetSystem.BundleServices.GetAssetBundleLoadPath(manifestPath);
                AssetBundle bundle       = AssetBundle.LoadFromFile(loadPath);
                if (bundle != null)
                {
                    string fileName = System.IO.Path.GetFileName(location);
                    result = bundle.LoadAsset <T>(fileName);
                }

                if (result == null)
                {
                    MotionLog.Log(ELogLevel.Error, $"Failed to load {loadPath}");
                }

                if (bundle != null)
                {
                    bundle.Unload(false);
                }
            }

            return(result as T);
        }
Exemple #23
0
        /// <summary>
        /// 获取AssetDatabase的加载路径
        /// </summary>
        internal static string FindDatabaseAssetPath(string location)
        {
#if UNITY_EDITOR
            string filePath = CombineAssetPath(AssetSystem.LocationRoot, location);
            if (File.Exists(filePath))
            {
                return(filePath);
            }

            // AssetDatabase加载资源需要提供文件后缀格式,然而资源定位地址并没有文件格式信息。
            // 所以我们通过查找该文件所在文件夹内同名的首个文件来确定AssetDatabase的加载路径。
            // 注意:AssetDatabase.FindAssets() 返回文件内包括递归文件夹内所有资源的GUID
            string   fileName  = Path.GetFileName(filePath);
            string   directory = GetDirectory(filePath);
            string[] guids     = UnityEditor.AssetDatabase.FindAssets(string.Empty, new[] { directory });
            for (int i = 0; i < guids.Length; i++)
            {
                string assetPath = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);

                if (UnityEditor.AssetDatabase.IsValidFolder(assetPath))
                {
                    continue;
                }

                string assetDirectory = GetDirectory(assetPath);
                if (assetDirectory != directory)
                {
                    continue;
                }

                string assetName = Path.GetFileNameWithoutExtension(assetPath);
                if (assetName == fileName)
                {
                    return(assetPath);
                }
            }

            // 没有找到同名的资源文件
            MotionLog.Warning($"Not found asset : {filePath}");
            return(filePath);
#else
            return(string.Empty);
#endif
        }
        public override void Update()
        {
            if (IsDone)
            {
                return;
            }

            if (States == EAssetStates.None)
            {
                States = EAssetStates.Loading;
            }

            // 1. 加载资源对象
            if (States == EAssetStates.Loading)
            {
                var mode = _param.IsAdditive ? LoadSceneMode.Additive : LoadSceneMode.Single;
                _asyncOp = SceneManager.LoadSceneAsync(AssetName, mode);
                if (_asyncOp != null)
                {
                    _asyncOp.allowSceneActivation = _param.ActivateOnLoad;
                    States = EAssetStates.Checking;
                }
                else
                {
                    MotionLog.Log(ELogLevel.Warning, $"Failed to load scene : {AssetName}");
                    States = EAssetStates.Fail;
                    InvokeCompletion();
                }
            }

            // 2. 检测加载结果
            if (States == EAssetStates.Checking)
            {
                if (_asyncOp.isDone || (_param.ActivateOnLoad == false && _asyncOp.progress == 0.9f))
                {
                    SceneInstance instance = new SceneInstance(_asyncOp);
                    instance.Scene = SceneManager.GetSceneByName(AssetName);
                    AssetObject    = instance;
                    States         = EAssetStates.Success;
                    InvokeCompletion();
                }
            }
        }
Exemple #25
0
        public void Load(bool isAdditive, bool activeOnLoad, System.Action <SceneInstance> callback)
        {
            if (_isLoadScene)
            {
                return;
            }

            // 场景加载参数
            SceneInstanceParam param = new SceneInstanceParam();

            param.IsAdditive     = isAdditive;
            param.ActivateOnLoad = activeOnLoad;

            MotionLog.Log($"Begin to load scene : {Location}");
            _isLoadScene       = true;
            _userCallback      = callback;
            _handle            = ResourceManager.Instance.LoadAssetAsync <SceneInstance>(Location, param);
            _handle.Completed += Handle_Completed;
        }
Exemple #26
0
        public override void Update()
        {
#if UNITY_EDITOR
            if (IsDone)
            {
                return;
            }

            if (States == EAssetStates.None)
            {
                States = EAssetStates.Loading;
            }

            // 1. 加载资源对象
            if (States == EAssetStates.Loading)
            {
                string assetPath  = Owner.BundleInfo.LocalPath;
                var    findAssets = UnityEditor.AssetDatabase.LoadAllAssetsAtPath(assetPath);
                List <UnityEngine.Object> result = new List <Object>(findAssets.Length);
                foreach (var findObj in findAssets)
                {
                    if (findObj.GetType() == AssetType)
                    {
                        result.Add(findObj);
                    }
                }
                AllAssets = result.ToArray();
                States    = EAssetStates.Checking;
            }

            // 2. 检测加载结果
            if (States == EAssetStates.Checking)
            {
                States = AllAssets == null ? EAssetStates.Fail : EAssetStates.Success;
                if (States == EAssetStates.Fail)
                {
                    MotionLog.Warning($"Failed to load all asset object : {Owner.BundleInfo.LocalPath}");
                }
                InvokeCompletion();
            }
#endif
        }
        public override void Update()
        {
#if UNITY_EDITOR
            if (IsDone)
            {
                return;
            }

            if (States == EAssetStates.None)
            {
                States = EAssetStates.Loading;
            }

            // 1. 加载资源对象
            if (States == EAssetStates.Loading)
            {
                string assetPath = _owner.BundleInfo.LocalPath;

                // 注意:如果加载路径指向的是文件夹
                if (UnityEditor.AssetDatabase.IsValidFolder(assetPath))
                {
                    string folderPath = assetPath;
                    string fileName   = AssetName;
                    assetPath = AssetPathHelper.FindDatabaseAssetPath(folderPath, fileName);
                }

                AssetObject = UnityEditor.AssetDatabase.LoadAssetAtPath(assetPath, AssetType);
                States      = EAssetStates.Checking;
            }

            // 2. 检测加载结果
            if (States == EAssetStates.Checking)
            {
                States = AssetObject == null ? EAssetStates.Fail : EAssetStates.Success;
                if (States == EAssetStates.Fail)
                {
                    MotionLog.Warning($"Failed to load asset object : {_owner.BundleInfo.LocalPath} : {AssetName}");
                }
                InvokeCompletion();
            }
#endif
        }
Exemple #28
0
        AssetBundleInfo IBundleServices.GetAssetBundleInfo(string bundleName)
        {
            if (_variantCollector != null)
            {
                bundleName = _variantCollector.RemapVariantName(_patchManifest, bundleName);
            }

            if (_patchManifest.Elements.TryGetValue(bundleName, out PatchElement element))
            {
                string          localPath  = AssetPathHelper.MakeStreamingLoadPath(element.MD5);
                AssetBundleInfo bundleInfo = new AssetBundleInfo(bundleName, localPath, string.Empty, element.Version, element.IsEncrypted);
                return(bundleInfo);
            }
            else
            {
                MotionLog.Warning($"Not found element in patch manifest : {bundleName}");
                AssetBundleInfo bundleInfo = new AssetBundleInfo(bundleName, string.Empty);
                return(bundleInfo);
            }
        }
        /// <summary>
        /// 获取场景当前的加载进度,如果场景不存在返回0
        /// </summary>
        public int GetSceneLoadProgress(string location)
        {
            if (_mainScene != null)
            {
                if (_mainScene.Location == location)
                {
                    return(_mainScene.Progress);
                }
            }

            AssetScene scene = TryGetAdditionScene(location);

            if (scene != null)
            {
                return(scene.Progress);
            }

            MotionLog.Warning($"Not found scene {location}");
            return(0);
        }
        /// <summary>
        /// 检测场景是否加载完毕,如果场景不存在返回false
        /// </summary>
        public bool CheckSceneIsDone(string location)
        {
            if (_mainScene != null)
            {
                if (_mainScene.Location == location)
                {
                    return(_mainScene.IsDone);
                }
            }

            AssetScene scene = TryGetAdditionScene(location);

            if (scene != null)
            {
                return(scene.IsDone);
            }

            MotionLog.Warning($"Not found scene {location}");
            return(false);
        }