/// <summary>
        /// Decrements reference count of an <see cref="AssetReference"/>.
        /// </summary>
        /// <param name="assetReference"></param>
        /// <param name="publicReference"></param>
        internal void DecrementReference(AssetReference assetReference, bool publicReference)
        {
            int referenceCount;
            if (publicReference)
            {
                if (assetReference.PublicReferenceCount <= 0)
                    throw new InvalidOperationException("Cannot release an object that doesn't have active public references. Load/Unload pairs must match.");

                referenceCount = --assetReference.PublicReferenceCount + assetReference.PrivateReferenceCount;
            }
            else
            {
                if (assetReference.PrivateReferenceCount <= 0)
                    throw new InvalidOperationException("Cannot release an object that doesn't have active private references. This is either due to non-matching Load/Unload pairs or an engine internal error.");
             
                referenceCount = --assetReference.PrivateReferenceCount + assetReference.PublicReferenceCount;
            }

            if (referenceCount == 0)
            {
                // Free the object itself
                ReleaseAsset(assetReference);

                // Free all its referenced objects
                foreach (var reference in assetReference.References)
                {
                    DecrementReference(reference, false);
                }
            }
            else if (publicReference && assetReference.PublicReferenceCount == 0)
            {
                // If there is no more public reference but object is still alive, let's kick a cycle GC
                CollectUnreferencedCycles();
            }
        }
Ejemplo n.º 2
0
        public IEnumerable<AssetReference> LoadAssets(AssetContainer<Func<Texture2D>> textureContainer,
                                                      AssetContainer<SpriteFont> fontContainer)
        {
            var assetTileReference = new AssetReference(typeof(ITile), Color.White, "blank");
            var snakeHeadReference = new AssetReference(typeof(SnakePiece), Color.White, "snakeHead");
            var snakeBodyReference = new AssetReference(typeof(SnakePiece), Color.Blue, "snakeBody");

            try
            {
                textureContainer.Add(assetTileReference.Reference,
                              content => new StaticTexture(content.Load<Texture2D>(@"Map/tile")).GetTexture);

                textureContainer.Add(snakeHeadReference.Reference,
                              content => new StaticTexture(content.Load<Texture2D>(@"Mobs/snakeHead")).GetTexture);

                textureContainer.Add(snakeBodyReference.Reference,
                              content => new StaticTexture(content.Load<Texture2D>(@"Mobs/snakeBody")).GetTexture);

                fontContainer.Add("scoreFont", content => content.Load<SpriteFont>(@"Fonts/scoreFont"));

            }
            catch (Exception ex)
            {
                Debug.Write("Error while loading content " + ex.Message);
                throw;
            }

            return new List<AssetReference>
            {
                assetTileReference,
                snakeHeadReference,
                snakeBodyReference
            };
        }
        /// <summary>
        /// Releases an asset.
        /// </summary>
        /// <param name="assetReference">The asset reference.</param>
        private void ReleaseAsset(AssetReference assetReference)
        {
            var referencable = assetReference.Object as IReferencable;
            if (referencable != null)
            {
                referencable.Release();
            }
            else
            {
                var disposable = assetReference.Object as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }

            // Remove AssetReference from loaded assets.
            var oldPrev = assetReference.Prev;
            var oldNext = assetReference.Next;
            if (oldPrev != null)
                oldPrev.Next = oldNext;
            if (oldNext != null)
                oldNext.Prev = oldPrev;

            if (oldPrev == null)
            {
                if (oldNext == null)
                    LoadedAssetUrls.Remove(assetReference.Url);
                else
                    LoadedAssetUrls[assetReference.Url] = oldNext;
            }
            LoadedAssetReferences.Remove(assetReference.Object);

            assetReference.Object = null;
        }
 /// <summary>
 /// Increments reference count of an <see cref="AssetReference"/>.
 /// </summary>
 /// <param name="assetReference"></param>
 /// <param name="publicReference"></param>
 internal void IncrementReference(AssetReference assetReference, bool publicReference)
 {
     if (publicReference)
     {
         assetReference.PublicReferenceCount++;
     }
     else
     {
         assetReference.PrivateReferenceCount++;
     }
 }
        public AssetManifestBuilder_Tests()
        {
            var asset = new Mock<IAsset>();
            asset.SetupGet(a => a.SourceFile.FullPath).Returns("~/asset");
            bundleReference = new AssetReference("~/bundle", asset.Object, 1, AssetReferenceType.DifferentBundle);
            urlReference = new AssetReference("http://example.com/", asset.Object, 2, AssetReferenceType.Url);
            rawFileReference = new AssetReference("~/file", asset.Object, 3, AssetReferenceType.RawFilename);
            var sameBundleReference = new AssetReference("~/same", asset.Object, 4, AssetReferenceType.SameBundle);
            asset.SetupGet(a => a.References)
                 .Returns(new[] { bundleReference, urlReference, rawFileReference, sameBundleReference });

            var builder = new AssetManifestBuilder();
            manifest = builder.BuildManifest(asset.Object);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Generate a precompiled sprite font from the current sprite font asset.
        /// </summary>
        /// <param name="asset">The sprite font asset</param>
        /// <param name="sourceAsset">The source sprite font asset item</param>
        /// <param name="texturePath">The path of the source texture</param>
        /// <param name="srgb">Indicate if the generated texture should be srgb</param>
        /// <returns>The precompiled sprite font asset</returns>
        public static PrecompiledSpriteFontAsset GeneratePrecompiledSDFSpriteFont(this SpriteFontAsset asset, AssetItem sourceAsset, string texturePath)
        {
            // TODO create PrecompiledSDFSpriteFontAsset
            var scalableFont = (SignedDistanceFieldSpriteFont)SignedDistanceFieldFontCompiler.Compile(FontDataFactory, asset);

            var referenceToSourceFont = new AssetReference<SpriteFontAsset>(sourceAsset.Id, sourceAsset.Location);
            var glyphs = new List<Glyph>(scalableFont.CharacterToGlyph.Values);
            var textures = scalableFont.Textures;

            var imageType = ImageFileType.Png;
            var textureFileName = new UFile(texturePath).GetFullPathWithoutExtension() + imageType.ToFileExtension();

            if (textures != null && textures.Count > 0)
            {
                // save the texture   TODO support for multi-texture
                using (var stream = File.OpenWrite(textureFileName))
                    scalableFont.Textures[0].GetSerializationData().Save(stream, imageType);
            }

            var precompiledAsset = new PrecompiledSpriteFontAsset
            {
                Glyphs = glyphs,
                Size = asset.FontType.Size,
                Style = asset.FontSource.Style,
                OriginalFont = referenceToSourceFont,
                FontDataFile = textureFileName,
                BaseOffset = scalableFont.BaseOffsetY,
                DefaultLineSpacing = scalableFont.DefaultLineSpacing,
                ExtraSpacing = scalableFont.ExtraSpacing,
                ExtraLineSpacing = scalableFont.ExtraLineSpacing,
                DefaultCharacter = asset.DefaultCharacter,
                FontName = asset.FontSource.GetFontName(),
                IsPremultiplied = asset.FontType.IsPremultiplied,
                IsSrgb = false,
            };

            return precompiledAsset;
        }
        /// <summary>
        /// Generate a precompiled sprite font from the current sprite font asset.
        /// </summary>
        /// <param name="asset">The sprite font asset</param>
        /// <param name="sourceAsset">The source sprite font asset item</param>
        /// <param name="texturePath">The path of the source texture</param>
        /// <param name="srgb">Indicate if the generated texture should be srgb</param>
        /// <returns>The precompiled sprite font asset</returns>
        public static PrecompiledSpriteFontAsset GeneratePrecompiledSpriteFont(this SpriteFontAsset asset, AssetItem sourceAsset, string texturePath, bool srgb)
        {
            var staticFont = (StaticSpriteFont)StaticFontCompiler.Compile(FontDataFactory, asset, srgb);

            var referenceToSourceFont = new AssetReference<SpriteFontAsset>(sourceAsset.Id, sourceAsset.Location);
            var glyphs = new List<Glyph>(staticFont.CharacterToGlyph.Values);
            var textures = staticFont.Textures;
            
            var imageType = ImageFileType.Png;
            var textureFileName = new UFile(texturePath).GetFullPathWithoutExtension() + imageType.ToFileExtension();

            if (textures != null && textures.Count > 0)
            {
                // save the texture   TODO support for multi-texture
                using (var stream = File.OpenWrite(textureFileName))
                    staticFont.Textures[0].GetSerializationData().Save(stream, imageType);
            }

            var precompiledAsset = new PrecompiledSpriteFontAsset
            {
                Glyphs = glyphs,
                Size = asset.Size,
                Style = asset.Style,
                Source = referenceToSourceFont,
                FontDataFile = textureFileName,
                BaseOffset = staticFont.BaseOffsetY,
                DefaultLineSpacing = staticFont.DefaultLineSpacing,
                ExtraSpacing = staticFont.ExtraSpacing,
                ExtraLineSpacing = staticFont.ExtraLineSpacing,
                DefaultCharacter = asset.DefaultCharacter,
                FontName = !string.IsNullOrEmpty(asset.Source) ? (asset.Source.GetFileName() ?? "") : asset.FontName,
                IsPremultiplied = asset.IsPremultiplied,
                IsSrgb = srgb
            };

            return precompiledAsset;
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Checks if a default scene exists for this game package.
        /// </summary>
        /// <param name="log">The log to output the result of the validation.</param>
        public override void Run(ILogger log)
        {
            if (log == null) throw new ArgumentNullException("log");

            foreach (var package in Session.Packages)
            {
                // Make sure package has its assets loaded
                if (package.State < PackageState.AssetsReady)
                    continue;

                var hasGameExecutable = package.Profiles.SelectMany(profile => profile.ProjectReferences).Any(projectRef => projectRef.Type == ProjectType.Executable);
                if (!hasGameExecutable)
                {
                    continue;
                }

                var sharedProfile = package.Profiles.FindSharedProfile();
                if (sharedProfile == null) continue;

                var defaultScene = sharedProfile.Properties.Get(GameSettingsAsset.DefaultScene);

                // If the pdxpkg does not reference any scene
                if (defaultScene == null)
                {
                    log.Error(package, null, AssetMessageCode.DefaultSceneNotFound, null);

                    // Creates a new default scene
                    // Checks we don't overwrite an existing asset
                    const string defaultSceneLocation = GameSettingsAsset.DefaultSceneLocation;
                    var existingDefault = package.Assets.Find(defaultSceneLocation);
                    if (existingDefault != null && existingDefault.Asset is SceneAsset)
                    {
                        // A scene at the default location already exists among the assets, let's reference it as the default scene
                        var sceneAsset = new AssetReference<SceneAsset>(existingDefault.Id, existingDefault.Location);
                        GameSettingsAsset.SetDefaultScene(package, sceneAsset);
                    }
                    else if (existingDefault != null)
                    {
                        // Very rare case: the default scene location is occupied by another asset which is not a scene
                        // Compute a new default name to not overwrite the existing asset
                        var newName = NamingHelper.ComputeNewName(defaultSceneLocation, package.Assets, a => a.Location);
                        GameSettingsAsset.CreateAndSetDefaultScene(package, newName);
                    } 
                    else
                    {
                        // Creates a new default scene asset
                        GameSettingsAsset.CreateAndSetDefaultScene(package, defaultSceneLocation);
                    }

                    continue;
                }

                // The pdxpkg references an asset
                var defaultAsset = package.Assets.Find(defaultScene.Location);

                if (defaultAsset != null) continue; // Default scene exists and is referenced

                // The asset referenced does not exist, create it
                log.Error(package, defaultScene, AssetMessageCode.AssetNotFound, defaultScene);
                GameSettingsAsset.CreateAndSetDefaultScene(package);
            }
        }
Ejemplo n.º 9
0
        private void SerializeObject(Queue <SerializeOperation> serializeOperations, string url, object obj, bool publicReference)
        {
            // Don't create context in case we don't want to serialize referenced objects
            //if (!SerializeReferencedObjects && obj != RootObject)
            //    return null;

            // Already saved?
            // TODO: Ref counting? Should we change it on save? Probably depends if we cache or not.
            if (LoadedAssetReferences.ContainsKey(obj))
            {
                return;
            }

            var serializer = Serializer.GetSerializer(null, obj.GetType());

            if (serializer == null)
            {
                throw new InvalidOperationException(string.Format("Content serializer for {0} could not be found.", obj.GetType()));
            }

            var contentSerializerContext = new ContentSerializerContext(url, ArchiveMode.Serialize, this);

            using (var stream = FileProvider.OpenStream(url, VirtualFileMode.Create, VirtualFileAccess.Write))
            {
                var streamWriter = new BinarySerializationWriter(stream);
                PrepareSerializerContext(contentSerializerContext, streamWriter.Context);

                ChunkHeader header = null;

                // Allocate space in the stream, and also include header version in the hash computation, which is better
                // If serialization type is null, it means there should be no header.
                var serializationType = serializer.SerializationType;
                if (serializationType != null)
                {
                    header      = new ChunkHeader();
                    header.Type = serializer.SerializationType.AssemblyQualifiedName;
                    header.Write(streamWriter);
                    header.OffsetToObject = (int)streamWriter.NativeStream.Position;
                }

                contentSerializerContext.SerializeContent(streamWriter, serializer, obj);

                // Write references and updated header
                if (header != null)
                {
                    header.OffsetToReferences = (int)streamWriter.NativeStream.Position;
                    contentSerializerContext.SerializeReferences(streamWriter);

                    // Move back to the pre-allocated header position in the steam
                    stream.Seek(0, SeekOrigin.Begin);

                    // Write actual header.
                    header.Write(new BinarySerializationWriter(stream));
                }
            }

            var assetReference = new AssetReference(url, publicReference);

            contentSerializerContext.AssetReference = assetReference;
            SetAssetObject(assetReference, obj);

            // Process content references
            // TODO: Should we work at ChunkReference level?
            foreach (var contentReference in contentSerializerContext.ContentReferences)
            {
                if (contentReference.ObjectValue != null)
                {
                    var attachedReference = AttachedReferenceManager.GetAttachedReference(contentReference.ObjectValue);
                    if (attachedReference == null || attachedReference.IsProxy)
                    {
                        continue;
                    }

                    serializeOperations.Enqueue(new SerializeOperation(contentReference.Location, contentReference.ObjectValue, false));
                }
            }
        }
 public static T SetConditionStartParticleReference <T>(this T entity, AssetReference value)
     where T : EffectParticleParameters
 {
     entity.SetField("conditionStartParticleReference", value);
     return(entity);
 }
 public static T SetEmissiveBorderSurfaceParticleReference <T>(this T entity, AssetReference value)
     where T : EffectParticleParameters
 {
     entity.SetField("emissiveBorderSurfaceParticleReference", value);
     return(entity);
 }
Ejemplo n.º 12
0
        private void LoadAsset(AssetMigrationContext context, PackageLoadingAssetFile assetFile, LoggerResult loggerResult)
        {
            var fileUPath = assetFile.FilePath;
            var sourceFolder = assetFile.SourceFolder;

            // Check if asset has been deleted by an upgrader
            if (assetFile.Deleted)
            {
                IsDirty = true;

                lock (filesToDelete)
                {
                    filesToDelete.Add(assetFile.FilePath);
                }

                // Don't create temporary assets for files deleted during package upgrading
                return;
            }

            // An exception can occur here, so we make sure that loading a single asset is not going to break 
            // the loop
            try
            {
                AssetMigration.MigrateAssetIfNeeded(context, assetFile, PackageStore.Instance.DefaultPackageName);

                // Try to load only if asset is not already in the package or assetRef.Asset is null
                var assetPath = assetFile.AssetPath;

                var assetFullPath = fileUPath.FullPath;
                var assetContent = assetFile.AssetContent;

                var projectInclude = assetFile.ProjectFile != null ? fileUPath.MakeRelative(assetFile.ProjectFile.GetFullDirectory()) : null;

                bool aliasOccurred;
                var asset = LoadAsset(context.Log, assetFullPath, assetPath, assetFile.ProjectFile, projectInclude, assetContent, out aliasOccurred);

                // Create asset item
                var assetItem = new AssetItem(assetPath, asset, this)
                {
                    IsDirty = assetContent != null || aliasOccurred,
                    SourceFolder = sourceFolder.MakeRelative(RootDirectory),
                    SourceProject = asset is SourceCodeAsset && assetFile.ProjectFile != null ? assetFile.ProjectFile : null
                };

                // Set the modified time to the time loaded from disk
                if (!assetItem.IsDirty)
                    assetItem.ModifiedTime = File.GetLastWriteTime(assetFullPath);

                // TODO: Let's review that when we rework import process
                // Not fixing asset import anymore, as it was only meant for upgrade
                // However, it started to make asset dirty, for ex. when we create a new texture, choose a file and reload the scene later
                // since there was no importer id and base.
                //FixAssetImport(assetItem);

                // Add to temporary assets
                lock (TemporaryAssets)
                {
                    TemporaryAssets.Add(assetItem);
                }
            }
            catch (Exception ex)
            {
                int row = 1;
                int column = 1;
                var yamlException = ex as YamlException;
                if (yamlException != null)
                {
                    row = yamlException.Start.Line + 1;
                    column = yamlException.Start.Column;
                }

                var module = context.Log.Module;

                var assetReference = new AssetReference<Asset>(Guid.Empty, fileUPath.FullPath);

                // TODO: Change this instead of patching LoggerResult.Module, use a proper log message
                if (loggerResult != null)
                {
                    loggerResult.Module = "{0}({1},{2})".ToFormat(Path.GetFullPath(fileUPath.FullPath), row, column);
                }

                context.Log.Error(this, assetReference, AssetMessageCode.AssetLoadingFailed, ex, fileUPath, ex.Message);

                if (loggerResult != null)
                {
                    loggerResult.Module = module;
                }
            }
        }
Ejemplo n.º 13
0
 // Sets the default scene within a package properties
 public static void SetDefaultScene(Package package, AssetReference<SceneAsset> defaultScene)
 {
     package.Profiles.FindSharedProfile().Properties.Set(DefaultScene, defaultScene);
     MarkPackageDirty(package);
 }
Ejemplo n.º 14
0
    private IEnumerator LoadAssets()
    {
        // 加载UI面板
        GameLogger.Log("Load UIRoot.");
        AssetReference rootRef    = new AssetReference("UIPanel/UIRoot");
        var            rootHandle = rootRef.LoadAssetAsync <GameObject>();

        yield return(rootHandle);

        GameObject uiRoot = rootHandle.InstantiateObject;         // 实例化对象

        // 加载窗口
        GameObject window;
        {
            AssetReference windowRef = new AssetReference("UIPanel/LoginWindow");
            var            handle    = windowRef.LoadAssetAsync <GameObject>();
            yield return(handle);

            window = handle.InstantiateObject;             // 实例化对象
            window.transform.SetParent(uiRoot.transform, false);

            var versionTxt = window.transform.BFSearch("Version").GetComponent <Text>();
            if (MotionEngine.Contains(typeof(PatchManager)))
            {
                versionTxt.text = PatchManager.Instance.GetGameVersion();
            }
            else
            {
                versionTxt.text = "NO Server";
            }
        }

        // 加载资源包
        {
            GameLogger.Log("Load texture package");
            AssetReference packRef = new AssetReference("UITexture/Foods");
            var            handle1 = packRef.LoadAssetAsync <Texture>("eggs");
            yield return(handle1);

            Texture tex1 = handle1.AssetObject as Texture;

            var handle2 = packRef.LoadAssetAsync <Texture>("apple");
            yield return(handle2);

            Texture tex2 = handle2.AssetObject as Texture;

            // 设置纹理1
            RawImage img1 = window.transform.BFSearch("FoodImg1").GetComponent <RawImage>();
            img1.texture = tex1;
            img1.SetNativeSize();

            // 设置纹理2
            RawImage img2 = window.transform.BFSearch("FoodImg2").GetComponent <RawImage>();
            img2.texture = tex2;
            img2.SetNativeSize();
        }

        // 加载模型
        {
            AssetReference entityRef = new AssetReference("Entity/Monster/Boss");
            var            handle    = entityRef.LoadAssetAsync <GameObject>();
            yield return(handle);

            var sphere = handle.InstantiateObject;             // 实例化对象
            sphere.transform.position   = new Vector3(5f, 0, 0);
            sphere.transform.localScale = sphere.transform.localScale * 2f;
        }
    }
Ejemplo n.º 15
0
        public void GivenAssetWithReferenceToUrl_WhenSaveContainer_ThenXmlHasReferenceElementWithUrlAsPath()
        {
            using (var cacheDir = new TempDirectory())
            {
                var settings = new CassetteSettings
                {
                    SourceDirectory = Mock.Of<IDirectory>(),
                    CacheDirectory = new FileSystemDirectory(cacheDir)
                };
                var cache = new BundleCache("VERSION", settings);
                var bundle = new TestableBundle("~/bundle-1");
                var asset = StubAsset();
                var reference = new AssetReference("http://test.com", asset.Object, -1, AssetReferenceType.Url);
                asset.SetupGet(a => a.References)
                     .Returns(new[] { reference });
                bundle.Assets.Add(asset.Object);

                cache.SaveBundleContainer(new BundleContainer(new Bundle[] { bundle, new ExternalScriptBundle("http://test.com"),  }));

                var xml = File.ReadAllText(Path.Combine(cacheDir, "container.xml"));
                xml.ShouldContain("<Reference Path=\"http://test.com\" />");
            }
        }
Ejemplo n.º 16
0
        public static ShaderPair Load(GraphicsDevice device, AssetReference <ShaderAsset> frag, AssetReference <ShaderAsset> vert, ShaderType type)
        {
            var fragShader = loadShader(frag, device.device, VkShaderStageFlags.Fragment);
            var vertShader = loadShader(vert, device.device, VkShaderStageFlags.Vertex);

            return(new ShaderPair(device, type, fragShader, vertShader));
        }
Ejemplo n.º 17
0
 public static T SetPrefabReference <T>(this T entity, AssetReference value)
     where T : MonsterPresentationDefinition
 {
     entity.SetField("prefabReference", value);
     return(entity);
 }
Ejemplo n.º 18
0
 public OwnerRegisterDataSourceCommand(UniTask <IContext> contextTask, AssetReference resource) : base(contextTask, resource)
 {
 }
Ejemplo n.º 19
0
        // Multi selection handling. Returns new list of selected instanceIDs
        internal static List <int> GetNewSelection(ref AssetReference clickedEntry, List <int> allEntryInstanceIDs, List <string> allEntryGuids, List <int> selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection, bool shiftKeyIsDown, bool actionKeyIsDown)
        {
            bool useShift     = shiftKeyIsDown || (actionKeyIsDown && useShiftAsActionKey);
            bool useActionKey = actionKeyIsDown && !useShiftAsActionKey;

            if (!allowMultiSelection)
            {
                useShift = useActionKey = false;
            }

            // Toggle selected node from selection
            if (useActionKey)
            {
                var newSelection = new List <int>(selectedInstanceIDs);
                if (newSelection.Contains(clickedEntry.instanceID))
                {
                    newSelection.Remove(clickedEntry.instanceID);
                }
                else
                {
                    if (TrySetInstanceId(ref clickedEntry))
                    {
                        newSelection.Add(clickedEntry.instanceID);
                    }
                }
                return(newSelection);
            }
            // Select everything between the first selected object and the selected
            else if (useShift)
            {
                if (clickedEntry.instanceID == lastClickedInstanceID)
                {
                    return(new List <int>(selectedInstanceIDs));
                }

                int firstIndex;
                int lastIndex;
                if (!GetFirstAndLastSelected(allEntryInstanceIDs, selectedInstanceIDs, out firstIndex, out lastIndex))
                {
                    // We had no selection
                    var newSelection = new List <int>(1);
                    if (TrySetInstanceId(ref clickedEntry))
                    {
                        newSelection.Add(clickedEntry.instanceID);
                    }

                    return(newSelection);
                }

                int newIndex  = -1;
                int prevIndex = -1;

                // Only valid in case the selection concerns assets

                if (!TrySetInstanceId(ref clickedEntry))
                {
                    return(new List <int>(selectedInstanceIDs));
                }

                int clickedInstanceID = clickedEntry.instanceID;

                if (lastClickedInstanceID != 0)
                {
                    for (int i = 0; i < allEntryInstanceIDs.Count; ++i)
                    {
                        if (allEntryInstanceIDs[i] == clickedInstanceID)
                        {
                            newIndex = i;
                        }

                        if (allEntryInstanceIDs[i] == lastClickedInstanceID)
                        {
                            prevIndex = i;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < allEntryInstanceIDs.Count; ++i)
                    {
                        if (allEntryInstanceIDs[i] == clickedInstanceID)
                        {
                            newIndex = i;
                        }
                    }
                }

                System.Diagnostics.Debug.Assert(newIndex != -1); // new item should be part of visible folder set
                int dir = 0;
                if (prevIndex != -1)
                {
                    dir = (newIndex > prevIndex) ? 1 : -1;
                }

                int from, to;
                if (newIndex > lastIndex)
                {
                    from = firstIndex;
                    to   = newIndex;
                }
                else if (newIndex >= firstIndex && newIndex < lastIndex)
                {
                    if (dir > 0)
                    {
                        from = newIndex;
                        to   = lastIndex;
                    }
                    else
                    {
                        from = firstIndex;
                        to   = newIndex;
                    }
                }
                else
                {
                    from = newIndex;
                    to   = lastIndex;
                }

                // Outcomment to debug
                //Debug.Log (clickedEntry + ",   firstIndex " + firstIndex + ", lastIndex " + lastIndex + ",    newIndex " + newIndex + " " + ", lastClickedIndex " + prevIndex + ",     from " + from + ", to " + to);
                if (allEntryGuids == null)
                {
                    return(allEntryInstanceIDs.GetRange(from, to - from + 1));
                }

                var foundInstanceIDs = TryGetInstanceIds(allEntryInstanceIDs, allEntryGuids, from, to);
                if (foundInstanceIDs != null)
                {
                    return(foundInstanceIDs);
                }

                return(new List <int>(selectedInstanceIDs));
            }
            // Just set the selection to the clicked object
            else
            {
                if (keepMultiSelection)
                {
                    // Don't change selection on mouse down when clicking on selected item.
                    // This is for dragging in case with multiple items selected or right click (mouse down should not unselect the rest).
                    if (selectedInstanceIDs.Contains(clickedEntry.instanceID))
                    {
                        return(new List <int>(selectedInstanceIDs));
                    }
                }

                if (TrySetInstanceId(ref clickedEntry))
                {
                    var newSelection = new List <int>(1);
                    newSelection.Add(clickedEntry.instanceID);
                    return(newSelection);
                }
                else
                {
                    return(new List <int>(selectedInstanceIDs));
                }
            }
        }
Ejemplo n.º 20
0
 internal static List <int> GetNewSelection(ref AssetReference clickedEntry, List <int> allEntryInstanceIDs, List <string> allEntryGuids, List <int> selectedInstanceIDs, int lastClickedInstanceID, bool keepMultiSelection, bool useShiftAsActionKey, bool allowMultiSelection)
 {
     return(GetNewSelection(ref clickedEntry, allEntryInstanceIDs, allEntryGuids, selectedInstanceIDs, lastClickedInstanceID, keepMultiSelection, useShiftAsActionKey, allowMultiSelection, Event.current.shift, EditorGUI.actionKey));
 }
Ejemplo n.º 21
0
	public static object GetAsset(AssetReference id) 
	{
		if(id.index == -1)
			return null;
		try
		{
			return assetStore[id.type][id.name][id.index];
		}
		catch
		{
			return null;
		}
	}
Ejemplo n.º 22
0
 public static T SetPrefabReference <T>(this T entity, AssetReference value)
     where T : PrefabByEnvironmentDescription
 {
     entity.SetField("prefabReference", value);
     return(entity);
 }
Ejemplo n.º 23
0
        public void GivenAssetWithReferenceToAnotherBundle_WhenSaveContainer_ThenXmlHasReferenceElementWithReferencedBundlePath()
        {
            using (var cacheDir = new TempDirectory())
            {
                var settings = new CassetteSettings
                {
                    SourceDirectory = Mock.Of<IDirectory>(),
                    CacheDirectory = new FileSystemDirectory(cacheDir)
                };
                var cache = new BundleCache("VERSION", settings);
                var bundle1 = new TestableBundle("~/bundle-1");
                var bundle2 = new TestableBundle("~/bundle-2");
                var asset1 = StubAsset();
                var reference = new AssetReference("~/bundle-2", asset1.Object, -1, AssetReferenceType.DifferentBundle);
                asset1.SetupGet(a => a.References)
                      .Returns(new[] { reference });
                bundle1.Assets.Add(asset1.Object);

                cache.SaveBundleContainer(new BundleContainer(new[] { bundle1, bundle2 }));

                var xml = File.ReadAllText(Path.Combine(cacheDir, "container.xml"));
                xml.ShouldContain("<Reference Path=\"~/bundle-2\" />");
            }
        }
Ejemplo n.º 24
0
 // Token: 0x060011CE RID: 4558 RVA: 0x00073AC1 File Offset: 0x00071EC1
 protected virtual void handleAssetReferenceDocked(AssetReference <T> assetReference)
 {
     base.inspectable.value = assetReference;
 }
Ejemplo n.º 25
0
        private static void UpdateRootAssets(RootAssetCollection rootAssetCollection, IReadOnlyDictionary<AssetId, Tuple<AssetId, UFile>> idRemap)
        {
            foreach (var rootAsset in rootAssetCollection.ToArray())
            {
                var id = rootAsset.Id;
                Tuple<AssetId, UFile> remap;

                if (idRemap.TryGetValue(id, out remap) && IsNewReference(remap, rootAsset))
                {
                    var newRootAsset = new AssetReference(remap.Item1, remap.Item2);
                    rootAssetCollection.Remove(rootAsset.Id);
                    rootAssetCollection.Add(newRootAsset);
                }
            }
        }
Ejemplo n.º 26
0
    public Dictionary <Material, int> GetMaterialsData(MeshRenderer[] allRenderers)
    {
        float3 ColorToVector(Color c)
        {
            return(float3(c.r, c.b, c.g));
        }

        float2 GetVector2(float4 vec)
        {
            return(float2(vec.x, vec.y));
        }

        var dict = new Dictionary <Material, int>(allRenderers.Length);

        allProperties = new List <MaterialProperties>(allRenderers.Length);
        var albedoTexs       = new List <Texture>(allRenderers.Length);
        var normalTexs       = new List <Texture>(allRenderers.Length);
        var smoTexs          = new List <Texture>(allRenderers.Length);
        var emissionTex      = new List <Texture>(allRenderers.Length);
        var heightTex        = new List <Texture>(allRenderers.Length);
        var secondAlbedoTex  = new List <Texture>(allRenderers.Length);
        var secondBumpTex    = new List <Texture>(allRenderers.Length);
        var secondSpecTex    = new List <Texture>(allRenderers.Length);
        var albedoDict       = new Dictionary <Texture, int>(allRenderers.Length);
        var normalDict       = new Dictionary <Texture, int>(allRenderers.Length);
        var smoDict          = new Dictionary <Texture, int>(allRenderers.Length);
        var emissionDict     = new Dictionary <Texture, int>(allRenderers.Length);
        var heightDict       = new Dictionary <Texture, int>(allRenderers.Length);
        var secondAlbedoDict = new Dictionary <Texture, int>(allRenderers.Length);
        var secondBumpDict   = new Dictionary <Texture, int>(allRenderers.Length);
        var secondSpecDict   = new Dictionary <Texture, int>(allRenderers.Length);
        int len = 0;

        int GetTextureIndex(List <Texture> lst, Dictionary <Texture, int> texDict, Texture tex)
        {
            int ind = -1;

            if (tex)
            {
                if (!texDict.TryGetValue(tex, out ind))
                {
                    ind = lst.Count;
                    lst.Add(tex);
                    texDict.Add(tex, ind);
                }
            }
            return(ind);
        }

        foreach (var r in allRenderers)
        {
            var ms = r.sharedMaterials;
            foreach (var m in ms)
            {
                if (!m)
                {
                    throw new System.Exception(r.name + " Has Null Mat");
                }
                if (!dict.ContainsKey(m))
                {
                    dict.Add(m, len);
                    Texture albedo            = m.GetTexture("_MainTex");
                    Texture normal            = m.GetTexture("_BumpMap");
                    Texture smo               = m.GetTexture("_SpecularMap");
                    Texture emission          = m.GetTexture("_EmissionMap");
                    Texture height            = m.GetTexture("_HeightMap");
                    Texture secondBump        = m.GetTexture("_SecondaryBumpMap");
                    Texture secondAlbedo      = m.GetTexture("_SecondaryMainTex");
                    Texture secondSpec        = m.GetTexture("_SecondarySpecularMap");
                    int     albedoIndex       = GetTextureIndex(albedoTexs, albedoDict, albedo);
                    int     normalIndex       = GetTextureIndex(normalTexs, normalDict, normal);
                    int     smoIndex          = GetTextureIndex(smoTexs, smoDict, smo);
                    int     emissionIndex     = GetTextureIndex(emissionTex, emissionDict, emission);
                    int     heightIndex       = GetTextureIndex(heightTex, heightDict, height);
                    int     secondBumpIndex   = GetTextureIndex(secondBumpTex, secondBumpDict, secondBump);
                    int     secondAlbedoIndex = GetTextureIndex(secondAlbedoTex, secondAlbedoDict, secondAlbedo);
                    int     secondSpecIndex   = GetTextureIndex(secondSpecTex, secondSpecDict, secondSpec);
                    allProperties.Add(new MaterialProperties
                    {
                        _Color                = ColorToVector(m.GetColor("_Color")),
                        _Glossiness           = m.GetFloat("_Glossiness"),
                        _DecalLayer           = (uint)m.GetInt("_DecalLayer"),
                        _EmissionColor        = ColorToVector(m.GetColor("_EmissionColor") * m.GetFloat("_EmissionMultiplier")),
                        _MetallicIntensity    = m.GetFloat("_MetallicIntensity"),
                        _SpecularIntensity    = m.GetFloat("_SpecularIntensity"),
                        _Occlusion            = m.GetFloat("_Occlusion"),
                        _NormalIntensity      = GetVector2(m.GetVector("_NormalIntensity")),
                        _TileOffset           = m.GetVector("_TileOffset"),
                        _BumpMap              = normalIndex,
                        _EmissionMap          = emissionIndex,
                        _MainTex              = albedoIndex,
                        _SpecularMap          = smoIndex,
                        _HeightMap            = heightIndex,
                        _HeightMapIntensity   = m.GetFloat("_HeightmapIntensity"),
                        _SecondaryBumpMap     = secondBumpIndex,
                        _SecondaryMainTex     = secondAlbedoIndex,
                        _SecondarySpecularMap = secondSpecIndex,
                        _SecondaryTileOffset  = m.GetVector("_SecondaryTileOffset")
                    });
                    len++;
                }
            }
        }
        ComputeShader readRTDataShader = Resources.Load <ComputeShader>("ReadRTData");

        void GetGUIDs(out AssetReference[] strs, List <Texture> texs, int typeIndex)
        {
            strs = new AssetReference[texs.Count];
            for (int i = 0; i < texs.Count; ++i)
            {
                string guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(texs[i]));
                SetObjectAddressable(texs[i], guid);
                strs[i] = new AssetReference(guid);
            }
        }

        GetGUIDs(out albedoGUIDs, albedoTexs, 0);
        GetGUIDs(out secondAlbedoGUIDs, secondAlbedoTex, 0);
        GetGUIDs(out normalGUIDs, normalTexs, 1);
        GetGUIDs(out secondNormalGUIDs, secondBumpTex, 1);
        GetGUIDs(out smoGUIDs, smoTexs, 0);
        GetGUIDs(out secondSpecGUIDs, secondSpecTex, 0);
        GetGUIDs(out emissionGUIDs, emissionTex, 2);
        GetGUIDs(out heightGUIDs, heightTex, 3);
        EditorUtility.SetDirty(AddressableAssetSettingsDefaultObject.Settings);
        return(dict);
    }
Ejemplo n.º 27
0
 public object GetAsset(AssetReference id)
 {
     if(id.index == -1)
         return null;
     try
     {
         var type = UnitySerializer.GetTypeEx(id.type);
         Index<string, List<UnityEngine.Object>> nameLookup;
         if(!assetReferences.TryGetValue(type, out nameLookup))
         {
             assetReferences[type] = nameLookup = new Index<string, List<UnityEngine.Object>>();
         var objectsOfType = Resources.FindObjectsOfTypeAll(type).Except(UnityEngine.Object.FindObjectsOfType(type));
             foreach(var reference in objectsOfType)
             {
                 nameLookup[reference.name].Add(reference);
             }
         }
         List<UnityEngine.Object> references;
         if(!nameLookup.TryGetValue(id.name, out references))
         {
             return null;
         }
         if(id.index >= references.Count)
             return null;
         return references[id.index];
     }
     catch
     {
         return null;
     }
 }
Ejemplo n.º 28
0
 public AsyncOperationHandle <GameObject> InstantiateReplicaAsync(AssetReference reference) => InstantiateReplicaAsync(reference.RuntimeKey, Vector3.zero, Quaternion.identity);
Ejemplo n.º 29
0
        internal void RegisterDeserializedObject <T>(string url, T obj)
        {
            var assetReference = new AssetReference(url, false);

            SetAssetObject(assetReference, obj);
        }
Ejemplo n.º 30
0
 public AsyncOperationHandle <GameObject> InstantiateReplicaAsync(AssetReference reference, Vector3 position, Quaternion rotation) => InstantiateReplicaAsync(reference.RuntimeKey, position, rotation);
 public static T SetActiveEffectSurfaceStartParticleReference <T>(this T entity, AssetReference value)
     where T : EffectParticleParameters
 {
     entity.SetField("activeEffectSurfaceStartParticleReference", value);
     return(entity);
 }
Ejemplo n.º 32
0
        public void TestLoadAssetSync()
        {
            AssetReference result = m_AssetManager.LoadAssetSync("ArtResources/Prefabs/MyPrefab.prefab");

            Assert.AreNotEqual(result, null);
        }
 void ManifestReferenceEqualsAssetReference(AssetReferenceManifest referenceManifest, AssetReference reference)
 {
     referenceManifest.Path.ShouldEqual(reference.Path);
     referenceManifest.Type.ShouldEqual(reference.Type);
     referenceManifest.SourceLineNumber.ShouldEqual(reference.SourceLineNumber);
 }
Ejemplo n.º 34
0
 bool IsUrlReferenceNotYetSeen(AssetReference reference)
 {
     var isUrl = reference.Type == AssetReferenceType.Url;
     var alreadySeenUrl = existingUrls.Contains(reference.ToPath);
     return isUrl && !alreadySeenUrl;
 }
Ejemplo n.º 35
0
        private static void UpdateRootAssets(RootAssetCollection rootAssetCollection, Dictionary<Guid, Tuple<Guid, UFile>> idRemap, Dictionary<UFile, UFile> locationRemap)
        {
            foreach (var rootAsset in rootAssetCollection.ToArray())
            {
                var location = (UFile)rootAsset.Location;
                var id = rootAsset.Id;

                Tuple<Guid, UFile> newId;
                UFile newLocation;

                bool changed = false;
                if (idRemap.TryGetValue(id, out newId))
                {
                    id = newId.Item1;
                    location = newId.Item2;
                    changed = true;
                }
                if (!changed && locationRemap.TryGetValue(location, out newLocation))
                {
                    location = newLocation;
                    changed = true;
                }

                if (changed)
                {
                    var newRootAsset = new AssetReference<Asset>(id, location);
                    rootAssetCollection.Remove(rootAsset.Id);
                    rootAssetCollection.Add(newRootAsset);
                }
            }
        }
        /// <summary>
        /// Generate an array of PricingStructurePoint from a set of input arrays
        /// The array can then be added to the Matrix
        /// </summary>
        /// <param name="expiry">Expiry values to use</param>
        /// <param name="strike">Strike values to use</param>
        /// <param name="volatility">An array of volatility values</param>
        /// <param name="strikeQuoteUnits">The strike quote units.</param>
        /// <param name="underlyingAssetReference">The underlying asset.</param>
        /// <returns></returns>
        private PricingStructurePoint[] ProcessRawSurface(String[] expiry, Double[] strike, double[,] volatility, PriceQuoteUnits strikeQuoteUnits, AssetReference underlyingAssetReference)
        {
            var expiryLength = expiry.Length;
            var strikeLength = strike.Length;
            var pointIndex   = 0;
            var points       = new PricingStructurePoint[expiryLength * strikeLength];

            for (var expiryIndex = 0; expiryIndex < expiryLength; expiryIndex++)
            {
                // extract the current expiry
                var expiryKeyPart = expiry[expiryIndex];
                for (var strikeIndex = 0; strikeIndex < strikeLength; strikeIndex++)
                {
                    // Extract the strike to use in the helper key
                    var strikeKeyPart = strike[strikeIndex];
                    // Extract the row,column indexed volatility
                    var vol = (decimal)volatility[expiryIndex, strikeIndex];
                    var key = new ExpiryTenorStrikeKey(expiryKeyPart, strikeKeyPart);
                    _matrixIndexHelper.Add(key, pointIndex);
                    // Add the value to the points array (dataPoints entry in the matrix)
                    var coordinates = new PricingDataPointCoordinate[1];
                    coordinates[0] = PricingDataPointCoordinateFactory.Create(expiry[expiryIndex], null, (Decimal)strike[strikeIndex]);
                    var pt = new PricingStructurePoint {
                        value                    = vol,
                        valueSpecified           = true,
                        coordinate               = coordinates,
                        underlyingAssetReference = underlyingAssetReference,
                        quoteUnits               = strikeQuoteUnits
                    };
                    points[pointIndex++] = pt;
                }
            }
            return(points);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Refreshes this package from the disk by loading or reloading all assets.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="assetFiles">The asset files (loaded from <see cref="ListAssetFiles"/> if null).</param>
        /// <param name="cancelToken">The cancel token.</param>
        /// <returns>A logger that contains error messages while refreshing.</returns>
        /// <exception cref="System.InvalidOperationException">Package RootDirectory is null
        /// or
        /// Package RootDirectory [{0}] does not exist.ToFormat(RootDirectory)</exception>
        public void LoadTemporaryAssets(ILogger log, IList<PackageLoadingAssetFile> assetFiles = null, CancellationToken? cancelToken = null)
        {
            if (log == null) throw new ArgumentNullException("log");

            // If FullPath is null, then we can't load assets from disk, just return
            if (FullPath == null)
            {
                log.Warning("Fullpath not set on this package");
                return;
            }

            // Clears the assets already loaded and reload them
            TemporaryAssets.Clear();

            // List all package files on disk
            if (assetFiles == null)
                assetFiles = ListAssetFiles(log, this, cancelToken);

            var progressMessage = String.Format("Loading Assets from Package [{0}]", FullPath.GetFileNameWithExtension());

            // Display this message at least once if the logger does not log progress (And it shouldn't in this case)
            var loggerResult = log as LoggerResult;
            if (loggerResult == null || !loggerResult.IsLoggingProgressAsInfo)
            {
                log.Info(progressMessage);
            }

            // Update step counter for log progress
            for (int i = 0; i < assetFiles.Count; i++)
            {
                var fileUPath = assetFiles[i].FilePath;
                var sourceFolder = assetFiles[i].SourceFolder;
                if (cancelToken.HasValue && cancelToken.Value.IsCancellationRequested)
                {
                    log.Warning("Skipping loading assets. PackageSession.Load cancelled");
                    break;
                }

                // Update the loading progress
                if (loggerResult != null)
                {
                    loggerResult.Progress(progressMessage, i, assetFiles.Count);
                }

                // Check if asset has been deleted by an upgrader
                if (assetFiles[i].Deleted)
                {
                    IsDirty = true;
                    filesToDelete.Add(assetFiles[i].FilePath);
                    continue;
                }

                // An exception can occur here, so we make sure that loading a single asset is not going to break 
                // the loop
                try
                {
                    AssetMigration.MigrateAssetIfNeeded(log, assetFiles[i]);

                    // Try to load only if asset is not already in the package or assetRef.Asset is null
                    var assetPath = fileUPath.MakeRelative(sourceFolder).GetDirectoryAndFileName();

                    var assetFullPath = fileUPath.FullPath;
                    var assetContent = assetFiles[i].AssetContent;

                    var asset = LoadAsset(log, assetFullPath, assetPath, fileUPath, assetContent);

                    // Create asset item
                    var assetItem = new AssetItem(assetPath, asset)
                    {
                        IsDirty = assetContent != null,
                        Package = this,
                        SourceFolder = sourceFolder.MakeRelative(RootDirectory)
                    };
                    // Set the modified time to the time loaded from disk
                    if (!assetItem.IsDirty)
                        assetItem.ModifiedTime = File.GetLastWriteTime(assetFullPath);

                    // TODO: Let's review that when we rework import process
                    // Not fixing asset import anymore, as it was only meant for upgrade
                    // However, it started to make asset dirty, for ex. when we create a new texture, choose a file and reload the scene later
                    // since there was no importer id and base.
                    //FixAssetImport(assetItem);

                    // Add to temporary assets
                    TemporaryAssets.Add(assetItem);
                }
                catch (Exception ex)
                {
                    int row = 1;
                    int column = 1;
                    var yamlException = ex as YamlException;
                    if (yamlException != null)
                    {
                        row = yamlException.Start.Line + 1;
                        column = yamlException.Start.Column;
                    }

                    var module = log.Module;

                    var assetReference = new AssetReference<Asset>(Guid.Empty, fileUPath.FullPath);

                    // TODO: Change this instead of patching LoggerResult.Module, use a proper log message
                    if (loggerResult != null)
                    {
                        loggerResult.Module = "{0}({1},{2})".ToFormat(Path.GetFullPath(fileUPath.FullPath), row, column);
                    }

                    log.Error(this, assetReference, AssetMessageCode.AssetLoadingFailed, ex, fileUPath, ex.Message);

                    if (loggerResult != null)
                    {
                        loggerResult.Module = module;
                    }
                }
            }
        }
Ejemplo n.º 38
0
 /// <summary>
 /// Constructor that provides an AddressableAudioSource by an AssetReference Primary Key (AssetGuid)
 /// </summary>
 /// <param name="assetReferenceGuid">The primary key (AssetGuid) of the AssetReference</param>
 public AddressableAudioSource(AssetReference assetReference)
 {
     AssetReference = assetReference;
 }
Ejemplo n.º 39
0
        public void GivenAssetWithRawFilenameReference_WhenSaveContainer_ThenXmlHasFileElement()
        {
            using (var cacheDir = new TempDirectory())
            {
                var settings = new CassetteSettings
                {
                    SourceDirectory = Mock.Of<IDirectory>(),
                    CacheDirectory = new FileSystemDirectory(cacheDir)
                };
                var cache = new BundleCache("VERSION", settings);
                var bundle = new TestableBundle("~/bundle-1");
                var asset = StubAsset();
                var reference = new AssetReference("~/images/test.png", asset.Object, -1, AssetReferenceType.RawFilename);
                asset.SetupGet(a => a.References)
                     .Returns(new[] { reference });
                bundle.Assets.Add(asset.Object);

                cache.SaveBundleContainer(new BundleContainer(new[] { bundle }));

                var xml = File.ReadAllText(Path.Combine(cacheDir, "container.xml"));
                xml.ShouldContain("<File Path=\"~/images/test.png\" />");
            }
        }
Ejemplo n.º 40
0
 public static async Task CreateAssetAddToList <T>(AssetReference reference, List <T> completedObjs)
     where T : Object
 {
     completedObjs.Add(await reference.InstantiateAsync().Task as T);
 }
Ejemplo n.º 41
0
        public void GivenAssetWithReferenceToAssetInSameBundle_WhenSaveContainer_ThenXmlHasNoReferenceElements()
        {
            using (var cacheDir = new TempDirectory())
            {
                var settings = new CassetteSettings
                {
                    SourceDirectory = Mock.Of<IDirectory>(),
                    CacheDirectory = new FileSystemDirectory(cacheDir)
                };
                var cache = new BundleCache("VERSION", settings);
                var bundle = new TestableBundle("~/bundle-1");
                var asset1 = StubAsset("~/bundle-1/asset1.js");
                var asset2 = StubAsset("~/bundle-1/asset2.js");
                var reference = new AssetReference("~/bundle-1/asset2.js", asset1.Object, -1, AssetReferenceType.SameBundle);
                asset1.SetupGet(a => a.References)
                      .Returns(new[] { reference });
                bundle.Assets.Add(new ConcatenatedAsset(new[]
                {
                    asset1.Object,
                    asset2.Object
                }));

                cache.SaveBundleContainer(new BundleContainer(new[] { bundle }));

                var xml = File.ReadAllText(Path.Combine(cacheDir, "container.xml"));
                xml.ShouldNotContain("<Reference ");
            }
        }
Ejemplo n.º 42
0
 public IEnumerator LoadContent <T>(AssetReference assetRef, Action <T> setter, Action <float> percentageSetter = null)
 {
     return(Utils.LoadContent(assetRef, setter, percentageSetter));
 }
Ejemplo n.º 43
0
        public void GivenAssetWithTwoReferencesToAssetsInAnotherBundle_WhenSaveContainer_ThenXmlHasOneReferenceElementWithReferencedBundlePath()
        {
            using (var cacheDir = new TempDirectory())
            {
                var settings = new CassetteSettings
                {
                    SourceDirectory = Mock.Of<IDirectory>(),
                    CacheDirectory = new FileSystemDirectory(cacheDir)
                };
                var cache = new BundleCache("VERSION", settings);
                var bundle1 = new TestableBundle("~/bundle-1");
                var bundle2 = new TestableBundle("~/bundle-2");
                var asset1 = StubAsset();
                var reference1 = new AssetReference("~/bundle-2/asset2.js", asset1.Object, -1, AssetReferenceType.DifferentBundle);
                var reference2 = new AssetReference("~/bundle-2/asset3.js", asset1.Object, -1, AssetReferenceType.DifferentBundle);
                asset1.SetupGet(a => a.References)
                      .Returns(new[] { reference1, reference2 });
                bundle1.Assets.Add(asset1.Object);

                bundle2.Assets.Add(
                    new ConcatenatedAsset(new[]
                    {
                        StubAsset("~/bundle-2/asset2.js").Object,
                        StubAsset("~/bundle-2/asset3.js").Object
                    })
                );

                cache.SaveBundleContainer(new BundleContainer(new[] { bundle1, bundle2 }));

                var xml = File.ReadAllText(Path.Combine(cacheDir, "container.xml"));
                Regex.Matches(xml, Regex.Escape("<Reference Path=\"~/bundle-2\" />")).Count.ShouldEqual(1);
            }
        }
Ejemplo n.º 44
0
 public void LoadAsset <T>(AssetReference assetRef, Action <T> setter)
 {
     Utils.LoadAsset(assetRef, setter);
 }
Ejemplo n.º 45
0
        /// <summary>
        /// Cleans the specified input items.
        /// </summary>
        /// <param name="package">The package to process (optional).</param>
        /// <param name="inputItems">The input items.</param>
        /// <param name="outputItems">The output items.</param>
        /// <param name="assetResolver">The asset resolver.</param>
        /// <param name="cloneInput">if set to <c>true</c> [clone input].</param>
        /// <param name="removeUnloadableObjects">If set to <c>true</c>, assets will be cloned with <see cref="AssetClonerFlags.RemoveUnloadableObjects"/>.</param>
        /// <exception cref="System.ArgumentNullException">
        /// inputItems
        /// or
        /// outputItems
        /// or
        /// assetResolver
        /// </exception>
        /// <exception cref="System.ArgumentException">List cannot contain null items;inputItems</exception>
        public static void Clean(Package package, ICollection<AssetItem> inputItems, ICollection<AssetItem> outputItems, AssetResolver assetResolver, bool cloneInput, bool removeUnloadableObjects)
        {
            if (inputItems == null) throw new ArgumentNullException(nameof(inputItems));
            if (outputItems == null) throw new ArgumentNullException(nameof(outputItems));
            if (assetResolver == null) throw new ArgumentNullException(nameof(assetResolver));

            // Check that all items are non-null
            if (inputItems.Any(item => item == null))
            {
                throw new ArgumentException("List cannot contain null items", nameof(inputItems));
            }

            var items = inputItems;
            if (cloneInput)
            {
                items = inputItems.Select(item => item.Clone(flags: removeUnloadableObjects ? AssetClonerFlags.RemoveUnloadableObjects : AssetClonerFlags.None)).ToList();
            }

            // idRemap should contain only assets that have either 1) their id remapped or 2) their location remapped
            var idRemap = new Dictionary<AssetId, Tuple<AssetId, UFile>>();
            var itemRemap = new Dictionary<AssetItem, Tuple<AssetId, UFile>>();
            foreach (var item in items)
            {
                if (outputItems.Contains(item))
                {
                    continue;
                }

                outputItems.Add(item);

                bool changed = false;
                AssetId newId;
                if (assetResolver.RegisterId(item.Id, out newId))
                {
                    changed = true;
                }

                UFile newLocation;
                if (assetResolver.RegisterLocation(item.Location, out newLocation))
                {
                    changed = true;
                }

                var tuple = new Tuple<AssetId, UFile>(newId != AssetId.Empty ? newId : item.Id, newLocation ?? item.Location);
                if (changed)
                {
                    if (!itemRemap.ContainsKey(item))
                    {
                        itemRemap.Add(item, tuple);
                    }
                }

                if (!idRemap.ContainsKey(item.Id))
                {
                    idRemap.Add(item.Id, tuple);
                }
            }

            // Process assets
            foreach (var item in outputItems)
            {
                Tuple<AssetId, UFile> remap;
                if (itemRemap.TryGetValue(item, out remap) && (remap.Item1 != item.Asset.Id || remap.Item2 != item.Location))
                {
                    item.Asset.Id = remap.Item1;
                    item.Location = remap.Item2;
                    item.IsDirty = true;
                }

                // The loop is a one or two-step. 
                // - If there is no link to update, and the asset has not been cloned, we can exist immediately
                // - If there is links to update, and the asset has not been cloned, we need to clone it and re-enter the loop
                //   to perform the update of the clone asset
                var links = AssetReferenceAnalysis.Visit(item.Asset).Where(link => link.Reference is IReference).ToList();

                foreach (var assetLink in links)
                {
                    var assetReference = (IReference)assetLink.Reference;

                    var newId = assetReference.Id;
                    if (idRemap.TryGetValue(newId, out remap) && IsNewReference(remap, assetReference))
                    {
                        assetLink.UpdateReference(remap.Item1, remap.Item2);
                        item.IsDirty = true;
                    }
                }

                // Fix base parts if there are any remap for them as well
                var assetComposite = item.Asset as IAssetComposite;
                if (assetComposite != null)
                {
                    foreach (var basePart in assetComposite.CollectParts())
                    {
                        if (basePart.Base != null && idRemap.TryGetValue(basePart.Base.BasePartAsset.Id, out remap) && IsNewReference(remap, basePart.Base.BasePartAsset))
                        {
                            var newAssetReference = new AssetReference(remap.Item1, remap.Item2);
                            basePart.UpdateBase(new BasePart(newAssetReference, basePart.Base.BasePartId, basePart.Base.InstanceId));
                            item.IsDirty = true;
                        }
                    }
                }
            }

            // Process roots (until references in package are handled in general)
            if (package != null)
            {
                UpdateRootAssets(package.RootAssets, idRemap);

                // We check dependencies to be consistent with other places, but nothing should be changed in there
                // (except if we were to instantiate multiple packages referencing each other at once?)
                foreach (var dependency in package.LocalDependencies)
                {
                    if (dependency.RootAssets != null)
                        UpdateRootAssets(dependency.RootAssets, idRemap);
                }
                foreach (var dependency in package.Meta.Dependencies)
                {
                    if (dependency.RootAssets != null)
                        UpdateRootAssets(dependency.RootAssets, idRemap);
                }
            }
        }
            protected override void UpgradeAsset(AssetMigrationContext context, PackageVersion currentVersion, PackageVersion targetVersion, dynamic asset, PackageLoadingAssetFile assetFile, OverrideUpgraderHint overrideHint)
            {
                var hierarchy = asset.Hierarchy;
                var entities = (DynamicYamlArray)hierarchy.Parts;
                foreach (dynamic entityDesign in entities)
                {
                    var entity = entityDesign.Entity;
                    foreach (var component in entity.Components)
                    {
                        try
                        {
                            var componentTag = component.Value.Node.Tag;
                            if (componentTag == "!ModelComponent")
                            {
                                var materials = component.Value.Materials;
                                var node = ((DynamicYamlMapping)materials).Node;
                                var i = -1;
                                foreach (var material in node.Children.ToList())
                                {
                                    ++i;
                                    node.Children.Remove(material.Key);
                                    if (((YamlScalarNode)material.Value).Value == "null")
                                        continue;

                                    node.Children.Add(new YamlScalarNode(((YamlScalarNode)material.Key).Value + '~' + i), material.Value);
                                }
                            }
                        }
                        catch (Exception)
                        {
                            try
                            {
                                // Component list serialized with the old version (as a sequence with ~Id in each item)
                                var componentTag = component.Node.Tag;
                                if (componentTag == "!ModelComponent")
                                {
                                    var materials = component.Materials;
                                    var node = ((DynamicYamlArray)materials).Node;
                                    var i = -1;
                                    dynamic newMaterial = new DynamicYamlMapping(new YamlMappingNode());
                                    foreach (var material in node.Children.ToList())
                                    {
                                        ++i;
                                        var reference = (YamlScalarNode)material;
                                        if (reference.Value == "null") // Skip null
                                            continue;

                                        UFile location;
                                        Guid referenceId;
                                        AssetId assetReference;
                                        if (AssetReference.TryParse(reference.Value, out assetReference, out location, out referenceId) && referenceId != Guid.Empty)
                                        {
                                            var itemId = new ItemId(referenceId.ToByteArray());
                                            newMaterial[itemId + "~" + i] = new AssetReference(assetReference, location);
                                        }
                                    }
                                    component["Materials"] = newMaterial;
                                }
                            }
                            catch (Exception e)
                            {
                                e.Ignore();
                            }
                        }
                    }
                }

            }
Ejemplo n.º 47
0
        /// <summary>
        /// Refreshes this package from the disk by loading or reloading all assets.
        /// </summary>
        /// <param name="log">The log.</param>
        /// <param name="cancelToken">The cancel token.</param>
        /// <returns>A logger that contains error messages while refreshing.</returns>
        /// <exception cref="System.InvalidOperationException">Package RootDirectory is null
        /// or
        /// Package RootDirectory [{0}] does not exist.ToFormat(RootDirectory)</exception>
        public void LoadTemporaryAssets(ILogger log, CancellationToken? cancelToken = null)
        {
            if (log == null) throw new ArgumentNullException("log");

            // If FullPath is null, then we can't load assets from disk, just return
            if (FullPath == null)
            {
                log.Warning("Fullpath not set on this package");
                return;
            }

            // Clears the assets already loaded and reload them
            TemporaryAssets.Clear();

            // List all package files on disk
            var listFiles = ListAssetFiles(log, this, cancelToken);

            var progressMessage = String.Format("Loading Assets from Package [{0}]", FullPath.GetFileNameWithExtension());

            // Display this message at least once if the logger does not log progress (And it shouldn't in this case)
            var loggerResult = log as LoggerResult;
            if (loggerResult == null || !loggerResult.IsLoggingProgressAsInfo)
            {
                log.Info(progressMessage);
            }

            // Update step counter for log progress
            for (int i = 0; i < listFiles.Count; i++)
            {
                var fileUPath = listFiles[i].Item1;
                var sourceFolder = listFiles[i].Item2;
                if (cancelToken.HasValue && cancelToken.Value.IsCancellationRequested)
                {
                    log.Warning("Skipping loading assets. PackageSession.Load cancelled");
                    break;
                }

                // Update the loading progress
                if (loggerResult != null)
                {
                    loggerResult.Progress(progressMessage, i, listFiles.Count);
                }

                // Try to load only if asset is not already in the package or assetRef.Asset is null
                var assetPath = fileUPath.MakeRelative(sourceFolder).GetDirectoryAndFileName();
                try
                {
                    // An exception can occur here, so we make sure that loading a single asset is not going to break 
                    // the loop
                    var assetFullPath = fileUPath.FullPath;
                    var asset = LoadAsset(log, assetFullPath, assetPath, fileUPath);

                    // Create asset item
                    var assetItem = new AssetItem(assetPath, asset)
                    {
                        IsDirty = false,
                        Package = this,
                        SourceFolder = sourceFolder.MakeRelative(RootDirectory)
                    };
                    // Set the modified time to the time loaded from disk
                    assetItem.ModifiedTime = File.GetLastWriteTime(assetFullPath);

                    FixAssetImport(assetItem);

                    // Add to temporary assets
                    TemporaryAssets.Add(assetItem);
                }
                catch (Exception ex)
                {
                    int row = 1;
                    int column = 1;
                    var yamlException = ex as YamlException;
                    if (yamlException != null)
                    {
                        row = yamlException.Start.Line + 1;
                        column = yamlException.Start.Column;
                    }

                    var module = log.Module;

                    var assetReference = new AssetReference<Asset>(Guid.Empty, fileUPath.FullPath);

                    // TODO: Change this instead of patching LoggerResult.Module, use a proper log message
                    if (loggerResult != null)
                    {
                        loggerResult.Module = "{0}({1},{2})".ToFormat(Path.GetFullPath(fileUPath.FullPath), row, column);
                    }

                    log.Error(this, assetReference, AssetMessageCode.AssetLoadingFailed, ex, fileUPath, ex.Message);

                    if (loggerResult != null)
                    {
                        loggerResult.Module = module;
                    }
                }
            }
        }
Ejemplo n.º 48
0
 protected abstract Task <GameObject> InstantiateSceneObject(AssetReference reference);
Ejemplo n.º 49
0
        public static void CreateAndSetDefaultScene(Package package, String location = "MainScene")
        {
            var defaultSceneAsset = SceneAsset.Create();

            var sceneAssetItem = new AssetItem(location, defaultSceneAsset);
            package.Assets.Add(sceneAssetItem);
            sceneAssetItem.IsDirty = true;
            var sceneAsset = new AssetReference<SceneAsset>(sceneAssetItem.Id, sceneAssetItem.Location);

            // Sets the scene created as default in the shared profile
            SetDefaultScene(package, sceneAsset);
        }
Ejemplo n.º 50
0
 public Type GetAssetType(AssetReference asset)
 {
     return(typeof(AnimationClip));
 }
Ejemplo n.º 51
0
        private object DeserializeObject(Queue <DeserializeOperation> serializeOperations, AssetReference parentAssetReference, string url, Type objType, object obj, AssetManagerLoaderSettings settings)
        {
            // Try to find already loaded object
            AssetReference assetReference = FindDeserializedObject(url, objType);

            if (assetReference != null && assetReference.Deserialized)
            {
                // Add reference
                bool isRoot = parentAssetReference == null;
                if (isRoot || parentAssetReference.References.Add(assetReference))
                {
                    IncrementReference(assetReference, isRoot);
                }

                return(assetReference.Object);
            }

            if (!FileProvider.FileExists(url))
            {
                HandleAssetNotFound(url);
                return(null);
            }

            ContentSerializerContext contentSerializerContext;
            object result;

            // Open asset binary stream
            try
            {
                using (var stream = FileProvider.OpenStream(url, VirtualFileMode.Open, VirtualFileAccess.Read))
                {
                    // File does not exist
                    // TODO/Benlitz: Add a log entry for that, it's not expected to happen
                    if (stream == null)
                    {
                        return(null);
                    }

                    Type headerObjType = null;

                    // Read header
                    var streamReader = new BinarySerializationReader(stream);
                    var chunkHeader  = ChunkHeader.Read(streamReader);
                    if (chunkHeader != null)
                    {
                        headerObjType = AssemblyRegistry.GetType(chunkHeader.Type);
                    }

                    // Find serializer
                    var serializer = Serializer.GetSerializer(headerObjType, objType);
                    if (serializer == null)
                    {
                        throw new InvalidOperationException(string.Format("Content serializer for {0}/{1} could not be found.", headerObjType, objType));
                    }
                    contentSerializerContext = new ContentSerializerContext(url, ArchiveMode.Deserialize, this)
                    {
                        LoadContentReferences = settings.LoadContentReferences
                    };

                    // Read chunk references
                    if (chunkHeader != null && chunkHeader.OffsetToReferences != -1)
                    {
                        // Seek to where references are stored and deserialize them
                        streamReader.NativeStream.Seek(chunkHeader.OffsetToReferences, SeekOrigin.Begin);
                        contentSerializerContext.SerializeReferences(streamReader);
                        streamReader.NativeStream.Seek(chunkHeader.OffsetToObject, SeekOrigin.Begin);
                    }

                    if (assetReference == null)
                    {
                        // Create AssetReference
                        assetReference = new AssetReference(url, parentAssetReference == null);
                        contentSerializerContext.AssetReference = assetReference;
                        result = obj ?? serializer.Construct(contentSerializerContext);
                        SetAssetObject(assetReference, result);
                    }
                    else
                    {
                        result = assetReference.Object;
                        contentSerializerContext.AssetReference = assetReference;
                    }

                    assetReference.Deserialized = true;

                    PrepareSerializerContext(contentSerializerContext, streamReader.Context);

                    contentSerializerContext.SerializeContent(streamReader, serializer, result);

                    // Add reference
                    if (parentAssetReference != null)
                    {
                        parentAssetReference.References.Add(assetReference);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new AssetManagerException(string.Format("Unexpected exception while loading asset [{0}]. Reason: {1}. Check inner-exception for details.", url, exception.Message), exception);
            }

            if (settings.LoadContentReferences)
            {
                // Process content references
                // TODO: Should we work at ChunkReference level?
                foreach (var contentReference in contentSerializerContext.ContentReferences)
                {
                    bool shouldBeLoaded = true;

                    //AssetReference childReference;

                    if (settings.ContentFilter != null)
                    {
                        settings.ContentFilter(contentReference, ref shouldBeLoaded);
                    }

                    if (shouldBeLoaded)
                    {
                        serializeOperations.Enqueue(new DeserializeOperation(assetReference, contentReference.Location, contentReference.Type, contentReference.ObjectValue));
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 52
0
 public static bool IsNullOrEmpty(this AssetReference aref)
 {
     return(aref == null || aref.RuntimeKey == Hash128.Parse(""));
 }
Ejemplo n.º 53
0
        /// <summary>
        /// Cleans the specified input items.
        /// </summary>
        /// <param name="package">The package to process (optional).</param>
        /// <param name="inputItems">The input items.</param>
        /// <param name="outputItems">The output items.</param>
        /// <param name="assetResolver">The asset resolver.</param>
        /// <param name="cloneInput">if set to <c>true</c> [clone input].</param>
        /// <param name="removeUnloadableObjects">If set to <c>true</c>, assets will be cloned with <see cref="AssetClonerFlags.RemoveUnloadableObjects"/>.</param>
        /// <exception cref="System.ArgumentNullException">
        /// inputItems
        /// or
        /// outputItems
        /// or
        /// assetResolver
        /// </exception>
        /// <exception cref="System.ArgumentException">List cannot contain null items;inputItems</exception>
        public static void Clean(Package package, ICollection <AssetItem> inputItems, ICollection <AssetItem> outputItems, AssetResolver assetResolver, bool cloneInput, bool removeUnloadableObjects)
        {
            if (inputItems == null)
            {
                throw new ArgumentNullException(nameof(inputItems));
            }
            if (outputItems == null)
            {
                throw new ArgumentNullException(nameof(outputItems));
            }
            if (assetResolver == null)
            {
                throw new ArgumentNullException(nameof(assetResolver));
            }

            // Check that all items are non-null
            if (inputItems.Any(item => item == null))
            {
                throw new ArgumentException("List cannot contain null items", nameof(inputItems));
            }

            var items = inputItems;

            if (cloneInput)
            {
                items = inputItems.Select(item => item.Clone(flags: removeUnloadableObjects ? AssetClonerFlags.RemoveUnloadableObjects : AssetClonerFlags.None)).ToList();
            }

            // idRemap should contain only assets that have either 1) their id remapped or 2) their location remapped
            var idRemap   = new Dictionary <AssetId, Tuple <AssetId, UFile> >();
            var itemRemap = new Dictionary <AssetItem, Tuple <AssetId, UFile> >();

            foreach (var item in items)
            {
                if (outputItems.Contains(item))
                {
                    continue;
                }

                outputItems.Add(item);

                bool    changed = false;
                AssetId newId;
                if (assetResolver.RegisterId(item.Id, out newId))
                {
                    changed = true;
                }

                UFile newLocation;
                if (assetResolver.RegisterLocation(item.Location, out newLocation))
                {
                    changed = true;
                }

                var tuple = new Tuple <AssetId, UFile>(newId != AssetId.Empty ? newId : item.Id, newLocation ?? item.Location);
                if (changed)
                {
                    if (!itemRemap.ContainsKey(item))
                    {
                        itemRemap.Add(item, tuple);
                    }
                }

                if (!idRemap.ContainsKey(item.Id))
                {
                    idRemap.Add(item.Id, tuple);
                }
            }

            // Process assets
            foreach (var item in outputItems)
            {
                Tuple <AssetId, UFile> remap;
                if (itemRemap.TryGetValue(item, out remap) && (remap.Item1 != item.Asset.Id || remap.Item2 != item.Location))
                {
                    item.Asset.Id = remap.Item1;
                    item.Location = remap.Item2;
                    item.IsDirty  = true;
                }

                // Fix base parts if there are any remap for them as well
                // This has to be done before the default resolver below because this fix requires to rewrite the base part completely, since the base part asset is immutable
                var assetComposite = item.Asset as IAssetComposite;
                if (assetComposite != null)
                {
                    foreach (var basePart in assetComposite.CollectParts())
                    {
                        if (basePart.Base != null && idRemap.TryGetValue(basePart.Base.BasePartAsset.Id, out remap) && IsNewReference(remap, basePart.Base.BasePartAsset))
                        {
                            var newAssetReference = new AssetReference(remap.Item1, remap.Item2);
                            basePart.UpdateBase(new BasePart(newAssetReference, basePart.Base.BasePartId, basePart.Base.InstanceId));
                            item.IsDirty = true;
                        }
                    }
                }

                // The loop is a one or two-step.
                // - If there is no link to update, and the asset has not been cloned, we can exist immediately
                // - If there is links to update, and the asset has not been cloned, we need to clone it and re-enter the loop
                //   to perform the update of the clone asset
                var links = AssetReferenceAnalysis.Visit(item.Asset).Where(link => link.Reference is IReference).ToList();

                foreach (var assetLink in links)
                {
                    var assetReference = (IReference)assetLink.Reference;

                    var newId = assetReference.Id;
                    if (idRemap.TryGetValue(newId, out remap) && IsNewReference(remap, assetReference))
                    {
                        assetLink.UpdateReference(remap.Item1, remap.Item2);
                        item.IsDirty = true;
                    }
                }
            }

            // Process roots (until references in package are handled in general)
            if (package != null)
            {
                UpdateRootAssets(package.RootAssets, idRemap);

                // We check dependencies to be consistent with other places, but nothing should be changed in there
                // (except if we were to instantiate multiple packages referencing each other at once?)
                foreach (var dependency in package.LocalDependencies)
                {
                    if (dependency.RootAssets != null)
                    {
                        UpdateRootAssets(dependency.RootAssets, idRemap);
                    }
                }
                foreach (var dependency in package.Meta.Dependencies)
                {
                    if (dependency.RootAssets != null)
                    {
                        UpdateRootAssets(dependency.RootAssets, idRemap);
                    }
                }
            }
        }
 public static T SetCasterQuickSpellParticleReference <T>(this T entity, AssetReference value)
     where T : EffectParticleParameters
 {
     entity.SetField("casterQuickSpellParticleReference", value);
     return(entity);
 }
Ejemplo n.º 55
0
 public string GetAssetExtension(AssetReference asset)
 {
     return(".dae");
 }
Ejemplo n.º 56
0
        internal static void DrawHint(Rect hintTriggerRect, Vector2 mousePosition, AssetReference assetReference)
        {
            if (!hintTriggerRect.Contains(mousePosition) || !GUIClip.visibleRect.Contains(mousePosition))
            {
                return;
            }

            string assetPath = AssetDatabase.GUIDToAssetPath(assetReference.guid);
            var    assetType = AssetDatabase.GetMainAssetTypeAtPath(assetPath);

            if (assetType == null) //this means the object or its base script has been deleted and is "Missing"
            {
                return;
            }

            var hintGenerators = TypeCache.GetMethodsWithAttribute <DynamicHintGeneratorAttribute>();

            if (assetType.IsSubclassOf(typeof(ScriptableObject)))
            {
                DynamicHintContent hint = GetDynamicHintContentOf(hintGenerators, assetType, assetPath);
                if (hint != null)
                {
                    DrawMouseTooltip(hint, hintTriggerRect);
                }
                return;
            }

            if (assetType == typeof(GameObject))
            {
                /* GameObjects can have multiple components with custom tooltips
                 * so for now we'll just display the first one.
                 * If needed, we could:
                 * 1) Implement a "priority system" (like OrderedCallbacks)
                 * 2) Display one big tooltip made up with all elements from custom tooltip
                 */

                GameObject assetGameObject = (GetLoadedObjectFromInstanceID(assetReference.instanceID) as GameObject);
                if (!assetGameObject)
                {
                    /* this seems to happen non-deterministically at project startup depending of what the user is hovering when the editor opens,
                     * or while the user is scrolling a list of objects and hovers one of them casually, even if the object hovered is actually a
                     * GameObject.
                     * */
                    return;
                }

                foreach (var component in assetGameObject.GetComponents <Component>())
                {
                    if (component == null)
                    {
                        continue;
                    }                                    //this means its script has been deleted and is "Missing"

                    DynamicHintContent hint = GetDynamicHintContentOf(hintGenerators, component.GetType(), string.Empty, component);
                    if (hint == null)
                    {
                        continue;
                    }

                    DrawMouseTooltip(hint, hintTriggerRect);
                    return;
                }
            }
        }