Пример #1
0
    internal static Rect GetEditorMainWindowPos()
    {
        if (s_MainWindow == null)
        {
            var containerWinType = GetAllDerivedTypes(typeof(ScriptableObject)).FirstOrDefault(t => t.Name == "ContainerWindow");
            if (containerWinType == null)
            {
                throw new MissingMemberException("Can't find internal type ContainerWindow. Maybe something has changed inside Unity");
            }
            var showModeField = containerWinType.GetField("m_ShowMode", BindingFlags.NonPublic | BindingFlags.Instance);
            if (showModeField == null)
            {
                throw new MissingFieldException("Can't find internal fields 'm_ShowMode'. Maybe something has changed inside Unity");
            }
            var windows = Resources.FindObjectsOfTypeAll(containerWinType);
            foreach (var win in windows)
            {
                var showMode = (int)showModeField.GetValue(win);
                if (showMode == 4) // main window
                {
                    s_MainWindow = win;
                    break;
                }
            }
        }

        if (s_MainWindow == null)
        {
            return(new Rect(0, 0, 800, 600));
        }

        var positionProperty = s_MainWindow.GetType().GetProperty("position", BindingFlags.Public | BindingFlags.Instance);

        if (positionProperty == null)
        {
            throw new MissingFieldException("Can't find internal fields 'position'. Maybe something has changed inside Unity.");
        }
        return((Rect)positionProperty.GetValue(s_MainWindow, null));
    }
Пример #2
0
        public ConstValue(Type type)
        {
            if (type == typeof(string))
            {
                Type  = new SType(typeof(LText));
                Value = new LText(true, "");
                return;
            }

            Type = new SType(type);

            if (type.IsValueType)
            {
                Value = Activator.CreateInstance(type);
            }
            else
            {
                _value       = null;
                _valueString = "null";
                _unityObject = null;
            }
        }
Пример #3
0
        public static string GetAssetPathNonResource(UnityEngine.Object rsrc)
        {
            if (rsrc == null)
            {
                return("");
            }
            var path = AssetDatabase.GetAssetPath(rsrc);

            while (String.IsNullOrEmpty(path))
            {
                var parent = PrefabUtility.GetPrefabParent(rsrc);

                if (parent == null)
                {
                    break;
                }

                path = AssetDatabase.GetAssetPath(parent);

                rsrc = parent;
            }
            return(path);
        }
        public bool Initialize(List <Framework.Parameter> parameters, BindingContext context, UnityEngine.Object target)
        {
            Parameters   = parameters;
            Provider     = context.Provider;
            Binder       = context.Binder;
            EditorTarget = target;

            var isOk = IsValid();

            if (isOk && ListDrawer == null)
            {
                ListDrawer = new UnityEditorInternal.ReorderableList
                             (
                    Parameters,
                    typeof(Framework.Parameter),
                    false,
                    true,
                    false,
                    false
                             );

                ListDrawer.drawHeaderCallback += rect =>
                {
                    var oldColor = GUI.color;
                    GUI.color = Color.white;
                    GUI.Label(rect, "Parameter Bindings", EditorStyles.whiteLabel);
                    GUI.color = oldColor;
                };

                ListDrawer.drawElementBackgroundCallback += (rect, index, active, focused) => { };
                ListDrawer.elementHeight         = BIND_ENTRY_HEIGHT;
                ListDrawer.showDefaultBackground = false;
                ListDrawer.drawElementCallback  += OnDrawBinding;
            }

            return(isOk);
        }
Пример #5
0
 /// <summary>
 /// Instantiate the specified _obj.
 /// </summary>
 /// <param name="_obj">_obj.</param>
 private UnityEngine.Object Instantiate(UnityEngine.Object _obj)
 {
     return(Instantiate(_obj, null));
 }
Пример #6
0
 public UnityEngine.Object GetAsset()
 {
     UnityEngine.Object asset = AssetDatabase.LoadMainAssetAtPath(assetPath);
     return(asset);
 }
Пример #7
0
 public void LogException(Exception exception, UnityEngine.Object context)
 {
     _log.Write(GetPrefix(LogType.Exception), 0, Framework.Log.FormatException(exception));
     _native.LogException(exception, context);
 }
Пример #8
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var oldShader = AssetDatabase.LoadAssetAtPath <Shader>(ctx.assetPath);

            if (oldShader != null)
            {
                ShaderUtil.ClearShaderMessages(oldShader);
            }

            List <PropertyCollector.TextureInfo> configuredTextures;
            string path = ctx.assetPath;
            var    sourceAssetDependencyPaths = new List <string>();

            var textGraph = File.ReadAllText(path, Encoding.UTF8);
            var graph     = new GraphData
            {
                messageManager = new MessageManager(), assetGuid = AssetDatabase.AssetPathToGUID(path)
            };

            MultiJson.Deserialize(graph, textGraph);
            graph.OnEnable();
            graph.ValidateGraph();

            Shader shader = null;

#if VFX_GRAPH_10_0_0_OR_NEWER
            if (!graph.isOnlyVFXTarget)
#endif
            {
                var text = GetShaderText(path, out configuredTextures, sourceAssetDependencyPaths, graph);

#if UNITY_2021_1_OR_NEWER
                // 2021.1 or later is guaranteed to have the new version of this function
                shader = ShaderUtil.CreateShaderAsset(ctx, text, false);
#else
                // earlier builds of Unity may or may not have it
                // here we try to invoke the new version via reflection
                var createShaderAssetMethod = typeof(ShaderUtil).GetMethod(
                    "CreateShaderAsset",
                    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.ExactBinding,
                    null,
                    new Type[] { typeof(AssetImportContext), typeof(string), typeof(bool) },
                    null);

                if (createShaderAssetMethod != null)
                {
                    shader = createShaderAssetMethod.Invoke(null, new Object[] { ctx, text, false }) as Shader;
                }
                else
                {
                    // method doesn't exist in this version of Unity, call old version
                    // this doesn't create dependencies properly, but is the best that we can do
                    shader = ShaderUtil.CreateShaderAsset(text, false);
                }
#endif

                if (graph.messageManager.nodeMessagesChanged)
                {
                    foreach (var pair in graph.messageManager.GetNodeMessages())
                    {
                        var node = graph.GetNodeFromId(pair.Key);
                        MessageManager.Log(node, path, pair.Value.First(), shader);
                    }
                }

                EditorMaterialUtility.SetShaderDefaults(
                    shader,
                    configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
                EditorMaterialUtility.SetShaderNonModifiableDefaults(
                    shader,
                    configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
            }

            UnityEngine.Object mainObject = shader;
#if VFX_GRAPH_10_0_0_OR_NEWER
            ShaderGraphVfxAsset vfxAsset = null;
            if (graph.hasVFXTarget)
            {
                vfxAsset = GenerateVfxShaderGraphAsset(graph);
                if (mainObject == null)
                {
                    mainObject = vfxAsset;
                }
                else
                {
                    //Correct main object if we have a shader and ShaderGraphVfxAsset : save as sub asset
                    vfxAsset.name = Path.GetFileNameWithoutExtension(path);
                    ctx.AddObjectToAsset("VFXShaderGraph", vfxAsset);
                }
            }
#endif

            Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon@64");
            ctx.AddObjectToAsset("MainAsset", mainObject, texture);
            ctx.SetMainObject(mainObject);

            foreach (var target in graph.activeTargets)
            {
                if (target is IHasMetadata iHasMetadata)
                {
                    var metadata = iHasMetadata.GetMetadataObject();
                    if (metadata == null)
                    {
                        continue;
                    }

                    metadata.hideFlags = HideFlags.HideInHierarchy;
                    ctx.AddObjectToAsset($"{iHasMetadata.identifier}:Metadata", metadata);
                }
            }

            var sgMetadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>();
            sgMetadata.hideFlags         = HideFlags.HideInHierarchy;
            sgMetadata.assetDependencies = new List <UnityEngine.Object>();
            var deps = GatherDependenciesFromSourceFile(ctx.assetPath);
            foreach (string dependency in deps)
            {
                sgMetadata.assetDependencies.Add(AssetDatabase.LoadAssetAtPath(dependency, typeof(UnityEngine.Object)));
            }
            ctx.AddObjectToAsset("SGInternal:Metadata", sgMetadata);


            foreach (var sourceAssetDependencyPath in sourceAssetDependencyPaths.Distinct())
            {
                // Ensure that dependency path is relative to project
                if (!sourceAssetDependencyPath.StartsWith("Packages/") && !sourceAssetDependencyPath.StartsWith("Assets/"))
                {
                    Debug.LogWarning($"Invalid dependency path: {sourceAssetDependencyPath}", mainObject);
                    continue;
                }

                ctx.DependsOnSourceAsset(sourceAssetDependencyPath);
            }
        }
        //===============================//
        // Logic
        //===============================//

        public FoldoutAttributeHandler(UnityEngine.Object target, SerializedObject serializedObject)
        {
            this.target           = target;
            this.serializedObject = serializedObject;
        }
        static void DrawIconTextureSlot(Rect elementRect, int row, DrawableResourceData data, ImageSize size, NotificationIconType newType, string newId, UnityEngine.Object target)
        {
            Rect  elementContentRect = GetContentRect(elementRect, 6f, 12f);
            float errorMsgWidth      = elementRect.width - kSlotSize * 3;

            var textureRect = new Rect(elementContentRect.width - (kMaxPreviewSize * 2 - kIconSpacing * 5),
                                       elementContentRect.y + kIconSpacing * row + kSlotSize * row, kMaxPreviewSize, kSlotSize);

            var errorBoxRect = GetContentRect(
                new Rect(elementContentRect.x,
                         elementContentRect.y + kIconSpacing * row + kSlotSize * row, errorMsgWidth, kSlotSize),
                4f, 4f);

            Rect previewTextureRect = new Rect(elementContentRect.width - (kMaxPreviewSize - kIconSpacing * 5),
                                               elementContentRect.y + kIconSpacing * row + kSlotSize * row, kMaxPreviewSize, kSlotSize);

            Texture2D assetTexture = null;

            if (size == ImageSize.XXHDPI)
            {
                assetTexture = data.AssetXXHDPI;
            }

            if (size == ImageSize.XHDPI)
            {
                assetTexture = data.AssetXHDPI;
            }

            if (size == ImageSize.HDPI)
            {
                assetTexture = data.AssetHDPI;
            }

            if (size == ImageSize.MDPI)
            {
                assetTexture = data.AssetMDPI;
            }

            if (size == ImageSize.LDPI)
            {
                assetTexture = data.AssetLDPI;
            }


            var newAsset = (Texture2D)EditorGUI.ObjectField(
                textureRect,
                assetTexture,
                typeof(Texture2D),
                false);

            // ---

            bool updatePreviewTexture = (newId != data.Id || newType != data.Type || newAsset != data.Asset);

            if (updatePreviewTexture)
            {
                Undo.RegisterCompleteObjectUndo(target, "Update icon data.");
                data.Id    = newId;
                data.Type  = newType;
                data.Asset = newAsset;

                if (size == ImageSize.XXHDPI)
                {
                    data.AssetXXHDPI = newAsset;
                }

                if (size == ImageSize.XHDPI)
                {
                    data.AssetXHDPI = newAsset;
                }

                if (size == ImageSize.HDPI)
                {
                    data.AssetHDPI = newAsset;
                }

                if (size == ImageSize.MDPI)
                {
                    data.AssetMDPI = newAsset;
                }

                if (size == ImageSize.LDPI)
                {
                    data.AssetLDPI = newAsset;
                }

                data.previewTexture = data.GetPreviewTexture(updatePreviewTexture);

                data.Clean();
                data.Verify();
            }

            // TODO Allocates a lot of memory for some reason, cache.


            if (data.Asset != null && !data.Verify())
            {
                EditorGUI.HelpBox(
                    errorBoxRect,
                    "Specified texture can't be used because: \n" + (errorMsgWidth > 145
                                                ? DrawableResourceData.GenerateErrorString(data.Errors)
                                                : "...expand to see more..."),
                    MessageType.Error
                    );

                if (data.Type == NotificationIconType.SmallIcon)
                {
                    GUIStyle helpBoxMessageTextStyle = new GUIStyle(GUI.skin.label);
                    helpBoxMessageTextStyle.fontSize  = 8;
                    helpBoxMessageTextStyle.wordWrap  = true;
                    helpBoxMessageTextStyle.alignment = TextAnchor.MiddleCenter;
                    GUI.Box(previewTextureRect, "Preview not available. \n Make sure the texture is readable!", helpBoxMessageTextStyle);
                }
            }
            else
            {
                if (data.previewTexture != null)
                {
                    GUIStyle previewLabelTextStyle = new GUIStyle(GUI.skin.label);
                    previewLabelTextStyle.fontSize  = 8;
                    previewLabelTextStyle.wordWrap  = true;
                    previewLabelTextStyle.alignment = TextAnchor.UpperCenter;

                    EditorGUI.LabelField(previewTextureRect, "Preview", previewLabelTextStyle);

                    Rect previewTextureRectPadded = GetContentRect(previewTextureRect, 6f, 6f);
                    previewTextureRectPadded.y += 8;

                    data.previewTexture.alphaIsTransparency = false;
                    GUI.DrawTexture(previewTextureRectPadded, data.previewTexture);
                }
            }
        }
Пример #11
0
 public override void Action(int instanceId, string pathName, string resourceFile)
 {
     pathName = Utility.GetCleanPath(pathName);
     UnityEngine.Object o = ProtoTemplateMenuItem.CreateScript(pathName, resourceFile);
     ProjectWindowUtil.ShowCreatedAsset(o);
 }
Пример #12
0
 public void Print(UnityEngine.Object m)
 {
     Debug.Log((m as IntVariable).value);
 }
Пример #13
0
 public void LogWarning(string message, UnityEngine.Object context = null)
 {
     ctx.LogImportWarning(message, context);
 }
Пример #14
0
 public void LogError(string message, UnityEngine.Object context = null)
 {
     // Note: if you get sent here by clicking on a ShaderGraph error message,
     // this is a bug in the scripted importer system, not being able to link import error messages to the imported asset
     ctx.LogImportError(message, context);
 }
Пример #15
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var    importLog = new AssetImportErrorLog(ctx);
            string path      = ctx.assetPath;

            AssetCollection assetCollection = new AssetCollection();

            MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection);

            var textGraph = File.ReadAllText(path, Encoding.UTF8);
            var graph     = new GraphData
            {
                messageManager = new MessageManager(),
                assetGuid      = AssetDatabase.AssetPathToGUID(path)
            };

            MultiJson.Deserialize(graph, textGraph);
            graph.OnEnable();
            graph.ValidateGraph();

            UnityEngine.Object mainObject = null;
#if VFX_GRAPH_10_0_0_OR_NEWER
            if (!graph.isOnlyVFXTarget)
#endif
            {
                // build shaders
                mainObject = BuildAllShaders(ctx, importLog, assetCollection, graph);
            }

#if VFX_GRAPH_10_0_0_OR_NEWER
            ShaderGraphVfxAsset vfxAsset = null;
            if (graph.hasVFXTarget)
            {
                vfxAsset = GenerateVfxShaderGraphAsset(graph);
                if (mainObject == null)
                {
                    mainObject = vfxAsset;
                }
                else
                {
                    //Correct main object if we have a shader and ShaderGraphVfxAsset : save as sub asset
                    vfxAsset.name = Path.GetFileNameWithoutExtension(path);
                    ctx.AddObjectToAsset("VFXShaderGraph", vfxAsset);
                }
            }
#endif

            Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon");
            ctx.AddObjectToAsset("MainAsset", mainObject, texture);
            ctx.SetMainObject(mainObject);

            foreach (var target in graph.activeTargets)
            {
                if (target is IHasMetadata iHasMetadata)
                {
                    var metadata = iHasMetadata.GetMetadataObject();
                    if (metadata == null)
                    {
                        continue;
                    }

                    metadata.hideFlags = HideFlags.HideInHierarchy;
                    ctx.AddObjectToAsset($"{iHasMetadata.identifier}:Metadata", metadata);
                }
            }

            var sgMetadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>();
            sgMetadata.hideFlags         = HideFlags.HideInHierarchy;
            sgMetadata.assetDependencies = new List <UnityEngine.Object>();

            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage))
                {
                    // this sucks that we have to fully load these assets just to set the reference,
                    // which then gets serialized as the GUID that we already have here.  :P

                    var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key);
                    if (!string.IsNullOrEmpty(dependencyPath))
                    {
                        sgMetadata.assetDependencies.Add(
                            AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object)));
                    }
                }
            }

            List <GraphInputData> inputInspectorDataList = new List <GraphInputData>();
            foreach (AbstractShaderProperty property in graph.properties)
            {
                // Don't write out data for non-exposed blackboard items
                if (!property.isExposed)
                {
                    continue;
                }

                // VTs are treated differently
                if (property is VirtualTextureShaderProperty virtualTextureShaderProperty)
                {
                    inputInspectorDataList.Add(MinimalCategoryData.ProcessVirtualTextureProperty(virtualTextureShaderProperty));
                }
                else
                {
                    inputInspectorDataList.Add(new GraphInputData()
                    {
                        referenceName = property.referenceName, propertyType = property.propertyType, isKeyword = false
                    });
                }
            }
            foreach (ShaderKeyword keyword in graph.keywords)
            {
                // Don't write out data for non-exposed blackboard items
                if (!keyword.isExposed)
                {
                    continue;
                }

                var sanitizedReferenceName = keyword.referenceName;
                if (keyword.keywordType == KeywordType.Boolean && keyword.referenceName.Contains("_ON"))
                {
                    sanitizedReferenceName = sanitizedReferenceName.Replace("_ON", String.Empty);
                }

                inputInspectorDataList.Add(new GraphInputData()
                {
                    referenceName = sanitizedReferenceName, keywordType = keyword.keywordType, isKeyword = true
                });
            }

            sgMetadata.categoryDatas = new List <MinimalCategoryData>();
            foreach (CategoryData categoryData in graph.categories)
            {
                // Don't write out empty categories
                if (categoryData.childCount == 0)
                {
                    continue;
                }

                MinimalCategoryData mcd = new MinimalCategoryData()
                {
                    categoryName  = categoryData.name,
                    propertyDatas = new List <GraphInputData>()
                };
                foreach (var input in categoryData.Children)
                {
                    GraphInputData propData;
                    // Only write out data for exposed blackboard items
                    if (input.isExposed == false)
                    {
                        continue;
                    }

                    // VTs are treated differently
                    if (input is VirtualTextureShaderProperty virtualTextureShaderProperty)
                    {
                        propData = MinimalCategoryData.ProcessVirtualTextureProperty(virtualTextureShaderProperty);
                        inputInspectorDataList.RemoveAll(inputData => inputData.referenceName == propData.referenceName);
                        mcd.propertyDatas.Add(propData);
                        continue;
                    }
                    else if (input is ShaderKeyword keyword)
                    {
                        var sanitizedReferenceName = keyword.referenceName;
                        if (keyword.keywordType == KeywordType.Boolean && keyword.referenceName.Contains("_ON"))
                        {
                            sanitizedReferenceName = sanitizedReferenceName.Replace("_ON", String.Empty);
                        }

                        propData = new GraphInputData()
                        {
                            referenceName = sanitizedReferenceName, keywordType = keyword.keywordType, isKeyword = true
                        };
                    }
                    else
                    {
                        var prop = input as AbstractShaderProperty;
                        propData = new GraphInputData()
                        {
                            referenceName = input.referenceName, propertyType = prop.propertyType, isKeyword = false
                        };
                    }

                    mcd.propertyDatas.Add(propData);
                    inputInspectorDataList.Remove(propData);
                }
                sgMetadata.categoryDatas.Add(mcd);
            }

            // Any uncategorized elements get tossed into an un-named category at the top as a fallback
            if (inputInspectorDataList.Count > 0)
            {
                sgMetadata.categoryDatas.Insert(0, new MinimalCategoryData()
                {
                    categoryName = "", propertyDatas = inputInspectorDataList
                });
            }

            ctx.AddObjectToAsset("SGInternal:Metadata", sgMetadata);

            // declare dependencies
            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.SourceDependency))
                {
                    ctx.DependsOnSourceAsset(asset.Key);

                    // I'm not sure if this warning below is actually used or not, keeping it to be safe
                    var assetPath = AssetDatabase.GUIDToAssetPath(asset.Key);

                    // Ensure that dependency path is relative to project
                    if (!string.IsNullOrEmpty(assetPath) && !assetPath.StartsWith("Packages/") && !assetPath.StartsWith("Assets/"))
                    {
                        importLog.LogWarning($"Invalid dependency path: {assetPath}", mainObject);
                    }
                }

                // NOTE: dependencies declared by GatherDependenciesFromSourceFile are automatically registered as artifact dependencies
                // HOWEVER: that path ONLY grabs dependencies via MinimalGraphData, and will fail to register dependencies
                // on GUIDs that don't exist in the project.  For both of those reasons, we re-declare the dependencies here.
                if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency))
                {
                    ctx.DependsOnArtifact(asset.Key);
                }
            }
        }
Пример #16
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var oldShader = AssetDatabase.LoadAssetAtPath <Shader>(ctx.assetPath);

            if (oldShader != null)
            {
                ShaderUtil.ClearShaderMessages(oldShader);
            }

            List <PropertyCollector.TextureInfo> configuredTextures;
            string path = ctx.assetPath;

            AssetCollection assetCollection = new AssetCollection();

            MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection);

            var textGraph = File.ReadAllText(path, Encoding.UTF8);
            var graph     = new GraphData
            {
                messageManager = new MessageManager(), assetGuid = AssetDatabase.AssetPathToGUID(path)
            };

            MultiJson.Deserialize(graph, textGraph);
            graph.OnEnable();
            graph.ValidateGraph();

            Shader shader = null;

#if VFX_GRAPH_10_0_0_OR_NEWER
            if (!graph.isOnlyVFXTarget)
#endif
            {
                // build the shader text
                // this will also add Target dependencies into the asset collection
                var text = GetShaderText(path, out configuredTextures, assetCollection, graph);

#if UNITY_2021_1_OR_NEWER
                // 2021.1 or later is guaranteed to have the new version of this function
                shader = ShaderUtil.CreateShaderAsset(ctx, text, false);
#else
                // earlier builds of Unity may or may not have it
                // here we try to invoke the new version via reflection
                var createShaderAssetMethod = typeof(ShaderUtil).GetMethod(
                    "CreateShaderAsset",
                    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.ExactBinding,
                    null,
                    new Type[] { typeof(AssetImportContext), typeof(string), typeof(bool) },
                    null);

                if (createShaderAssetMethod != null)
                {
                    shader = createShaderAssetMethod.Invoke(null, new Object[] { ctx, text, false }) as Shader;
                }
                else
                {
                    // method doesn't exist in this version of Unity, call old version
                    // this doesn't create dependencies properly, but is the best that we can do
                    shader = ShaderUtil.CreateShaderAsset(text, false);
                }
#endif

                ReportErrors(graph, shader, path);

                EditorMaterialUtility.SetShaderDefaults(
                    shader,
                    configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
                EditorMaterialUtility.SetShaderNonModifiableDefaults(
                    shader,
                    configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
            }

            UnityEngine.Object mainObject = shader;
#if VFX_GRAPH_10_0_0_OR_NEWER
            ShaderGraphVfxAsset vfxAsset = null;
            if (graph.hasVFXTarget)
            {
                vfxAsset = GenerateVfxShaderGraphAsset(graph);
                if (mainObject == null)
                {
                    mainObject = vfxAsset;
                }
                else
                {
                    //Correct main object if we have a shader and ShaderGraphVfxAsset : save as sub asset
                    vfxAsset.name = Path.GetFileNameWithoutExtension(path);
                    ctx.AddObjectToAsset("VFXShaderGraph", vfxAsset);
                }
            }
#endif

            Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon");
            ctx.AddObjectToAsset("MainAsset", mainObject, texture);
            ctx.SetMainObject(mainObject);

            foreach (var target in graph.activeTargets)
            {
                if (target is IHasMetadata iHasMetadata)
                {
                    var metadata = iHasMetadata.GetMetadataObject();
                    if (metadata == null)
                    {
                        continue;
                    }

                    metadata.hideFlags = HideFlags.HideInHierarchy;
                    ctx.AddObjectToAsset($"{iHasMetadata.identifier}:Metadata", metadata);
                }
            }

            var sgMetadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>();
            sgMetadata.hideFlags         = HideFlags.HideInHierarchy;
            sgMetadata.assetDependencies = new List <UnityEngine.Object>();

            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage))
                {
                    // this sucks that we have to fully load these assets just to set the reference,
                    // which then gets serialized as the GUID that we already have here.  :P

                    var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key);
                    if (!string.IsNullOrEmpty(dependencyPath))
                    {
                        sgMetadata.assetDependencies.Add(
                            AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object)));
                    }
                }
            }

            List <MinimalCategoryData.GraphInputData> inputInspectorDataList = new List <MinimalCategoryData.GraphInputData>();
            foreach (AbstractShaderProperty property in graph.properties)
            {
                // Don't write out data for non-exposed blackboard items
                if (!property.isExposed)
                {
                    continue;
                }

                // VTs are treated differently
                if (property is VirtualTextureShaderProperty virtualTextureShaderProperty)
                {
                    inputInspectorDataList.Add(MinimalCategoryData.ProcessVirtualTextureProperty(virtualTextureShaderProperty));
                }
                else
                {
                    inputInspectorDataList.Add(new MinimalCategoryData.GraphInputData()
                    {
                        referenceName = property.referenceName, propertyType = property.propertyType, isKeyword = false
                    });
                }
            }
            foreach (ShaderKeyword keyword in graph.keywords)
            {
                // Don't write out data for non-exposed blackboard items
                if (!keyword.isExposed)
                {
                    continue;
                }

                var sanitizedReferenceName = keyword.referenceName;
                if (keyword.keywordType == KeywordType.Boolean && keyword.referenceName.Contains("_ON"))
                {
                    sanitizedReferenceName = sanitizedReferenceName.Replace("_ON", String.Empty);
                }

                inputInspectorDataList.Add(new MinimalCategoryData.GraphInputData()
                {
                    referenceName = sanitizedReferenceName, keywordType = keyword.keywordType, isKeyword = true
                });
            }

            sgMetadata.categoryDatas = new List <MinimalCategoryData>();
            foreach (CategoryData categoryData in graph.categories)
            {
                // Don't write out empty categories
                if (categoryData.childCount == 0)
                {
                    continue;
                }

                MinimalCategoryData mcd = new MinimalCategoryData()
                {
                    categoryName  = categoryData.name,
                    propertyDatas = new List <MinimalCategoryData.GraphInputData>()
                };
                foreach (var input in categoryData.Children)
                {
                    MinimalCategoryData.GraphInputData propData;
                    // Only write out data for exposed blackboard items
                    if (input.isExposed == false)
                    {
                        continue;
                    }

                    // VTs are treated differently
                    if (input is VirtualTextureShaderProperty virtualTextureShaderProperty)
                    {
                        propData = MinimalCategoryData.ProcessVirtualTextureProperty(virtualTextureShaderProperty);
                        inputInspectorDataList.RemoveAll(inputData => inputData.referenceName == propData.referenceName);
                        mcd.propertyDatas.Add(propData);
                        continue;
                    }
                    else if (input is ShaderKeyword keyword)
                    {
                        var sanitizedReferenceName = keyword.referenceName;
                        if (keyword.keywordType == KeywordType.Boolean && keyword.referenceName.Contains("_ON"))
                        {
                            sanitizedReferenceName = sanitizedReferenceName.Replace("_ON", String.Empty);
                        }

                        propData = new MinimalCategoryData.GraphInputData()
                        {
                            referenceName = sanitizedReferenceName, keywordType = keyword.keywordType, isKeyword = true
                        };
                    }
                    else
                    {
                        var prop = input as AbstractShaderProperty;
                        propData = new MinimalCategoryData.GraphInputData()
                        {
                            referenceName = input.referenceName, propertyType = prop.propertyType, isKeyword = false
                        };
                    }

                    mcd.propertyDatas.Add(propData);
                    inputInspectorDataList.Remove(propData);
                }
                sgMetadata.categoryDatas.Add(mcd);
            }

            // Any uncategorized elements get tossed into an un-named category at the top as a fallback
            if (inputInspectorDataList.Count > 0)
            {
                sgMetadata.categoryDatas.Insert(0, new MinimalCategoryData()
                {
                    categoryName = "", propertyDatas = inputInspectorDataList
                });
            }

            ctx.AddObjectToAsset("SGInternal:Metadata", sgMetadata);

            // declare dependencies
            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.SourceDependency))
                {
                    ctx.DependsOnSourceAsset(asset.Key);

                    // I'm not sure if this warning below is actually used or not, keeping it to be safe
                    var assetPath = AssetDatabase.GUIDToAssetPath(asset.Key);

                    // Ensure that dependency path is relative to project
                    if (!string.IsNullOrEmpty(assetPath) && !assetPath.StartsWith("Packages/") && !assetPath.StartsWith("Assets/"))
                    {
                        Debug.LogWarning($"Invalid dependency path: {assetPath}", mainObject);
                    }
                }

                // NOTE: dependencies declared by GatherDependenciesFromSourceFile are automatically registered as artifact dependencies
                // HOWEVER: that path ONLY grabs dependencies via MinimalGraphData, and will fail to register dependencies
                // on GUIDs that don't exist in the project.  For both of those reasons, we re-declare the dependencies here.
                if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency))
                {
                    ctx.DependsOnArtifact(asset.Key);
                }
            }
        }
Пример #17
0
 public bool SetPositionProperty(Vector3Int position, String name, UnityEngine.Object positionProperty)
 {
     return(SetPositionProperty(position, name, GridInformationType.UnityObject, positionProperty));
 }
Пример #18
0
 public void AddScript(UnityEngine.Object script)
 {
     Scripts.Add(script.name, script.ToString());
 }
Пример #19
0
 public static void Warn(string msg, UnityEngine.Object obj)
 {
     Debug.Log("<b>HandUI: </b>" + msg, obj);
 }
Пример #20
0
 public void LogException(Exception exception, UnityEngine.Object context)
 {
     Console.WriteLine("{0} - {1}", context, exception);
 }
Пример #21
0
        public void LogFormat(LogType logType, UnityEngine.Object context, string format, params object[] args)
        {
            var formatted = string.Format(format, args);

            Console.WriteLine("{0}:{1} - {2}", logType, context, formatted);
        }
Пример #22
0
 // Unity Object Info
 public static string GetScenePath(this UnityEngine.Object component)
 {
     return(GetScenePath(component as Component));
 }
Пример #23
0
        static bool ExposedReferenceProperty(FieldInfo p_fieldInfo, Object p_object, GUIContent p_name, IReferencable p_reference)
        {
            if (!IsExposedReferenceProperty(p_fieldInfo))
            {
                return(false);
            }

            IExposedPropertyTable propertyTable = DashEditorCore.EditorConfig.editingController;
            var exposedReference = p_fieldInfo.GetValue(p_object);

            PropertyName exposedName = (PropertyName)exposedReference.GetType().GetField("exposedName").GetValue(exposedReference);
            bool         isDefault   = PropertyName.IsNullOrEmpty(exposedName);

            GUILayout.BeginHorizontal();
            GUILayout.Label(p_name, GUILayout.Width(160));
            HandleReferencing(p_reference, p_fieldInfo);
            EditorGUI.BeginChangeCheck();

            UnityEngine.Object exposedValue = (UnityEngine.Object)exposedReference.GetType().GetMethod("Resolve")
                                              .Invoke(exposedReference, new object[] { propertyTable });
            var newValue = EditorGUILayout.ObjectField(exposedValue, p_fieldInfo.FieldType.GetGenericArguments()[0], true);

            GUILayout.EndHorizontal();

            if (EditorGUI.EndChangeCheck())
            {
                if (propertyTable != null)
                {
                    Undo.RegisterCompleteObjectUndo(propertyTable as UnityEngine.Object, "Set Exposed Property");
                }

                if (!isDefault)
                {
                    if (newValue == null)
                    {
                        propertyTable.ClearReferenceValue(exposedName);
                        exposedReference.GetType().GetField("exposedName").SetValue(exposedReference, null);
                        p_fieldInfo.SetValue(p_object, exposedReference);
                    }
                    else
                    {
                        propertyTable.SetReferenceValue(exposedName, newValue);
                    }
                }
                else
                {
                    if (newValue != null)
                    {
                        PropertyName newExposedName = new PropertyName(GUID.Generate().ToString());
                        exposedReference.GetType().GetField("exposedName")
                        .SetValue(exposedReference, newExposedName);
                        propertyTable.SetReferenceValue(newExposedName, newValue);
                        p_fieldInfo.SetValue(p_object, exposedReference);
                    }
                }

                return(true);
            }

            return(false);
        }
Пример #24
0
 // placeholder, this should not be called in runtime
 public static string GetAssetPath(UnityEngine.Object rsrc)
 {
     return(rsrc.name);
 }
 static UnityEngine.Object ObjectField(UnityEngine.Object obj, System.Type type)
 {
     return(helper.ObjectField(obj, type));
 }
        private static void CollectProxy(List <LinkResolver> temporaryResolvers, Type proxyType) //AnimTrackProxy
        {
            GameObject GetPassthroughGameObject(UnityEngine.Object obj)
            {
                if (obj is Component asComponent)
                {
                    return(asComponent.gameObject);
                }
                else if (obj is GameObject asGO)
                {
                    return(asGO);
                }

                throw new NotSupportedException($"Unsupported passthrough type {obj.GetType()}.");
            }

            var proxy = Activator.CreateInstance(proxyType) as CrossSceneReferenceProxy;

            // Search all open scenes for GameObject components matching the proxy's relevant component type
            foreach (Component relevantComponent in UnityEngine.Object.FindObjectsOfType(proxy.RelevantComponentType, true))
            {
                // Generate a context for the proxy to effectively operate on targets & passthroughs.
                UnityEngine.Object context = proxy.AcquireContext(relevantComponent);

                // Iterate through all the proxy-type members contained within the relevant component instance.
                UnityEngine.Object[] proxyTargets = proxy.GetTargets(context);

                // However, if there are no valid targets, the context is useless.
                // No further logic is necessary for this iteration. Let's interrupt & dispose.
                if (proxyTargets == null || proxyTargets.Length == 0)
                {
                    proxy.ReleaseContext(context);
                    continue;
                }

                for (int i = 0; i < proxyTargets.Length; ++i)
                {
                    var target = proxyTargets[i] as object;

                    // Obtain the component at the other end of the proxy.
                    UnityEngine.Object passthrough = proxy.GetPassthrough(ref target, context);

                    if (passthrough == null)
                    {
                        continue; // No proxying to be done. Skip iteration.
                    }
                    // By now, we guarantee a GameObject component with a valid proxy endpoint.
                    // Create a resolver to connect both proxy endpoints.
                    CrossSceneReferenceResolver resolver = GetOrCreateResolver(relevantComponent);

                    // Set up a CrossSceneReferenceLocator and get the GUID which has been assigned to the passthrough component.
                    CrossSceneReferenceLocator loc = GetOrCreateLocator(GetPassthroughGameObject(passthrough));

                    int locGuidIdx = loc.Passthroughs.FindIndex(x => x == passthrough);
                    if (locGuidIdx == -1)
                    {
                        // Only generate new GUID for unique entries.
                        loc.ComponentGUIDS.Add(GUID.Generate().ToString());
                        loc.Passthroughs.Add(passthrough);

                        locGuidIdx = loc.ComponentGUIDS.Count - 1;
                    }

                    // Mark relevant component's scene for saving to serialize the resolver on the Unity scene.
                    Scene scene = relevantComponent.gameObject.scene;
                    EditorSceneManager.MarkSceneDirty(scene);

                    // Store the data required so that the link can be restored at runtime
                    CrossSceneReferenceSetupData data = new CrossSceneReferenceSetupData()
                    {
                        ClassHash = CodeGenerator.ClassHashFromType(proxyType),
                        RouteHash = proxy.GenerateRouteHash(passthrough, context),
                        Target    = target as UnityEngine.Object,
                        GUID      = loc.ComponentGUIDS[locGuidIdx],
                        Context   = context
                    };
                    resolver.AddResolverData(data);

                    // More immediate way to restore the links once save is complete
                    temporaryResolvers.Add(new TemporaryProxyLinkResolver() // REVIEW: Consider not overloading Temp Link Resolver. Make specific classes for use case.
                    {
                        ProxyType = proxyType,
                        Target    = target,
                        Value     = passthrough,
                        Context   = context,
                        Route     = data.RouteHash
                    });

                    // Set to null during Scene save, otherwise Unity will complain about cross scene refs
                    proxy.Set(data.RouteHash, target, null, context);
                }
            }
        }
Пример #27
0
 public void LogFormat(LogType logType, UnityEngine.Object context, String format, params Object[] args)
 {
     _log.Write(GetPrefix(logType), 0, format, args);
     _native.LogFormat(logType, context, format, args);
 }
Пример #28
0
 /// <summary>
 /// Loads the instance.
 /// </summary>
 /// <returns>The instance.</returns>
 /// <param name="_path">_path.</param>
 public UnityEngine.Object LoadInstance(string _path)
 {
     UnityEngine.Object _obj = Load(_path);
     return(Instantiate(_obj));
 }
Пример #29
0
        public override void OnImportAsset(AssetImportContext ctx)
        {
            var oldShader = AssetDatabase.LoadAssetAtPath <Shader>(ctx.assetPath);

            if (oldShader != null)
            {
                ShaderUtil.ClearShaderMessages(oldShader);
            }

            List <PropertyCollector.TextureInfo> configuredTextures;
            string path = ctx.assetPath;

            AssetCollection assetCollection = new AssetCollection();

            MinimalGraphData.GatherMinimalDependenciesFromFile(assetPath, assetCollection);

            var textGraph = File.ReadAllText(path, Encoding.UTF8);
            var graph     = new GraphData
            {
                messageManager = new MessageManager(), assetGuid = AssetDatabase.AssetPathToGUID(path)
            };

            MultiJson.Deserialize(graph, textGraph);
            graph.OnEnable();
            graph.ValidateGraph();

            Shader shader = null;

#if VFX_GRAPH_10_0_0_OR_NEWER
            if (!graph.isOnlyVFXTarget)
#endif
            {
                // build the shader text
                // this will also add Target dependencies into the asset collection
                var text = GetShaderText(path, out configuredTextures, assetCollection, graph);

#if UNITY_2021_1_OR_NEWER
                // 2021.1 or later is guaranteed to have the new version of this function
                shader = ShaderUtil.CreateShaderAsset(ctx, text, false);
#else
                // earlier builds of Unity may or may not have it
                // here we try to invoke the new version via reflection
                var createShaderAssetMethod = typeof(ShaderUtil).GetMethod(
                    "CreateShaderAsset",
                    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.ExactBinding,
                    null,
                    new Type[] { typeof(AssetImportContext), typeof(string), typeof(bool) },
                    null);

                if (createShaderAssetMethod != null)
                {
                    shader = createShaderAssetMethod.Invoke(null, new Object[] { ctx, text, false }) as Shader;
                }
                else
                {
                    // method doesn't exist in this version of Unity, call old version
                    // this doesn't create dependencies properly, but is the best that we can do
                    shader = ShaderUtil.CreateShaderAsset(text, false);
                }
#endif

                if (graph.messageManager.nodeMessagesChanged)
                {
                    foreach (var pair in graph.messageManager.GetNodeMessages())
                    {
                        var node = graph.GetNodeFromId(pair.Key);
                        MessageManager.Log(node, path, pair.Value.First(), shader);
                    }
                }

                EditorMaterialUtility.SetShaderDefaults(
                    shader,
                    configuredTextures.Where(x => x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
                EditorMaterialUtility.SetShaderNonModifiableDefaults(
                    shader,
                    configuredTextures.Where(x => !x.modifiable).Select(x => x.name).ToArray(),
                    configuredTextures.Where(x => !x.modifiable).Select(x => EditorUtility.InstanceIDToObject(x.textureId) as Texture).ToArray());
            }

            UnityEngine.Object mainObject = shader;
#if VFX_GRAPH_10_0_0_OR_NEWER
            ShaderGraphVfxAsset vfxAsset = null;
            if (graph.hasVFXTarget)
            {
                vfxAsset = GenerateVfxShaderGraphAsset(graph);
                if (mainObject == null)
                {
                    mainObject = vfxAsset;
                }
                else
                {
                    //Correct main object if we have a shader and ShaderGraphVfxAsset : save as sub asset
                    vfxAsset.name = Path.GetFileNameWithoutExtension(path);
                    ctx.AddObjectToAsset("VFXShaderGraph", vfxAsset);
                }
            }
#endif

            Texture2D texture = Resources.Load <Texture2D>("Icons/sg_graph_icon");
            ctx.AddObjectToAsset("MainAsset", mainObject, texture);
            ctx.SetMainObject(mainObject);

            foreach (var target in graph.activeTargets)
            {
                if (target is IHasMetadata iHasMetadata)
                {
                    var metadata = iHasMetadata.GetMetadataObject();
                    if (metadata == null)
                    {
                        continue;
                    }

                    metadata.hideFlags = HideFlags.HideInHierarchy;
                    ctx.AddObjectToAsset($"{iHasMetadata.identifier}:Metadata", metadata);
                }
            }

            var sgMetadata = ScriptableObject.CreateInstance <ShaderGraphMetadata>();
            sgMetadata.hideFlags         = HideFlags.HideInHierarchy;
            sgMetadata.assetDependencies = new List <UnityEngine.Object>();

            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.IncludeInExportPackage))
                {
                    // this sucks that we have to fully load these assets just to set the reference,
                    // which then gets serialized as the GUID that we already have here.  :P

                    var dependencyPath = AssetDatabase.GUIDToAssetPath(asset.Key);
                    if (!string.IsNullOrEmpty(dependencyPath))
                    {
                        sgMetadata.assetDependencies.Add(
                            AssetDatabase.LoadAssetAtPath(dependencyPath, typeof(UnityEngine.Object)));
                    }
                }
            }
            ctx.AddObjectToAsset("SGInternal:Metadata", sgMetadata);

            // declare dependencies
            foreach (var asset in assetCollection.assets)
            {
                if (asset.Value.HasFlag(AssetCollection.Flags.SourceDependency))
                {
                    ctx.DependsOnSourceAsset(asset.Key);

                    // I'm not sure if this warning below is actually used or not, keeping it to be safe
                    var assetPath = AssetDatabase.GUIDToAssetPath(asset.Key);

                    // Ensure that dependency path is relative to project
                    if (!string.IsNullOrEmpty(assetPath) && !assetPath.StartsWith("Packages/") && !assetPath.StartsWith("Assets/"))
                    {
                        Debug.LogWarning($"Invalid dependency path: {assetPath}", mainObject);
                    }
                }

                // NOTE: dependencies declared by GatherDependenciesFromSourceFile are automatically registered as artifact dependencies
                // HOWEVER: that path ONLY grabs dependencies via MinimalGraphData, and will fail to register dependencies
                // on GUIDs that don't exist in the project.  For both of those reasons, we re-declare the dependencies here.
                if (asset.Value.HasFlag(AssetCollection.Flags.ArtifactDependency))
                {
                    ctx.DependsOnArtifact(asset.Key);
                }
            }
        }
Пример #30
0
 public Parameter(UnityEngine.Object obj, String field)
 {
     this.obj   = obj;
     this.field = field;
 }