public void TestAssetCache( ) { AssetCache cache = new AssetCache( ); int key = new Location( m_LocationManagers, "blarg" ).Key; // Add an asset to the cache object asset = new object( ); cache.Add( key, asset ); // Make sure that it can be retrived from its key Assert.AreEqual( asset, cache.Find( key ) ); // Collect garbage (will clean up asset) asset = null; GC.Collect( ); // Make sure that the asset is no longer in the cache Assert.AreEqual( cache.Find( key ), asset ); }
private void DecDependedLoadingCountRecursively(AssetCache cache) { cache.DecDependedLoadingCount(); if (cache.assetDepends != null) { foreach (var depend in cache.assetDepends.deps) { AssetCache dependCache = m_assetCacheMap[depend.path]; DecDependedLoadingCountRecursively(dependCache); } } }
private static void LoadOrResolveResourceInternal(Boolean bAsync, String path, Boolean syncIO, Boolean createImmediate, ResolveLevel resolveLevel, Action<UnityObject> onLoadFinish, Int32 dependLevel, String parentPath) { if (path == null) throw new ArgumentNullException("AsyncLoadOrResolveResource, path is null"); //Debug.Log("AsyncLoadOrResolveResource: " + resolveLevel + ": " + path); AssetCache cache; if (!Instance.m_assetCacheMap.TryGetValue(path, out cache)) //缓存中无任何记录 { cache = new AssetCache { path = path, asset = new WeakReference(null), bLoading = false, onLoadFinish = null, dependedLoadingCount = 0 }; Instance.m_assetCacheMap.Add(path, cache); } Instance.IncDependedLoadingCount(cache); if (cache.bLoading) //在加载中 { ++cache.concurrentLoadingCount; //等前一次加载完成 cache.onLoadFinish += (asset) => { onLoadFinish(asset); }; return; } { UnityObject asset = cache.Asset; if (asset != null) //已有资源缓存 { if (resolveLevel <= ResolveLevel.None) //只有ResolveLevel.None,才能直接返回此值,否则它的依赖还未 Resolve { if (!(asset is Material) || MakeSureIsMaterialAndHasAllTexture(cache)) { Instance.IncChildrenDependedLoadingCount(cache); //从Cache取出 ProtectedOnLoadFinish(path, onLoadFinish, asset); return; } } if (cache.AssetBundle != null && (MakeSureIsMaterialAndHasAllTexture(cache) || Instance.m_donotReleaseOrResolveDepResPathSet.Contains(path))) { Instance.IncChildrenDependedLoadingCount(cache); //从Cache取出 ProtectedOnLoadFinish(path, onLoadFinish, asset); return; } } } //if (m_bEnableLog && dependLevel == 0) // Log("no cache: " + path); //if (syncIO && createImmediate) // Debug.LogWarning(String.Format("Really load bundle {0}, {1}, {2} #{3}", path, syncIO, createImmediate, dependLevel)); //开始加载 cache.bLoading = true; cache.concurrentLoadingCount = 0; if (cache.onLoadFinish != null) throw new Exception("cache.onLoadFinish should be null, got " + cache.onLoadFinish.ToString()); cache.onLoadFinish += onLoadFinish; //加载好 AssetBundle 后执行这段 Action<bool, AssetBundle, ECAssetBundleHeader, bool> onAssetBundleOK = (bLoadNew, assetBundle, assetDepends, async) => { if (assetBundle == null) { Debug.LogWarning("Failed to load assetbundle file: " + path); cache.asset.Target = null; CacheFinishLoading(cache, null); return; } cache.SetAssetBundle(assetBundle); cache.assetDepends = assetDepends; //加载好所有依赖后执行这段,asset 可为空 (此时加载 assetBundle.mainAsset) Action<UnityObject> onDependsOK = (manuallyLoadedAsset) => { //加载 Asset if (cache.AssetBundle == null) Debug.LogWarning("asset bundle is null when loading asset: " + path); Action<UnityObject> onAssetLoaded = (mainAsset) => //Load asset 后调用 { //ReloadProperty(asset); if (mainAsset == null) Debug.LogError("Failed to load main asset of: " + path); Boolean bInCache = (cache.Asset != null); var resourceAsset = mainAsset; cache.asset.Target = resourceAsset; if (resourceAsset != null && !bInCache && Instance.ShouldKeepCache(cache)) { //!bInCache 即首次加载才需记录 Instance.m_donotReleaseAssetHolder.Add(resourceAsset); } if (m_bEnableLog) Log("LoadAsset finish: " + path + "@ " + Time.realtimeSinceStartup); if (resolveLevel <= ResolveLevel.None && (assetDepends.option & ECAssetBundleHeader.BundleOption.ManuallyResolve) == ECAssetBundleHeader.BundleOption.ManuallyResolve) { //cache.UnloadAssetBundle(); //Unload后好像有bug } CacheFinishLoading(cache, resourceAsset); }; if (manuallyLoadedAsset != null) { onAssetLoaded(manuallyLoadedAsset); } else if (!bLoadNew && cache.Asset != null && !(cache.Asset is Material)) { onAssetLoaded(cache.Asset); } else { if (async || EnablePauseFlag) { ResourceLoader.GetTaskQueue().AddCoroutineInMainThread(AsyncLoadAsset(assetBundle, onAssetLoaded, path)); } else { ////checkres(path, typeof(Texture), dependLevel); CheckDependBundlesInCache(path); UnityObject mainAsset = assetBundle.Load("1"); if (mainAsset == null) Debug.LogWarning("Failed to Load asset with name '1' from: " + path); if (m_bEnableLog) Log("AssetBundle.Load finish: " + path + "@ " + Time.realtimeSinceStartup); ReloadProperty(mainAsset); onAssetLoaded(mainAsset); } } }; //开始加载所有依赖 if (assetDepends == null || assetDepends.deps.Length == 0) //无依赖 { onDependsOK(null); } else //有依赖 { ////var CurPath = path; var specialType = assetDepends.specialType; Int32 leftDependsCount = assetDepends.deps.Length; if (specialType == ECAssetBundleHeader.BundleSpecialType.Material) //特殊处理 Material //TODO 移到 assetDepends 中处理 { var dependAssets = new UnityObject[assetDepends.deps.Length]; //material 的依赖加载完毕,手动设置贴图 Action onMaterialDependsOK = ()=> { Material matAsset = assetBundle.Load("1") as Material; for (Int32 iDepend=0; iDepend<assetDepends.deps.Length; ++iDepend) { var depend = assetDepends.deps[iDepend]; if (!String.IsNullOrEmpty(depend.name)) { Texture tex = dependAssets[iDepend] as Texture; matAsset.SetTexture(depend.name, tex); } } ReloadProperty(matAsset); onDependsOK(matAsset); }; for (Int32 iDepend=0; iDepend<assetDepends.deps.Length; ++iDepend) { Int32 dependIndex = iDepend; var depend = assetDepends.deps[dependIndex]; //Material 手动加载贴图 if (!String.IsNullOrEmpty(depend.name)) { LoadOrResolveResource(bAsync, depend.path, syncIO, createImmediate, ResolveLevel.None, (dependAsset)=> { PromptIfLoadDependFailed(path, dependAsset); dependAssets[dependIndex] = dependAsset; --leftDependsCount; if ((dependAsset as Texture) == null) { Debug.LogError("Failed to load texture bundle: " + depend.path + " for material: " + path); } if (leftDependsCount == 0) //已加载所有依赖项 { onMaterialDependsOK(); } }, dependLevel+1, parentPath); } else //其他依赖正常加载 { LoadOrResolveResource(bAsync, depend.path, syncIO, createImmediate, IncreaseResolveLevel(resolveLevel), (dependAsset)=> //TODO 去重 { PromptIfLoadDependFailed(path, dependAsset); --leftDependsCount; if (leftDependsCount == 0) //已加载所有依赖项 { onMaterialDependsOK(); } }, dependLevel+1, parentPath); } } } else //通用处理 { foreach (var depend_ in assetDepends.deps) { var depend = depend_; //创建新的局部变量 LoadOrResolveResource(bAsync, depend.path, syncIO, createImmediate, IncreaseResolveLevel(resolveLevel), (dependAsset)=> { PromptIfLoadDependFailed(path, dependAsset); --leftDependsCount; if (leftDependsCount == 0) //已加载所有依赖项 { onDependsOK(null); //尽量先加载依赖 } }, dependLevel+1, parentPath); } } } }; if (cache.AssetBundle != null) //有缓冲 { onAssetBundleOK(false, cache.AssetBundle, cache.assetDepends, cache.createFromFile); } else { Action<AssetBundle, ECAssetBundleHeader, bool> onLoadBundleFinished = (assetBundle, assetDepends, createfromfile)=> { cache.createFromFile = createfromfile; if (m_bEnableLog) Log("LoadAssetBundle finish: " + path + "@ " + Time.realtimeSinceStartup); onAssetBundleOK(true, assetBundle, assetDepends, createfromfile); }; if (m_bEnableLog) Log("LoadAssetBundle begin: " + path + "@ " + Time.realtimeSinceStartup); if (bAsync) { ResourceLoader.AsyncLoadAssetBundle(path, syncIO, createImmediate, onLoadBundleFinished); } else { ResourceLoader.LoadAssetBundleImmediate(path, onLoadBundleFinished); } } }
private Boolean ShouldReleaseLRUCache(AssetCache cache, Int32 curTime) { Int32 minCacheTime = 20 * 1; //约 1 s Int32 maxCacheTime = 20 * 120; //约 120 s Int32 minCacheCount = 1000/100 * 5; //约 5 MB Int32 maxCacheCount = 1000/100 * 10; //约 10 MB Int32 dtime = curTime - cache.LRUAccessTime; if (dtime < minCacheTime) return false; if (m_assetLRUCacheCount < minCacheCount) return false; Double timeFactor = (Double)(dtime - minCacheTime) / (maxCacheTime - minCacheTime); Double countFactor = (Double)(m_assetLRUCacheCount - minCacheCount) / (maxCacheCount - minCacheCount); return timeFactor * countFactor > 0.618; }
private static Boolean MakeSureIsMaterialAndHasAllTexture(AssetCache cache) { if (!IsMaterialHasAllTexture(cache)) return false; ReloadProperty(cache.Asset); return true; }
private Boolean ShouldKeepBundle(AssetCache cache) { return ShouldKeepInLRU(cache.Asset) || ShouldKeepCache(cache); }
private void RefreshLRUAccessTimeRecursively(AssetCache cache) { if (IsCacheInLRU(cache)) { cache.LRUAccessTime = GetTime(); MoveLRUCacheToRear(cache); } if (cache.assetDepends != null) { foreach (var depend in cache.assetDepends.deps) { AssetCache dependCache = m_assetCacheMap[depend.path]; RefreshLRUAccessTimeRecursively(dependCache); } } }
private void PushBackCacheToLRU(AssetCache cache) { var prev = m_assetLRUCacheRear.prevLRUCache; var next = m_assetLRUCacheRear; prev.nextLRUCache = cache; next.prevLRUCache = cache; cache.prevLRUCache = prev; cache.nextLRUCache = next; ++m_assetLRUCacheCount; }
public override bool LoadSpritesAsync(string fileName, Action <float, bool, UnityEngine.Object[]> onProcess) { return(LoadObjectAsync <Texture>(fileName, ResourceCacheType.rctRefAdd, delegate(float process, bool isDone, Texture obj) { if (isDone) { if (obj == null) { if (onProcess != null) { onProcess(process, isDone, null); } return; } AssetCache cache = AssetCacheManager.Instance.FindOrgObjCache(obj); if (cache == null) { if (onProcess != null) { onProcess(process, isDone, null); } return; } ResourceMgr.Instance.DestroyObject(obj); ResourceAssetCache resCache = cache as ResourceAssetCache; if (resCache == null) { if (onProcess != null) { onProcess(process, isDone, null); } return; } if (!IsResLoaderFileName(ref fileName)) { if (onProcess != null) { onProcess(process, isDone, null); } return; } Sprite[] ret = Resources.LoadAll <Sprite>(fileName); if (ret == null || ret.Length <= 0) { if (onProcess != null) { onProcess(process, isDone, null); } return; } AddRefSprites(resCache, ret, ResourceCacheType.rctRefAdd); if (onProcess != null) { onProcess(process, isDone, ret); } return; } if (onProcess != null) { onProcess(process, isDone, null); } } )); }
public bool LoadObjectAsync <T>(string fileName, ResourceCacheType cacheType, Action <float, bool, T> onProcess) where T : UnityEngine.Object { if (string.IsNullOrEmpty(fileName)) { return(false); } string orgFileName = fileName; #if USE_HAS_EXT T obj = FindCache <T>(orgFileName); if (obj != null) { if (AddRefCache(orgFileName, obj, cacheType, typeof(T)) != null) { if (onProcess != null) { onProcess(1.0f, true, obj); } return(true); } } #endif if (!IsResLoaderFileName(ref fileName)) { return(false); } // 同时反复调用可能产生多个Timer ResourceRequest request = Resources.LoadAsync(fileName, typeof(T)); if (request == null) { return(false); } if (request.isDone) { T orgObj = request.asset as T; if (orgObj == null) { string err = string.Format("LoadObjectAsync: ({0}) error!", fileName); LogMgr.Instance.LogError(err); return(false); } AssetCache cache = AddRefCache(orgFileName, orgObj, cacheType, typeof(T)); #if USE_HAS_EXT AddCacheMap(cache); #endif if (onProcess != null) { onProcess(request.progress, request.isDone, orgObj); } return(true); } var ret = AsyncOperationMgr.Instance.AddAsyncOperation <ResourceRequest, System.Object> (request, delegate(ResourceRequest req) { if (req.isDone) { T orgObj = req.asset as T; if (orgObj == null) { string err = string.Format("LoadObjectAsync: ({0}) error!", fileName); LogMgr.Instance.LogError(err); return; } AssetCache cache = AddRefCache(orgFileName, orgObj, cacheType, typeof(T)); #if USE_HAS_EXT AddCacheMap(cache); #endif if (onProcess != null) { onProcess(req.progress, req.isDone, orgObj); } } else { if (onProcess != null) { onProcess(req.progress, req.isDone, null); } } } ); return(ret != null); }
private void Add(Asset asset, AssetCache.CachedAsset item) { cacheTable[asset.Family].AddItem(asset.Name, item); }
private IAsset TranslateInternal(IAsset asset) { IAsset result; var chronometer = EngineContext.Current.Resolve <IChronometer>(); using (chronometer.Step("Translate asset {0}".FormatInvariant(asset.VirtualPath))) { bool validationMode = ThemeHelper.IsStyleValidationRequest(); if (validationMode || !TryGetCachedAsset(asset, out result)) { using (KeyedLock.Lock("CachedAsset:" + asset.VirtualPath)) { if (validationMode || !TryGetCachedAsset(asset, out result)) { using (chronometer.Step("Compile asset {0}".FormatInvariant(asset.VirtualPath))) { result = _inner.Translate(asset); var cachedAsset = new CachedAsset { AssetTypeCode = AssetTypeCode.Css, IsStylesheet = true, Minified = result.Minified, Combined = result.Combined, Content = result.Content, OriginalAssets = asset.OriginalAssets, VirtualPath = asset.VirtualPath, VirtualPathDependencies = result.VirtualPathDependencies, Url = asset.Url }; result = AssetTranslorUtil.PostProcessAsset(cachedAsset, this.IsDebugMode); if (!validationMode) { var pCodes = new List <string>(3); if (cachedAsset.Minified) { pCodes.Add(DefaultAssetCache.MinificationCode); } if (cachedAsset.RelativePathsResolved) { pCodes.Add(DefaultAssetCache.UrlRewriteCode); } if (cachedAsset.Autoprefixed) { pCodes.Add(DefaultAssetCache.AutoprefixCode); } AssetCache.InsertAsset( cachedAsset.VirtualPath, cachedAsset.VirtualPathDependencies, cachedAsset.Content, pCodes.ToArray()); } } } } } } return(result); }
// changed is return true bool UpdateAssetRefMap() { bool ret = false; // used list var list = AssetCacheManager.Instance.UsedCacheList; if (list.Count != mUsedAssetRefMap.Count) { ret = true; } HashSet <string> hash = new HashSet <string> (); HashSet <string> removeHash = new HashSet <string> (); var node = list.First; while (node != null) { AssetCache cache = node.Value; if (cache != null) { AssetBundleCache bundleCache = cache as AssetBundleCache; if ((bundleCache != null) && (bundleCache.Target != null)) { string key = GetBundleKey(bundleCache.Target.FileName); hash.Add(key); if (mUsedAssetRefMap.ContainsKey(key)) { if (mUsedAssetRefMap[key] != cache.RefCount) { mUsedAssetRefMap[key] = cache.RefCount; ret = true; } } else { mUsedAssetRefMap.Add(key, cache.RefCount); ret = true; } } else { ResourceAssetCache resCache = cache as ResourceAssetCache; if ((resCache != null) && (resCache.Target != null)) { string key = StringHelper.Format("Res:{0}", resCache.Target.name); hash.Add(key); if (mUsedAssetRefMap.ContainsKey(key)) { if (mUsedAssetRefMap[key] != cache.RefCount) { mUsedAssetRefMap[key] = cache.RefCount; ret = true; } } else { mUsedAssetRefMap.Add(key, cache.RefCount); ret = true; } } } } node = node.Next; } var iter = mUsedAssetRefMap.GetEnumerator(); while (iter.MoveNext()) { string key = iter.Current.Key; if (!hash.Contains(key)) { removeHash.Add(key); } } iter.Dispose(); var removeIter = removeHash.GetEnumerator(); while (removeIter.MoveNext()) { mUsedAssetRefMap.Remove(removeIter.Current); } removeIter.Dispose(); hash.Clear(); removeHash.Clear(); // not used list list = AssetCacheManager.Instance.NotUsedCacheList; if (list.Count != mNotUsedAssetRefMap.Count) { ret = true; } node = list.First; while (node != null) { AssetCache cache = node.Value; if (cache != null) { AssetBundleCache bundleCache = cache as AssetBundleCache; if ((bundleCache != null) && (bundleCache.Target != null)) { string key = GetBundleKey(bundleCache.Target.FileName); hash.Add(key); if (mNotUsedAssetRefMap.ContainsKey(key)) { if (mNotUsedAssetRefMap[key] != cache.RefCount) { mNotUsedAssetRefMap[key] = cache.RefCount; ret = true; } } else { mNotUsedAssetRefMap.Add(key, cache.RefCount); ret = true; } } else { ResourceAssetCache resCache = cache as ResourceAssetCache; if ((resCache != null) && (resCache.Target != null)) { string key = StringHelper.Format("Res:{0}", resCache.Target.name); hash.Add(key); if (mNotUsedAssetRefMap.ContainsKey(key)) { if (mNotUsedAssetRefMap[key] != cache.RefCount) { mNotUsedAssetRefMap[key] = cache.RefCount; ret = true; } } else { mNotUsedAssetRefMap.Add(key, cache.RefCount); ret = true; } } } } node = node.Next; } iter = mNotUsedAssetRefMap.GetEnumerator(); while (iter.MoveNext()) { string key = iter.Current.Key; if (!hash.Contains(key)) { removeHash.Add(key); } } iter.Dispose(); removeIter = removeHash.GetEnumerator(); while (removeIter.MoveNext()) { mNotUsedAssetRefMap.Remove(removeIter.Current); } removeIter.Dispose(); hash.Clear(); removeHash.Clear(); return(ret); }
/// <summary> /// send asset /// </summary> /// <param name="sender"></param> /// <param name="receivers"></param> /// <param name="asset"></param> /// <returns></returns> public async Task <object> SendToMultiAddress(MultiReceiverRequest[] receivers, string asset = "neo", UInt160 sender = null) { if (CurrentWallet == null) { return(Error(ErrorCode.WalletNotOpen)); } if (receivers.IsEmpty()) { return(Error(ErrorCode.ParameterIsNull, $"receivers is null!")); } UInt160 assetHash = ConvertToAssetId(asset, out var convertError); if (assetHash == null) { return(Error(ErrorCode.InvalidPara, $"asset is not valid:{convertError}")); } var assetInfo = AssetCache.GetAssetInfo(assetHash); if (assetInfo == null) { return(Error(ErrorCode.InvalidPara, $"asset is not valid:{convertError}")); } if (sender != null) { var account = CurrentWallet.GetAccount(sender); if (account == null) { return(Error(ErrorCode.AddressNotFound)); } } var toes = new List <(UInt160 scriptHash, BigDecimal amount)>(); foreach (var receiver in receivers) { if (!BigDecimal.TryParse(receiver.Amount, assetInfo.Decimals, out BigDecimal sendAmount) || sendAmount.Sign <= 0) { return(Error(ErrorCode.InvalidPara, $"Incorrect Amount Format:{receiver.Amount}")); } toes.Add((receiver.Address, sendAmount)); } var outputs = toes.Select(t => new TransferOutput() { AssetId = assetHash, Value = t.amount, ScriptHash = t.scriptHash, }).ToArray(); try { Transaction tx = CurrentWallet.MakeTransaction(outputs, sender); if (tx == null) { return(Error(ErrorCode.BalanceNotEnough, "Insufficient funds")); } var(signSuccess, context) = CurrentWallet.TrySignTx(tx); if (!signSuccess) { return(Error(ErrorCode.SignFail, context.SafeSerialize())); } await tx.Broadcast(); return(new TransactionModel(tx)); } catch (Exception ex) { if (ex.Message.Contains("Insufficient GAS")) { return(Error(ErrorCode.GasNotEnough)); } return(Error(ErrorCode.TransferError, ex.Message)); } }
/// <summary> /// send asset /// </summary> /// <param name="sender"></param> /// <param name="receiver"></param> /// <param name="amount"></param> /// <param name="asset"></param> /// <returns></returns> public async Task <object> SendToAddress(UInt160 receiver, string amount, string asset = "neo", UInt160 sender = null) { if (CurrentWallet == null) { return(Error(ErrorCode.WalletNotOpen)); } if (receiver == null) { return(Error(ErrorCode.ParameterIsNull, $"receiver address is null!")); } UInt160 assetHash = ConvertToAssetId(asset, out var convertError); if (assetHash == null) { return(Error(ErrorCode.InvalidPara, $"asset is not valid:{convertError}")); } var assetInfo = AssetCache.GetAssetInfo(assetHash); if (assetInfo == null) { return(Error(ErrorCode.InvalidPara, $"asset is not valid:{convertError}")); } if (!BigDecimal.TryParse(amount, assetInfo.Decimals, out BigDecimal sendAmount) || sendAmount.Sign <= 0) { return(Error(ErrorCode.InvalidPara, "Incorrect Amount Format")); } if (sender != null) { var account = CurrentWallet.GetAccount(sender); if (account == null) { return(Error(ErrorCode.AddressNotFound)); } var balance = sender.GetBalanceOf(assetHash); if (balance.Value < sendAmount.Value) { return(Error(ErrorCode.BalanceNotEnough)); } } try { Transaction tx = CurrentWallet.MakeTransaction(new[] { new TransferOutput { AssetId = assetHash, Value = sendAmount, ScriptHash = receiver } }, sender); if (tx == null) { return(Error(ErrorCode.BalanceNotEnough, "Insufficient funds")); } var(signSuccess, context) = CurrentWallet.TrySignTx(tx); if (!signSuccess) { return(Error(ErrorCode.SignFail, context.SafeSerialize())); } await tx.Broadcast(); return(new TransactionModel(tx)); } catch (Exception ex) { if (ex.Message.Contains("Insufficient GAS")) { return(Error(ErrorCode.GasNotEnough)); } return(Error(ErrorCode.TransferError, ex.Message)); } }
private Boolean IsCacheInLRU(AssetCache cache) { return cache.prevLRUCache != null && cache.nextLRUCache != null; }
private void RemoveCacheFromLRU(AssetCache cache) { var prev = cache.prevLRUCache; var next = cache.nextLRUCache; prev.nextLRUCache = next; next.prevLRUCache = prev; cache.prevLRUCache = null; cache.nextLRUCache = null; --m_assetLRUCacheCount; }
public void GenerateCodeForGame(AssetLoadMode loadMode, bool clearAssetCache, bool skipLevels) { BeginGenerateModules(); string projectPath = FPaths.ProjectFilePath; string projectName = FPaths.GetBaseFilename(projectPath); UnrealModuleInfo module = new UnrealModuleInfo(null, projectName, projectPath); BeginGenerateModule(module); UClass worldClass = GCHelper.Find <UClass>(Classes.UWorld); AssetCache assetCache = new AssetCache(this); if (!clearAssetCache) { assetCache.Load(); } List <string> assetBlacklist = LoadAssetBlacklist(); AssetLogClear(); AssetLogLine("Load assets {0}", DateTime.Now); bool registeredCrashHandler = false; if (Settings.CatchCrashOnAssetLoading) { FCoreDelegates.OnHandleSystemError.Bind(OnAssetLoadingCrash); registeredCrashHandler = true; } using (FARFilter filter = new FARFilter()) { filter.RecursiveClasses = true; filter.ClassNames.Add(UClass.GetClass <UBlueprint>().GetFName()); filter.ClassNames.Add(UClass.GetClass <UBlueprintGeneratedClass>().GetFName()); filter.ClassNames.Add(UClass.GetClass <UUserDefinedStruct>().GetFName()); filter.ClassNames.Add(UClass.GetClass <UUserDefinedEnum>().GetFName()); if (!skipLevels && worldClass != null) { filter.ClassNames.Add(worldClass.GetFName()); } List <FAssetData> assets = FAssetData.Load(filter); foreach (FAssetData asset in assets) { string assetFileName, assetFileNameError; if (!asset.TryGetFilename(out assetFileName, out assetFileNameError)) { FMessage.Log(string.Format("FAssetData.TryGetFilename failed. ObjectPath:'{0}' reason:'{1}'", asset.ObjectPath.ToString(), assetFileNameError)); continue; } bool isEngineAsset = FPaths.IsSameOrSubDirectory(FPaths.EngineContentDir, FPaths.GetPath(assetFileName)); if (loadMode != AssetLoadMode.All) { if ((isEngineAsset && loadMode != AssetLoadMode.Engine) || (!isEngineAsset && loadMode != AssetLoadMode.Game)) { continue; } } if (!assetCache.HasAssetChanged(asset, assetFileName)) { if (Settings.LogAssetLoadingVerbose) { AssetLogLine("'{0}' unchanged", assetFileName); } continue; } // Log that we are loading this asset so we know which assets crash on load AssetLog("'{0}' - ", asset.ObjectPath.ToString()); if (assetBlacklist.Contains(asset.ObjectPath.ToString())) { AssetLogLine("blacklisted"); continue; } loadingAsset = asset.ObjectPath.ToString(); UObject obj = asset.GetAsset(); loadingAsset = null; UClass unrealClass = asset.GetClass(); if (obj == null || unrealClass == null) { AssetLogLine("null"); continue; } AssetLogLine("done"); if (unrealClass.IsChildOf <UBlueprint>()) { UBlueprint blueprint = obj as UBlueprint; if (blueprint != null) { UBlueprintGeneratedClass blueprintGeneratedClass = blueprint.GeneratedClass as UBlueprintGeneratedClass; if (blueprintGeneratedClass != null) { GenerateCodeForStruct(module, blueprintGeneratedClass); } } } else if (unrealClass.IsChildOf <UBlueprintGeneratedClass>()) { UBlueprintGeneratedClass blueprintGeneratedClass = obj as UBlueprintGeneratedClass; if (blueprintGeneratedClass != null) { GenerateCodeForStruct(module, blueprintGeneratedClass); } } else if (unrealClass.IsChildOf <UUserDefinedStruct>()) { UUserDefinedStruct unrealStruct = obj as UUserDefinedStruct; if (unrealStruct != null) { GenerateCodeForStruct(module, unrealStruct); } } else if (unrealClass.IsChildOf <UUserDefinedEnum>()) { UUserDefinedEnum unrealEnum = obj as UUserDefinedEnum; if (unrealEnum != null) { GenerateCodeForEnum(module, unrealEnum); } } else if (unrealClass.IsChildOf(worldClass)) { TArrayUnsafeRef <UObject> levels = new TArrayUnsafeRef <UObject>(Native.Native_UWorld.GetLevels(obj.Address)); foreach (UObject level in levels) { using (TArrayUnsafe <UBlueprint> levelBlueprints = new TArrayUnsafe <UBlueprint>()) { Native.Native_ULevel.GetLevelBlueprints(level.Address, levelBlueprints.Address); foreach (UBlueprint blueprint in levelBlueprints) { UBlueprintGeneratedClass blueprintGeneratedClass = blueprint.GeneratedClass as UBlueprintGeneratedClass; if (blueprintGeneratedClass != null) { //GenerateCodeForStruct(blueprintGeneratedClass); } } } } } } } if (registeredCrashHandler) { FCoreDelegates.OnHandleSystemError.Unbind(OnAssetLoadingCrash); } assetCache.Save(); EndGenerateModule(module); EndGenerateModules(); }
private void MoveLRUCacheToRear(AssetCache cache) { RemoveCacheFromLRU(cache); PushBackCacheToLRU(cache); }
public override string Render(Change entityDataGridViewChange, Guid entityDataGridViewInstanceID, AssetCache assetCache, int currentColumnIndex) { AssetCache imageCache = assetCache; Change currentChange = entityDataGridViewChange; List <EntityData> entityDatas = currentChange.GetEntityDatas(); string attributeName = entityDatas.Select(ed => ed.Attribute.AttributeName).FirstOrDefault() ?? string.Empty; var currentSKuOrders = NatalieTools.Instance.SkuOrders[entityDataGridViewInstanceID]; var skusWithValues = entityDatas.Select( ed => new { ed.Sku, ed.Value, Image = imageCache.GetAsset(ed.Sku), SkuIndex = currentSKuOrders.IndexOf(ed.Sku.ID) }); var skusWithBlanks = currentChange.GetBlanks().Select( sku => new { Sku = sku, Value = "<blank>", Image = imageCache.GetAsset(sku), SkuIndex = currentSKuOrders.IndexOf(sku.ID) }); if (!entityDatas.Any()) { skusWithBlanks = skusWithBlanks.Union( currentChange.GetSkus().Select( sku => new { Sku = sku, Value = string.Empty, Image = imageCache.GetAsset(sku), SkuIndex = currentSKuOrders.IndexOf(sku.ID) })); } //group by image filename var files = skusWithValues.Union(skusWithBlanks).GroupBy(s => s.Image).OrderBy(p => p.Min(q => q.SkuIndex)).ToList(); var html = new StringBuilder(); html.Append( @"<html> <head> <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" /> <style type=""text/css""> img.skuImage { max-width: 300px; max-height: 300px; margin-right: 10px; } div.inline { float:left;margin-right:20px;margin-bottom:10px; } .clearBoth { clear:both; } table { border-width: 2px; border-spacing: 3px; border-style: outset; border-color: gray; } td, th { border: 1px solid gray; } .topLine{ width:600px; position:fixed; top:0; left:0; z-index:1; text-align:left; height: auto; border: 0 none; padding: 2px; background-color: #DDE5FF; margin-left: 8px; margin-top: 5px; } a img { text-decoration: none; border: 0 none; } </style> <script type=""text/javascript"" src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'></script>" ); html.AppendFormat(@" <link rel=""stylesheet"" type=""text/css"" href=""{0}\CSS\ImageAreaSelect\imgareaselect-animated.css"" /> <link rel=""stylesheet"" type=""text/css"" href=""{0}\CSS\Colorbox\colorbox.css"" /> <script type='text/javascript' src='http://toolsuite.bytemanagers.com/Javascripts/ImageAreaSelect/jquery.imgareaselect.pack.js'></script> <script type='text/javascript' src='http://toolsuite.bytemanagers.com/Javascripts/Colorbox/jquery.colorbox-min.js'></script> <script type='text/javascript' src='http://toolsuite.bytemanagers.com/Javascripts/Cookie/jquery.cookie.js'></script> " , Environment.CurrentDirectory); html.Append(@" <script type=""text/javascript""> var currentIASObjects; var zoomEnabled=false; var showAllSkuTables=false; $(document).ready(function () { currentIASObjects = $('.skuImage').imgAreaSelect({ instance: true, handles: true, onSelectChange: preview }); $('#clearAllIAS').click(function() { if( currentIASObjects == undefined || currentIASObjects.length == 0 ) return; $.each(currentIASObjects, function(index, value) { value.cancelSelection(); }); }); //bug in Windows server 2003, does not load the margin for the div $('#skuImageContainer').css('margin-top','61px'); $('a.imageLink').click(function(e) { $.cookie('czimg',$(this).attr('id')); e.preventDefault(); }); $('.imageLink').ready(function() { var zoomed = $.cookie('enablezoom'); if(zoomed != null && zoomed == '1') { $('#toggleZoom').click(); } var czimg = $.cookie('czimg'); if ( czimg != null && $('#'+czimg).length > 0) { $('#'+czimg).click(); } }); function skuTablesCheckAndToggle() { if($('table.skuTable:visible').length == 0) { $('#toggleSkuTables').html('Show All Skus'); } else { $('#toggleSkuTables').html('Hide All Skus'); } } $('#toggleSkuTables').click(function() { if(showAllSkuTables) { $('.skuTable').hide(); showAllSkuTables=false; $(this).html('Show All Skus'); } else { $('.skuTable').show(); showAllSkuTables=true; $(this).html('Hide All Skus'); } }); $('#toggleZoom').click(function() { if(!zoomEnabled) { var zoomValue = $.cookie('zoomvalue'); if(zoomValue != null) { $('#zoomPercent').val(zoomValue); enableZoom(zoomValue,zoomValue); } else enableZoom('100%','100%'); $(this).html('Disable Zoom'); } else { disableZoom(); $(this).html('Enable Zoom'); } }); $('#zoomPercent').change(function() { disableZoom(); p = $(this).val(); $.cookie('zoomvalue',p); enableZoom(p,p); }); $(document).bind('cbox_closed', function(){ $.cookie('czimg',null); }); $('#pinBrowser').click(function(){ if ($(this).is(':checked')) { if (window.external) { window.external.PinCurrentImages(); } } else { if (window.external) { window.external.UnPinCurrentImages(); } } }); }); function enableZoom(maxWidth,maxHeight) { if(maxWidth == '-' || maxHeight == '-') $(""a[rel='skuImageLink']"").colorbox({photo:true}); else $(""a[rel='skuImageLink']"").colorbox({photo:true, maxWidth:maxWidth, maxHeight:maxHeight}); $.colorbox.init(); zoomEnabled = true; $('#zoomPercent').show(); $.cookie('enablezoom','1'); } function disableZoom() { $.colorbox.remove(); zoomEnabled = false; $('#zoomPercent').hide(); $.cookie('enablezoom',null); } function skuTablesCheckAndToggle() { if($('table.skuTable:visible').length == 0) { $('#toggleSkuTables').html('Show All Skus'); showAllSkuTables=false; } else { $('#toggleSkuTables').html('Hide All Skus'); showAllSkuTables=true; } } function preview(img, selection) { if (!selection.width || !selection.height) return; $('#x1').val(selection.x1); $('#y1').val(selection.y1); $('#x2').val(selection.x2); $('#y2').val(selection.y2); $('#width').val(selection.width); $('#height').val(selection.height); } function selectSku(skuID,columnIndex) { if (window.external) { window.external.SelectSku(skuID,columnIndex); } } </script> " ); html.Append(@"</head><body> <div class='topLine'> <a href='javascript:void(0);' id='clearAllIAS'>Clear All</a> | <a href='javascript:void(0);' id='toggleSkuTables'>Show All Skus</a> | <a href='javascript:void(0);' id='toggleZoom'>Enable Zoom</a> <select id='zoomPercent' style='display:none;'> <option value='100%'>50%</option> <option value='200%'>75%</option> <option value='-'>100%</option> </select> | <input type='checkbox' id='pinBrowser'>Pin</input> <br/> <b>Width</b> <input type='text' value='-' id='width' style='width:30px;text-align:center;margin-right:15px;'> <b>Height</b> <input type='text' value='-' id='height' style='width:30px;text-align:center;margin-right:15px;'> <b>X<sub>1</sub></b> <input type='text' value='-' id='x1' style='width:30px;text-align:center;margin-right:15px;'> <b>Y<sub>1</sub></b> <input type='text' value='-' id='y1' style='width:30px;text-align:center;margin-right:15px;'> <b>X<sub>2</sub></b> <input type='text' value='-' id='x2' style='width:30px;text-align:center;margin-right:15px;'> <b>Y<sub>2</sub></b> <input type='text' value='-' id='y2' style='width:30px;text-align:center;margin-right:15px;'> </div> <div id='skuImageContainer' style='margin-top:60px;'> " ); var anyImagesToLoad = false; foreach (var valueGroup in files.Where(p => p.Key != null)) { var tableId = Guid.NewGuid(); html.AppendFormat( @"<div class=""inline""><a id='{5}' rel='skuImageLink' class='imageLink' href='{0}'> <img class='skuImage' src = ""{0}"" /></a> <br /> <a href=""javascript:void(0);"" onclick=""$('#{1}').toggle();skuTablesCheckAndToggle();"">{3} SKUs</a> <table id = {1} class='skuTable' style=""display:none;""> <tr><th>Item</th><th>{2}</th></tr>{4}" , valueGroup.Key.AssetLocation, tableId, attributeName, valueGroup.Count(), Environment.NewLine, valueGroup.Key.AssetName); //foreach (var val in valueGroup.OrderBy(v => v.Value)) // html.AppendFormat( // "<tr><td>{0}</td><td>{1}</td></tr>{2}", val.Sku, val.Value, Environment.NewLine); foreach (var val in valueGroup.OrderBy(v => v.SkuIndex)) { html.AppendFormat( @"<tr><td><a href='javascript:void(0);' onclick=""selectSku('{3}','0');"">{0}</a></td><td><a href='javascript:void(0);' onclick=""selectSku('{3}','{4}');"">{1}</a></td></tr>{2}", val.Sku, val.Value, Environment.NewLine, val.Sku.ID, currentColumnIndex); } html.Append("</table></div>" + Environment.NewLine); anyImagesToLoad = true; } if (!anyImagesToLoad) { html.AppendFormat("<h2>No Image(s)</h2>"); } html.Append(@"<br class=""clearBoth"" /></div></body></html>"); var fileName = NatalieTools.Instance.ItemImagesTempFile; File.WriteAllText(fileName, html.ToString()); //using (var stream = new FileStream(fileName, FileMode.Create)) //using (TextWriter writer = new StreamWriter(stream)) //{ // writer.Write(html.ToString()); //} return(fileName); }
private Boolean ShouldKeepCache(AssetCache cache) { if (cache.assetDepends != null && (cache.assetDepends.option & ECAssetBundleHeader.BundleOption.DonotRelease) == ECAssetBundleHeader.BundleOption.DonotRelease) return true; if (m_donotReleaseOrResolveDepResPathSet.Contains(cache.path)) return true; return false; }
public void AddItem(string name, AssetCache.CachedAsset item) { this.m_assetMap.Add(name, item); }
private static Boolean IsMaterialHasAllTexture(AssetCache cache) { if (cache.assetDepends != null && cache.assetDepends.specialType == ECAssetBundleHeader.BundleSpecialType.Material) { Material matAsset = cache.Asset as Material; if (matAsset != null) { //检查是否所有贴图都已加载 bool hasMissingTexture = false; foreach (var depend in cache.assetDepends.deps) { if (!String.IsNullOrEmpty(depend.name)) { if (matAsset.GetTexture(depend.name) == null) { hasMissingTexture = true; break; } } } if (m_bEnableLog) //D Log("Check Material HasAllTexture: " + cache.path + ": " + !hasMissingTexture); return !hasMissingTexture; } } return false; }
private void IncDependedLoadingCount(AssetCache cache) { cache.IncDependedLoadingCount(); //if (m_bEnableLog) // Log("IncDependedLoadingCount: " + cache.path + " => " + cache.dependedLoadingCount); }
private static UnityObject GetResourceInCache(String path, ResolveLevel resolveLevel, out AssetCache cache) { cache = null; if (path == null) return null; if (resolveLevel > ResolveLevel.None) //如果非ResolveLevel.None,不能直接返回此值,因为它的依赖还未 Resolve return null; path = UnifyPath(path); if (!Instance.m_assetCacheMap.TryGetValue(path, out cache)) //缓存中无任何记录 { return null; } var asset = cache.GetAssetIfReady(); if (!(asset is Material) || MakeSureIsMaterialAndHasAllTexture(cache)) { return asset; } else { return null; } }
private void IncChildrenDependedLoadingCount(AssetCache cache) { if (cache.assetDepends != null) { foreach (var depend in cache.assetDepends.deps) { AssetCache dependCache = m_assetCacheMap[depend.path]; IncDependedLoadingCount(dependCache); IncChildrenDependedLoadingCount(dependCache); } } }
private static void CacheFinishLoading(AssetCache cache, UnityObject asset) { cache.bLoading = false; for (Int32 i = 0; i < cache.concurrentLoadingCount; ++i) //为并发的加载增加计数 Instance.IncChildrenDependedLoadingCount(cache); cache.concurrentLoadingCount = 0; //加入 LRU 缓存 if (cache.AssetBundle != null && ShouldKeepInLRU(asset)) { if (!Instance.IsCacheInLRU(cache)) { Instance.PushBackCacheToLRU(cache); } } var onLoadFinishTemp = cache.onLoadFinish; cache.onLoadFinish = null; if (onLoadFinishTemp != null) ProtectedOnLoadFinish(cache.path, onLoadFinishTemp, asset, true); }
private void DecDependedLoadingCountRecursively(AssetCache cache) { cache.DecDependedLoadingCount(); //if (m_bEnableLog) // Log("DecDependedLoadingCount: " + cache.path + " => " + cache.dependedLoadingCount); if (cache.assetDepends != null) { foreach (var depend in cache.assetDepends.deps) { AssetCache dependCache = m_assetCacheMap[depend.path]; DecDependedLoadingCountRecursively(dependCache); } } }
/// <summary> /// Default constructor /// </summary> /// <param name="client">A reference to the GridClient object</param> public AssetManager(GridClient client) { Client = client; Cache = new AssetCache(client); Texture = new TexturePipeline(client); // Transfer packets for downloading large assets Client.Network.RegisterCallback(PacketType.TransferInfo, TransferInfoHandler); Client.Network.RegisterCallback(PacketType.TransferPacket, TransferPacketHandler); // Xfer packets for uploading large assets Client.Network.RegisterCallback(PacketType.RequestXfer, RequestXferHandler); Client.Network.RegisterCallback(PacketType.ConfirmXferPacket, ConfirmXferPacketHandler); Client.Network.RegisterCallback(PacketType.AssetUploadComplete, AssetUploadCompleteHandler); // Xfer packets for downloading misc assets Client.Network.RegisterCallback(PacketType.SendXferPacket, SendXferPacketHandler); Client.Network.RegisterCallback(PacketType.AbortXfer, AbortXferHandler); // Simulator is responding to a request to download a file Client.Network.RegisterCallback(PacketType.InitiateDownload, InitiateDownloadPacketHandler); }
/// <summary> /// Creates a scene based off loaded JSON. Includes loading in binary and image data to construct the meshes required. /// </summary> /// <param name="sceneIndex">The index of scene in gltf file to load</param> /// <param name="isMultithreaded">Whether to use a thread to do loading</param> /// <returns></returns> protected IEnumerator ImportScene(int sceneIndex = -1, bool isMultithreaded = false) { Scene scene; if (sceneIndex >= 0 && sceneIndex < _root.Scenes.Count) { scene = _root.Scenes[sceneIndex]; } else { scene = _root.GetDefaultScene(); } if (scene == null) { throw new Exception("No default scene in gltf file."); } _assetCache = new AssetCache( _root.Images != null ? _root.Images.Count : 0, _root.Textures != null ? _root.Textures.Count : 0, _root.Materials != null ? _root.Materials.Count : 0, _root.Buffers != null ? _root.Buffers.Count : 0, _root.Meshes != null ? _root.Meshes.Count : 0 ); if (_lastLoadedScene == null) { if (_root.Buffers != null) { // todo add fuzzing to verify that buffers are before uri for (int i = 0; i < _root.Buffers.Count; ++i) { GLTF.Schema.Buffer buffer = _root.Buffers[i]; if (buffer.Uri != null) { yield return(LoadBuffer(_gltfDirectoryPath, buffer, i)); } else //null buffer uri indicates GLB buffer loading { byte[] glbBuffer; GLTFParser.ExtractBinaryChunk(_gltfData, i, out glbBuffer); _assetCache.BufferCache[i] = glbBuffer; } } } if (_root.Images != null) { for (int i = 0; i < _root.Images.Count; ++i) { Image image = _root.Images[i]; yield return(LoadImage(_gltfDirectoryPath, image, i)); } } #if !WINDOWS_UWP // generate these in advance instead of as-needed if (isMultithreaded) { yield return(_asyncAction.RunOnWorkerThread(() => BuildAttributesForMeshes())); } #endif } var sceneObj = CreateScene(scene); if (_sceneParent != null) { sceneObj.transform.SetParent(_sceneParent, false); } _lastLoadedScene = sceneObj; }