Esempio n. 1
0
 private Action <ContactMaterial, int> PreContactMaterialEditor(ContactMaterialEntry[] entries)
 {
     return((cm, index) =>
     {
         using (InspectorGUI.IndentScope.Single) {
             entries[index].IsOriented = InspectorGUI.Toggle(GUI.MakeLabel("Is Oriented",
                                                                           false,
                                                                           "Enable/disable oriented friction models."),
                                                             entries[index].IsOriented);
             if (entries[index].IsOriented)
             {
                 using (InspectorGUI.IndentScope.Single) {
                     entries[index].ReferenceObject = (GameObject)EditorGUILayout.ObjectField(GUI.MakeLabel("Reference Object"),
                                                                                              entries[index].ReferenceObject,
                                                                                              typeof(GameObject),
                                                                                              true);
                     entries[index].PrimaryDirection = (FrictionModel.PrimaryDirection)EditorGUILayout.EnumPopup(GUI.MakeLabel("Primary Direction",
                                                                                                                               false,
                                                                                                                               "Primary direction in object local frame."),
                                                                                                                 entries[index].PrimaryDirection,
                                                                                                                 InspectorEditor.Skin.Popup);
                 }
             }
         }
     });
 }
        public void OnInspectorGUI(bool onlyNameAndMaterial = false)
        {
            if (!onlyNameAndMaterial)
            {
                InspectorGUI.OnDropdownToolBegin("Create visual representation of this shape.");
            }

            Name = EditorGUILayout.TextField(GUI.MakeLabel("Name"),
                                             Name,
                                             InspectorEditor.Skin.TextField);

            InspectorGUI.UnityMaterial(GUI.MakeLabel("Material"),
                                       Material,
                                       newMaterial => Material = newMaterial);

            if (!onlyNameAndMaterial)
            {
                var createCancelState = InspectorGUI.PositiveNegativeButtons(Preview != null,
                                                                             "Create",
                                                                             "Create new shape visual.",
                                                                             "Cancel");

                InspectorGUI.OnDropdownToolEnd();

                if (createCancelState == InspectorGUI.PositiveNegativeResult.Positive)
                {
                    CreateShapeVisual();
                }
                if (createCancelState != InspectorGUI.PositiveNegativeResult.Neutral)
                {
                    PerformRemoveFromParent();
                }
            }
        }
        private static void PostBuildInternal(string agxDynamicsPath,
                                              string agxPluginPath,
                                              FileInfo targetExecutableFileInfo,
                                              string targetDataPath)
        {
            // Assuming all dlls are present in the plugins directory and that
            // "Components" are in a folder named "agx" in the plugins directory.
            // Unity will copy the dlls.
            var sourceDirectory      = new DirectoryInfo(IO.Utils.AGXUnityPluginDirectoryFull + Path.DirectorySeparatorChar + "agx");
            var destinationDirectory = new DirectoryInfo(AGXUnity.IO.Environment.GetPlayerAGXRuntimePath(targetDataPath));

            Debug.Log(GUI.AddColorTag("Copying AGX runtime data from: " +
                                      IO.Utils.AGXUnityPluginDirectory +
                                      Path.DirectorySeparatorChar +
                                      "agx" +
                                      " to " +
                                      destinationDirectory.FullName, Color.green));
            CopyDirectory(sourceDirectory, destinationDirectory);

            // Deleting all .meta-files that are present in our "agx" folder.
            foreach (var fi in destinationDirectory.EnumerateFiles("*.meta", SearchOption.AllDirectories))
            {
                fi.Delete();
            }
        }
Esempio n. 4
0
        public Statistics RemoveUnreferencedObjects(GameObject prefabInstance)
        {
            // If this is a re-import, remove any game object that hasn't been
            // referenced, i.e., UuidObjectDb.GetOrCreateGameObject hasn't been
            // called with the UUID of this game object. This doesn't affect game
            // objects created in the prefab editor since these objects doesn't
            // have an UUID component, still, other components added to this game
            // object will be removed as well.
            var unreferencedGameObjects = GetUnreferencedGameObjects();

            m_statistics.NumRemovedGameObjects += unreferencedGameObjects.Length;
            foreach (var unreferencedGameObject in unreferencedGameObjects)
            {
                Debug.Log($"{m_filename}: {GUI.AddColorTag( "Removing game object:", Color.yellow )} {unreferencedGameObject.name}");
                Object.DestroyImmediate(unreferencedGameObject, true);
                EditorUtility.SetDirty(prefabInstance);
            }

            var unreferencedAssets = GetUnreferencedAssets();

            m_statistics.NumRemovedAssets += unreferencedAssets.Length;
            foreach (var asset in unreferencedAssets)
            {
                Debug.Log($"{m_filename}: {GUI.AddColorTag( "Removing asset:", Color.red )} {asset.name}");
#if UNITY_2018_1_OR_NEWER
                AssetDatabase.RemoveObjectFromAsset(asset);
#else
                Object.DestroyImmediate(asset, true);
#endif
            }

            return(m_statistics);
        }
Esempio n. 5
0
        private void OnRollerGUI(GameObject roller, int index)
        {
            var wheel = roller.GetComponent <TrackWheel>();

            if (wheel == null)
            {
                return;
            }
            var newModel = (TrackWheelModel)EditorGUILayout.EnumPopup(GUI.MakeLabel("Model"),
                                                                      wheel.Model,
                                                                      InspectorEditor.Skin.Popup);
            var newProperties = (TrackWheelProperty)EditorGUILayout.EnumFlagsField(GUI.MakeLabel("Properties"),
                                                                                   wheel.Properties,
                                                                                   InspectorEditor.Skin.Popup);

            if (newModel != wheel.Model || newProperties != wheel.Properties)
            {
                var trackWheels = roller.GetComponents <TrackWheel>();
                Undo.RecordObjects(trackWheels, "Track Wheel Model");
                foreach (var trackWheel in trackWheels)
                {
                    trackWheel.Model      = newModel;
                    trackWheel.Properties = newProperties;
                }
            }
        }
Esempio n. 6
0
        public override void OnPostTargetMembersGUI()
        {
            if (NumTargets != 1)
            {
                return;
            }

            using (new GUI.EnabledBlock(!EditorApplication.isPlayingOrWillChangePlaymode)) {
                Undo.RecordObject(Sink, "Sink template");

                var sinkAll = InspectorGUI.Toggle(GUI.MakeLabel("Sink All"), Sink.SinkAll);
                if (sinkAll != Sink.SinkAll)
                {
                    Sink.SinkAll = sinkAll;
                }

                if (!Sink.SinkAll)
                {
                    InspectorGUI.ToolListGUI(this,
                                             Sink.Templates,
                                             "Sink Templates",
                                             m_availableTemplates,
                                             OnTemplateAdd,
                                             OnTemplateRemove);
                }
            }
        }
Esempio n. 7
0
        public static Mesh ShapeMeshSourceGUI(Mesh currentSource)
        {
            var newSource = EditorGUILayout.ObjectField(GUI.MakeLabel("Source"),
                                                        currentSource,
                                                        typeof(Mesh),
                                                        false) as Mesh;

            return(newSource != currentSource ? newSource : null);
        }
Esempio n. 8
0
        private void HandleDownloadInstall()
        {
            var skin = InspectorEditor.Skin;
            var downloadOrInstallPressed = false;

            var rect     = EditorGUILayout.GetControlRect();
            var orgWidth = rect.width;

            rect.width = 74;

            var buttonText = m_status == Status.AwaitInstall ? "Install" : "Download";

            using (new GUI.EnabledBlock(m_status == Status.AwaitDownload ||
                                        (m_currentVersion.IsValid && m_status == Status.AwaitInstall)))
                downloadOrInstallPressed = UnityEngine.GUI.Button(rect,
                                                                  GUI.MakeLabel(buttonText),
                                                                  skin.Button);
            rect.x    += rect.width + EditorGUIUtility.standardVerticalSpacing;
            rect.width = orgWidth - rect.x;
            using (new GUI.EnabledBlock(m_status == Status.Downloading))
                EditorGUI.ProgressBar(rect,
                                      m_downloadProgress,
                                      m_serverVersion.VersionStringShort +
                                      (m_status == Status.Downloading ? $": { (int)(100.0f * m_downloadProgress + 0.5f) }%" : ""));

            if (m_status == Status.AwaitInstall)
            {
                InspectorGUI.Separator(1, 4);

                EditorGUILayout.LabelField(GUI.MakeLabel($"AGXDynamicsForUnity-{m_serverVersion.VersionStringShort} is ready to be installed!\n\n" +
                                                         GUI.AddColorTag("During the installation Unity will be restarted.",
                                                                         Color.Lerp(Color.red, Color.white, 0.25f))),
                                           skin.TextAreaMiddleCenter);
            }

            if (downloadOrInstallPressed)
            {
                if (m_status == Status.AwaitDownload)
                {
                    if (File.Exists(Target))
                    {
                        File.Delete(Target);
                    }

                    Web.RequestHandler.Get($"https://us.download.algoryx.se/AGXUnity/packages/{m_sourceFilename}",
                                           new FileInfo(Target).Directory,
                                           OnDownloadComplete,
                                           OnDownloadProgress);
                    m_status = Status.Downloading;
                }
                else if (m_status == Status.AwaitInstall)
                {
                    InstallTarget();
                }
            }
        }
Esempio n. 9
0
 private void OnRenderProbabilityWeight(RigidBody template, int index)
 {
     using (InspectorGUI.IndentScope.Single) {
         GUILayout.Space(2);
         var entry = Emitter.TemplateEntries[index];
         entry.ProbabilityWeight = Mathf.Clamp01(EditorGUILayout.FloatField(GUI.MakeLabel("Probability weight"),
                                                                            entry.ProbabilityWeight));
         GUILayout.Space(6);
     }
 }
Esempio n. 10
0
        public override void OnPostTargetMembersGUI()
        {
            if (IsMultiSelect)
            {
                return;
            }

            var shapeVisual = ShapeVisual.Find(Shape);

            if (shapeVisual == null)
            {
                return;
            }

            var materials = shapeVisual.GetMaterials();

            if (materials.Length > 1)
            {
                var names = (from renderer in shapeVisual.GetComponentsInChildren <MeshRenderer>()
                             from material in renderer.sharedMaterials
                             select renderer.name).ToArray();

                var distinctMaterials = materials.Distinct().ToArray();
                var isExtended        = false;
                if (distinctMaterials.Length == 1)
                {
                    isExtended = ShapeVisualMaterialGUI("Common Render Material",
                                                        distinctMaterials[0],
                                                        newMaterial => shapeVisual.SetMaterial(newMaterial));
                }
                else
                {
                    isExtended = InspectorGUI.Foldout(EditorData.Instance.GetData(Shape, "Render Materials"),
                                                      GUI.MakeLabel("Render Materials"));
                }

                if (isExtended)
                {
                    using (InspectorGUI.IndentScope.Single)
                        for (int i = 0; i < materials.Length; ++i)
                        {
                            ShapeVisualMaterialGUI(names[i],
                                                   materials[i],
                                                   newMaterial => shapeVisual.ReplaceMaterial(i, newMaterial));
                        }
                }
            }
            else if (materials.Length == 1)
            {
                ShapeVisualMaterialGUI("Render Material",
                                       materials[0],
                                       newMaterial => shapeVisual.ReplaceMaterial(0, newMaterial));
            }
        }
Esempio n. 11
0
        private NodeFoldoutState NodeFoldout(Route <NodeT> .ValidatedNode validatedNode)
        {
            if (s_invalidNodeStyle == null)
            {
                s_invalidNodeStyle = new GUIStyle(InspectorEditor.Skin.Label);
                s_invalidNodeStyle.normal.background = GUI.CreateColoredTexture(1,
                                                                                1,
                                                                                Color.Lerp(UnityEngine.GUI.color,
                                                                                           Color.red,
                                                                                           0.75f));
            }

            var state = new NodeFoldoutState();
            var node  = validatedNode.Node;

            var verticalScope = !validatedNode.Valid ?
                                new EditorGUILayout.VerticalScope(s_invalidNodeStyle) :
                                null;
            var horizontalScope = node == Selected ?
                                  new EditorGUILayout.HorizontalScope(InspectorEditor.Skin.Label) :
                                  new EditorGUILayout.HorizontalScope(InspectorEditor.Skin.TextArea);

            state.Foldout = InspectorGUI.Foldout(GetFoldoutData(node),
                                                 GUI.MakeLabel(GetNodeTypeString(node) + ' ' +
                                                               SelectGameObjectDropdownMenuTool.GetGUIContent(node.Parent).text,
                                                               !validatedNode.Valid,
                                                               validatedNode.ErrorString),
                                                 newState =>
            {
                Selected = newState ? node : null;
                EditorUtility.SetDirty(Parent);
            });

            state.InsertBefore = InspectorGUI.Button(MiscIcon.EntryInsertBefore,
                                                     true,
                                                     "Insert a new node before this node.",
                                                     GUILayout.Width(18));
            state.InsertAfter = InspectorGUI.Button(MiscIcon.EntryInsertAfter,
                                                    true,
                                                    "Insert a new node after this node.",
                                                    GUILayout.Width(18));
            state.Erase = InspectorGUI.Button(MiscIcon.EntryRemove,
                                              true,
                                              "Remove this node from the route.",
                                              GUILayout.Width(18));
            horizontalScope?.Dispose();
            verticalScope?.Dispose();

            return(state);
        }
        public void OnInspectorGUI()
        {
            if (RigidBody == null || GetChildren().Length == 0)
            {
                PerformRemoveFromParent();
                return;
            }

            var skin = InspectorEditor.Skin;

            InspectorGUI.OnDropdownToolBegin("Create visual representation of this rigid body given all supported shapes.");

            foreach (var tool in GetChildren <ShapeVisualCreateTool>())
            {
                if (ShapeVisual.HasShapeVisual(tool.Shape))
                {
                    continue;
                }

                EditorGUILayout.PrefixLabel(GUI.MakeLabel(tool.Shape.name,
                                                          true),
                                            skin.Label);
                using (InspectorGUI.IndentScope.Single)
                    tool.OnInspectorGUI(true);
            }

            var createCancelState = InspectorGUI.PositiveNegativeButtons(true,
                                                                         "Create",
                                                                         "Create shape visual for shapes that hasn't already got one.",
                                                                         "Cancel");

            if (createCancelState == InspectorGUI.PositiveNegativeResult.Positive)
            {
                foreach (var tool in GetChildren <ShapeVisualCreateTool>())
                {
                    if (!ShapeVisual.HasShapeVisual(tool.Shape))
                    {
                        tool.CreateShapeVisual();
                    }
                }
            }

            InspectorGUI.OnDropdownToolEnd();

            if (createCancelState != InspectorGUI.PositiveNegativeResult.Neutral)
            {
                PerformRemoveFromParent();
            }
        }
Esempio n. 13
0
        private bool ShapeVisualMaterialGUI(string name, Material material, Action <Material> onNewMaterial)
        {
            var editorData = EditorData.Instance.GetData(Shape, "Visual_" + name);
            var result     = InspectorGUI.FoldoutObjectField(GUI.MakeLabel(name),
                                                             material,
                                                             typeof(Material),
                                                             editorData,
                                                             false) as Material;

            if (result != material)
            {
                onNewMaterial?.Invoke(result);
            }

            return(editorData.Bool);
        }
Esempio n. 14
0
        public override void OnInspectorGUI()
        {
            if (Utils.KeyHandler.HandleDetectKeyOnGUI(this.targets, Event.current))
            {
                return;
            }

            var editorData = this.target as EditorData;
            var skin       = InspectorEditor.Skin;

            using (GUI.AlignBlock.Center)
                GUILayout.Label(GUI.MakeLabel("Editor data", 18, true), skin.Label);

            const float firstLabelWidth = 190;

            GUILayout.BeginHorizontal();
            {
                TimeSpan span = TimeSpan.FromSeconds(editorData.SecondsSinceLastGC);
                GUILayout.Label(GUI.MakeLabel("Seconds since last GC:"), skin.Label, GUILayout.Width(firstLabelWidth));
                GUILayout.Label(GUI.MakeLabel(string.Format("{0:D2}m:{1:D2}s", span.Minutes, span.Seconds), true), skin.Label);
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            {
                GUILayout.Label(GUI.MakeLabel("Number of data entries:"), skin.Label, GUILayout.Width(firstLabelWidth));
                GUILayout.Label(GUI.MakeLabel(editorData.NumEntries.ToString(), true), skin.Label);
            }
            GUILayout.EndHorizontal();

            GUILayout.BeginHorizontal();
            {
                GUILayout.Label(GUI.MakeLabel("Number of cached data entries:"), skin.Label, GUILayout.Width(firstLabelWidth));
                GUILayout.Label(GUI.MakeLabel(editorData.NumCachedEntries.ToString(), true), skin.Label);
            }
            GUILayout.EndHorizontal();

            using (new GUI.ColorBlock(Color.Lerp(UnityEngine.GUI.color, Color.green, 0.25f)))
                using (GUI.AlignBlock.Center) {
                    if (GUILayout.Button(GUI.MakeLabel("Collect garbage"), skin.Button, GUILayout.Width(110)))
                    {
                        editorData.GC();
                    }
                }

            EditorUtility.SetDirty(target);
        }
        private void HandleCollisionGroupEntry(CollisionGroupEntry entry)
        {
            bool buttonPressed = false;

            GUILayout.BeginHorizontal();
            {
                entry.Tag     = GUILayout.TextField(entry.Tag, InspectorEditor.Skin.TextField);
                buttonPressed = InspectorGUI.Button(MiscIcon.ContextDropdown,
                                                    true,
                                                    "Add collision group.",
                                                    1.1f,
                                                    GUILayout.Width(18));
            }
            GUILayout.EndHorizontal();

            if (buttonPressed)
            {
                m_findActiveGroupNameEntry = m_findActiveGroupNameEntry == entry ? null : entry;

                if (m_findActiveGroupNameEntry != null)
                {
                    m_groups = (from cg in Object.FindObjectsOfType <CollisionGroups>()
                                from cgEntry in cg.Groups
                                select cgEntry.Tag).Distinct().ToList();
                    m_groups.Sort(new StringLowerComparer());
                }
            }

            if (m_findActiveGroupNameEntry == entry && buttonPressed)
            {
                GenericMenu groupNameMenu = new GenericMenu();
                groupNameMenu.AddDisabledItem(GUI.MakeLabel("Groups in scene"));
                groupNameMenu.AddSeparator(string.Empty);
                foreach (var groupName in m_groups)
                {
                    groupNameMenu.AddItem(GUI.MakeLabel(groupName), groupName == m_findActiveGroupNameEntry.Tag, () =>
                    {
                        m_findActiveGroupNameEntry.Tag = groupName;
                        m_findActiveGroupNameEntry     = null;
                    });
                }

                groupNameMenu.ShowAsContext();
            }
        }
Esempio n. 16
0
        private void HandleLineToolInspectorGUI(LineTool lineTool, string name)
        {
            // If visible, the vertical maker starts under the foldout, otherwise
            // render the marker through the fouldout label.
            var isVisible = GetLineToggleData(name).Bool;
            var color     = Color.Lerp(lineTool.Color, InspectorGUI.BackgroundColor, 0.25f);

            using (new InspectorGUI.VerticalScopeMarker(color)) {
                if (!InspectorGUI.Foldout(GetLineToggleData(name),
                                          GUI.MakeLabel(name, true)))
                {
                    return;
                }
                //using ( new InspectorGUI.VerticalScopeMarker( color ) )
                using (InspectorGUI.IndentScope.Single)
                    lineTool.OnInspectorGUI();
            }
        }
Esempio n. 17
0
        public override void OnSceneViewGUI(SceneView sceneView)
        {
            var shouldValidateEdges = !EditorApplication.isPlaying &&
                                      m_requestEdgeValidate &&
                                      TopEdgeLineTool.Line.Valid &&
                                      CuttingEdgeLineTool.Line.Valid &&
                                      CuttingDirectionLineTool.Line.Valid;

            if (shouldValidateEdges)
            {
                m_edgeIssues.Clear();

                var cuttingDir   = CuttingEdgeLineTool.Line.Direction;
                var cuttingToTop = Vector3.Normalize(TopEdgeLineTool.Line.Start.Position - CuttingEdgeLineTool.Line.Start.Position);
                var rayCenter    = 0.5f * (CuttingEdgeLineTool.Line.Center + TopEdgeLineTool.Line.Center);
                var rayDir       = Vector3.Cross(cuttingDir, cuttingToTop).normalized;

                if (Vector3.Dot(cuttingDir, TopEdgeLineTool.Line.Direction) < 0.95f)
                {
                    m_edgeIssues.Add("\u2022 " +
                                     GUI.AddColorTag("Top", Color.Lerp(Color.yellow, Color.white, 0.35f)) +
                                     " and " +
                                     GUI.AddColorTag("Cutting", Color.Lerp(Color.red, Color.white, 0.35f)) +
                                     " edge direction expected to be approximately parallel with dot product > 0.95, currently: " +
                                     GUI.AddColorTag(Vector3.Dot(cuttingDir, TopEdgeLineTool.Line.Direction).ToString(), Color.red));
                }
                if (!Utils.Raycast.Intersect(new Ray(rayCenter, rayDir), Shovel.GetComponentsInChildren <MeshFilter>()).Hit)
                {
                    m_edgeIssues.Add("\u2022 " +
                                     GUI.AddColorTag("Top", Color.Lerp(Color.yellow, Color.white, 0.35f)) +
                                     " and " +
                                     GUI.AddColorTag("Cutting", Color.Lerp(Color.red, Color.white, 0.35f)) +
                                     " edges appears to be directed in the wrong way - raycast from center bucket plane into the bucket didn't hit the bucket.");
                }
                if (Vector3.Dot(rayDir, CuttingDirectionLineTool.Line.Direction) > -0.5f)
                {
                    m_edgeIssues.Add("\u2022 " +
                                     GUI.AddColorTag("Cutting direction", Color.Lerp(Color.green, Color.white, 0.35f)) +
                                     " appears to be directed towards the bucket - it should be in the bucket separation plate plane, directed out from the bucket.");
                }

                m_requestEdgeValidate = false;
            }
        }
        private void HandleCollisionGroupEntryPair(CollisionGroupEntryPair entryPair)
        {
            GUILayout.BeginHorizontal();
            {
                GUILayout.BeginVertical(GUILayout.Width(12));
                {
                    GUILayout.Space(4);
                    GUILayout.Label(GUI.MakeLabel("[", 20), InspectorEditor.Skin.Label, GUILayout.Height(32), GUILayout.Width(12));
                }
                GUILayout.EndVertical();

                GUILayout.BeginVertical();
                {
                    HandleCollisionGroupEntry(entryPair.First);
                    HandleCollisionGroupEntry(entryPair.Second);
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal();
        }
Esempio n. 19
0
        private void RenderButtons(Vector2 buttonSize,
                                   bool buttonsEnabled,
                                   bool buttonsActive)
        {
            GUILayout.Label(GUI.MakeLabel(buttonsEnabled && buttonsActive ?
                                          "Enabled and active" :
                                          buttonsEnabled == buttonsActive ?
                                          "Disabled and inactive" :
                                          buttonsEnabled ?
                                          "Enabled and inactive" :
                                          "Disabled and active??????????"),
                            InspectorGUISkin.Instance.LabelMiddleCenter);
            var numIconsPerRow = (int)(position.width / buttonSize.x);
            var currIconIndex  = 0;

            while (currIconIndex < m_iconNames.Count)
            {
                var rect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(false, buttonSize.y));
                rect.width = buttonSize.x;

                for (int i = 0; currIconIndex < m_iconNames.Count && i < numIconsPerRow; ++currIconIndex, ++i)
                {
                    var buttonType = i == 0 && m_iconNames.Count - currIconIndex - 1 == 0              ? InspectorGUISkin.ButtonType.Normal :
                                     i == 0                                                            ? InspectorGUISkin.ButtonType.Left :
                                     i == numIconsPerRow - 1 || currIconIndex == m_iconNames.Count - 1 ? InspectorGUISkin.ButtonType.Right :
                                     InspectorGUISkin.ButtonType.Middle;
                    var content = new GUIContent(IconManager.GetIcon(m_iconNames[currIconIndex]),
                                                 m_iconNames[currIconIndex] + $" | active: {buttonsActive}, enabled: {buttonsEnabled}");
                    var pressed = ToolButton(rect,
                                             content,
                                             buttonType,
                                             buttonsActive,
                                             buttonsEnabled);
                    if (pressed)
                    {
                        EditorGUIUtility.systemCopyBuffer = m_iconNames[currIconIndex];
                    }
                    rect.x += rect.width;
                }
            }
        }
Esempio n. 20
0
 public override void OnPostTargetMembersGUI()
 {
     if (Targets.Length == 1)
     {
         InspectorGUI.ToolArrayGUI(this, ArticulatedRoot.RigidBodies, "Rigid Bodies");
     }
     else
     {
         for (int i = 0; i < NumTargets; ++i)
         {
             var articulatedRoot = Targets[i] as ArticulatedRoot;
             InspectorGUI.ToolArrayGUI(this,
                                       articulatedRoot.RigidBodies,
                                       $"{GUI.AddColorTag( articulatedRoot.name, InspectorGUISkin.BrandColor )}: Rigid Bodies");
             if (i < NumTargets - 1)
             {
                 InspectorGUI.Separator();
             }
         }
     }
 }
Esempio n. 21
0
        public override void OnPreTargetMembersGUI()
        {
            var skin           = InspectorEditor.Skin;
            var directory      = AssetDatabase.GUIDToAssetPath(RestoredAGXFile.DataDirectoryId);
            var directoryValid = directory.Length > 0 && AssetDatabase.IsValidFolder(directory);

            using (new GUILayout.HorizontalScope()) {
                EditorGUILayout.PrefixLabel(GUI.MakeLabel("Data directory"),
                                            skin.Label);

                var statusColor = directoryValid ?
                                  Color.Lerp(InspectorGUI.BackgroundColor, Color.green, EditorGUIUtility.isProSkin ? 0.8f : 0.2f) :
                                  Color.Lerp(Color.white, Color.red, EditorGUIUtility.isProSkin ? 0.8f : 0.2f);
                var prevColor = UnityEngine.GUI.backgroundColor;

                UnityEngine.GUI.backgroundColor = statusColor;
                EditorGUILayout.SelectableLabel(directory,
                                                skin.TextField,
                                                GUILayout.Height(EditorGUIUtility.singleLineHeight));
                UnityEngine.GUI.backgroundColor = prevColor;
                if (GUILayout.Button(GUI.MakeLabel("...", false, "Open file panel"),
                                     skin.Button,
                                     GUILayout.Width(28)))
                {
                    var newDirectory = EditorUtility.OpenFolderPanel("Prefab data directory", "Assets", "");
                    if (newDirectory.Length > 0)
                    {
                        var relPath = IO.Utils.MakeRelative(newDirectory, Application.dataPath).Replace('\\', '/');
                        if (AssetDatabase.IsValidFolder(relPath))
                        {
                            RestoredAGXFile.DataDirectoryId = AssetDatabase.AssetPathToGUID(relPath);
                            EditorUtility.SetDirty(RestoredAGXFile);
                        }
                    }
                }
            }

            AssemblyTool.OnObjectListsGUI(this);
        }
Esempio n. 22
0
        public override void OnPostTargetMembersGUI()
        {
            if (FrictionModel.Type != FrictionModel.EType.ConstantNormalForceBoxFriction)
            {
                return;
            }

            EditorGUI.showMixedValue = ShowMixed((fm1, fm2) => !AGXUnity.Utils.Math.Approximately(fm1.NormalForceMagnitude,
                                                                                                  fm2.NormalForceMagnitude));
            var normalForce = Mathf.Max(EditorGUILayout.FloatField(GUI.MakeLabel("Normal Force Magnitude"),
                                                                   FrictionModel.NormalForceMagnitude),
                                        0.0f);

            if (UnityEngine.GUI.changed)
            {
                foreach (var fm in GetTargets <FrictionModel>())
                {
                    fm.NormalForceMagnitude = normalForce;
                }
            }
            UnityEngine.GUI.changed = false;

            EditorGUI.showMixedValue = ShowMixed((fm1, fm2) => fm1.ScaleNormalForceWithDepth != fm2.ScaleNormalForceWithDepth);

            var scaleNormalForceWithDepth = InspectorGUI.Toggle(GUI.MakeLabel("Scale Normal Force With Depth"),
                                                                FrictionModel.ScaleNormalForceWithDepth);

            if (UnityEngine.GUI.changed)
            {
                foreach (var fm in GetTargets <FrictionModel>())
                {
                    fm.ScaleNormalForceWithDepth = scaleNormalForceWithDepth;
                }
            }

            EditorGUI.showMixedValue = false;
            UnityEngine.GUI.changed  = false;
        }
Esempio n. 23
0
        public override void OnPreTargetMembersGUI()
        {
            var skin = InspectorEditor.Skin;

            GUILayout.Label(GUI.MakeLabel("Debug render manager", 16, true),
                            skin.LabelMiddleCenter);

            var newRenderState = InspectorGUI.Toggle(GUI.MakeLabel("Debug render shapes"), Manager.RenderShapes);

            if (newRenderState != Manager.RenderShapes)
            {
                Manager.RenderShapes = newRenderState;
                EditorUtility.SetDirty(Manager);
            }
            InspectorGUI.UnityMaterial(GUI.MakeLabel("Shape material"),
                                       Manager.ShapeRenderMaterial,
                                       newMaterial => Manager.ShapeRenderMaterial = newMaterial);

            using (new GUILayout.HorizontalScope()) {
                Manager.RenderContacts = InspectorGUI.Toggle(GUI.MakeLabel("Render contacts"), Manager.RenderContacts);
                Manager.ContactColor   = EditorGUILayout.ColorField(Manager.ContactColor);
            }

            Manager.ContactScale = EditorGUILayout.Slider(GUI.MakeLabel("Scale"), Manager.ContactScale, 0.0f, 1.0f);

            Manager.ColorizeBodies = InspectorGUI.Toggle(GUI.MakeLabel("Colorize bodies",
                                                                       false,
                                                                       "Every rigid body instance will be rendered with a unique color (wire framed)."),
                                                         Manager.ColorizeBodies);
            Manager.HighlightMouseOverObject = InspectorGUI.Toggle(GUI.MakeLabel("Highlight mouse over object",
                                                                                 false,
                                                                                 "Highlight mouse over object in scene view."),
                                                                   Manager.HighlightMouseOverObject);
            Manager.IncludeInBuild = InspectorGUI.Toggle(GUI.MakeLabel("Include in build",
                                                                       false,
                                                                       "Include debug rendering when building the project."),
                                                         Manager.IncludeInBuild);
        }
        public static GUIContent GetGUIContent(GameObject gameObject)
        {
            bool isNull       = gameObject == null;
            bool hasVisual    = !isNull && gameObject.GetComponent <MeshFilter>() != null;
            bool hasRigidBody = !isNull && gameObject.GetComponent <RigidBody>() != null;
            bool hasShape     = !isNull && gameObject.GetComponent <AGXUnity.Collide.Shape>() != null;
            bool hasWire      = !isNull && gameObject.GetComponent <Wire>() != null;
            bool hasCable     = !isNull && gameObject.GetComponent <Cable>() != null;
            bool hasTrack     = !isNull && gameObject.GetComponent <AGXUnity.Model.Track>() != null;
            bool hasTerrain   = !isNull && gameObject.GetComponent <AGXUnity.Model.DeformableTerrain>() != null;

            string nullTag      = isNull       ? GUI.AddColorTag("[null]", Color.red) : "";
            string visualTag    = hasVisual    ? GUI.AddColorTag("[Visual]", Color.yellow) : "";
            string rigidBodyTag = hasRigidBody ? GUI.AddColorTag("[RigidBody]", Color.Lerp(Color.blue, Color.white, 0.35f)) : "";
            string shapeTag     = hasShape     ? GUI.AddColorTag("[" + gameObject.GetComponent <AGXUnity.Collide.Shape>().GetType().Name + "]", Color.Lerp(Color.green, Color.black, 0.4f)) : "";
            string wireTag      = hasWire      ? GUI.AddColorTag("[Wire]", Color.Lerp(Color.cyan, Color.black, 0.35f)) : "";
            string cableTag     = hasCable     ? GUI.AddColorTag("[Cable]", Color.Lerp(Color.yellow, Color.red, 0.65f)) : "";
            string trackTag     = hasTrack     ? GUI.AddColorTag("[Track]", Color.Lerp(Color.yellow, Color.red, 0.45f)) : "";
            string terrainTag   = hasTerrain   ? GUI.AddColorTag("[Terrain]", Color.Lerp(Color.green, Color.yellow, 0.25f)) : "";

            string name = isNull ? "World" : gameObject.name;

            return(GUI.MakeLabel(name + " " + nullTag + rigidBodyTag + shapeTag + visualTag + wireTag + cableTag + trackTag + terrainTag));
        }
Esempio n. 25
0
        private void OnGUI()
        {
            AboutWindow.AGXDynamicsForUnityLogoGUI();

            EditorGUILayout.LabelField(GUI.MakeLabel("Current version"),
                                       GUI.MakeLabel(m_currentVersion.IsValid ?
                                                     m_currentVersion.VersionStringShort :
                                                     "git checkout",
                                                     Color.white));
            using (new EditorGUILayout.HorizontalScope()) {
                var newVersionAvailable = m_serverVersion.IsValid && m_serverVersion > m_currentVersion;
                EditorGUILayout.LabelField(GUI.MakeLabel("Latest version"),
                                           GUI.MakeLabel(m_serverVersion.IsValid ?
                                                         m_serverVersion.VersionStringShort :
                                                         "...",
                                                         newVersionAvailable ?
                                                         Color.Lerp(Color.green, Color.black, 0.35f) :
                                                         Color.white),
                                           InspectorEditor.Skin.Label);
                GUILayout.FlexibleSpace();
                if (newVersionAvailable && InspectorGUI.Link(GUI.MakeLabel("Changelog")))
                {
                    Application.OpenURL(TopMenu.AGXUnityChangelogURL);
                }
                else if (!newVersionAvailable)
                {
                    GUILayout.Label("", InspectorEditor.Skin.Label);
                }
            }

            InspectorGUI.Separator(1, 4);

            var isUpToDate = m_currentVersion.IsValid &&
                             m_serverVersion.IsValid &&
                             m_currentVersion >= m_serverVersion;

            if (isUpToDate)
            {
                EditorGUILayout.LabelField(GUI.MakeLabel("The version of AGX Dynamics for Unity is up to date.",
                                                         Color.Lerp(Color.green, Color.black, 0.35f)),
                                           InspectorEditor.Skin.TextAreaMiddleCenter);
            }
            else if (m_status == Status.Passive)
            {
                if (Web.RequestHandler.Get(@"https://us.download.algoryx.se/AGXUnity/latest.php",
                                           OnPackageNameRequest))
                {
                    m_status = Status.CheckingForUpdate;
                }
            }
            else if (m_status == Status.CheckingForUpdate)
            {
                Repaint();
            }
            else
            {
                if (m_serverVersion.IsValid)
                {
                    HandleDownloadInstall();
                    if (m_status == Status.Downloading)
                    {
                        Repaint();
                    }
                }
            }

            var manualPackageButtonSize = new Vector2(110, EditorGUIUtility.singleLineHeight);
            var manualPackageRect       = new Rect(maxSize - manualPackageButtonSize - new Vector2(2.0f * EditorGUIUtility.standardVerticalSpacing,
                                                                                                   2.0f * EditorGUIUtility.standardVerticalSpacing),
                                                   manualPackageButtonSize);
            var manualSelectPressed = false;

            using (new GUI.EnabledBlock(m_status != Status.Installing && m_status != Status.Downloading))
                manualSelectPressed = UnityEngine.GUI.Button(manualPackageRect,
                                                             GUI.MakeLabel("Manual select..."),
                                                             InspectorEditor.Skin.Button);
            if (manualSelectPressed)
            {
                if (!Directory.Exists(GetManualPackageDirectoryData().String))
                {
                    GetManualPackageDirectoryData().String = "Assets";
                }
                var manualPackageFilename = EditorUtility.OpenFilePanelWithFilters("AGX Dynamics for Unity package",
                                                                                   GetManualPackageDirectoryData().String,
                                                                                   new string[]
                {
                    "AGXUnity package",
                    "*.*.*unitypackage"
                });
                if (!string.IsNullOrEmpty(manualPackageFilename))
                {
                    var manualTargetFileInfo = new FileInfo(manualPackageFilename);
                    GetManualPackageDirectoryData().String = manualTargetFileInfo.Directory.FullName;

                    if (!manualTargetFileInfo.Exists)
                    {
                        Debug.LogWarning($"The target package \"{manualTargetFileInfo.FullName}\" doesn't exist. Aborting.");
                    }
                    else if (!VersionInfo.Parse(manualTargetFileInfo.Name).IsValid)
                    {
                        Debug.LogWarning($"Unable to parse version from package name \"{manualTargetFileInfo.Name}\". Aborting.");
                    }
                    else if (!manualTargetFileInfo.Name.StartsWith("AGXDynamicsForUnity-"))
                    {
                        Debug.LogWarning($"Package name \"{manualTargetFileInfo.Name}\" doesn't seems to be an AGX Dynamics for Unity package. Aborting.");
                    }
                    else if (EditorUtility.DisplayDialog("AGX Dynamics for Unity update",
                                                         "AGX Dynamics for Unity is about to be updated/downgraded " +
                                                         "to version " +
                                                         VersionInfo.Parse(manualTargetFileInfo.Name).VersionString +
                                                         ".\n\nDo you want to continue with the update/downgrade?",
                                                         "Continue",
                                                         "Cancel"))
                    {
                        Target   = manualTargetFileInfo.FullName;
                        m_status = Status.AwaitInstall;
                        InstallTarget();
                    }
                }
            }
        }
Esempio n. 26
0
        private void OnGUI()
        {
            var iconDirectoryInfo = new DirectoryInfo(IconManager.Directory);

            if (!iconDirectoryInfo.Exists)
            {
                return;
            }

            if (iconDirectoryInfo.GetFiles("*.png.meta").Length != m_iconNames.Count)
            {
                Debug.LogWarning("Icon count changed - reloading icons...");
                OnEnable();
            }

            Undo.RecordObject(EditorData.Instance, "IconManager");

            var selectIconDir = false;
            var editorData    = GetEditorData();

            m_scroll = EditorGUILayout.BeginScrollView(m_scroll);

            using (new EditorGUILayout.HorizontalScope()) {
                EditorGUILayout.LabelField(GUI.MakeLabel("Icons directory"),
                                           GUI.MakeLabel(IconManager.Directory.Replace('\\', '/')),
                                           InspectorGUISkin.Instance.TextField);
                selectIconDir = GUILayout.Button(GUI.MakeLabel("..."),
                                                 InspectorGUISkin.Instance.Button,
                                                 GUILayout.Width(24));
            }

            EditorGUILayout.LabelField(GUI.MakeLabel("Number of icons"),
                                       GUI.MakeLabel(m_iconNames.Count.ToString()),
                                       InspectorGUISkin.Instance.Label);
            IconManager.Scale = editorData.Float = Mathf.Clamp(EditorGUILayout.Slider(GUI.MakeLabel("Scale"),
                                                                                      editorData.Float,
                                                                                      0.0f,
                                                                                      2.0f), 1.0E-3f, 2.0f);
            var newWidth = EditorGUILayout.Slider(GUI.MakeLabel("Button width"),
                                                  editorData.Vector2.x,
                                                  6.0f,
                                                  75.0f);

            using (new GUI.EnabledBlock(false)) {
                var newHeight = EditorGUILayout.Slider(GUI.MakeLabel("Button height"),
                                                       editorData.Vector2.y,
                                                       6.0f,
                                                       75.0f);
                InspectorGUISkin.ToolButtonSize = editorData.Vector2 = new Vector2(newWidth, newHeight);
            }

            InspectorGUI.BrandSeparator(1, 6);
            RenderButtons(editorData.Vector2, true, false);
            InspectorGUI.BrandSeparator(1, 6);
            RenderButtons(editorData.Vector2, true, true);
            InspectorGUI.BrandSeparator(1, 6);
            RenderButtons(editorData.Vector2, false, false);
            InspectorGUI.BrandSeparator(1, 6);

            IconManager.NormalColorDark = GetEditorData("NormalColorDark").Color = EditorGUILayout.ColorField(GUI.MakeLabel("Normal Dark"),
                                                                                                              GetEditorData("NormalColorDark").Color);
            IconManager.ActiveColorDark = GetEditorData("ActiveColorDark").Color = EditorGUILayout.ColorField(GUI.MakeLabel("Active Dark"),
                                                                                                              GetEditorData("ActiveColorDark").Color);
            IconManager.DisabledColorDark = GetEditorData("DisabledColorDark").Color = EditorGUILayout.ColorField(GUI.MakeLabel("Disabled Dark"),
                                                                                                                  GetEditorData("DisabledColorDark").Color);

            IconManager.NormalColorLight = GetEditorData("NormalColorLight").Color = EditorGUILayout.ColorField(GUI.MakeLabel("Normal Light"),
                                                                                                                GetEditorData("NormalColorLight").Color);
            IconManager.ActiveColorLight = GetEditorData("ActiveColorLight").Color = EditorGUILayout.ColorField(GUI.MakeLabel("Active Light"),
                                                                                                                GetEditorData("ActiveColorLight").Color);
            IconManager.DisabledColorLight = GetEditorData("DisabledColorLight").Color = EditorGUILayout.ColorField(GUI.MakeLabel("Disabled Light"),
                                                                                                                    GetEditorData("DisabledColorLight").Color);

            EditorGUILayout.LabelField(GUI.MakeLabel("Brand color"),
                                       new GUIContent(GUI.CreateColoredTexture((int)EditorGUIUtility.currentViewWidth,
                                                                               (int)EditorGUIUtility.singleLineHeight,
                                                                               InspectorGUISkin.BrandColor)));

            var numLines = 6;
            var rect     = EditorGUILayout.GetControlRect(false, numLines * EditorGUIUtility.singleLineHeight);

            EditorGUI.SelectableLabel(rect, GetColorsString(), InspectorEditor.Skin.TextFieldMiddleLeft);

            InspectorGUI.BrandSeparator(1, 6);

            RenderIcons(IconManager.Scale * 24.0f * Vector2.one);

            InspectorGUI.BrandSeparator(1, 6);

            RenderIcons();

            InspectorGUI.BrandSeparator(1, 6);

            EditorGUILayout.EndScrollView();

            if (selectIconDir)
            {
                var result = EditorUtility.OpenFolderPanel("Icons directory",
                                                           new DirectoryInfo(IconManager.Directory).Parent.FullName,
                                                           "");
                if (!string.IsNullOrEmpty(result))
                {
                    var di = new DirectoryInfo(result);
                    if (di.Exists)
                    {
                        editorData.String = IO.Utils.MakeRelative(result, Application.dataPath);
                        OnEnable();
                    }
                }
            }
        }
Esempio n. 27
0
        public override void OnPreTargetMembersGUI()
        {
            var skin = InspectorEditor.Skin;

            bool toggleShapeCreate           = false;
            bool toggleConstraintCreate      = false;
            bool toggleDisableCollisions     = false;
            bool toggleRigidBodyVisualCreate = false;

            if (!IsMultiSelect && ToolsActive)
            {
                InspectorGUI.ToolButtons(InspectorGUI.ToolButtonData.Create(ToolIcon.CreateConstraint,
                                                                            ConstraintCreateTool,
                                                                            "Create new constraint to this rigid body.",
                                                                            () => toggleConstraintCreate = true),
                                         InspectorGUI.ToolButtonData.Create(ToolIcon.DisableCollisions,
                                                                            DisableCollisionsTool,
                                                                            "Disable collisions against other objects.",
                                                                            () => toggleDisableCollisions = true),
                                         InspectorGUI.ToolButtonData.Create(ToolIcon.CreateShapeGivenVisual,
                                                                            ShapeCreateTool,
                                                                            "Create shape from child visual object.",
                                                                            () => toggleShapeCreate = true),
                                         InspectorGUI.ToolButtonData.Create(ToolIcon.CreateVisual,
                                                                            RigidBodyVisualCreateTool,
                                                                            "Create visual representation of each physical shape in this body.",
                                                                            () => toggleRigidBodyVisualCreate = true,
                                                                            Tools.RigidBodyVisualCreateTool.ValidForNewShapeVisuals(RigidBody)));
            }

            if (ConstraintCreateTool)
            {
                GetChild <ConstraintCreateTool>().OnInspectorGUI();
            }
            if (DisableCollisionsTool)
            {
                GetChild <DisableCollisionsTool>().OnInspectorGUI();
            }
            if (ShapeCreateTool)
            {
                GetChild <ShapeCreateTool>().OnInspectorGUI();
            }
            if (RigidBodyVisualCreateTool)
            {
                GetChild <RigidBodyVisualCreateTool>().OnInspectorGUI();
            }

            EditorGUILayout.LabelField(GUI.MakeLabel("Mass properties", true), skin.Label);
            using (InspectorGUI.IndentScope.Single)
                InspectorEditor.DrawMembersGUI(GetTargets <RigidBody>().Select(rb => rb.MassProperties).ToArray());

            if (toggleConstraintCreate)
            {
                ConstraintCreateTool = !ConstraintCreateTool;
            }
            if (toggleDisableCollisions)
            {
                DisableCollisionsTool = !DisableCollisionsTool;
            }
            if (toggleShapeCreate)
            {
                ShapeCreateTool = !ShapeCreateTool;
            }
            if (toggleRigidBodyVisualCreate)
            {
                RigidBodyVisualCreateTool = !RigidBodyVisualCreateTool;
            }
        }
Esempio n. 28
0
        public void OnInspectorGUI()
        {
            if (Mode == ToolMode.Direction)
            {
                StartFrameNameId = "Frame";
            }

            StartFrameToolEnable = Line.Valid;
            EndFrameToolEnable   = Line.Valid;

            bool toggleCreateEdge    = false;
            bool toggleFlipDirection = false;
            bool toggleRenderAsArrow = false;
            bool showTools           = !EditorApplication.isPlaying;

            if (showTools)
            {
                var toolButtonData = new List <InspectorGUI.ToolButtonData>();
                toolButtonData.Add(InspectorGUI.ToolButtonData.Create(ToolIcon.VisualizeLineDirection,
                                                                      RenderAsArrow,
                                                                      "Visualize line direction.",
                                                                      () => toggleRenderAsArrow = true,
                                                                      Mode != ToolMode.Direction));
                toolButtonData.Add(InspectorGUI.ToolButtonData.Create(ToolIcon.FlipDirection,
                                                                      false,
                                                                      "Flip direction.",
                                                                      () => toggleFlipDirection = true,
                                                                      Line.Valid));
                toolButtonData.Add(InspectorGUI.ToolButtonData.Create(ToolIcon.FindTransformGivenEdge,
                                                                      EdgeDetectionToolEnable,
                                                                      "Find line given edge.",
                                                                      () => toggleCreateEdge = true));
                InspectorGUI.ToolButtons(toolButtonData.ToArray());
            }

            if (toggleCreateEdge)
            {
                EdgeDetectionToolEnable = !EdgeDetectionToolEnable;
            }

            if (toggleFlipDirection && EditorUtility.DisplayDialog("Line direction",
                                                                   "Flip direction of " + Name + "?",
                                                                   "Yes",
                                                                   "No"))
            {
                StartFrameToolEnable = false;

                if (Mode == ToolMode.Direction)
                {
                    Line.End.Position   = Line.End.Position - 2.0f * Line.Length * Line.Direction;
                    Line.Start.Rotation = Quaternion.Euler(-Line.Start.Rotation.eulerAngles);
                    Line.End.Rotation   = Quaternion.Euler(-Line.End.Rotation.eulerAngles);
                }
                else
                {
                    var tmp = Line.Start;
                    Line.Start = Line.End;
                    Line.End   = tmp;
                }
            }
            if (toggleRenderAsArrow)
            {
                RenderAsArrow = !RenderAsArrow;
            }

            if (!Line.Valid)
            {
                InspectorGUI.WarningLabel(Name + " isn't created - use Tools to configure.");
            }

            if (StartFrameToolEnable)
            {
                if (InspectorGUI.Foldout(GetToggleData(StartFrameNameId),
                                         GUI.MakeLabel(StartFrameNameId, true)))
                {
                    StartFrameTool.ForceDisableTransformHandle = EditorApplication.isPlaying;
                    using (new GUI.EnabledBlock(!EditorApplication.isPlaying))
                        InspectorGUI.HandleFrame(StartFrameTool.Frame, 1);
                }
            }
            if (EndFrameToolEnable)
            {
                if (InspectorGUI.Foldout(GetToggleData(EndFrameNameId),
                                         GUI.MakeLabel(EndFrameNameId, true)))
                {
                    EndFrameTool.ForceDisableTransformHandle = EditorApplication.isPlaying;
                    using (new GUI.EnabledBlock(!EditorApplication.isPlaying))
                        InspectorGUI.HandleFrame(EndFrameTool.Frame, 1);
                }
            }

            Synchronize();
        }
Esempio n. 29
0
        public void OnInspectorGUI()
        {
            if (AttachmentFrameTool == null || AttachmentFrameTool.AttachmentPairs[0] == null)
            {
                PerformRemoveFromParent();
                return;
            }

            InspectorGUI.OnDropdownToolBegin("Create constraint given type and use additional tools to " +
                                             "configure the constraint frames.");

            var skin = InspectorEditor.Skin;

            m_createConstraintData.Name = EditorGUILayout.TextField(GUI.MakeLabel("Name", true),
                                                                    m_createConstraintData.Name,
                                                                    skin.TextField);


#if UNITY_2018_1_OR_NEWER
            m_createConstraintData.ConstraintType = (ConstraintType)EditorGUILayout.EnumPopup(GUI.MakeLabel("Type", true),
                                                                                              m_createConstraintData.ConstraintType,
                                                                                              val => (ConstraintType)val != ConstraintType.Unknown,
                                                                                              false,
                                                                                              skin.Popup);
#else
            m_createConstraintData.ConstraintType = (ConstraintType)EditorGUILayout.EnumPopup(GUI.MakeLabel("Type", true),
                                                                                              m_createConstraintData.ConstraintType,
                                                                                              skin.Popup);
#endif

            AttachmentFrameTool.OnPreTargetMembersGUI();
            AttachmentFrameTool.AttachmentPairs[0].Synchronize();

            m_createConstraintData.CollisionState = ConstraintTool.ConstraintCollisionsStateGUI(m_createConstraintData.CollisionState);
            m_createConstraintData.SolveType      = ConstraintTool.ConstraintSolveTypeGUI(m_createConstraintData.SolveType);

            var createCancelState = InspectorGUI.PositiveNegativeButtons(m_createConstraintData.AttachmentPair.ReferenceObject != null &&
                                                                         m_createConstraintData.AttachmentPair.ReferenceObject.GetComponentInParent <RigidBody>() != null,
                                                                         "Create",
                                                                         "Create the constraint",
                                                                         "Cancel");

            if (createCancelState == InspectorGUI.PositiveNegativeResult.Positive)
            {
                GameObject constraintGameObject = Factory.Create(m_createConstraintData.ConstraintType,
                                                                 m_createConstraintData.AttachmentPair);
                Constraint constraint = constraintGameObject.GetComponent <Constraint>();
                constraintGameObject.name  = m_createConstraintData.Name;
                constraint.CollisionsState = m_createConstraintData.CollisionState;

                if (MakeConstraintChildToParent)
                {
                    constraintGameObject.transform.SetParent(Parent.transform);
                }

                Undo.RegisterCreatedObjectUndo(constraintGameObject, "New constraint '" + constraintGameObject.name + "' created");

                m_onCreate?.Invoke(constraint);

                m_createConstraintData.Reset();
            }

            if (createCancelState != InspectorGUI.PositiveNegativeResult.Neutral)
            {
                PerformRemoveFromParent();
            }

            InspectorGUI.OnDropdownToolEnd();
        }
Esempio n. 30
0
        public override void OnPreTargetMembersGUI()
        {
            var isMultiSelect = AttachmentPairs.Length > 1;

            Undo.RecordObjects(AttachmentPairs, "Constraint Attachment");

            var skin          = InspectorEditor.Skin;
            var guiWasEnabled = UnityEngine.GUI.enabled;

            var connectedFrameSynchronized = AttachmentPairs.All(ap => ap.Synchronized);

            EditorGUILayout.LabelField(GUI.MakeLabel("Reference frame", true), skin.Label);
            InspectorGUI.HandleFrames(AttachmentPairs.Select(ap => ap.ReferenceFrame).ToArray(), 1);

            GUILayout.Space(4);

            var rect     = EditorGUILayout.GetControlRect(false, EditorGUIUtility.singleLineHeight);
            var orgWidth = rect.xMax;

            UnityEngine.GUI.Label(EditorGUI.IndentedRect(rect),
                                  GUI.MakeLabel("Connected frame", true),
                                  InspectorEditor.Skin.Label);

            var buttonWidth        = 1.1f * EditorGUIUtility.singleLineHeight;
            var buttonHeightOffset = 1.0f;

            rect.x     = EditorGUIUtility.labelWidth + InspectorGUI.LayoutMagicNumber;
            rect.y    -= buttonHeightOffset;
            rect.width = buttonWidth;
            var toggleSynchronized = InspectorGUI.Button(rect,
                                                         connectedFrameSynchronized ?
                                                         MiscIcon.SynchEnabled :
                                                         MiscIcon.SynchDisabled,
                                                         true,
                                                         "Toggle synchronized with reference frame.",
                                                         1.17f);

            rect.x    += rect.width + 2.0f;
            rect.width = orgWidth - rect.x;
            rect.y    += buttonHeightOffset;

            UnityEngine.GUI.Label(rect,
                                  GUI.MakeLabel($"{( connectedFrameSynchronized ? "Synchronized" : "Free" )}"),
                                  InspectorEditor.Skin.Label);

            if (toggleSynchronized)
            {
                foreach (var ap in AttachmentPairs)
                {
                    ap.Synchronized = !connectedFrameSynchronized;
                }

                if (!isMultiSelect && AttachmentPairs[0].Synchronized)
                {
                    ConnectedFrameTool.TransformHandleActive = false;
                }
            }

            UnityEngine.GUI.enabled = !connectedFrameSynchronized && !isMultiSelect;
            InspectorGUI.HandleFrames(AttachmentPairs.Select(ap => ap.ConnectedFrame).ToArray(), 1);
            UnityEngine.GUI.enabled = guiWasEnabled;
        }