private void OnLoadResourceAgentHelperLoadComplete(object sender, LoadResourceAgentHelperLoadCompleteEventArgs e) { AssetObject assetObject = null; if (m_Task.IsScene) { assetObject = m_AssetPool.Spawn(m_Task.AssetName); } if (assetObject == null) { assetObject = new AssetObject(m_Task.AssetName, e.Asset, m_Task.GetDependencyAssets(), m_Task.Resource, m_AssetPool, m_ResourcePool, m_ResourceHelper, m_ResourceLoader.m_DependencyCount); m_AssetPool.Register(assetObject, true); } m_LoadingAsset = false; s_LoadingAssetNames.Remove(m_Task.AssetName); OnAssetObjectReady(assetObject); }
/// <summary> /// 销毁对象池 /// </summary> public void Destroy() { // 卸载资源对象 if (_asset != null) { _asset.UnLoad(); _asset = null; } // 销毁游戏对象 foreach (var item in _pool) { GameObject.Destroy(item); } _pool.Clear(); // 清空回调 _callbacks = null; SpawnCount = 0; }
private void OnAssetObjectReady(AssetObject assetObject) { m_Helper.Reset(); object asset = assetObject.Target; object instance = null; if (m_Task.IsInstantiate) { instance = m_Helper.Instantiate(asset); m_ResourceLoader.m_InstanceToAssetMap.Add(instance, asset); } if (m_Task.IsScene) { m_ResourceLoader.m_SceneToAssetMap.Add(m_Task.AssetName, asset); } m_Task.OnLoadSuccess(this, asset, instance, (float)(DateTime.Now - m_Task.StartTime).TotalSeconds); m_Task.Done = true; }
public IEnumerator UpdateItemView(TournamentObject tournament) { var asset = new AssetObject(); asset = null; TournamentManager.Instance.GetAssetObject(tournament.Options.BuyIn.Asset.Id) .Then(assetResult => asset = assetResult); while (asset.IsNull()) { yield return(null); } tournamentIdText.text = "#RPS" + tournament.Id; tournamentGameText.text = "RPS"; tournamentnumberOfPlayersText.text = tournament.RegisteredPlayers.ToString(); tournamentStartTimeText.text = tournament.StartTime.Value.ToString("dd MMM, yyyy. hh:mm"); tournamentRegisterDeadlineText.text = tournament.Options.RegistrationDeadline.ToString("dd MMM, yyyy. hh:mm"); tournamentBuyinText.text = tournament.Options.BuyIn.Amount / Mathf.Pow(10, asset.Precision) + asset.Symbol; tournamentJackpotText.text = tournament.PrizePool / Mathf.Pow(10, asset.Precision) + asset.Symbol; liveMessage.SetActive(tournament.State.Equals(ChainTypes.TournamentState.InProgress)); }
public void Unload(AssetObject assetObj) { if (assetObj == null) { Debug.LogError("Unknow Destroy!"); return; } Tangzx.ABSystem.ObjectPool <AssetObject> aPool = null; if (!_cachedAssetObj.TryGetValue(assetObj.key, out aPool)) { aPool = new Tangzx.ABSystem.ObjectPool <AssetObject>(null, null); } if (aPool.countInactive > 5) { GameObject.DestroyImmediate(assetObj.gameObject); } else { assetObj.CachedTransform.SetParent(_cachedParent); aPool.Release(assetObj); } }
bool IsTournamentContains(TournamentObject tournament, AssetObject asset, string searchText, AccountObject account) { var search = searchText.ToLower(); var tournamentId = tournament.Id.ToString().ToLower().Contains(search); var buyIn = ((tournament.Options.BuyIn.Amount / Math.Pow(10, asset.Precision)) + asset.Symbol).ToLower().Contains(search); var jackpot = ((tournament.Options.BuyIn.Amount / Math.Pow(10, asset.Precision) * tournament.Options.NumberOfPlayers) + asset.Symbol).ToLower().Contains(search); var time = tournament.Options.RegistrationDeadline - DateTime.UtcNow; var registerDeadline = false; registerDeadline = ("Register: <" + (time.TotalDays < 1 ? 1 : (int)Math.Round(time.TotalDays)) + "d").Contains(searchText); var startDelay = "2 minutes after full".Contains(search); var gameName = ("#rps" + tournament.Id).Contains(search); if (tournament.State.Equals(ChainTypes.TournamentState.Concluded)) { var result = account.Id.Equals(AuthorizationManager.Instance.UserData.FullAccount.Account.Id) ? ((tournament.Options.BuyIn.Amount / Math.Pow(10, asset.Precision) * (tournament.Options.NumberOfPlayers - 1)) + asset.Symbol).ToLower().Contains(search) : ("-" + (tournament.Options.BuyIn.Amount / Math.Pow(10, asset.Precision)) + asset.Symbol).ToLower().Contains(search); var winner = account.Name.ToLower().Contains(search); return(buyIn || gameName || tournamentId || winner || result); } return(buyIn || jackpot || registerDeadline || gameName || tournamentId || startDelay); }
private void TryLoadAsset() { if (!m_Task.IsScene) { AssetObject assetObject = m_AssetPool.Spawn(m_Task.AssetName); if (assetObject != null) { OnAssetObjectReady(assetObject); return; } } m_LoadingAsset = true; s_LoadingAssetNames.Add(m_Task.AssetName); foreach (string dependencyAssetName in m_Task.GetDependencyAssetNames()) { if (!m_AssetPool.CanSpawn(dependencyAssetName)) { if (!IsAssetLoading(dependencyAssetName)) { OnError(LoadResourceStatus.DependencyError, string.Format("Can not find dependency asset object named '{0}'.", dependencyAssetName)); return; } m_LoadingDependencyAssetNames.AddLast(dependencyAssetName); } } if (m_LoadingDependencyAssetNames.Count > 0) { m_WaitingType = WaitingType.WaitForDependencyAsset; return; } OnDependencyAssetReady(); }
void UpdateBalances(AuthorizationManager.AuthorizationData data) { assetsData.Clear(); balanceDropdown.ClearOptions(); if (data.IsNull()) { return; } if (AuthorizationController.Instance.accountBalances.Count == 0) { var options = new List <Dropdown.OptionData>(); options.Add(new Dropdown.OptionData("PPY")); balanceDropdown.AddOptions(options); TournamentManager.Instance.GetAssetObject() .Then(asset => { selectAssetObject = asset; SetAvailableBalanceText(0 + " " + selectAssetObject.Symbol); assetsData.Add(asset); }); } else { TournamentManager.Instance.GetAssetsObject(Array.ConvertAll(AuthorizationController.Instance.accountBalances.ToArray(), assetId => assetId.Asset.Id)) .Then(objects => { var options = new List <Dropdown.OptionData>(); foreach (var assetObject in objects) { assetsData.Add(assetObject); options.Add(new Dropdown.OptionData(assetObject.Symbol)); } balanceDropdown.AddOptions(options); selectAssetObject = objects[0]; SetAvailableBalanceText((AuthorizationController.Instance.accountBalances[0].Amount / Mathf.Pow(10, selectAssetObject.Precision)) + " " + selectAssetObject.Symbol); }); } }
public virtual IEnumerator UpdateItem(TournamentObject info) { if (gameObject.activeSelf && gameObject.activeInHierarchy) { CurrentTournament = info; if (tournamentDetailsObject.IsNull() || !tournamentDetailsObject.Tournament.Equals(info.Id)) { var detailsObject = new List <TournamentDetailsObject>(); yield return(TournamentManager.Instance.GetTournamentDetailsObject(info.Id.Id, detailsObject)); tournamentDetailsObject = detailsObject[0]; } ID = "#RPS" + info.Id; PlayerRegistered = info.RegisteredPlayers.ToString(); MaxPlayers = info.Options.NumberOfPlayers.ToString(); if (currentAsset.IsNull() || !currentAsset.Id.Equals(currentTournament.Options.BuyIn.Asset)) { AssetObject asset = null; TournamentManager.Instance.GetAssetObject(currentTournament.Options.BuyIn.Asset.Id) .Then(assetResult => asset = assetResult); while (asset.IsNull()) { yield return(null); } currentAsset = asset; } var buyIn = Decimal.Parse((info.Options.BuyIn.Amount / Math.Pow(10, currentAsset.Precision)).ToString(), NumberStyles.Float); BuyIn = buyIn + currentAsset.Symbol; Jackpot = buyIn * info.Options.NumberOfPlayers + currentAsset.Symbol; UpdateStartTime(); } }
/// <summary> /// Add asset to this dictionary /// </summary> /// <param name="type">asset type</param> /// <param name="sName">asset name</param> /// <param name="sPath">asset path</param> /// <param name="o">asset </param> public void AddAsset(System.Type type, string sName, string sPath, Object o) { List <AssetObject> pList = null; if (m_AssetMap.ContainsKey(type) == false) { pList = new List <AssetObject>(); m_AssetMap.Add(type, pList); } pList = m_AssetMap[type]; foreach (AssetObject tempO in pList) { if (tempO.m_sName.Equals(sName) && tempO.m_sPath.Equals(sPath)) { return; } } AssetObject ao = new AssetObject(); ao.m_sName = sName; ao.m_sPath = sPath; ao.m_Asset = o; pList.Add(ao); }
/// <summary> /// /// </summary> /// <param name="settings"></param> /// <param name="asset"></param> /// <param name="destinationDir"></param> /// <param name="streams"></param> /// <returns></returns> private static bool LockAllContents(ZombieSettings settings, AssetObject asset, string destinationDir, out Dictionary <string, FileStream> streams) { streams = new Dictionary <string, FileStream>(); var dir = FileUtils.GetZombieDownloadsDirectory(); var filePath = Path.Combine(dir, asset.Name); if (!GitHubUtils.DownloadAssets(settings, asset.Url, filePath)) { return(false); } try { using (var zip = ZipFile.Open(filePath, ZipArchiveMode.Read)) { foreach (var file in zip.Entries) { var completeFileName = Path.Combine(FilePathUtils.CreateUserSpecificPath(destinationDir), file.FullName); if (file.Name == string.Empty || !Directory.Exists(Path.GetDirectoryName(completeFileName))) { continue; } var fs = new FileStream(completeFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); streams.Add(completeFileName, fs); } } } catch (Exception e) { _logger.Fatal(e.Message); return(false); } return(true); }
/// <summary> /// 加载资源代理轮询。 /// </summary> /// <param name="elapseSeconds">逻辑流逝时间,以秒为单位。</param> /// <param name="realElapseSeconds">真实流逝时间,以秒为单位。</param> public void Update(float elapseSeconds, float realElapseSeconds) { if (m_WaitingType == WaitingType.None) { return; } if (m_WaitingType == WaitingType.WaitForAsset) { if (IsAssetLoading(m_Task.AssetName)) { return; } m_WaitingType = WaitingType.None; AssetObject assetObject = m_AssetPool.Spawn(m_Task.AssetName); if (assetObject == null) { TryLoadAsset(); return; } OnAssetObjectReady(assetObject); return; } if (m_WaitingType == WaitingType.WaitForDependencyAsset) { LinkedListNode <string> current = m_LoadingDependencyAssetNames.First; while (current != null) { if (!IsAssetLoading(current.Value)) { LinkedListNode <string> next = current.Next; if (!m_AssetPool.CanSpawn(current.Value)) { OnError(LoadResourceStatus.DependencyError, string.Format("Can not find dependency asset object named '{0}'.", current.Value)); return; } m_LoadingDependencyAssetNames.Remove(current); current = next; continue; } current = current.Next; } if (m_LoadingDependencyAssetNames.Count > 0) { return; } m_WaitingType = WaitingType.None; OnDependencyAssetReady(); return; } if (m_WaitingType == WaitingType.WaitForResource) { if (IsResourceLoading(m_Task.ResourceInfo.ResourceName.Name)) { return; } ResourceObject resourceObject = m_ResourcePool.Spawn(m_Task.ResourceInfo.ResourceName.Name); if (resourceObject == null) { OnError(LoadResourceStatus.DependencyError, string.Format("Can not find resource object named '{0}'.", m_Task.ResourceInfo.ResourceName.Name)); return; } m_WaitingType = WaitingType.None; OnResourceObjectReady(resourceObject); return; } }
public static List <Asset> ConvertObjects(GMData data) { var dataAssets = ((GMChunkOBJT)data.Chunks["OBJT"]).List; var dataSprites = ((GMChunkSPRT)data.Chunks["SPRT"]).List; var dataCode = ((GMChunkCODE)data.Chunks["CODE"])?.List; List <Asset> list = new List <Asset>(); for (int i = 0; i < dataAssets.Count; i++) { GMObject asset = dataAssets[i]; AssetObject projectAsset = new AssetObject() { Name = asset.Name.Content, Sprite = asset.SpriteID >= 0 ? dataSprites[asset.SpriteID].Name.Content : null, Visible = asset.Visible, Solid = asset.Solid, Depth = asset.Depth, Persistent = asset.Persistent, ParentObject = asset.ParentObjectID >= 0 ? dataAssets[asset.ParentObjectID].Name.Content : (asset.ParentObjectID == -100 ? "<undefined>" : null), MaskSprite = asset.MaskSpriteID >= 0 ? dataSprites[asset.MaskSpriteID].Name.Content : null, Physics = asset.Physics, PhysicsSensor = asset.PhysicsSensor, PhysicsShape = asset.PhysicsShape, PhysicsDensity = asset.PhysicsDensity, PhysicsRestitution = asset.PhysicsRestitution, PhysicsGroup = asset.PhysicsGroup, PhysicsLinearDamping = asset.PhysicsLinearDamping, PhysicsAngularDamping = asset.PhysicsAngularDamping, PhysicsVertices = new List <AssetObject.PhysicsVertex>(), PhysicsFriction = asset.PhysicsFriction, PhysicsAwake = asset.PhysicsAwake, PhysicsKinematic = asset.PhysicsKinematic, Events = new SortedDictionary <AssetObject.EventType, List <AssetObject.Event> >() }; list.Add(projectAsset); foreach (GMObject.PhysicsVertex v in asset.PhysicsVertices) { projectAsset.PhysicsVertices.Add(new AssetObject.PhysicsVertex() { X = v.X, Y = v.Y }); } for (int j = 0; j < asset.Events.Count; j++) { List <AssetObject.Event> projectEvents = new List <AssetObject.Event>(); AssetObject.EventType type = (AssetObject.EventType)j; projectAsset.Events[type] = projectEvents; void addActions(GMObject.Event ev, AssetObject.Event newEv) { foreach (var ac in ev.Actions) { newEv.Actions.Add(new AssetObject.Action() { Code = (dataCode == null) ? ac.CodeID.ToString() : dataCode[ac.CodeID].Name.Content, ID = ac.ID, UseApplyTo = ac.UseApplyTo, ActionName = ac.ActionName?.Content, ArgumentCount = ac.ArgumentCount }); } } switch (type) { case AssetObject.EventType.Alarm: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventAlarm() { Actions = new List <AssetObject.Action>(), AlarmNumber = ev.Subtype }; addActions(ev, newEv); projectEvents.Add(newEv); } break; case AssetObject.EventType.Step: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventStep() { Actions = new List <AssetObject.Action>(), SubtypeStep = (AssetObject.EventStep.Subtype)ev.Subtype }; addActions(ev, newEv); projectEvents.Add(newEv); } break; case AssetObject.EventType.Collision: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventCollision() { Actions = new List <AssetObject.Action>(), ObjectName = dataAssets[ev.Subtype].Name.Content }; addActions(ev, newEv); projectEvents.Add(newEv); } break; case AssetObject.EventType.Keyboard: case AssetObject.EventType.KeyPress: case AssetObject.EventType.KeyRelease: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventKeyboard() { Actions = new List <AssetObject.Action>(), SubtypeKey = (AssetObject.EventKeyboard.Subtype)ev.Subtype }; addActions(ev, newEv); projectEvents.Add(newEv); } break; case AssetObject.EventType.Mouse: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventMouse() { Actions = new List <AssetObject.Action>(), SubtypeMouse = (AssetObject.EventMouse.Subtype)ev.Subtype }; addActions(ev, newEv); projectEvents.Add(newEv); } break; case AssetObject.EventType.Other: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventOther() { Actions = new List <AssetObject.Action>(), SubtypeOther = (AssetObject.EventOther.Subtype)ev.Subtype }; addActions(ev, newEv); projectEvents.Add(newEv); } break; case AssetObject.EventType.Draw: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventDraw() { Actions = new List <AssetObject.Action>(), SubtypeDraw = (AssetObject.EventDraw.Subtype)ev.Subtype }; addActions(ev, newEv); projectEvents.Add(newEv); } break; case AssetObject.EventType.Gesture: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventGesture() { Actions = new List <AssetObject.Action>(), SubtypeGesture = (AssetObject.EventGesture.Subtype)ev.Subtype }; addActions(ev, newEv); projectEvents.Add(newEv); } break; default: foreach (var ev in asset.Events[j]) { var newEv = new AssetObject.EventNormal() { Actions = new List <AssetObject.Action>() }; addActions(ev, newEv); projectEvents.Add(newEv); } break; } } } return(list); }
public T FindScript <T>(Predicate <MonoBehaviorAssetData> cond, Predicate <T> condition) where T : BehaviorData { AssetObject obj = GetAssetObjectFromScript(cond, condition); return(obj != null ? ((obj.data as MonoBehaviorAssetData).data as T) : null); }
static void LoadAssetFile(Stream s, out List <string> materials, out List <string> gameObjects) { var es = new EndianStream(s, EndianType.BigEndian); var metaSize = es.ReadUInt32(); var fileSize = es.ReadUInt32(); var format = es.ReadInt32(); var dataOffset = es.ReadUInt32(); if (format >= 9) { var endianness = es.ReadUInt32(); if (endianness == 0) { es.endian = EndianType.LittleEndian; } } var types = new TypeMeta(); types.Load(es, format); var longObjIds = format >= 14 || (format >= 7 && es.ReadInt32() != 0); var numObjs = es.ReadUInt32(); var objs = new AssetObject[numObjs]; for (uint i = 0; i < numObjs; i++) { if (format >= 14) { es.AlignStream(4); } objs[i] = LoadObject(es, format, types); } materials = new List <string>(); gameObjects = new List <string>(); foreach (var obj in objs) { types.TypeTrees.TryGetValue(obj.ClassId, out TreeNode type); es.Position = dataOffset + obj.DataOfs; if (obj.ClassId == 21) { es.Position = dataOffset + obj.DataOfs; materials.Add(es.ReadAlignedString(es.ReadInt32())); } if (obj.ClassId == 1) { var v = (Dictionary <string, object>)ReadValue(es, type); gameObjects.Add((string)v["m_Name"]); } /* * if (obj.ClassId == 1 || obj.ClassId == 21) { * var v = (Dictionary<string, object>)ReadValue(es, type); * Debug.WriteLine(type.type + " " + v["m_Name"]); * } */ /* * if (type.children.Count != 0 && type.children[0].type == "string") { * es.Position = dataOffset + obj.DataOfs; * Debug.WriteLine(es.ReadAlignedString(es.ReadInt32())); * } */ } //Debug.WriteLine(type); }
private object LoadDependencyAssetSync(string assetName, IResourceHelper resourceHelper) { ResourceInfo?resourceInfo = null; string[] dependencyAssetNames = null; string[] scatteredDependencyAssetNames = null; string resourceChildName = null; if (!CheckAsset(assetName, out resourceInfo, out dependencyAssetNames, out scatteredDependencyAssetNames, out resourceChildName)) { Log.Debug("Can not load asset '{0}'.", assetName); return(false); } AssetObject assetObject = m_AssetPool.Spawn(assetName); if (assetObject != null) { return(true); } object[] dependencyAssets = new object[dependencyAssetNames.Length]; for (int i = 0; i < dependencyAssetNames.Length; i++) { object asset = LoadDependencyAssetSync(dependencyAssetNames[i], resourceHelper); if (asset != null) { dependencyAssets[i] = asset; } else { string errorMessage = string.Format( "Can not load dependency asset '{0}' when load asset '{1}'.", dependencyAssetNames[i], assetName); throw new GameFrameworkException(errorMessage); } } ResourceObject resourceObject = m_ResourcePool.Spawn(resourceInfo.Value.ResourceName.Name); if (resourceObject != null) { object asset = m_SyncLoadResourceHelper.LoadAssetSync(resourceObject.Target, resourceChildName); AssetObject assetObj = new AssetObject(assetName, asset, dependencyAssets, resourceObject.Target, m_AssetPool, m_ResourcePool, resourceHelper); m_AssetPool.Register(assetObj, true); return(true); } string fullPath = Utility.Path.GetCombinePath( resourceInfo.Value.StorageInReadOnly ? m_ReadOnlyPath : m_ReadWritePath, Utility.Path.GetResourceNameWithSuffix(resourceInfo.Value.ResourceName.FullName)); object resourceObj = null; if (resourceInfo.Value.LoadType == LoadType.LoadFromFile) { resourceObj = m_SyncLoadResourceHelper.ReadFileSync(fullPath); } else { resourceObj = m_SyncLoadResourceHelper.ReadBytesSync(fullPath, (int)resourceInfo.Value.LoadType); } if (resourceObj != null) { ResourceObject resObject = new ResourceObject(resourceInfo.Value.ResourceName.Name, resourceObj, resourceHelper); m_ResourcePool.Register(resObject, true); object asset = m_SyncLoadResourceHelper.LoadAssetSync(resObject.Target, resourceChildName); AssetObject assetObj = new AssetObject(assetName, asset, dependencyAssets, resObject.Target, m_AssetPool, m_ResourcePool, resourceHelper); m_AssetPool.Register(assetObj, true); return(true); } else { string errorMessage = string.Format("Can not load asset '{0}' when load asset '{1}'.", assetName); throw new GameFrameworkException(errorMessage); } }
public SerializedAssets(Stream stream, Apk.Version v) { apkVersion = v; BinaryReader reader = new BinaryReader(stream); // ===== Parse Header int metadataSize = reader.ReadInt32BE(); int fileSize = reader.ReadInt32BE(); int generation = reader.ReadInt32BE(); if (generation != parsedGeneration) { throw new ParseException("Unsupported format version"); } int dataOffset = reader.ReadInt32BE(); int isBigEndian = reader.ReadInt32BE(); if (isBigEndian != 0) { throw new ParseException("Must be little endian"); } paddingLen = dataOffset - (metadataSize + headerLen); // ===== Parse Metadata version = reader.ReadStringToNull(); if (version != "2018.3.10f1") { throw new ParseException("Unsupported Unity version"); } targetPlatform = reader.ReadInt32(); enableTypeTree = reader.ReadBoolean(); if (enableTypeTree) { throw new ParseException("Type trees aren't supported"); } types = reader.ReadPrefixedList(r => new TypeRef(r)); objects = reader.ReadPrefixedList(r => new AssetObject(r)); scripts = reader.ReadPrefixedList(r => new Script(r)); externals = reader.ReadPrefixedList(r => new External(r)); // this is necessary to get headerLen+metadataSize to match up with offset if (reader.ReadByte() != 0) { throw new ParseException("Expected metadata to end with 0"); } if (!reader.ReadAllZeros(paddingLen)) { throw new ParseException("Expected zeros for padding"); } Debug.Assert(reader.BaseStream.Position == dataOffset, "Parsed metadata wrong"); // ===== Extra stuff scriptIDToScriptPtr = new Dictionary <byte[], AssetPtr>(new ByteArrayComparer()); environmentIDToPtr = new Dictionary <string, AssetPtr>(); assetTypeToTypeID = new Dictionary <Type, int>(); scriptTypeToTypeID = new Dictionary <Type, int>(); // ===== Parse Data for (int i = 0; i < objects.Count - 1; i++) { objects[i].paddingLen = objects[i + 1].offset - (objects[i].offset + objects[i].size); } // I've never seen any padding after the last object but handle it just in case AssetObject last = objects[objects.Count - 1]; int dataSize = fileSize - dataOffset; last.paddingLen = dataSize - (last.offset + last.size); foreach (AssetObject obj in objects) { // Console.WriteLine((reader.BaseStream.Position-dataOffset, obj.offset, obj.size)); if (reader.BaseStream.Position - dataOffset != obj.offset) { throw new ParseException("Objects aren't in order"); } long startOffset = reader.BaseStream.Position; if (types.Count <= obj.typeID) { // Console.WriteLine($"TypeID of SimpleColor: {objects[52].typeID} with type: {objects[52].data.GetType()}"); throw new ParseException($"Could not find typeID: {obj.typeID}, maximum is: {types.Count}"); } switch (types[obj.typeID].classID) { case MonoBehaviorAssetData.ClassID: byte[] scriptID = types[obj.typeID].scriptID; var monob = new MonoBehaviorAssetData(reader, obj.size, types[obj.typeID], apkVersion); scriptTypeToTypeID[monob.data.GetType()] = obj.typeID; scriptIDToScriptPtr[scriptID] = monob.script; obj.data = monob; break; case AudioClipAssetData.ClassID: obj.data = new AudioClipAssetData(reader, obj.size); break; case Texture2DAssetData.ClassID: obj.data = new Texture2DAssetData(reader, obj.size); break; case SpriteAssetData.ClassID: obj.data = new SpriteAssetData(reader, obj.size); break; case GameObjectAssetData.ClassID: obj.data = new GameObjectAssetData(reader, obj.size); break; case MeshFilterAssetData.ClassID: obj.data = new MeshFilterAssetData(reader, obj.size); break; case TextAssetData.ClassID: obj.data = new TextAssetData(reader, obj.size); break; default: obj.data = new UnknownAssetData(reader, obj.size); break; } assetTypeToTypeID[obj.data.GetType()] = obj.typeID; long bytesParsed = reader.BaseStream.Position - startOffset; if (bytesParsed != obj.size) { throw new ParseException($"Parsed {bytesParsed} bytes but expected {obj.size} for path ID {obj.pathID}"); } if (!reader.ReadAllZeros(obj.paddingLen)) { throw new ParseException("Expected zeros for padding"); } } FindEnvironmentPointers(); }
public SerializedAssets(Stream stream) { BinaryReader reader = new BinaryReader(stream); // ===== Parse Header int metadataSize = reader.ReadInt32BE(); int fileSize = reader.ReadInt32BE(); int generation = reader.ReadInt32BE(); if (generation != parsedGeneration) { throw new ParseException("Unsupported format version"); } int dataOffset = reader.ReadInt32BE(); int isBigEndian = reader.ReadInt32BE(); if (isBigEndian != 0) { throw new ParseException("Must be little endian"); } paddingLen = dataOffset - (metadataSize + headerLen); // ===== Parse Metadata version = reader.ReadStringToNull(); if (version != "2018.3.10f1") { throw new ParseException("Unsupported Unity version"); } targetPlatform = reader.ReadInt32(); enableTypeTree = reader.ReadBoolean(); if (enableTypeTree) { throw new ParseException("Type trees aren't supported"); } types = reader.ReadPrefixedList(r => new TypeRef(r)); objects = reader.ReadPrefixedList(r => new AssetObject(r)); scripts = reader.ReadPrefixedList(r => new Script(r)); externals = reader.ReadPrefixedList(r => new External(r)); // this is necessary to get headerLen+metadataSize to match up with offset if (reader.ReadByte() != 0) { throw new ParseException("Expected metadata to end with 0"); } if (!reader.ReadAllZeros(paddingLen)) { throw new ParseException("Expected zeros for padding"); } Debug.Assert(reader.BaseStream.Position == dataOffset, "Parsed metadata wrong"); // ===== Parse Data for (int i = 0; i < objects.Count - 1; i++) { objects[i].paddingLen = objects[i + 1].offset - (objects[i].offset + objects[i].size); } // I've never seen any padding after the last object but handle it just in case AssetObject last = objects[objects.Count - 1]; int dataSize = fileSize - dataOffset; last.paddingLen = dataSize - (last.offset + last.size); foreach (AssetObject obj in objects) { // Console.WriteLine((reader.BaseStream.Position-dataOffset, obj.offset, obj.size)); if (reader.BaseStream.Position - dataOffset != obj.offset) { throw new ParseException("Objects aren't in order"); } long startOffset = reader.BaseStream.Position; switch (types[obj.typeID].classID) { case 114: obj.data = new MonoBehaviorAssetData(reader, obj.size); break; case 83: obj.data = new AudioClipAssetData(reader, obj.size); break; default: obj.data = new UnknownAssetData(reader, obj.size); break; } long bytesParsed = reader.BaseStream.Position - startOffset; if (bytesParsed != obj.size) { throw new ParseException($"Parsed {bytesParsed} but expected {obj.size} for {obj.pathID}"); } if (!reader.ReadAllZeros(obj.paddingLen)) { throw new ParseException("Expected zeros for padding"); } } }
private static void AddToAssetGroups(string assetName, string groupName, AssetObject packet) { if (AssetGroups.ContainsKey(groupName)) { AssetGroups[groupName].Add(assetName, packet); } else { AssetGroups.Add(groupName, new Dictionary<string, AssetObject>()); AssetGroups[groupName].Add(assetName, packet); } }
void Update() { if (m_WaitingType == WaitingType.None) { return; } if (m_WaitingType == WaitingType.WaitForAsset) { if (IsAssetLoading(m_Task.AssetName)) { return; } m_WaitingType = WaitingType.None; AssetObject assetObject = m_AssetPool.Spawn(m_Task.AssetName); if (assetObject == null) { TryLoadAsset(); return; } OnAssetObjectReady(); return; } if (m_WaitingType == WaitingType.WaitForDependencyAsset) { LinkedListNode<string> current = m_LoadingDependencyAssetName.First; while (current != null) { if (!IsAssetLoading(current.Value)) { LinkedListNode<string> next = current.Next; if (!m_AssetPool.CanSpawn(current.Value)) { OnError(LoadResourceStatus.DependencyError); return; } m_LoadingDependencyAssetNames.Remove(current); current = next; continue; } } if (m_LoadingDependencyAssetNames.Count > 0) { return; } m_WaitingType = WaitingType.None; OnDependencyAssetReady(); return; } if (m_WaitingType == WaitingType.WaitForResource) { if (IsResourceLoading(m_Task.ResourceInfo) { return; } ResourceObject resourceObject = ResourcePool.Spawn(m_Task.ResourceInfo); if (resourceObject == null) { OnError(LoadResourceStatus.DependencyError); return; } m_WaitingType = WaitingType.None; OnResourceObjectReady(resourceObject); return; } }
/// --------------------------------------------------------------------------------- /// <summary> /// 销毁 Asset 相关的资源 /// </summary> /// --------------------------------------------------------------------------------- public virtual void Destroy() { LoaderObj = null; mainAsset = null; }
/// <summary> /// 开始处理加载资源任务。 /// </summary> /// <param name="task">要处理的加载资源任务。</param> /// <returns>开始处理任务的状态。</returns> public StartTaskStatus Start(LoadResourceTaskBase task) { if (task == null) { throw new GameFrameworkException("Task is invalid."); } m_Task = task; m_Task.StartTime = DateTime.Now; if (IsAssetLoading(m_Task.AssetName)) { m_Task.StartTime = default(DateTime); return(StartTaskStatus.HasToWait); } if (!m_Task.IsScene) { AssetObject assetObject = m_ResourceLoader.m_AssetPool.Spawn(m_Task.AssetName); if (assetObject != null) { OnAssetObjectReady(assetObject); return(StartTaskStatus.Done); } } foreach (string dependencyAssetName in m_Task.GetDependencyAssetNames()) { if (!m_ResourceLoader.m_AssetPool.CanSpawn(dependencyAssetName)) { m_Task.StartTime = default(DateTime); return(StartTaskStatus.HasToWait); } } string resourceName = m_Task.ResourceInfo.ResourceName.Name; if (IsResourceLoading(resourceName)) { m_Task.StartTime = default(DateTime); return(StartTaskStatus.HasToWait); } s_LoadingAssetNames.Add(m_Task.AssetName); ResourceObject resourceObject = m_ResourceLoader.m_ResourcePool.Spawn(resourceName); if (resourceObject != null) { OnResourceObjectReady(resourceObject); return(StartTaskStatus.CanResume); } s_LoadingResourceNames.Add(resourceName); string fullPath = null; if (!s_CachedResourceNames.TryGetValue(resourceName, out fullPath)) { fullPath = Utility.Path.GetRegularPath(Path.Combine(m_Task.ResourceInfo.StorageInReadOnly ? m_ReadOnlyPath : m_ReadWritePath, Utility.Path.GetResourceNameWithSuffix(m_Task.ResourceInfo.ResourceName.FullName))); s_CachedResourceNames.Add(resourceName, fullPath); } if (m_Task.ResourceInfo.LoadType == LoadType.LoadFromFile) { m_Helper.ReadFile(fullPath); } else { m_Helper.ReadBytes(fullPath, (int)m_Task.ResourceInfo.LoadType); } return(StartTaskStatus.CanResume); }
// HashSet<System.Action> endUseCallbacks; /* * called when the attached event player plays an * "Animations" event and chooses an appropriate asset object * * endUseCallbacks should be called whenever the animation is done * * in this case, this component tracks when the animator is exiting an animation * that has been played */ protected override void UseAssetObject(AssetObject assetObject, bool asInterrupter, MiniTransform transforms, HashSet <System.Action> endUseCallbacks) { bool looped = assetObject["Looped"].GetValue <bool>(); int layer = assetObject["Layer"].GetValue <int>(); if (!looped) { if (this.endUseCallbacksPerLayer[layer] != null && this.endUseCallbacksPerLayer[layer].Count != 0) { // Debug.Log("clearing old callbacks"); this.endUseCallbacksPerLayer[layer].Clear(); } this.endUseCallbacksPerLayer[layer] = endUseCallbacks; // if (this.endUseCallbacks != null && this.endUseCallbacks.Count != 0) { // Debug.Log("clearing old callbacks"); // this.endUseCallbacks.Clear(); // } // this.endUseCallbacks = endUseCallbacks; } //get asset object parameter values int mirrorMode = assetObject["Mirror"].GetValue <int>(); bool mirror = (mirrorMode == 2) ? Random.value < .5f : mirrorMode == 1; float timeOffset = assetObject["TimeOffset"].GetValue <float>(); AnimationClip clip = assetObject.objRef as AnimationClip;// ((AnimationClip)assetObject.objRef); if (timeOffset != 0) { if (clip != null) { timeOffset = timeOffset * clip.length; } else { timeOffset = 0; } } Play( clip, assetObject.id, asInterrupter, mirror, looped, //if null clip and assetObject["Transition"].GetValue <float>(), assetObject["Speed"].GetValue <float>(), layer, timeOffset ); if (looped) { if (assetObject.objRef != null) { // Debug.Log("playing loop: " + assetObject.objRef.name); } //BroadcastEndUse(); //dont leave loops hanging } else { lastPlayed = assetObject.objRef.name; Debug.Log("playing: " + assetObject.objRef.name); // Debug.Break(); } }
private static void ConvertObjects(ProjectFile pf) { GMList <GMObject> dataAssets = ((GMChunkOBJT)pf.DataHandle.Chunks["OBJT"]).List; GMList <GMSprite> dataSprites = ((GMChunkSPRT)pf.DataHandle.Chunks["SPRT"]).List; GMList <GMCode> dataCode = ((GMChunkCODE)pf.DataHandle.Chunks["CODE"]).List; int getSprite(string name) { if (name == null) { return(-1); } try { return(dataSprites.Select((elem, index) => new { elem, index }).First(p => p.elem.Name.Content == name).index); } catch (InvalidOperationException) { return(-1); } } int getCode(string name) { try { return(dataCode.Select((elem, index) => new { elem, index }).First(p => p.elem.Name.Content == name).index); } catch (InvalidOperationException) { return(-1); } } int getObject(string name) { if (name == null) { return(-1); } if (name == "<undefined>") { return(-100); } try { return(dataAssets.Select((elem, index) => new { elem, index }).First(p => p.elem.Name.Content == name).index); } catch (InvalidOperationException) { return(-1); } } List <GMObject> newList = new List <GMObject>(); for (int i = 0; i < pf.Objects.Count; i++) { AssetObject projectAsset = pf.Objects[i]; GMObject dataAsset = new GMObject() { Name = pf.DataHandle.DefineString(projectAsset.Name), SpriteID = getSprite(projectAsset.Sprite), Visible = projectAsset.Visible, Solid = projectAsset.Solid, Depth = projectAsset.Depth, Persistent = projectAsset.Persistent, ParentObjectID = getObject(projectAsset.ParentObject), MaskSpriteID = getSprite(projectAsset.MaskSprite), Physics = projectAsset.Physics, PhysicsSensor = projectAsset.PhysicsSensor, PhysicsShape = projectAsset.PhysicsShape, PhysicsDensity = projectAsset.PhysicsDensity, PhysicsRestitution = projectAsset.PhysicsRestitution, PhysicsGroup = projectAsset.PhysicsGroup, PhysicsLinearDamping = projectAsset.PhysicsLinearDamping, PhysicsAngularDamping = projectAsset.PhysicsAngularDamping, PhysicsVertices = new List <GMObject.PhysicsVertex>(), PhysicsFriction = projectAsset.PhysicsFriction, PhysicsAwake = projectAsset.PhysicsAwake, PhysicsKinematic = projectAsset.PhysicsKinematic, Events = new GMPointerList <GMPointerList <GMObject.Event> >() }; foreach (AssetObject.PhysicsVertex v in projectAsset.PhysicsVertices) { dataAsset.PhysicsVertices.Add(new GMObject.PhysicsVertex() { X = v.X, Y = v.Y }); } foreach (var events in projectAsset.Events.Values) { var newEvents = new GMPointerList <GMObject.Event>(); foreach (var ev in events) { GMObject.Event newEv = new GMObject.Event() { Subtype = 0, Actions = new GMPointerList <GMObject.Event.Action>() { new GMObject.Event.Action() { LibID = 1, ID = ev.Actions[0].ID, Kind = 7, UseRelative = false, IsQuestion = false, UseApplyTo = ev.Actions[0].UseApplyTo, ExeType = 2, ActionName = ev.Actions[0].ActionName != null?pf.DataHandle.DefineString(ev.Actions[0].ActionName) : null, CodeID = getCode(ev.Actions[0].Code), ArgumentCount = ev.Actions[0].ArgumentCount, Who = -1, Relative = false, IsNot = false } } }; // Handle subtype switch (ev) { case AssetObject.EventAlarm e: newEv.Subtype = e.AlarmNumber; break; case AssetObject.EventStep e: newEv.Subtype = (int)e.SubtypeStep; break; case AssetObject.EventCollision e: newEv.Subtype = getObject(e.ObjectName); break; case AssetObject.EventKeyboard e: newEv.Subtype = (int)e.SubtypeKey; break; case AssetObject.EventMouse e: newEv.Subtype = (int)e.SubtypeMouse; break; case AssetObject.EventOther e: newEv.Subtype = (int)e.SubtypeOther; break; case AssetObject.EventDraw e: newEv.Subtype = (int)e.SubtypeDraw; break; case AssetObject.EventGesture e: newEv.Subtype = (int)e.SubtypeGesture; break; } newEvents.Add(newEv); } dataAsset.Events.Add(newEvents); } newList.Add(dataAsset); } dataAssets.Clear(); foreach (var obj in newList) { dataAssets.Add(obj); } }
/// <summary> /// Saves the story to this asset's file path. /// </summary> public override void Save() { AssetObject.Save(FileInfo.FullName, true); }
static void AddToReferenceList(string assetName, Action<UnityEngine.Object> callback, string groupName) { AssetObject packet = new AssetObject(); packet.callbacks += callback; AssetGroupRefences.Add(assetName, groupName); AddToAssetGroups(assetName, groupName, packet); }
public AssetViewModel(AssetObject asset) { Asset = asset; ShowContents = new RelayCommand(OnShowContents); }
public override void Clear() { buyinSettingsFieldView.CurrentDoubleValue = 0.0; selectAssetObject = assetsData[0]; }
/// <summary> /// 开始处理加载资源任务。 /// </summary> /// <param name="task">要处理的加载资源任务。</param> /// <returns>开始处理任务的状态。</returns> public StartTaskStatus Start(LoadResourceTaskBase task) { if (task == null) { throw new GameFrameworkException("Task is invalid."); } m_Task = task; m_Task.StartTime = DateTime.UtcNow; ResourceInfo resourceInfo = m_Task.ResourceInfo; if (!resourceInfo.Ready) { m_Task.StartTime = default(DateTime); return(StartTaskStatus.HasToWait); } if (IsAssetLoading(m_Task.AssetName)) { m_Task.StartTime = default(DateTime); return(StartTaskStatus.HasToWait); } if (!m_Task.IsScene) { AssetObject assetObject = m_ResourceLoader.m_AssetPool.Spawn(m_Task.AssetName); if (assetObject != null) { OnAssetObjectReady(assetObject); return(StartTaskStatus.Done); } } foreach (string dependencyAssetName in m_Task.GetDependencyAssetNames()) { if (!m_ResourceLoader.m_AssetPool.CanSpawn(dependencyAssetName)) { m_Task.StartTime = default(DateTime); return(StartTaskStatus.HasToWait); } } string resourceName = resourceInfo.ResourceName.Name; if (IsResourceLoading(resourceName)) { m_Task.StartTime = default(DateTime); return(StartTaskStatus.HasToWait); } s_LoadingAssetNames.Add(m_Task.AssetName); ResourceObject resourceObject = m_ResourceLoader.m_ResourcePool.Spawn(resourceName); if (resourceObject != null) { OnResourceObjectReady(resourceObject); return(StartTaskStatus.CanResume); } s_LoadingResourceNames.Add(resourceName); string fullPath = null; if (!s_CachedResourceNames.TryGetValue(resourceName, out fullPath)) { fullPath = Utility.Path.GetRegularPath(Path.Combine(resourceInfo.StorageInReadOnly ? m_ReadOnlyPath : m_ReadWritePath, resourceInfo.UseFileSystem ? resourceInfo.FileSystemName : resourceInfo.ResourceName.FullName)); s_CachedResourceNames.Add(resourceName, fullPath); } if (resourceInfo.LoadType == LoadType.LoadFromFile) { if (resourceInfo.UseFileSystem) { IFileSystem fileSystem = m_ResourceLoader.m_ResourceManager.GetFileSystem(resourceInfo.FileSystemName, resourceInfo.StorageInReadOnly); m_Helper.ReadFile(fileSystem, resourceInfo.ResourceName.FullName); } else { m_Helper.ReadFile(fullPath); } } else if (resourceInfo.LoadType == LoadType.LoadFromMemory || resourceInfo.LoadType == LoadType.LoadFromMemoryAndQuickDecrypt || resourceInfo.LoadType == LoadType.LoadFromMemoryAndDecrypt) { if (resourceInfo.UseFileSystem) { IFileSystem fileSystem = m_ResourceLoader.m_ResourceManager.GetFileSystem(resourceInfo.FileSystemName, resourceInfo.StorageInReadOnly); m_Helper.ReadBytes(fileSystem, resourceInfo.ResourceName.FullName); } else { m_Helper.ReadBytes(fullPath); } } else { throw new GameFrameworkException(Utility.Text.Format("Resource load type '{0}' is not supported.", resourceInfo.LoadType.ToString())); } return(StartTaskStatus.CanResume); }
static AssetObject[] ReadAssetObjects(BinaryReader es, out uint dataOffset) { var metaSize = SwapUInt(es.ReadUInt32()); var fileSize = SwapUInt(es.ReadUInt32()); var format = SwapUInt(es.ReadUInt32()); dataOffset = SwapUInt(es.ReadUInt32()); if (format >= 9) { var endianness = es.ReadUInt32(); if (endianness != 0) { throw new Exception("Only little-endian assets supported"); } } var ClassIds = new List <int>(); var Hashes = new Dictionary <int, byte[]>(); var version = es.ReadStringToNull(); var target = es.ReadInt32(); //Debug.WriteLine(version + " target " + target); if (format >= 13) { var hasTypeTrees = es.ReadByte() != 0; if (hasTypeTrees) { throw new Exception("Assets with type trees not supported"); } var num = es.ReadInt32(); for (int i = 0; i < num; i++) { int classId = es.ReadInt32(); if (format >= 17) { var unk0 = es.ReadByte(); var scriptId = es.ReadInt16(); if (classId == 114) { if (scriptId >= 0) { classId = -2 - scriptId; } else { classId = -1; } } } ClassIds.Add(classId); var hash = es.ReadBytes(classId < 0 ? 32 : 16); if (classId != -1) { Hashes.Add(classId, hash); } //if (hasTypeTrees) // TypeTrees.Add(classId, LoadTree(es, format)); } } var longObjIds = format >= 14 || (format >= 7 && es.ReadInt32() != 0); var numObjs = es.ReadUInt32(); var objs = new AssetObject[numObjs]; for (uint i = 0; i < numObjs; i++) { if (format >= 14) { es.AlignStream(4); } objs[i] = ReadAssetObject(es, format, ClassIds); } return(objs); }