public static void Build() { bool success = false; try { ms_Context = new Context(); AssetBundleBuild[] assetBundleBuild = GenerateAssetBundle(); success = BuildAB(assetBundleBuild, out AssetBundleManifest assetBundleManifest); if (success) { GenerateAssetMapAndAssetKeyEnumFile(); } if (success && BuildSetting.GetInstance().BuildAssetBuild) { GenerateBundleInfosAndAssetInfosAndAssetKeyEnumFile(assetBundleManifest); } } catch (Exception e) { MDebug.LogError("AssetBundle", "Build AssetBundle Exception:\n" + e.ToString()); } finally { ms_Context = null; EditorUtility.ClearProgressBar(); EditorUtility.DisplayDialog("AssetBundle" , "Build AB " + (success ? "Success" : "Failed") , "OK"); } }
private void SafeInvoke(int eventId, bool isImmediately, IUserData userData) { EventFunction listener = m_Listeners[eventId]; if (listener == null) { MDebug.LogVerbose("EventCenter", $"Event ({m_EventIdToName[eventId]}) not have listener."); if (userData is IObjectPoolItem poolItem) { Kernel.ObjectPool.Release(poolItem); } return; } try { MDebug.LogVerbose("EventCenter" , $"Event ({m_EventIdToName[eventId]}) begin invoke."); listener.Invoke(eventId, isImmediately, userData); if (userData is IObjectPoolItem poolItem) { Kernel.ObjectPool.Release(poolItem); } MDebug.LogVerbose("EventCenter" , $"Event ({m_EventIdToName[eventId]}) end invoke."); } catch (Exception e) { MDebug.LogError("EventCenter" , $"Event ({m_EventIdToName[eventId]}) invoke Exception:\n{e.ToString()}"); } }
protected void FixedUpdate() { BeginFrame(); float deltaTime = Time.fixedDeltaTime; for (int iBehaviour = 0; iBehaviour < m_BehavioursForTraverse.Count; iBehaviour++) { BaseBehaviour iterBehaviour = m_BehavioursForTraverse[iBehaviour]; if (!iterBehaviour.CanUpdate()) { continue; } try { MDebug.LogVerbose("Core" , $"Before execute {iterBehaviour.GetName()}.OnFixedUpdate"); iterBehaviour.OnFixedUpdate(deltaTime); MDebug.LogVerbose("Core" , $"After execute {iterBehaviour.GetName()}.OnFixedUpdate"); } catch (Exception e) { MDebug.LogError("Core" , $"Execute {iterBehaviour.GetName()}.OnFixedUpdate Exception:{e.ToString()}"); } } }
public unsafe void Send(byte[] data, int offset, int count) { if (!IsConnected()) { MDebug.LogError(LOG_TAG, $"Client({GetName()}) 并未连接,无法发送数据"); return; } byte[] buffer = m_WaitSendBuffer.GetBuffer(); int writePosition = m_WaitSendBuffer.GetOffset() + m_WaitSendBufferSize; fixed(byte *pBuffer = &buffer[writePosition]) { *((TLength *)pBuffer) = PACKAGE_HEADER_SIZE + count; writePosition += PACKAGE_HEADER_SIZE; m_WaitSendBufferSize += PACKAGE_HEADER_SIZE; } Array.Copy(data , offset , m_WaitSendBuffer.GetBuffer() , writePosition , count); m_WaitSendBufferSize += count; StartSend(); }
private void DisableBehaviour(BaseBehaviour behaviour) { if (!behaviour.IsEnable() && behaviour.IsLastEnable()) { try { MDebug.LogVerbose("Core" , $"Before execute {behaviour.GetName()}.OnDisable"); behaviour.OnDisable(); MDebug.LogVerbose("Core" , $"After execute {behaviour.GetName()}.OnDisable"); } catch (Exception e) { MDebug.LogError("Core" , $"Execute {behaviour.GetName()}.OnDisable Exception:{e.ToString()}"); } finally { behaviour.SetLastEnable(false); } } }
/// <summary> /// 等待所有的<see cref="TaskUpdate"/>完成 /// </summary> private void WaitTaskUpdate() { for (int iTask = 0; iTask < m_TaskItemsCache.Count; iTask++) { TaskUpdateItem taskItem = m_TaskItemsCache[iTask]; taskItem.ManualResetEvent.WaitOne(); BaseBehaviour iterBehaviour = taskItem.Behaviour; try { MDebug.LogVerbose("Core" , $"Before execute {iterBehaviour.GetName()}.OnAfterTaskUpdate"); iterBehaviour.OnAfterTaskUpdate(taskItem.Output); MDebug.LogVerbose("Core" , $"After execute {iterBehaviour.GetName()}.OnAfterTaskUpdate"); } catch (Exception e) { MDebug.LogError("Core" , $"Execute {iterBehaviour.GetName()}.OnAfterTaskUpdate Exception:{e.ToString()}"); } m_TaskItemPool.Release(taskItem); } m_TaskItemsCache.Clear(); }
public void Release() { #if GF_DEBUG if (m_Root._After != null) { MDebug.Assert(m_Root._After == null , "ArrayPool" , "m_Root._After == null"); StringBuilder stringBuilder = StringUtility.AllocStringBuilder(); stringBuilder.Append("ArrayPool<").Append(typeof(T).FullName).Append(">has memory leak!\n"); Node iterNode = m_Root; while (iterNode != null) { stringBuilder.Append("Offset:").Append(iterNode.GetOffset()) .Append("\tSize:").Append(iterNode.GetSize()) .Append("\tIsUsed:").Append(iterNode.IsUsed()) .Append('\n'); iterNode = iterNode._After; } MDebug.LogError("ArrayPool" , StringUtility.ReleaseStringBuilder(stringBuilder)); } #endif m_Buffer = null; ms_NodePool.Release(m_Root); m_Root = null; }
public bool TryExecuteAction(AssetAction assetAction) { switch (assetAction) { case AssetAction.Load: return(TryLoadAsset()); case AssetAction.Unload: return(TryUnloadAsset()); case AssetAction.LoadedCallback: try { m_OnAssetLoaded?.Invoke(m_AssetKey, m_Asset); } catch (Exception e) { MDebug.LogError(LOG_TAG, "LoadedCallBack Error \n\n" + e.ToString()); } finally { m_OnAssetLoaded = null; } return(true); default: MDebug.Assert(false, LOG_TAG, "Not support AssetAction: " + assetAction); return(false); } }
public void Release(T element) { m_LastUsingTime = MDebug.GetMillisecondsSinceStartup(); #if GF_DEBUG MDebug.Assert(element != null, "Pool", $"element == null"); bool removedFromUsing = false; for (int iObject = 0; iObject < m_Using.Count; iObject++) { UsingObject usingObject = m_Using[iObject]; if (usingObject.Obj.Equals(element)) { removedFromUsing = true; m_Using.RemoveAt(iObject); break; } } if (!removedFromUsing) { MDebug.LogError("Pool" , $"Object({element.ToString()}) not alloc by ObjectPool<{typeof(T).FullName}>!"); } #endif element.OnRelease(); m_Stack.Push(element); m_UsingCount--; }
protected void Update() { // 这里也要调用一次的原因是,当前帧可能没执行FixedUpdate BeginFrame(); float deltaTime = Time.deltaTime; int frameCount = Time.frameCount; ParallelUpdate(deltaTime); for (int iBehaviour = 0; iBehaviour < m_BehavioursForTraverse.Count; iBehaviour++) { BaseBehaviour iterBehaviour = m_BehavioursForTraverse[iBehaviour]; if (!iterBehaviour.CanUpdate()) { continue; } float behaviourDeltaTime; if (iterBehaviour.HasFeature(FeatureFlag.UpdateFrequency)) { try { if (!iterBehaviour.ControlUpdateFrequency(out behaviourDeltaTime, deltaTime, frameCount)) { continue; } } catch (Exception e) { MDebug.LogError("Core" , $"Execute {iterBehaviour.GetName()}.ControlUpdateFrequency Exception:{e.ToString()}"); continue; } } else { behaviourDeltaTime = deltaTime; } try { MDebug.LogVerbose("Core" , $"Before execute {iterBehaviour.GetName()}.OnUpdate"); iterBehaviour.OnUpdate(behaviourDeltaTime); MDebug.LogVerbose("Core" , $"After execute {iterBehaviour.GetName()}.OnUpdate"); } catch (Exception e) { MDebug.LogError("Core" , $"Execute {iterBehaviour.GetName()}.OnUpdate Exception:{e.ToString()}"); } } }
private void ProcessConnect(object sender, SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { MDebug.Log(LOG_TAG, $"Client({GetName()}) 连接成功"); m_BufferPool = new ArrayPool <byte>(1024 * 512); lock (m_TcpConnectActionLock) { m_TcpConnectData = new TcpConnectData(this, e, ConnectState.Connected); } m_IsSending = false; lock (m_BufferPool) { m_SendEventArgs = new SocketAsyncEventArgs(); m_SendEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(ProcessSend); m_SendingBuffer = m_BufferPool.AllocBuffer(DEFAULT_BUFFER_SIZE); m_WaitSendBuffer = m_BufferPool.AllocBuffer(DEFAULT_BUFFER_SIZE); m_WaitSendBufferSize = 0; m_SendEventArgs.SetBuffer(m_SendingBuffer.GetBuffer(), m_SendingBuffer.GetOffset(), 0); m_ReceiveEventArgs = new SocketAsyncEventArgs(); m_ReceiveEventArgs.Completed += new EventHandler <SocketAsyncEventArgs>(ProcessReceive); m_ReceiveBuffer = m_BufferPool.AllocBuffer(DEFAULT_BUFFER_SIZE); m_ReceiveEventArgs.SetBuffer(m_ReceiveBuffer.GetBuffer(), m_ReceiveBuffer.GetOffset(), m_ReceiveBuffer.GetSize()); m_ReceiveState = ReceiveState.ReceivingPackageLength; m_ReceivedPackageCount = 0; m_ReceiveHeaderBuffer = m_BufferPool.AllocBuffer(PACKAGE_HEADER_SIZE); } lock (m_ReceiveLock) { m_ReceivedPackages = new Queue <ArrayPool <byte> .Node>(); m_ReceivedPackages2 = new BetterList <ArrayPool <byte> .Node>(4); m_ReceivedPackages2._SetCount(m_ReceivedPackages2.Capacity); } StartReceive(); } else { MDebug.LogError(LOG_TAG , $"Client({GetName()}) 连接失败: {e.SocketError.ToString()}\n{e.ConnectByNameError.ToString()}"); lock (m_TcpConnectActionLock) { m_TcpConnectData = new TcpConnectData(this, e, ConnectState.ConnectFailed); } m_Client.Close(); m_Client = null; } }
private static int Error(IntPtr luaState) { int success = GetLog(luaState, out string tag, out string message); if (success == 1) { MDebug.LogError(tag, message); } return(success); }
internal void AddBehavior(BaseBehaviour behaviour) { if (!behaviour.IsAlive()) { m_BehaviourOrdered.Add(behaviour); m_AddBehavioursCache.Add(behaviour); } else { MDebug.LogError("Core" , $"AddBehavior ({behaviour.GetName()}) failed. It already alive."); } }
/// <summary> /// 单个协程结束下载 /// </summary> /// <param name="arg1"></param> /// <param name="arg2"></param> /// <param name="arg3"></param> private void RoutineAssetFinishCallBack(bool isSuccess, int downloadedCount, long downloadedSize) { //ToDo if (isSuccess) { MDebug.Log(LOG_TAG, $"RoutineAsset Finish! Result:Success!,DownloadedCount:{downloadedCount},DownloadedSize:{downloadedSize}"); } else { //考虑是否资源出错,重新下载 MDebug.LogError(LOG_TAG, $"RoutineAsset Finish! Result:Failed!,DownloadedCount:{downloadedCount},DownloadedSize:{downloadedSize}"); } }
/// <summary> /// 根据平台生成平台包下的所有文件的配置信息 /// </summary> public static void GenerateAssetVersionFile() { AssetVersionSetting setting = AssetVersionSetting.GetInstance(); string directory = string.Empty; directory = Path.GetDirectoryName(setting.GetFormatedAssetVersionFilePath()); DirectoryInfo directoryInfo = new DirectoryInfo(directory); directory = directoryInfo.FullName; directory = directory.Replace("\\", "/"); if (string.IsNullOrEmpty(directory)) { MDebug.LogError(LOG_NAME, "Target AssetVersionFile Path invalid !"); return; } if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } string assetVersionFilePath = setting.GetFormatedAssetVersionFilePath(); StringBuilder str = new StringBuilder(); FileInfo[] files = directoryInfo.GetFiles("*", SearchOption.AllDirectories); if (files != null) { string assetVersionFileName = setting.GetAssetVersionFileName(); for (int i = 0; i < files.Length; i++) { FileInfo fileInfo = files[i]; string fileFullName = fileInfo.FullName; fileFullName = fileFullName.Replace("\\", "/"); string fileName = fileFullName.Substring(fileFullName.LastIndexOf("/") + 1); string fileRelativePath = fileFullName.Substring(directory.Length + 1); if (fileName.Contains(".meta") || fileName.Equals(assetVersionFileName)) { continue; } string md5 = EncrypUtil.GetFileMD5(fileFullName); string size = Math.Ceiling(fileInfo.Length / 1024f).ToString(); string commitStr = $"{fileRelativePath} {md5} {size}"; str.AppendLine(commitStr); } } File.WriteAllText(assetVersionFilePath, str.ToString()); EditorUtility.DisplayDialog(LOG_NAME , "生成资源版本文件完成!" , "OK"); }
internal void RemoveBehavior(BaseBehaviour behaviour) { if (behaviour.IsAlive()) { behaviour.SetEnable(false); behaviour.SetAlive(false); m_BehaviourOrdered.DeleteByIndex(m_BehaviourOrdered.GetIndexByKey(behaviour)); m_RemoveBehavioursCache.Add(behaviour); } else { MDebug.LogError("Core" , $"RemoveBehavior ({behaviour.GetName()}) failed. It doesn't alive."); } }
public void Release <T>(T obj) where T : class , IObjectPoolItem , new() { ObjectPool <T> pool = GetPool <T>(false); if (pool != null) { pool.Release(obj); } else { MDebug.LogError("Pool" , $"Release object<{typeof(T).FullName}> failed. Because ObjectPool not exist, maybe has memory leak."); } }
public void Release(object obj) { Type type = obj.GetType(); string key = TypeToKey(type); if (m_WeakObjectPools.TryGetValue(key, out WeakReference weakReference) && weakReference.IsAlive) { ((IObjectPool)weakReference.Target).Release(obj); } else { MDebug.LogError("Pool" , $"Release object<{type.FullName}> failed. Because ObjectPool not exist, maybe has memory leak."); } }
private void TryGenerateSetting(int preprocessShadersIndex , PreprocessShadersForGUI preprocessShadersForGUI) { for (int iPreprocessShaders = 0; iPreprocessShaders < m_PreprocessShadersForGUIs.Count; iPreprocessShaders++) { if (iPreprocessShaders == preprocessShadersIndex) { continue; } PreprocessShadersForGUI iterPreprocessShadersForGUI = m_PreprocessShadersForGUIs[iPreprocessShaders]; if (iterPreprocessShadersForGUI.Script == preprocessShadersForGUI.Script) { MDebug.LogWarning("Shader", "不能选择两个相同的脚本"); preprocessShadersForGUI.Script = null; return; } } Type type = preprocessShadersForGUI.Script.GetClass(); if (type.IsAbstract) { MDebug.LogWarning("Shader", "不能是Abstract类"); preprocessShadersForGUI.Script = null; return; } try { Type baseType = type; while (true) { baseType = baseType.BaseType; if (baseType.IsGenericType) { break; } } Type settingType = baseType.GenericTypeArguments[0]; object preprocessShadersSetting = settingType.Assembly.CreateInstance(settingType.FullName); preprocessShadersForGUI.Setting = preprocessShadersSetting as BasePreprocessShadersSetting; } catch (Exception e) { MDebug.LogError("Shader", "生成Setting失败\n" + e.ToString()); preprocessShadersForGUI.Script = null; } }
/// <summary> /// 初始化相关配置,外部调用 /// </summary> /// <param name="initializeData"></param> /// <returns></returns> public IEnumerator InitializeAsync(KernelInitializeData initializeData) { //加载Bundle依赖文件 string bundleInfosJson = string.Empty; try { bundleInfosJson = File.ReadAllText(initializeData.BundleMapFile); m_BundleInfos = JsonMapper.ToObject <BundleInfo[]>(new JsonReader(bundleInfosJson)); } catch (Exception e) { MDebug.LogError(LOG_TAG, $"解析BundleMap:({initializeData.BundleMapFile})失败。\nJson:({bundleInfosJson})\n\n{e.ToString()}"); } yield return(null); //加载AssetMap string assetInfosJson = string.Empty; try { assetInfosJson = File.ReadAllText(initializeData.AssetInfosFile); m_AssetInfos = JsonMapper.ToObject <AssetInfo[]>(new JsonReader(assetInfosJson)); } catch (Exception e) { MDebug.LogError(LOG_TAG, $"解析AssetInfos:({initializeData.AssetInfosFile})失败。\nJson:({assetInfosJson})\n\n{e.ToString()}"); } yield return(null); m_RootBundlePath = initializeData.BundlePath; m_BundleActionRequests = new Queue <BundleActionRequest>(); m_BundleHandlerPool = new ObjectPool <BundleHandler>(); m_BundleHandlers = new BundleHandler[m_BundleInfos.Length]; m_AssetActionRequests = new Queue <AssetActionRequest>(); m_AssetHandlerPool = new ObjectPool <AssetHandler>(); m_AssetHandlers = new AssetHandler[m_AssetInfos.Length]; m_AssetToAssetHandlerMap = new Dictionary <UnityEngine.Object, AssetHandler>(m_AssetInfos.Length); m_AssetToGameObjectInstantiateData = new Dictionary <string, Queue <GameObjectInstantiateData> >(); m_GameObjectToAsset = new Dictionary <GameObject, UnityEngine.Object>(); // 恢复Update SetEnable(true); }
public byte[] CustomLoader(ref string filepath) { #if UNITY_EDITOR if (m_FileToCodes == null) { string luaRoot = XLuaSetting.GetInstance().ExportedLuaRoot; string luaPath = $"{luaRoot}/{filepath.Replace('.', '/')}.lua.txt"; TextAsset luaTextAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(luaPath) as TextAsset; if (luaTextAsset == null) { MDebug.LogError("XLua", $"Not found lua script: " + filepath); return(null); } return(System.Text.Encoding.UTF8.GetBytes(LuaScriptParser.s_Instance.Parse(luaTextAsset.text))); } #endif if (m_FileToCodes.TryGetValue(filepath, out byte[] code))
private void ReleaseBehaviour(BaseBehaviour behaviour) { try { MDebug.LogVerbose("Core" , $"Before execute {behaviour.GetName()}.OnRelease"); behaviour.OnRelease(); MDebug.LogVerbose("Core" , $"After execute {behaviour.GetName()}.OnRelease"); } catch (Exception e) { MDebug.LogError("Core" , $"Execute {behaviour.GetName()}.OnRelease Exception:{e.ToString()}"); } }
/// <summary> /// 根据string,获取数据,但是会传值 /// </summary> /// <param name="dataText"></param> /// <returns></returns> private DownloadDataEntity GetDataEntity(string dataText) { if (!string.IsNullOrEmpty(dataText)) { string[] paramStr = dataText.Split(' '); if (paramStr != null && paramStr.Length >= m_DataParameters.Length) { MDebug.Log(LOG_TAG, $"Data FileName:{paramStr[0]},MD5:{paramStr[1]},Size:{paramStr[2]}"); DownloadDataEntity dataEntity = new DownloadDataEntity(paramStr[0], paramStr[1], long.Parse(paramStr[2])); return(dataEntity); } else { MDebug.LogError(LOG_TAG, $"Data No Enough Parameters,DataText:{dataText}"); } } return(new DownloadDataEntity()); }
private IEnumerator DownloadServerVersionFile(string filePath) { using (UnityWebRequest data = UnityWebRequest.Get(filePath)) { data.timeout = m_DownloadTimeOut; yield return(data.SendWebRequest()); if (string.IsNullOrEmpty(data.error)) { string content = data.downloadHandler.text; m_ServerVersionFileCallBack?.Invoke(content); } else { MDebug.LogError(LOG_TAG, "Download failed !" + data.error); } } }
public void SaveDB() { lock (m_Lock) { try { System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Restart(); FileUtility.WriteToBinaryFile(m_DBPath, m_Assets); MDebug.Log("AssetDB", $"保存AssetDB耗时{stopwatch.ElapsedMilliseconds}ms"); m_IsDirty = false; } catch (Exception e) { MDebug.LogError("AssetDB", $"保存({m_DBPath})失败, Exception:\n{e.ToString()}"); } } }
private void ProcessSend(object sender, SocketAsyncEventArgs e) { lock (m_SendEventArgs) { m_IsSending = false; } if (e.SocketError == SocketError.Success) { StartSend(); } else { MDebug.LogError(LOG_TAG , $"Client({GetName()}) 发送消息失败: {e.SocketError.ToString()}, 即将断开连接"); Disconnect(e); } }
public void LoadDB() { if (File.Exists(m_DBPath)) { try { m_Assets = FileUtility.ReadFromBinaryFile(m_DBPath) as BetterDictionary <string, Asset>; } catch (Exception e) { MDebug.LogError("AssetDB", $"解析({m_DBPath})失败, Exception:\n{e.ToString()}"); m_Assets = new BetterDictionary <string, Asset>(); } } else { m_Assets = new BetterDictionary <string, Asset>(); } }
public static void OnAfter() { BeforePreprocessShaders.s_Handled = false; MDebug.Log("Shader", $"AfterPreprocessShaders"); for (int iPreprocessShaders = 0; iPreprocessShaders < s_PreprocessShaders.Count; iPreprocessShaders++) { IMPreprocessShaders iterPreprocessShaders = s_PreprocessShaders[iPreprocessShaders]; try { iterPreprocessShaders.OnAfter(); } catch (Exception e) { MDebug.LogError("Shader", $"处理Shader({iterPreprocessShaders.GetType().FullName}).OnAfter失败\n{e.ToString()}"); } } }
public void Attach(GameObject root) { Transform rootTransform = root.transform; for (int iRenderer = 0; iRenderer < RenderersIndices.Count; iRenderer++) { int[] iterIndices = RenderersIndices[iRenderer].Value; RendererData iterRendererData = RenderersData[iRenderer]; Transform iterTransform = rootTransform; for (int iIndex = 0; iIndex < iterIndices.Length; iIndex++) { int index = iterIndices[iIndex]; if (iterTransform.childCount > index) { iterTransform = iterTransform.GetChild(index); } else { MDebug.LogError("Renderer" , $"LightmapAttach cant find transform({iterTransform.name}) child({index})" , iterTransform); iterTransform = null; break; } } if (iterTransform) { UnityEngine.Renderer iterRenderer = iterTransform.GetComponent <UnityEngine.Renderer>(); if (iterRenderer) { iterRendererData.Attache(iterRenderer); } else { MDebug.LogError("Renderer" , $"LightmapAttach cant find renderer on transform({iterTransform.name})" , iterTransform); } } } }
private IEnumerator InitializeAsync(KernelInitializeData initializeData) { //加载AssetMap string assetInfosJson = string.Empty; try { assetInfosJson = File.ReadAllText(initializeData.AssetInfosFile); m_AssetInfos = JsonMapper.ToObject <AssetInfo[]>(new JsonReader(assetInfosJson)); } catch (Exception e) { MDebug.LogError(LOG_TAG, $"解析AssetInfos:({initializeData.AssetInfosFile})失败。\nJson:({assetInfosJson})\n\n{e.ToString()}"); } m_AssetCallBackDic = new Dictionary <int, Action <AssetKey, UnityEngine.Object> >(); m_AssetToGameObjectInstantiateData = new Dictionary <string, Queue <GameObjectInstantiateData> >(); yield return(null); SetEnable(true); }