text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace UnityEditor.Experimental.Rendering { public interface IScriptableBakedReflectionSystem : IDisposable { int stageCount { get; } Hash128[] stateHashes { get; } void Tick(SceneStateHash sceneStateHash, IScriptableBakedReflectionSystemStageNotifier handle); void SynchronizeReflectionProbes(); void Clear(); void Cancel(); bool BakeAllReflectionProbes(); } }
UnityCsReference/Editor/Mono/Camera/IScriptableBakedReflectionSystem.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Camera/IScriptableBakedReflectionSystem.cs", "repo_id": "UnityCsReference", "token_count": 219 }
299
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using Unity.CodeEditor; using UnityEngine.Scripting; namespace UnityEditor { internal class CodeEditorProjectSync : AssetPostprocessor { class BuildTargetChangedHandler : Build.IActiveBuildTargetChanged { public int callbackOrder => 0; public void OnActiveBuildTargetChanged(BuildTarget oldTarget, BuildTarget newTarget) { CodeEditor.Editor.CurrentCodeEditor.SyncAll(); } } [RequiredByNativeCode] public static void SyncEditorProject() { CodeEditor.Editor.CurrentCodeEditor.SyncAll(); } // For the time being this doesn't use the callback public static void PostprocessSyncProject( string[] importedAssets, string[] addedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { CodeEditor.Editor.CurrentCodeEditor.SyncIfNeeded(addedAssets, deletedAssets, movedAssets, movedFromAssetPaths, importedAssets); } [MenuItem("Assets/Open C# Project", secondaryPriority = 1)] static void SyncAndOpenSolution() { // Ensure that the mono islands are up-to-date AssetDatabase.Refresh(); CodeEditor.Editor.CurrentCodeEditor.SyncAll(); CodeEditor.Editor.CurrentCodeEditor.OpenProject(); } } }
UnityCsReference/Editor/Mono/CodeEditor/CodeEditorProjectSync.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/CodeEditor/CodeEditorProjectSync.cs", "repo_id": "UnityCsReference", "token_count": 649 }
300
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor { public static class ConsoleWindowUtility { public static event Action consoleLogsChanged; public static void GetConsoleLogCounts(out int error, out int warn, out int log) { int outError = 0; int outWarn = 0; int outLog = 0; LogEntries.GetCountsByType(ref outError, ref outWarn, ref outLog); error = outError; warn = outWarn; log = outLog; } internal static void Internal_CallLogsHaveChanged() { consoleLogsChanged?.Invoke(); } } }
UnityCsReference/Editor/Mono/ConsoleWindowUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ConsoleWindowUtility.cs", "repo_id": "UnityCsReference", "token_count": 344 }
301
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnityEditor { internal class DisplayUtility { static string s_DisplayStr = "Display {0}"; private static GUIContent[] s_GenericDisplayNames = { EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 1)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 2)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 3)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 4)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 5)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 6)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 7)), EditorGUIUtility.TextContent(string.Format(s_DisplayStr, 8)) }; private static readonly int[] s_DisplayIndices = { 0, 1, 2, 3, 4, 5, 6, 7 }; public static GUIContent[] GetGenericDisplayNames() { return s_GenericDisplayNames; } public static int[] GetDisplayIndices() { return s_DisplayIndices; } public static GUIContent[] GetDisplayNames() { GUIContent[] platformDisplayNames = Modules.ModuleManager.GetDisplayNames(EditorUserBuildSettings.activeBuildTarget.ToString()); return platformDisplayNames != null ? platformDisplayNames : s_GenericDisplayNames; } } }
UnityCsReference/Editor/Mono/DisplayUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/DisplayUtility.cs", "repo_id": "UnityCsReference", "token_count": 635 }
302
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text.RegularExpressions; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Scripting; using UnityEngine.Rendering; using UnityEditorInternal; using UnityEditor.Scripting.ScriptCompilation; using Object = UnityEngine.Object; using Event = UnityEngine.Event; using UnityEditor.StyleSheets; using UnityEditor.VersionControl; using UnityEngine.Internal; using VirtualTexturing = UnityEngine.Rendering.VirtualTexturing; using PreviewMaterialType = UnityEditor.EditorGUIUtility.PreviewType; using System.Linq; using System.Reflection; using Unity.Profiling; using UnityEngine.Experimental.Rendering; using UnityEngine.UIElements; using UnityEditor.UIElements; using UnityEngine.Bindings; namespace UnityEditor { // Class for editor-only GUI. This class contains general purpose 2D additions to UnityGUI. // These work pretty much like the normal GUI functions - and also have matching implementations in [[EditorGUILayout]] [SuppressMessage("ReSharper", "NotAccessedField.Local")] public sealed partial class EditorGUI { private static RecycledTextEditor activeEditor; internal static DelayedTextEditor s_DelayedTextEditor = new DelayedTextEditor(); internal static RecycledTextEditor s_RecycledEditor = new RecycledTextEditor(); internal static string s_OriginalText = ""; internal static string s_RecycledCurrentEditingString; private static bool bKeyEventActive = false; internal static bool s_DragToPosition = false; internal static bool s_Dragged = false; internal static bool s_SelectAllOnMouseUp = true; private const double kFoldoutExpandTimeout = 0.7; private static double s_FoldoutDestTime; private static int s_DragUpdatedOverID = 0; private const int kSearchFieldTextLimit = 1024; private static bool s_SearchFieldTextLimitApproved = false; private static int s_SavekeyboardControl = 0; private static readonly int s_FoldoutHash = "Foldout".GetHashCode(); private static readonly int s_TagFieldHash = "s_TagFieldHash".GetHashCode(); private static readonly int s_PPtrHash = "s_PPtrHash".GetHashCode(); private static readonly int s_ObjectFieldHash = "s_ObjectFieldHash".GetHashCode(); private static readonly int s_ToggleHash = "s_ToggleHash".GetHashCode(); private static readonly int s_ColorHash = "s_ColorHash".GetHashCode(); private static readonly int s_CurveHash = "s_CurveHash".GetHashCode(); private static readonly int s_LayerMaskField = "s_LayerMaskField".GetHashCode(); private static readonly int s_MaskField = "s_MaskField".GetHashCode(); private static readonly int s_EnumFlagsField = "s_EnumFlagsField".GetHashCode(); private static readonly int s_GenericField = "s_GenericField".GetHashCode(); private static readonly int s_PopupHash = "EditorPopup".GetHashCode(); private static readonly int s_KeyEventFieldHash = "KeyEventField".GetHashCode(); private static readonly int s_TextFieldHash = "EditorTextField".GetHashCode(); private static readonly int s_SearchFieldHash = "EditorSearchField".GetHashCode(); private static readonly int s_TextAreaHash = "EditorTextField".GetHashCode(); private static readonly int s_PasswordFieldHash = "PasswordField".GetHashCode(); private static readonly int s_FloatFieldHash = "EditorTextField".GetHashCode(); private static readonly int s_DelayedTextFieldHash = "DelayedEditorTextField".GetHashCode(); private static readonly int s_ArraySizeFieldHash = "ArraySizeField".GetHashCode(); private static readonly int s_SliderHash = "EditorSlider".GetHashCode(); private static readonly int s_SliderKnobHash = "EditorSliderKnob".GetHashCode(); private static readonly int s_MinMaxSliderHash = "EditorMinMaxSlider".GetHashCode(); private static readonly int s_TitlebarHash = "GenericTitlebar".GetHashCode(); private static readonly int s_ProgressBarHash = "s_ProgressBarHash".GetHashCode(); private static readonly int s_SelectableLabelHash = "s_SelectableLabel".GetHashCode(); private static readonly int s_SortingLayerFieldHash = "s_SortingLayerFieldHash".GetHashCode(); private static readonly int s_TextFieldDropDownHash = "s_TextFieldDropDown".GetHashCode(); private enum DragCandidateState { NotDragging, InitiatedDragging, CurrentlyDragging } private static DragCandidateState s_DragCandidateState = DragCandidateState.NotDragging; private const float kDragDeadzone = 16; private static Vector2 s_DragStartPos; private static double s_DragStartValue = 0; private static long s_DragStartIntValue = 0; private static double s_DragSensitivity = 0; private static readonly GUIContent s_LargerChar = EditorGUIUtility.TextContent("W"); // kMiniLabelW is used for all the PrefixLabelWidths irrsepective of the character,to fix the case 1297283 internal static float kMiniLabelW => EditorGUI.CalcPrefixLabelWidth(s_LargerChar); internal const float kPrefixPaddingRight = 2; internal const float kLabelW = 80; internal const float kSpacing = 5; internal const float kSpacingSubLabel = 4; internal const float kSliderMinW = 50; internal const float kSliderMaxW = 100; internal const float kSingleLineHeight = 18f; internal const float kSingleSmallLineHeight = 16f; internal const float kStructHeaderLineHeight = 18; internal const float kObjectFieldThumbnailHeight = 64; internal const float kObjectFieldMiniThumbnailHeight = 18f; internal const float kObjectFieldMiniThumbnailWidth = 32f; internal const float kLabelWidthRatio = 0.45f; internal const float kLabelWidthPadding = 3f; internal const float kLabelWidthMargin = 40f; internal const float kMinLabelWidth = 120f; internal static string kFloatFieldFormatString = UINumericFieldsUtils.k_FloatFieldFormatString; internal static string kDoubleFieldFormatString = UINumericFieldsUtils.k_DoubleFieldFormatString; internal static string kIntFieldFormatString = UINumericFieldsUtils.k_IntFieldFormatString; internal static int ms_IndentLevel = 0; internal const float kIndentPerLevel = 15; internal const int kControlVerticalSpacingLegacy = 2; internal const int kDefaultSpacing = 6; internal static readonly SVC<float> kControlVerticalSpacing = new SVC<float>("--theme-control-vertical-spacing", 2.0f); internal static readonly SVC<float> kVerticalSpacingMultiField = new SVC<float>("--theme-multifield-vertical-spacing", 0.0f); internal static string s_UnitString = ""; internal const int kInspTitlebarIconWidth = 16; internal const int kInspTitlebarFoldoutIconWidth = 13; internal static readonly SVC<float> kWindowToolbarHeight = new SVC<float>("--window-toolbar-height", 21f); internal const int kTabButtonHeight = 22; internal const int kLargeButtonHeight = 24; private const string kEnabledPropertyName = "m_Enabled"; private const string k_MultiEditValueString = "<>"; private const float kDropDownArrowMargin = 2; private const float kDropDownArrowWidth = 12; private const float kDropDownArrowHeight = 12; private static readonly float[] s_Vector2Floats = {0, 0}; private static readonly int[] s_Vector2Ints = { 0, 0 }; private static readonly GUIContent[] s_XYLabels = {EditorGUIUtility.TextContent("X"), EditorGUIUtility.TextContent("Y")}; private static readonly float[] s_Vector3Floats = {0, 0, 0}; private static readonly int[] s_Vector3Ints = { 0, 0, 0 }; private static readonly GUIContent[] s_XYZLabels = {EditorGUIUtility.TextContent("X"), EditorGUIUtility.TextContent("Y"), EditorGUIUtility.TextContent("Z")}; private static readonly float[] s_Vector4Floats = {0, 0, 0, 0}; private static readonly GUIContent[] s_XYZWLabels = {EditorGUIUtility.TextContent("X"), EditorGUIUtility.TextContent("Y"), EditorGUIUtility.TextContent("Z"), EditorGUIUtility.TextContent("W")}; private const float kQuaternionFloatPrecision = 1e-6f; private static readonly GUIContent[] s_WHLabels = {EditorGUIUtility.TextContent("W"), EditorGUIUtility.TextContent("H")}; private static readonly GUIContent s_CenterLabel = EditorGUIUtility.TrTextContent("Center"); private static readonly GUIContent s_ExtentLabel = EditorGUIUtility.TrTextContent("Extent"); private static readonly GUIContent s_PositionLabel = EditorGUIUtility.TrTextContent("Position"); private static readonly GUIContent s_SizeLabel = EditorGUIUtility.TrTextContent("Size"); internal static GUIContent s_PleasePressAKey = EditorGUIUtility.TrTextContent("[Please press a key]"); internal static readonly GUIContent s_ClipingPlanesLabel = EditorGUIUtility.TrTextContent("Clipping Planes", "The distances from the Camera where rendering starts and stops."); internal static readonly GUIContent[] s_NearAndFarLabels = { EditorGUIUtility.TrTextContent("Near", "The closest point to the Camera where drawing occurs."), EditorGUIUtility.TrTextContent("Far", "The furthest point from the Camera that drawing occurs.") }; internal const float kNearFarLabelsWidth = 35f; private static int s_ColorPickID; private static int s_CurveID; internal static Color kCurveColor = Color.green; internal static Color kCurveBGColor = new Color(0.337f, 0.337f, 0.337f, 1f); internal static EditorGUIUtility.SkinnedColor kSplitLineSkinnedColor = new EditorGUIUtility.SkinnedColor(new Color(0.6f, 0.6f, 0.6f, 1.333f), new Color(0.12f, 0.12f, 0.12f, 1.333f)); internal static Color k_OverrideMarginColor = new Color(1f / 255f, 153f / 255f, 235f / 255f, 0.75f); internal static Color k_OverrideMarginColorSelected = new Color(239f / 255f, 239f / 255f, 239f / 239f, 1f); internal static Color k_OverrideMarginColorNotApplicable = new Color(1f / 255f, 153f / 255f, 235f / 255f, 0.35f); internal static Color k_LiveModifiedMarginLightThemeColor = new Color(183f / 255f, 60f / 255f, 21f / 255f, 1f); internal static Color k_LiveModifiedMarginDarkThemeColor = new Color(255f / 255f, 165f / 255f, 60f / 255f, 1f); private const int kInspTitlebarSpacing = 4; private static readonly GUIContent s_PropertyFieldTempContent = new GUIContent(); private static GUIContent s_IconDropDown; private static Material s_IconTextureInactive; private static bool s_HasPrefixLabel; private static readonly GUIContent s_PrefixLabel = new GUIContent((string)null); private static Rect s_PrefixTotalRect; private static Rect s_PrefixRect; private static GUIStyle s_PrefixStyle; private static GUIStyle s_IconButtonStyle; private static Color s_PrefixGUIColor; private static string s_LabelHighlightContext; private static Color s_LabelHighlightColor; private static Color s_LabelHighlightSelectionColor; private static string[] m_FlagNames; private static int[] m_FlagValues; internal static float lineHeight { get; set; } = kSingleLineHeight; // Makes the following controls give the appearance of editing multiple different values. public static bool showMixedValue { get; set; } private static readonly GUIContent s_MixedValueContent = EditorGUIUtility.TrTextContent("\u2014", "Mixed Values"); internal static GUIContent mixedValueContent => s_MixedValueContent; private static readonly Color s_MixedValueContentColor = new Color(1, 1, 1, 0.5f); private static Color s_MixedValueContentColorTemp = Color.white; internal static SavedBool s_ShowRepaintDots = new SavedBool("ShowRepaintDots", true); internal static readonly Regex s_ATagRegex = new Regex(@"(?<=\b="")[^""]*"); internal static readonly Regex s_LinkTagRegex = new Regex(@"(?<=\b=')[^']*"); static class Styles { public static Texture2D prefabOverlayAddedIcon = EditorGUIUtility.LoadIcon("PrefabOverlayAdded Icon"); public static Texture2D prefabOverlayRemovedIcon = EditorGUIUtility.LoadIcon("PrefabOverlayRemoved Icon"); public static readonly GUIStyle linkButton = "FloatFieldLinkButton"; public static Texture2D repaintDot = EditorGUIUtility.LoadIcon("RepaintDot"); public static string revertPropertyValueIdenticalToSource = L10n.Tr("Revert (identical value to Prefab '{0}')"); } static EditorGUI() { hyperLinkClicked += EditorGUI_OpenFileOnHyperLinkClicked; } internal static void BeginHandleMixedValueContentColor() { s_MixedValueContentColorTemp = GUI.contentColor; GUI.contentColor = showMixedValue ? (GUI.contentColor * s_MixedValueContentColor) : GUI.contentColor; } internal static void EndHandleMixedValueContentColor() { GUI.contentColor = s_MixedValueContentColorTemp; } [RequiredByNativeCode] internal static bool IsEditingTextField() { return RecycledTextEditor.s_ActuallyEditing && activeEditor != null; } internal static void EndEditingActiveTextField() { activeEditor?.EndEditing(); } public static void FocusTextInControl(string name) { GUI.FocusControl(name); EditorGUIUtility.editingTextField = true; } // STACKS internal static void ClearStacks() { s_EnabledStack.Clear(); s_IsInsideListStack.Clear(); GUI.isInsideList = false; s_ChangedStack.Clear(); s_PropertyStack.Clear(); MaterialProperty.ClearStack(); ScriptAttributeUtility.s_DrawerStack.Clear(); s_FoldoutHeaderGroupActive = 0; } private static readonly Stack<PropertyGUIData> s_PropertyStack = new Stack<PropertyGUIData>(); private static readonly Stack<bool> s_EnabledStack = new Stack<bool>(); private static readonly Stack<(bool insideList, int depth)> s_IsInsideListStack = new Stack<(bool insideList, int depth)>(); // @TODO: API soon to be deprecated but still in a grace period; documentation states that users // are encouraged to use EditorGUI.DisabledScope instead. Uncomment next line when appropriate. // [System.Obsolete("Use DisabledScope instead", false)] public class DisabledGroupScope : GUI.Scope { public DisabledGroupScope(bool disabled) { BeginDisabledGroup(disabled); } protected override void CloseScope() { EndDisabledGroup(); } } // Create a group of controls that can be disabled. // @TODO: API soon to be deprecated but still in a grace period; documentation states that users // are encouraged to use EditorGUI.DisabledScope instead. Uncomment next line when appropriate. // [System.Obsolete("Use DisabledScope instead", false)] public static void BeginDisabledGroup(bool disabled) { BeginDisabled(disabled); } // Ends a disabled group started with BeginDisabledGroup. // @TODO: API soon to be deprecated but still in a grace period; documentation states that users // are encouraged to use EditorGUI.DisabledScope instead. Uncomment next line when appropriate. // [System.Obsolete("Use DisabledScope instead", false)] public static void EndDisabledGroup() { EndDisabled(); } public struct DisabledScope : IDisposable { bool m_Disposed; public DisabledScope(bool disabled) { m_Disposed = false; BeginDisabled(disabled); } public void Dispose() { if (m_Disposed) return; m_Disposed = true; if (!GUIUtility.guiIsExiting) EndDisabled(); } } internal class DisabledGuiViewInputScope : GUI.Scope { GUIView m_View; bool m_WasDisabled; public DisabledGuiViewInputScope(GUIView view, bool disabled) { m_View = view; if (m_View != null) { m_WasDisabled = view.disableInputEvents; m_View.disableInputEvents = disabled; } } protected override void CloseScope() { if (m_View != null) m_View.disableInputEvents = m_WasDisabled; } } internal struct LabelHighlightScope : IDisposable { bool m_Disposed; public LabelHighlightScope(string labelHighlightContext, Color selectionColor, Color textColor) { m_Disposed = false; BeginLabelHighlight(labelHighlightContext, selectionColor, textColor); } public void Dispose() { if (m_Disposed) return; m_Disposed = true; if (!GUIUtility.guiIsExiting) EndLabelHighlight(); } } internal struct CursorColorScope : IDisposable { private Color oldCursorColor; public CursorColorScope(Color color) { oldCursorColor = GUI.skin.settings.cursorColor; GUI.skin.settings.cursorColor = color; } public void Dispose() { GUI.skin.settings.cursorColor = oldCursorColor; } } // Create a group of controls that can be disabled. internal static void BeginDisabled(bool disabled) { s_EnabledStack.Push(GUI.enabled); GUI.enabled &= !disabled; } // Ends a disabled group started with BeginDisabled. internal static void EndDisabled() { // Stack might have been cleared with ClearStack(), check before pop. if (s_EnabledStack.Count > 0) GUI.enabled = s_EnabledStack.Pop(); } internal static void BeginIsInsideList(int depth) { s_IsInsideListStack.Push((GUI.isInsideList, depth)); GUI.isInsideList = true; } internal static int GetInsideListDepth() { if (s_IsInsideListStack.Count > 0) return s_IsInsideListStack.Peek().depth; return -1; } internal static void EndIsInsideList() { // Stack might have been cleared with ClearStack(), check before pop. if (s_IsInsideListStack.Count > 0) GUI.isInsideList = s_IsInsideListStack.Pop().insideList; else GUI.isInsideList = false; } private static readonly Stack<bool> s_ChangedStack = new Stack<bool>(); public class ChangeCheckScope : GUI.Scope { bool m_ChangeChecked; bool m_Changed; public bool changed { get { if (!m_ChangeChecked) { m_ChangeChecked = true; m_Changed = EndChangeCheck(); } return m_Changed; } } public ChangeCheckScope() { BeginChangeCheck(); } protected override void CloseScope() { if (!m_ChangeChecked) EndChangeCheck(); } } // Check if any control was changed inside a block of code. public static void BeginChangeCheck() { s_ChangedStack.Push(GUI.changed); GUI.changed = false; } // Ends a change check started with BeginChangeCheck (). // Note: BeginChangeCheck/EndChangeCheck supports nesting // For ex., // BeginChangeCheck() // BeginChangeCheck() // <GUI control changes> // EndChangeCheck() <-- will return true // EndChangeCheck() <-- will return true public static bool EndChangeCheck() { // as we allow external code to clear stacks through ClearStacks(), // we must be resilient to stacks having been unexpectedly emptied, // when that happens, it is reasonable to assume things indeed have changed if (s_ChangedStack.Count == 0) { GUI.changed = true; return true; } bool changed = GUI.changed; GUI.changed |= s_ChangedStack.Pop(); return changed; } public struct MixedValueScope : IDisposable { bool m_DefaultMixedValue; public MixedValueScope(bool newMixedValue) { m_DefaultMixedValue = showMixedValue; showMixedValue = newMixedValue; } void IDisposable.Dispose() { showMixedValue = m_DefaultMixedValue; } } internal class RecycledTextEditor : TextEditor { internal static bool s_ActuallyEditing = false; // internal so we can save this state. internal static bool s_AllowContextCutOrPaste = true; // e.g. selectable labels only allow for copying private long[] s_OriginalLongValues; private double[] s_OriginalDoubleValues; IMECompositionMode m_IMECompositionModeBackup; public long[] GetOriginalLongValues() { return s_OriginalLongValues; } public double[] GetOriginalDoubleValues() { return s_OriginalDoubleValues; } internal bool IsEditingControl(int id) { return GUIUtility.keyboardControl == id && controlID == id && s_ActuallyEditing && GUIView.current.hasFocus; } public virtual void BeginEditing(int id, string newText, Rect position, GUIStyle style, bool multiline, bool passwordField) { if (IsEditingControl(id)) { return; } activeEditor?.EndEditing(); activeEditor = this; controlID = id; text = s_OriginalText = newText; isMultiline = multiline; this.position = position; this.style = style; isPasswordField = passwordField; s_ActuallyEditing = true; scrollOffset = Vector2.zero; UnityEditor.Undo.IncrementCurrentGroup(); m_IMECompositionModeBackup = Input.imeCompositionMode; Input.imeCompositionMode = IMECompositionMode.On; if (EditorGUI.s_PropertyStack.Count > 0) { var property = EditorGUI.s_PropertyStack.Peek().property; switch (property.propertyType) { case SerializedPropertyType.Integer: s_OriginalLongValues = new long[property.serializedObject.targetObjectsCount]; property.allLongValues.CopyTo(s_OriginalLongValues, 0); break; case SerializedPropertyType.Float: s_OriginalDoubleValues = new double[property.serializedObject.targetObjectsCount]; property.allDoubleValues.CopyTo(s_OriginalDoubleValues, 0); break; default: s_OriginalDoubleValues = null; s_OriginalLongValues = null; break; } } } public virtual void EndEditing() { if (activeEditor == this) { activeEditor = null; } controlID = 0; s_ActuallyEditing = false; s_AllowContextCutOrPaste = true; UnityEditor.Undo.IncrementCurrentGroup(); Input.imeCompositionMode = m_IMECompositionModeBackup; } } // There can be two way something can get focus internal sealed class DelayedTextEditor : RecycledTextEditor { private int controlThatHadFocus = 0, messageControl = 0; internal string controlThatHadFocusValue = ""; private GUIView viewThatHadFocus; private bool m_CommitCommandSentOnLostFocus; private const string CommitCommand = "DelayedControlShouldCommit"; private bool m_IgnoreBeginGUI = false; public void BeginGUI() { if (m_IgnoreBeginGUI) { return; } if (GUIUtility.keyboardControl == controlID) { controlThatHadFocus = GUIUtility.keyboardControl; controlThatHadFocusValue = text; viewThatHadFocus = GUIView.current; } else { controlThatHadFocus = 0; } } public void EndGUI(EventType type) { int sendID = 0; if (controlThatHadFocus != 0 && controlThatHadFocus != GUIUtility.keyboardControl) { sendID = controlThatHadFocus; controlThatHadFocus = 0; } if (sendID != 0 && !m_CommitCommandSentOnLostFocus) { messageControl = sendID; // Debug.Log ("" + messageControl + " lost focus to " + GUIUtility.keyboardControl+ " in " + type+". Sending Message. value:" + controlThatHadFocusValue); m_IgnoreBeginGUI = true; // Explicitly set the keyboardControl for the view that had focus in preparation for the following SendEvent, // but only if the current view is the view that had focus. // This is necessary as GUIView::OnInputEvent (native) will load the old keyboardControl for nested OnGUI calls. if (GUIView.current == viewThatHadFocus) viewThatHadFocus.SetKeyboardControl(GUIUtility.keyboardControl); viewThatHadFocus.SendEvent(EditorGUIUtility.CommandEvent(CommitCommand)); m_IgnoreBeginGUI = false; // Debug.Log ("Afterwards: " + GUIUtility.keyboardControl); messageControl = 0; } } public override void EndEditing() { //The following block handles the case where a different window is focus while editing delayed text box if (Event.current == null) { // We set this flag because of a bug that was trigger when you switched focus to another window really fast // right after focusing on the text box. For some reason keyboardControl was changed and the commit message // was being sent twice which caused layout issues. m_CommitCommandSentOnLostFocus = true; m_IgnoreBeginGUI = true; messageControl = controlID; var temp = GUIUtility.keyboardControl; if (viewThatHadFocus != null) { viewThatHadFocus.SetKeyboardControl(0); viewThatHadFocus.SendEvent(EditorGUIUtility.CommandEvent(CommitCommand)); viewThatHadFocus.SetKeyboardControl(temp); } m_IgnoreBeginGUI = false; messageControl = 0; } base.EndEditing(); } public string OnGUI(int id, string value, out bool changed) { Event evt = Event.current; if (evt.type == EventType.ExecuteCommand && evt.commandName == CommitCommand && id == messageControl) { m_CommitCommandSentOnLostFocus = false; // Only set changed to true if the value has actually changed. Otherwise EditorGUI.EndChangeCheck will report false positives, // which could for example cause unwanted undo's to be registered (in the case of e.g. editing terrain resolution, this can cause several seconds of delay) if (!showMixedValue || controlThatHadFocusValue != k_MultiEditValueString) changed = value != controlThatHadFocusValue; else changed = false; evt.Use(); messageControl = 0; return controlThatHadFocusValue; } changed = false; return value; } } internal sealed class PopupMenuEvent { public string commandName; public GUIView receiver; public PopupMenuEvent(string cmd, GUIView v) { commandName = cmd; receiver = v; } public void SendEvent() { if (receiver) { receiver.SendEvent(EditorGUIUtility.CommandEvent(commandName)); } else { Debug.LogError("BUG: We don't have a receiver set up, please report"); } } } static void ShowTextEditorPopupMenu() { GenericMenu pm = new GenericMenu(); var enabled = GUI.enabled; // Cut if (RecycledTextEditor.s_AllowContextCutOrPaste) { if ((s_RecycledEditor.hasSelection || s_DelayedTextEditor.hasSelection) && !s_RecycledEditor.isPasswordField && enabled && !EditorGUI.showMixedValue) pm.AddItem(EditorGUIUtility.TrTextContent("Cut"), false, new PopupMenuEvent(EventCommandNames.Cut, GUIView.current).SendEvent); else pm.AddDisabledItem(EditorGUIUtility.TrTextContent("Cut")); } // Copy -- when GUI is disabled, allow Copy even with no selection (will copy everything) if (((s_RecycledEditor.hasSelection || s_DelayedTextEditor.hasSelection) || !enabled) && !s_RecycledEditor.isPasswordField && !EditorGUI.showMixedValue) pm.AddItem(EditorGUIUtility.TrTextContent("Copy"), false, new PopupMenuEvent(EventCommandNames.Copy, GUIView.current).SendEvent); else pm.AddDisabledItem(EditorGUIUtility.TrTextContent("Copy")); // Paste if (s_RecycledEditor.CanPaste() && RecycledTextEditor.s_AllowContextCutOrPaste && enabled) { pm.AddItem(EditorGUIUtility.TrTextContent("Paste"), false, new PopupMenuEvent(EventCommandNames.Paste, GUIView.current).SendEvent); } else { // pm.AddDisabledItem (EditorGUIUtility.TrTextContent ("Paste")); } pm.ShowAsContext(); } // Is the platform-dependent "action" modifier key held down? (RO) public static bool actionKey { get { if (Event.current == null) { return false; } if (Application.platform == RuntimePlatform.OSXEditor) { return Event.current.command; } else { return Event.current.control; } } } [RequiredByNativeCode] internal static void BeginCollectTooltips() { isCollectingTooltips = true; } [RequiredByNativeCode] internal static void EndCollectTooltips() { isCollectingTooltips = false; } public static void DropShadowLabel(Rect position, string text) { DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), "PreOverlayLabel", .6f); } public static void DropShadowLabel(Rect position, GUIContent content) { DoDropShadowLabel(position, content, "PreOverlayLabel", .6f); } public static void DropShadowLabel(Rect position, string text, GUIStyle style) { DoDropShadowLabel(position, EditorGUIUtility.TempContent(text), style, .6f); } // Draws a label with a drop shadow. public static void DropShadowLabel(Rect position, GUIContent content, GUIStyle style) { DoDropShadowLabel(position, content, style, .6f); } internal static void DoDropShadowLabel(Rect position, GUIContent content, GUIStyle style, float shadowOpa) { if (Event.current.type != EventType.Repaint) { return; } DrawLabelShadow(position, content, style, shadowOpa); style.Draw(position, content, false, false, false, false); } internal static void DrawLabelShadow(Rect position, GUIContent content, GUIStyle style, float shadowOpa) { Color temp = GUI.color, temp2 = GUI.contentColor, temp3 = GUI.backgroundColor; // Draw only background GUI.contentColor = new Color(0, 0, 0, 0); style.Draw(position, content, false, false, false, false); // Blur foreground position.y += 1; GUI.backgroundColor = new Color(0, 0, 0, 0); GUI.contentColor = temp2; Draw4(position, content, 1, GUI.color.a * shadowOpa, style); Draw4(position, content, 2, GUI.color.a * shadowOpa * .42f, style); // Draw final foreground GUI.color = temp; GUI.backgroundColor = temp3; } private static void Draw4(Rect position, GUIContent content, float offset, float alpha, GUIStyle style) { GUI.color = new Color(0, 0, 0, alpha); position.y -= offset; style.Draw(position, content, false, false, false, false); position.y += offset * 2; style.Draw(position, content, false, false, false, false); position.y -= offset; position.x -= offset; style.Draw(position, content, false, false, false, false); position.x += offset * 2; style.Draw(position, content, false, false, false, false); } private static string ValidateTextLimit(String editorText) { string title = "Search String Character Limit Exceeded"; string fullMessage = string.Format("You have entered {0} characters. The character limit is {1} characters because of risk of Editor slowdown. Please confirm that you would like to continue (not recommended) or clear the field", editorText.Length, kSearchFieldTextLimit); bool selectedContinueOption = EditorUtility.DisplayDialog(title, fullMessage, "Continue", "Cancel"); if (selectedContinueOption) s_SearchFieldTextLimitApproved = true; else editorText = editorText.Substring(0, kSearchFieldTextLimit); GUIUtility.SetKeyboardControlToLastControlId(); return editorText; } static bool IsPrintableChar(char c) { if (c < 32) { return false; } return true; } internal static bool MightBePrintableKey(Event evt) { if (evt.command || evt.control) return false; if (evt.keyCode >= KeyCode.Mouse0 && evt.keyCode <= KeyCode.Mouse6) return false; if (evt.keyCode >= KeyCode.JoystickButton0 && evt.keyCode <= KeyCode.Joystick8Button19) return false; if (evt.keyCode >= KeyCode.F1 && evt.keyCode <= KeyCode.F15) return false; switch (evt.keyCode) { case KeyCode.AltGr: case KeyCode.Backspace: case KeyCode.CapsLock: case KeyCode.Clear: case KeyCode.Delete: case KeyCode.DownArrow: case KeyCode.End: case KeyCode.Escape: case KeyCode.Help: case KeyCode.Home: case KeyCode.Insert: case KeyCode.LeftAlt: case KeyCode.LeftArrow: case KeyCode.LeftCommand: // same as LeftApple case KeyCode.LeftControl: case KeyCode.LeftShift: case KeyCode.LeftWindows: case KeyCode.Menu: case KeyCode.Numlock: case KeyCode.PageDown: case KeyCode.PageUp: case KeyCode.Pause: case KeyCode.Print: case KeyCode.RightAlt: case KeyCode.RightArrow: case KeyCode.RightCommand: // same as RightApple case KeyCode.RightControl: case KeyCode.RightShift: case KeyCode.RightWindows: case KeyCode.ScrollLock: case KeyCode.SysReq: case KeyCode.UpArrow: return false; case KeyCode.None: return IsPrintableChar(evt.character); default: return true; } } static EventType GetEventTypeForControlAllowDisabledContextMenuPaste(Event evt, int id) { // UI is enabled: regular code path var wasEnabled = GUI.enabled; if (wasEnabled) return evt.GetTypeForControl(id); // UI is disabled: get type as if it was enabled GUI.enabled = true; var type = evt.GetTypeForControl(id); GUI.enabled = false; // these events are always processed, no matter the enabled/disabled state (IMGUI::GetEventType) if (type == EventType.Repaint || type == EventType.Layout || type == EventType.Used) return type; // allow context / right click, and "Copy" commands if (type == EventType.ContextClick) return type; if (type == EventType.MouseDown && evt.button == 1) return type; if ((type == EventType.ValidateCommand || type == EventType.ExecuteCommand) && evt.commandName == EventCommandNames.Copy) return type; // ignore all other events for disabled controls return EventType.Ignore; } internal static string DoTextField(RecycledTextEditor editor, int id, Rect position, string text, GUIStyle style, string allowedletters, out bool changed, bool reset, bool multiline, bool passwordField) { return DoTextField(editor, id, position, text, style, allowedletters, out changed, reset, multiline, passwordField, null); } // Should we select all text from the current field when the mouse goes up? // (We need to keep track of this to support both SwipeSelection & initial click selects all) internal static string DoTextField(RecycledTextEditor editor, int id, Rect position, string text, GUIStyle style, string allowedletters, out bool changed, bool reset, bool multiline, bool passwordField, GUIStyle cancelButtonStyle, bool checkTextLimit = false) { Event evt = Event.current; // If the text field represents multiple values, the text should always start out being empty when editing it. // This empty text will not be saved when simply clicking in the text field, or tabbing to it, // since GUI.changed is only set to true if the user alters the string. // Nevertheless, we also backup and return the original value if nothing changed. // It's just nice that output is the same as input when nothing changed, // even if the output should really be ignored when GUI.changed is false. string origText = text; // We assume the text is actually valid, but we do not want to change the returned value if nothing was changed // So we should only check for null string on the internal text and not affect the origText which will be returned if nothing changed if (text == null) { text = string.Empty; } if (showMixedValue) { text = k_MultiEditValueString; } // If we have keyboard control and our window have focus, we need to sync up the editor. if (HasKeyboardFocus(id) && Event.current.type != EventType.Layout) { // If the editor is already set up, we just need to sync position, etc... if (editor.IsEditingControl(id)) { // Fast path flag to ensure that we only update the scroll offset if the text area grew (dynamic height) bool requireUpdateScrollOffset = editor.position.height != position.height; editor.position = position; editor.style = style; editor.controlID = id; editor.isMultiline = multiline; editor.isPasswordField = passwordField; editor.DetectFocusChange(); editor.UpdateTextHandle(); if (requireUpdateScrollOffset) editor.UpdateScrollOffset(); } else if (EditorGUIUtility.editingTextField || (evt.GetTypeForControl(id) == EventType.ExecuteCommand && evt.commandName == EventCommandNames.NewKeyboardFocus)) { // This one is worse: we are the new keyboardControl, but didn't know about it. // this means a Tab operation or setting focus from code. editor.BeginEditing(id, text, position, style, multiline, passwordField); // If cursor is invisible, it's a selectable label, and we don't want to select all automatically if (GUI.skin.settings.cursorColor.a > 0) editor.SelectAll(); if (evt.GetTypeForControl(id) == EventType.ExecuteCommand) { evt.Use(); } } } // Inform editor that someone removed focus from us. if (editor.controlID == id && GUIUtility.keyboardControl != id || (evt.type == EventType.ValidateCommand && evt.commandName == EventCommandNames.UndoRedoPerformed)) { editor.EndEditing(); } bool mayHaveChanged = false; string textBeforeKey = editor.text; var wasEnabled = GUI.enabled; switch (GetEventTypeForControlAllowDisabledContextMenuPaste(evt, id)) { case EventType.ValidateCommand: if (GUIUtility.keyboardControl == id) { switch (evt.commandName) { case EventCommandNames.Cut: case EventCommandNames.Copy: if (editor.hasSelection) { evt.Use(); } break; case EventCommandNames.Paste: if (editor.CanPaste()) { evt.Use(); } break; case EventCommandNames.SelectAll: case EventCommandNames.Delete: evt.Use(); break; case EventCommandNames.UndoRedoPerformed: editor.text = text; evt.Use(); break; } } break; case EventType.ExecuteCommand: if (GUIUtility.keyboardControl == id) { switch (evt.commandName) { case EventCommandNames.OnLostFocus: activeEditor?.EndEditing(); evt.Use(); break; case EventCommandNames.Cut: editor.BeginEditing(id, text, position, style, multiline, passwordField); editor.Cut(); mayHaveChanged = true; break; case EventCommandNames.Copy: if (wasEnabled) editor.Copy(); else if (!passwordField) GUIUtility.systemCopyBuffer = text; evt.Use(); break; case EventCommandNames.Paste: editor.BeginEditing(id, text, position, style, multiline, passwordField); editor.Paste(); mayHaveChanged = true; break; case EventCommandNames.SelectAll: editor.SelectAll(); evt.Use(); break; case EventCommandNames.Delete: // This "Delete" command stems from a Shift-Delete in the text editor. // On Windows, Shift-Delete in text does a cut whereas on Mac, it does a delete. editor.BeginEditing(id, text, position, style, multiline, passwordField); if (SystemInfo.operatingSystemFamily == OperatingSystemFamily.MacOSX) { editor.Delete(); } else { editor.Cut(); } mayHaveChanged = true; evt.Use(); break; } } break; case EventType.MouseUp: if (GUIUtility.hotControl == id) { if (s_Dragged && s_DragToPosition) { //GUIUtility.keyboardControl = id; //editor.BeginEditing (id, text, position, style, multiline, passwordField); editor.MoveSelectionToAltCursor(); mayHaveChanged = true; } else if (s_SelectAllOnMouseUp) { // If cursor is invisible, it's a selectable label, and we don't want to select all automatically if (GUI.skin.settings.cursorColor.a > 0) { editor.SelectAll(); } s_SelectAllOnMouseUp = false; } else if (!s_Dragged && evt.button == 0) { // Extract hyperlink info Dictionary<string, string> hyperLinkData; if (editor.HasClickedOnHREF(Event.current.mousePosition, out string href)) { Application.OpenURL(href); } else if (HasClickedOnHyperlink(editor, out hyperLinkData)) // Check if the cursor is between hyperlink tags and store the hyperlink info (tag arguments in a dictionary) { // Raise event with the info var window = GUIView.current is HostView hostView ? hostView.actualView : null; hyperLinkClicked(window, new UnityEditor.HyperLinkClickedEventArgs(hyperLinkData)); } } editor.MouseDragSelectsWholeWords(false); s_DragToPosition = true; s_Dragged = false; if (evt.button == 0) { GUIUtility.hotControl = 0; evt.Use(); } } break; case EventType.MouseDown: if (position.Contains(evt.mousePosition) && evt.button == 0) { // Does this text field already have focus? if (editor.IsEditingControl(id)) { // if so, process the event normally if (Event.current.clickCount == 2 && GUI.skin.settings.doubleClickSelectsWord) { editor.MoveCursorToPosition(Event.current.mousePosition); editor.SelectCurrentWord(); editor.MouseDragSelectsWholeWords(true); editor.DblClickSnap(TextEditor.DblClickSnapping.WORDS); s_DragToPosition = false; } else if (Event.current.clickCount == 3 && GUI.skin.settings.tripleClickSelectsLine) { editor.MoveCursorToPosition(Event.current.mousePosition); editor.SelectCurrentParagraph(); editor.MouseDragSelectsWholeWords(true); editor.DblClickSnap(TextEditor.DblClickSnapping.PARAGRAPHS); s_DragToPosition = false; } else { editor.MoveCursorToPosition(Event.current.mousePosition); s_SelectAllOnMouseUp = false; } } else { // Otherwise, mark this as initial click and begin editing GUIUtility.keyboardControl = id; editor.BeginEditing(id, text, position, style, multiline, passwordField); editor.MoveCursorToPosition(Event.current.mousePosition); // If cursor is invisible, it's a selectable label, and we don't want to select all automatically if (GUI.skin.settings.cursorColor.a > 0) { s_SelectAllOnMouseUp = true; } } GUIUtility.hotControl = id; evt.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { if (!evt.shift && editor.hasSelection && s_DragToPosition) { editor.MoveAltCursorToPosition(Event.current.mousePosition); } else { if (evt.shift) { editor.MoveCursorToPosition(Event.current.mousePosition); } else { editor.SelectToPosition(Event.current.mousePosition); } s_DragToPosition = false; s_SelectAllOnMouseUp = !editor.hasSelection; } s_Dragged = true; evt.Use(); } break; case EventType.ContextClick: if (position.Contains(evt.mousePosition)) { if (!editor.IsEditingControl(id)) { // First click: focus before showing popup GUIUtility.keyboardControl = id; if (wasEnabled) { editor.BeginEditing(id, text, position, style, multiline, passwordField); editor.MoveCursorToPosition(Event.current.mousePosition); } } ShowTextEditorPopupMenu(); Event.current.Use(); } break; case EventType.KeyDown: var nonPrintableTab = false; if (GUIUtility.keyboardControl == id) { char c = evt.character; // Let the editor handle all cursor keys, etc... if (editor.IsEditingControl(id) && editor.HandleKeyEvent(evt)) { evt.Use(); mayHaveChanged = true; break; } if (evt.keyCode == KeyCode.Escape) { if (editor.IsEditingControl(id)) { if (style == EditorStyles.toolbarSearchField || style == EditorStyles.searchField || style.name.Contains("SearchText")) { s_OriginalText = ""; } if (s_PropertyStack.Count > 0) { if (s_RecycledEditor.GetOriginalDoubleValues() != null) s_PropertyStack.Peek().property.allDoubleValues = s_RecycledEditor.GetOriginalDoubleValues(); if (s_RecycledEditor.GetOriginalLongValues() != null) s_PropertyStack.Peek().property.allLongValues = s_RecycledEditor.GetOriginalLongValues(); } editor.text = s_OriginalText; editor.EndEditing(); mayHaveChanged = true; } } else if (c == '\n' || c == 3) { if (!editor.IsEditingControl(id)) { editor.BeginEditing(id, text, position, style, multiline, passwordField); editor.SelectAll(); } else { if (!multiline || (evt.alt || evt.shift || evt.control)) { editor.EndEditing(); } else { editor.Insert(c); mayHaveChanged = true; break; } } evt.Use(); } else if (c == '\t' || evt.keyCode == KeyCode.Tab) { // Only insert tabs if multiline if (multiline && editor.IsEditingControl(id)) { bool validTabCharacter = (allowedletters == null || allowedletters.IndexOf(c) != -1); bool validTabEvent = !(evt.alt || evt.shift || evt.control) && c == '\t'; if (validTabEvent && validTabCharacter) { editor.Insert(c); mayHaveChanged = true; } } else { nonPrintableTab = true; } } else if (c == 25 || c == 27) { // Note, OS X send characters for the following keys that we need to eat: // ASCII 25: "End Of Medium" on pressing shift tab // ASCII 27: "Escape" on pressing ESC nonPrintableTab = true; } else if (editor.IsEditingControl(id)) { bool validCharacter = (allowedletters == null || allowedletters.IndexOf(c) != -1) && IsPrintableChar(c); if (validCharacter) { editor.Insert(c); mayHaveChanged = true; } else { // If the composition string is not empty, then it's likely that even though we didn't add a printable // character to the string, we should refresh the GUI, to update the composition string. if (Input.compositionString != "") { editor.ReplaceSelection(""); mayHaveChanged = true; } } } // consume Keycode events that might result in a printable key so they aren't passed on to other controls or shortcut manager later if ( editor.IsEditingControl(id) && MightBePrintableKey(evt) && !nonPrintableTab // only consume tabs that actually result in a character (above) so we don't disable tabbing between keyboard controls ) { evt.Use(); } } break; case EventType.Repaint: string drawText; if (editor.IsEditingControl(id)) { if (showMixedValue && editor.text == k_MultiEditValueString) drawText = string.Empty; else drawText = passwordField ? "".PadRight(editor.text.Length, '*') : editor.text; } else if (showMixedValue) { drawText = s_MixedValueContent.text; } else { drawText = passwordField ? "".PadRight(text.Length, '*') : text; } if (!string.IsNullOrEmpty(s_UnitString) && !passwordField) drawText += " " + s_UnitString; if (!editor.IsEditingControl(id)) { BeginHandleMixedValueContentColor(); style.Draw(position, EditorGUIUtility.TempContent(drawText), id, false, position.Contains(Event.current.mousePosition)); EndHandleMixedValueContentColor(); } else { editor.DrawCursor(drawText); } var cursorRect = position; if (cancelButtonStyle != null && !String.IsNullOrEmpty(text)) cursorRect.width -= cancelButtonStyle.fixedWidth; if (cursorRect.Contains(evt.mousePosition)) { bool showLinkCursor = false; // Add the link cursor for the hyperlinks found on the editor foreach (var rect in editor.GetHyperlinksRect()) { EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link); if (!showLinkCursor && rect.Contains(evt.mousePosition)) showLinkCursor = true; } // Only change mouse cursor if hotcontrol is not grabbed if (!showLinkCursor && GUIUtility.hotControl == 0) EditorGUIUtility.AddCursorRect(cursorRect, MouseCursor.Text); } break; case EventType.ScrollWheel: // Scroll offset might need to be updated editor.UpdateScrollOffset(); break; } if (GUIUtility.keyboardControl == id) { // TODO: remove the need for this with Optimized GUI blocks GUIUtility.textFieldInput = EditorGUIUtility.editingTextField; } changed = false; if (mayHaveChanged) { // If some action happened that could change the text AND // the text actually changed, then set changed to true. // Don't just compare the text only, since it also changes when changing text field. // Don't leave out comparing the text though, since it will result in false positives. changed = (textBeforeKey != editor.text); evt.Use(); } if (changed) { if (GUIUtility.keyboardControl != s_SavekeyboardControl) { s_SavekeyboardControl = GUIUtility.keyboardControl; s_SearchFieldTextLimitApproved = false; } if (editor.text.Length > kSearchFieldTextLimit && checkTextLimit) { if ((evt.control || evt.command || evt.commandName == EventCommandNames.Paste) && !s_SearchFieldTextLimitApproved) { editor.text = ValidateTextLimit(editor.text); } else if (editor.text.Length == kSearchFieldTextLimit + 1 && evt.keyCode != KeyCode.Backspace && !s_SearchFieldTextLimitApproved) { editor.text = ValidateTextLimit(editor.text); } } GUI.changed = true; return editor.text; } RecycledTextEditor.s_AllowContextCutOrPaste = true; return origText; } private static bool HasClickedOnHyperlink(RecycledTextEditor editor, out Dictionary<string, string> hyperLinkData) { hyperLinkData = new Dictionary<string, string>(); Vector2 mousePosition = Event.current.mousePosition; if (!editor.HasClickedOnLink(mousePosition, out string link)) return false; MatchCollection matches = s_ATagRegex.Matches(link); if (matches.Count == 0) matches = s_LinkTagRegex.Matches(link); int endPreviousAttributeIndex = 0; // for each attribute we need to find the attribute name foreach (Match match in matches) { // We are only working on the text between the previous attribute and the current string namePart = link.Substring(endPreviousAttributeIndex, (match.Index - 2) - endPreviousAttributeIndex); // -2 is the character before =" int indexName = namePart.LastIndexOf(' ') + 1; string name = namePart.Substring(indexName); // Add the name of the attribute and its value in the dictionary hyperLinkData.Add(name, match.Value); endPreviousAttributeIndex = match.Index + match.Value.Length + 1; } return true; } public static event Action<EditorWindow, UnityEditor.HyperLinkClickedEventArgs> hyperLinkClicked; private static void EditorGUI_OpenFileOnHyperLinkClicked(EditorWindow window, UnityEditor.HyperLinkClickedEventArgs args) { string path; if (!args.hyperLinkData.TryGetValue("href", out path)) return; string lineString; args.hyperLinkData.TryGetValue("line", out lineString); int line = -1; Int32.TryParse(lineString, out line); var sanitizedPath = path.Replace('\\', '/'); if (!String.IsNullOrEmpty(sanitizedPath)) { if (Uri.IsWellFormedUriString(sanitizedPath, UriKind.Absolute)) Application.OpenURL(path); else LogEntries.OpenFileOnSpecificLineAndColumn(path, line, -1); } } // KEYEVENTFIELD HERE =============================================================== internal static Event KeyEventField(Rect position, Event evt) { return DoKeyEventField(position, evt, GUI.skin.textField); } internal static Event DoKeyEventField(Rect position, Event _event, GUIStyle style) { int id = GUIUtility.GetControlID(s_KeyEventFieldHash, FocusType.Passive, position); Event evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: // If the mouse is inside the button, we say that we're the hot control if (position.Contains(evt.mousePosition)) { GUIUtility.hotControl = id; evt.Use(); bKeyEventActive = !bKeyEventActive; EditorGUIUtility.editingTextField = bKeyEventActive; } return _event; case EventType.MouseUp: if (GUIUtility.hotControl == id) { GUIUtility.hotControl = id; // If we got the mousedown, the mouseup is ours as well // (no matter if the click was in the button or not) evt.Use(); } return _event; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { evt.Use(); } break; case EventType.Repaint: if (bKeyEventActive) { style.Draw(position, s_PleasePressAKey, id); } else { string str = InternalEditorUtility.TextifyEvent(_event); style.Draw(position, EditorGUIUtility.TempContent(str), id); } break; case EventType.KeyDown: if ((GUIUtility.hotControl == id) && bKeyEventActive) { // ignore presses of just modifier keys if (evt.character == '\0') { if (evt.alt && (evt.keyCode == KeyCode.AltGr || evt.keyCode == KeyCode.LeftAlt || evt.keyCode == KeyCode.RightAlt) || evt.control && (evt.keyCode == KeyCode.LeftControl || evt.keyCode == KeyCode.RightControl) || evt.command && (evt.keyCode == KeyCode.LeftApple || evt.keyCode == KeyCode.RightApple || evt.keyCode == KeyCode.LeftWindows || evt.keyCode == KeyCode.RightWindows) || evt.shift && (evt.keyCode == KeyCode.LeftShift || evt.keyCode == KeyCode.RightShift || (int)evt.keyCode == 0)) { return _event; } } bKeyEventActive = false; GUI.changed = true; GUIUtility.hotControl = 0; EditorGUIUtility.editingTextField = false; Event e = new Event(evt); evt.Use(); return e; } break; } return _event; } internal static Rect GetInspectorTitleBarObjectFoldoutRenderRect(Rect rect) { return GetInspectorTitleBarObjectFoldoutRenderRect(rect, null); } internal static Rect GetInspectorTitleBarObjectFoldoutRenderRect(Rect rect, GUIStyle baseStyle) { return new Rect(rect.x + EditorStyles.titlebarFoldout.margin.left + 1f, rect.y + (rect.height - kInspTitlebarFoldoutIconWidth) / 2 + (baseStyle != null ? baseStyle.padding.top : 0), kInspTitlebarFoldoutIconWidth, kInspTitlebarFoldoutIconWidth); } [SuppressMessage("ReSharper", "RedundantCast.0")] [SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse")] [SuppressMessage("ReSharper", "HeuristicUnreachableCode")] static bool IsValidForContextMenu(Object target) { // if the reference is *really* null, don't allow showing the context menu if ((object)target == null) return false; // UnityEngine.Object overrides == null, which means we might be dealing with an invalid object bool isUnityNull = target == null; // if scripted object compares to null, then we are dealing with a missing script // for which we still want to display context menu if (isUnityNull && NativeClassExtensionUtilities.ExtendsANativeType(target.GetType())) return true; return !isUnityNull; } internal static bool DoObjectMouseInteraction(bool foldout, Rect interactionRect, Object[] targetObjs, int id) { // Always enabled, regardless of editor enabled state var enabled = GUI.enabled; GUI.enabled = true; // Context menu Event evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (interactionRect.Contains(evt.mousePosition)) { if (evt.button == 0 && !(Application.platform == RuntimePlatform.OSXEditor && evt.control)) { GUIUtility.hotControl = id; GUIUtility.keyboardControl = id; DragAndDropDelay delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); delay.mouseDownPosition = evt.mousePosition; evt.Use(); } } break; case EventType.ContextClick: if (interactionRect.Contains(evt.mousePosition) && IsValidForContextMenu(targetObjs[0])) { EditorUtility.DisplayObjectContextMenu(new Rect(evt.mousePosition.x, evt.mousePosition.y, 0, 0), targetObjs, 0); evt.Use(); } break; case EventType.MouseUp: if (GUIUtility.hotControl == id) { GUIUtility.hotControl = 0; evt.Use(); if (interactionRect.Contains(evt.mousePosition)) { GUI.changed = true; foldout = !foldout; } } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { DragAndDropDelay delay = (DragAndDropDelay)GUIUtility.GetStateObject(typeof(DragAndDropDelay), id); if (delay.CanStartDrag()) { GUIUtility.hotControl = 0; DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = targetObjs; DragAndDrop.StartDrag(targetObjs.Length > 1 ? "<Multiple>" : ObjectNames.GetDragAndDropTitle(targetObjs[0])); } evt.Use(); } break; case EventType.DragUpdated: if (s_DragUpdatedOverID == id) { if (interactionRect.Contains(evt.mousePosition)) { if (Time.realtimeSinceStartup > s_FoldoutDestTime) { foldout = true; HandleUtility.Repaint(); } } else { s_DragUpdatedOverID = 0; } } else { if (interactionRect.Contains(evt.mousePosition)) { s_DragUpdatedOverID = id; s_FoldoutDestTime = Time.realtimeSinceStartup + kFoldoutExpandTimeout; } } if (interactionRect.Contains(evt.mousePosition)) { DragAndDrop.visualMode = DragAndDrop.DropOnInspectorWindow(targetObjs, false); Event.current.Use(); } break; case EventType.DragPerform: if (interactionRect.Contains(evt.mousePosition)) { DragAndDrop.visualMode = DragAndDrop.DropOnInspectorWindow(targetObjs, true); DragAndDrop.AcceptDrag(); Event.current.Use(); } break; case EventType.KeyDown: if (GUIUtility.keyboardControl == id) { if (evt.keyCode == KeyCode.LeftArrow) { foldout = false; evt.Use(); } if (evt.keyCode == KeyCode.RightArrow) { foldout = true; evt.Use(); } } break; } // Restore enabled state for the editors. GUI.enabled = enabled; return foldout; } // This is assumed to be called from the inspector only private static void DoObjectFoldoutInternal(bool foldout, Rect renderRect, int id) { // Always enabled, regardless of editor enabled state var enabled = GUI.enabled; GUI.enabled = true; // Context menu Event evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.Repaint: bool isPressed = GUIUtility.hotControl == id; EditorStyles.titlebarFoldout.Draw(renderRect, isPressed, isPressed, foldout, false); break; } // Restore enabled state for the editors. GUI.enabled = enabled; } internal static bool DoObjectFoldout(bool foldout, Rect interactionRect, Rect renderRect, Object[] targetObjs, int id) { foldout = DoObjectMouseInteraction(foldout, interactionRect, targetObjs, id); DoObjectFoldoutInternal(foldout, renderRect, id); return foldout; } // Make a label field. (Useful for showing read-only info.) internal static void LabelFieldInternal(Rect position, GUIContent label, GUIContent label2, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Passive, position); position = PrefixLabel(position, id, label); if (Event.current.type == EventType.Repaint) { style.Draw(position, label2, id); } } public static bool Toggle(Rect position, bool value) { int id = GUIUtility.GetControlID(s_ToggleHash, FocusType.Keyboard, position); return EditorGUIInternal.DoToggleForward(IndentedRect(position), id, value, GUIContent.none, EditorStyles.toggle); } public static bool Toggle(Rect position, string label, bool value) { return Toggle(position, EditorGUIUtility.TempContent(label), value); } public static bool Toggle(Rect position, bool value, GUIStyle style) { int id = GUIUtility.GetControlID(s_ToggleHash, FocusType.Keyboard, position); return EditorGUIInternal.DoToggleForward(position, id, value, GUIContent.none, style); } public static bool Toggle(Rect position, string label, bool value, GUIStyle style) { return Toggle(position, EditorGUIUtility.TempContent(label), value, style); } public static bool Toggle(Rect position, GUIContent label, bool value) { int id = GUIUtility.GetControlID(s_ToggleHash, FocusType.Keyboard, position); return EditorGUIInternal.DoToggleForward(PrefixLabel(position, id, label), id, value, GUIContent.none, EditorStyles.toggle, false); } // Make a toggle. public static bool Toggle(Rect position, GUIContent label, bool value, GUIStyle style) { int id = GUIUtility.GetControlID(s_ToggleHash, FocusType.Keyboard, position); return EditorGUIInternal.DoToggleForward(PrefixLabel(position, id, label), id, value, GUIContent.none, style); } // Make a toggle with the label on the right. internal static bool ToggleLeftInternal(Rect position, GUIContent label, bool value, GUIStyle labelStyle) { int id = GUIUtility.GetControlID(s_ToggleHash, FocusType.Keyboard, position); Rect toggleRect = IndentedRect(position); Rect labelRect = IndentedRect(position); var topOffset = (EditorStyles.toggle.margin.top - EditorStyles.toggle.margin.bottom) / 2; labelRect.xMin += EditorStyles.toggle.padding.left; labelRect.yMin -= topOffset; labelRect.yMax -= topOffset; HandlePrefixLabel(position, labelRect, label, id, labelStyle); return EditorGUIInternal.DoToggleForward(toggleRect, id, value, GUIContent.none, EditorStyles.toggle); } internal static bool DoToggle(Rect position, int id, bool value, GUIContent content, GUIStyle style) { return EditorGUIInternal.DoToggleForward(position, id, value, content, style); } internal static string TextFieldInternal(int id, Rect position, string text, GUIStyle style) { bool dummy; text = DoTextField(s_RecycledEditor, id, IndentedRect(position), text, style, null, out dummy, false, false, false); return text; } internal static string TextFieldInternal(int id, Rect position, string text, GUIStyle style, GUIStyle cancelButtonStyle) { bool dummy; text = DoTextField(s_RecycledEditor, id, IndentedRect(position), text, style, null, out dummy, false, false, false, cancelButtonStyle); return text; } internal static string TextFieldInternal(Rect position, string text, GUIStyle style) { int id = GUIUtility.GetControlID(s_TextFieldHash, FocusType.Keyboard, position); bool dummy; text = DoTextField(s_RecycledEditor, id, IndentedRect(position), text, style, null, out dummy, false, false, false); return text; } // Make a text field. internal static string TextFieldInternal(Rect position, GUIContent label, string text, GUIStyle style) { int id = GUIUtility.GetControlID(s_TextFieldHash, FocusType.Keyboard, position); bool dummy; text = DoTextField(s_RecycledEditor, id, PrefixLabel(position, id, label), text, style, null, out dummy, false, false, false); return text; } internal static string TextFieldInternal(int id, Rect position, GUIContent label, string text, GUIStyle style) { bool dummy; text = DoTextField(s_RecycledEditor, id, PrefixLabel(position, id, label), text, style, null, out dummy, false, false, false); return text; } internal static string ToolbarSearchField(Rect position, string text, bool showWithPopupArrow) { int id = GUIUtility.GetControlID(s_SearchFieldHash, FocusType.Keyboard, position); return ToolbarSearchField(id, position, text, showWithPopupArrow); } internal static string ToolbarSearchField(int id, Rect position, string text, bool showWithPopupArrow) { return ToolbarSearchField( id, position, text, showWithPopupArrow ? EditorStyles.toolbarSearchFieldPopup : EditorStyles.toolbarSearchField, text != "" ? EditorStyles.toolbarSearchFieldCancelButton : EditorStyles.toolbarSearchFieldCancelButtonEmpty); } internal static string ToolbarSearchField(int id, Rect position, string text, GUIStyle searchFieldStyle, GUIStyle cancelButtonStyle) { bool dummy; Rect textRect = position; const float k_CancelButtonWidth = 14f; Rect buttonRect = position; buttonRect.x += position.width - k_CancelButtonWidth; buttonRect.width = k_CancelButtonWidth; if (!String.IsNullOrEmpty(text)) EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Arrow); if (Event.current.type == EventType.MouseUp && buttonRect.Contains(Event.current.mousePosition)) { s_RecycledEditor.text = text = ""; GUI.changed = true; } text = DoTextField(s_RecycledEditor, id, textRect, text, searchFieldStyle, null, out dummy, false, false, false, cancelButtonStyle, true); GUI.Button(buttonRect, GUIContent.none, cancelButtonStyle); return text; } internal static string ToolbarSearchField(Rect position, string[] searchModes, ref int searchMode, string text) { int id = GUIUtility.GetControlID(s_SearchFieldHash, FocusType.Keyboard, position); return ToolbarSearchField(id, position, searchModes, ref searchMode, text); } internal static string ToolbarSearchField(int id, Rect position, string[] searchModes, ref int searchMode, string text) { return ToolbarSearchField( id, position, searchModes, ref searchMode, text, EditorStyles.toolbarSearchFieldPopup, EditorStyles.toolbarSearchField, text != "" ? EditorStyles.toolbarSearchFieldCancelButton : EditorStyles.toolbarSearchFieldCancelButtonEmpty); } internal static string ToolbarSearchField(int id, Rect position, string[] searchModes, ref int searchMode, string text, GUIStyle searchFieldWithPopupStyle, GUIStyle searchFieldNoPopupStyle, GUIStyle cancelButtonStyle) { bool hasPopup = searchModes != null; if (hasPopup) { searchMode = PopupCallbackInfo.GetSelectedValueForControl(id, searchMode); Rect popupPosition = position; popupPosition.width = 20; if (Event.current.type == EventType.MouseDown && popupPosition.Contains(Event.current.mousePosition)) { PopupCallbackInfo.instance = new PopupCallbackInfo(id); EditorUtility.DisplayCustomMenu(position, EditorGUIUtility.TempContent(searchModes), searchMode, PopupCallbackInfo.instance.SetEnumValueDelegate, null); if (s_RecycledEditor.IsEditingControl(id)) { Event.current.Use(); } } } text = ToolbarSearchField(id, position, text, hasPopup ? searchFieldWithPopupStyle : searchFieldNoPopupStyle, cancelButtonStyle); if (hasPopup && text == "" && !s_RecycledEditor.IsEditingControl(id) && Event.current.type == EventType.Repaint) { using (new DisabledScope(true)) { var placeHolderTextRect = EditorStyles.toolbarSearchFieldPopup.padding.Remove(new Rect(position.x, position.y, position.width , EditorStyles.toolbarSearchFieldPopup.fixedHeight > 0 ? EditorStyles.toolbarSearchFieldPopup.fixedHeight : position.height)); var oldFontSize = EditorStyles.label.fontSize; EditorStyles.label.fontSize = EditorStyles.toolbarSearchFieldPopup.fontSize; EditorStyles.label.Draw(placeHolderTextRect, EditorGUIUtility.TempContent(searchModes[searchMode]), false, false, false, false); EditorStyles.label.fontSize = oldFontSize; } } return text; } internal static string SearchField(Rect position, string text) { int id = GUIUtility.GetControlID(s_SearchFieldHash, FocusType.Keyboard, position); bool dummy; Rect textRect = position; textRect.width -= 15; text = DoTextField(s_RecycledEditor, id, textRect, text, EditorStyles.searchField, null, out dummy, false, false, false); Rect buttonRect = position; buttonRect.x += position.width - 15; buttonRect.width = 15; if (GUI.Button(buttonRect, GUIContent.none, text != "" ? EditorStyles.searchFieldCancelButton : EditorStyles.searchFieldCancelButtonEmpty) && text != "") { s_RecycledEditor.text = text = ""; GUIUtility.keyboardControl = 0; } return text; } internal static string ScrollableTextAreaInternal(Rect position, string text, ref Vector2 scrollPosition, GUIStyle style) { if (Event.current.type == EventType.Layout) return text; int id = GUIUtility.GetControlID(s_TextAreaHash, FocusType.Keyboard, position); position = IndentedRect(position); float fullTextHeight = style.CalcHeight(GUIContent.Temp(text), position.width); Rect viewRect = new Rect(0, 0, position.width, fullTextHeight); Vector2 oldStyleScrollValue = style.contentOffset; if (position.height < viewRect.height) { //Scroll bar position Rect scrollbarPosition = position; scrollbarPosition.width = GUI.skin.verticalScrollbar.fixedWidth; scrollbarPosition.height -= 2; scrollbarPosition.y += 1; scrollbarPosition.x = position.x + position.width - scrollbarPosition.width; position.width -= scrollbarPosition.width; //textEditor width changed, recalculate Text and viewRect areas. fullTextHeight = style.CalcHeight(GUIContent.Temp(text), position.width); viewRect = new Rect(0, 0, position.width, fullTextHeight); if (position.Contains(Event.current.mousePosition) && Event.current.type == EventType.ScrollWheel) { const float mouseWheelMultiplier = 10f; float desiredY = scrollPosition.y + Event.current.delta.y * mouseWheelMultiplier; scrollPosition.y = Mathf.Clamp(desiredY, 0f, viewRect.height); Event.current.Use(); } scrollPosition.y = GUI.VerticalScrollbar(scrollbarPosition, scrollPosition.y, position.height, 0, viewRect.height); if (!s_RecycledEditor.IsEditingControl(id)) { //When not editing we use the style.draw, so we need to change the offset on the style instead of the RecycledEditor. style.contentOffset -= scrollPosition; style.Internal_clipOffset = scrollPosition; } else { //Move the Editor offset to match our scrollbar s_RecycledEditor.scrollOffset = scrollPosition; } } bool dummy; EventType beforeTextFieldEventType = Event.current.type; string newValue = DoTextField(s_RecycledEditor, id, position, text, style, null, out dummy, false, true, false); //Only update the our scrollPosition if the user has interacted with the TextArea (the current event was used) if (beforeTextFieldEventType != Event.current.type) { scrollPosition = s_RecycledEditor.scrollOffset; } style.contentOffset = oldStyleScrollValue; style.Internal_clipOffset = Vector2.zero; return newValue; } // Make a text area. internal static string TextAreaInternal(Rect position, string text, GUIStyle style) { int id = GUIUtility.GetControlID(s_TextAreaHash, FocusType.Keyboard, position); bool dummy; text = DoTextField(s_RecycledEditor, id, IndentedRect(position), text, style, null, out dummy, false, true, false); return text; } // Make a selectable label field. (Useful for showing read-only info that can be copy-pasted.) internal static void SelectableLabelInternal(Rect position, string text, GUIStyle style) { int id = GUIUtility.GetControlID(s_SelectableLabelHash, FocusType.Keyboard, position); Event e = Event.current; var sendEventToTextEditor = true; if (GUIUtility.keyboardControl == id && e.GetTypeForControl(id) == EventType.KeyDown) { switch (e.keyCode) { case KeyCode.LeftArrow: case KeyCode.RightArrow: case KeyCode.UpArrow: case KeyCode.DownArrow: case KeyCode.Home: case KeyCode.End: case KeyCode.PageUp: case KeyCode.PageDown: break; case KeyCode.Space: GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; break; default: sendEventToTextEditor = false; break; } } if (e.type == EventType.ExecuteCommand && (e.commandName == EventCommandNames.Paste || e.commandName == EventCommandNames.Cut) && GUIUtility.keyboardControl == id) { sendEventToTextEditor = false; } // Its possible that DoTextField will throw so we use a scoped cursor that we can safely reset the color. using (new CursorColorScope(Color.clear)) { RecycledTextEditor.s_AllowContextCutOrPaste = false; if (sendEventToTextEditor) { bool dummy; DoTextField(s_RecycledEditor, id, IndentedRect(position), text, style, string.Empty, out dummy, false, true, false); } } } [Obsolete("Use PasswordField instead.")] public static string DoPasswordField(int id, Rect position, string password, GUIStyle style) { bool guiChanged; return DoTextField(s_RecycledEditor, id, position, password, style, null, out guiChanged, false, false, true); } [Obsolete("Use PasswordField instead.")] public static string DoPasswordField(int id, Rect position, GUIContent label, string password, GUIStyle style) { bool guiChanged; return DoTextField(s_RecycledEditor, id, PrefixLabel(position, id, label), password, style, null, out guiChanged, false, false, true); } internal static string PasswordFieldInternal(Rect position, string password, GUIStyle style) { int id = GUIUtility.GetControlID(s_PasswordFieldHash, FocusType.Keyboard, position); bool guiChanged; return DoTextField(s_RecycledEditor, id, IndentedRect(position), password, style, null, out guiChanged, false, false, true); } // Make a text field where the user can enter a password. internal static string PasswordFieldInternal(Rect position, GUIContent label, string password, GUIStyle style) { int id = GUIUtility.GetControlID(s_PasswordFieldHash, FocusType.Keyboard, position); bool guiChanged; return DoTextField(s_RecycledEditor, id, PrefixLabel(position, id, label), password, style, null, out guiChanged, false, false, true); } internal static float FloatFieldInternal(Rect position, float value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); return DoFloatField(s_RecycledEditor, IndentedRect(position), new Rect(0, 0, 0, 0), id, value, kFloatFieldFormatString, style, false); } // Make a text field for entering floats. internal static float FloatFieldInternal(Rect position, GUIContent label, float value, GUIStyle style) { NumberFieldValue v = new NumberFieldValue(value); FloatFieldInternal(position, label, ref v, style); return MathUtils.ClampToFloat(v.doubleVal); } internal static void FloatFieldInternal(Rect position, GUIContent label, ref NumberFieldValue value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); Rect position2 = PrefixLabel(position, id, label); position.xMax = position2.x; var dragSensitivity = Event.current.GetTypeForControl(id) == EventType.MouseDown ? (float)NumericFieldDraggerUtility.CalculateFloatDragSensitivity(s_DragStartValue) : 0.0f; DoNumberField(s_RecycledEditor, position2, position, id, ref value, kFloatFieldFormatString, style, true, dragSensitivity); } internal static double DoubleFieldInternal(Rect position, double value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); return DoDoubleField(s_RecycledEditor, IndentedRect(position), new Rect(0, 0, 0, 0), id, value, kDoubleFieldFormatString, style, false); } // Make a text field for entering floats. internal static double DoubleFieldInternal(Rect position, GUIContent label, double value, GUIStyle style) { NumberFieldValue v = new NumberFieldValue(value); DoubleFieldInternal(position, label, ref v, style); return v.doubleVal; } internal static void DoubleFieldInternal(Rect position, GUIContent label, ref NumberFieldValue value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); Rect position2 = PrefixLabel(position, id, label); position.xMax = position2.x; var dragSensitivity = Event.current.GetTypeForControl(id) == EventType.MouseDown ? NumericFieldDraggerUtility.CalculateFloatDragSensitivity(s_DragStartValue) : 0.0; DoNumberField(s_RecycledEditor, position2, position, id, ref value, kDoubleFieldFormatString, style, true, dragSensitivity); } // Handle dragging of value internal static void DragNumberValue(Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, double dragSensitivity) { NumberFieldValue v = default; v.isDouble = isDouble; v.doubleVal = doubleVal; v.longVal = longVal; DragNumberValue(dragHotZone, id, ref v, dragSensitivity); doubleVal = v.doubleVal; longVal = v.longVal; } static void DragNumberValue(Rect dragHotZone, int id, ref NumberFieldValue value, double dragSensitivity) { Event evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (GUIUtility.HitTest(dragHotZone, evt) && evt.button == 0) { // When clicking the dragging rect ensure that the number field is not // editing: otherwise we don't see the actual value but the edited temp value EditorGUIUtility.editingTextField = false; GUIUtility.hotControl = id; activeEditor?.EndEditing(); evt.Use(); GUIUtility.keyboardControl = id; s_DragCandidateState = DragCandidateState.InitiatedDragging; s_DragStartValue = value.doubleVal; s_DragStartIntValue = value.longVal; s_DragStartPos = evt.mousePosition; s_DragSensitivity = dragSensitivity; evt.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } break; case EventType.MouseUp: if (GUIUtility.hotControl == id && s_DragCandidateState != DragCandidateState.NotDragging) { GUIUtility.hotControl = 0; s_DragCandidateState = DragCandidateState.NotDragging; evt.Use(); EditorGUIUtility.SetWantsMouseJumping(0); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { switch (s_DragCandidateState) { case DragCandidateState.InitiatedDragging: if ((Event.current.mousePosition - s_DragStartPos).sqrMagnitude > kDragDeadzone) { s_DragCandidateState = DragCandidateState.CurrentlyDragging; GUIUtility.keyboardControl = id; } evt.Use(); break; case DragCandidateState.CurrentlyDragging: // Don't change the editor.content.text here. // Instead, wait for scripting validation to enforce clamping etc. and then // update the editor.content.text in the repaint event. if (value.isDouble) { value.doubleVal += HandleUtility.niceMouseDelta * s_DragSensitivity; value.doubleVal = MathUtils.RoundBasedOnMinimumDifference(value.doubleVal, s_DragSensitivity); } else { value.longVal += (long)Math.Round(HandleUtility.niceMouseDelta * s_DragSensitivity); } value.success = true; GUI.changed = true; evt.Use(); break; } } break; case EventType.KeyDown: if (GUIUtility.hotControl == id && evt.keyCode == KeyCode.Escape && s_DragCandidateState != DragCandidateState.NotDragging) { value.doubleVal = s_DragStartValue; value.longVal = s_DragStartIntValue; value.success = true; GUI.changed = true; // s_LastEditorControl = -1; GUIUtility.hotControl = 0; evt.Use(); } break; case EventType.Repaint: EditorGUIUtility.AddCursorRect(dragHotZone, MouseCursor.SlideArrow); break; } } internal static float DoFloatField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable) { return DoFloatField(editor, position, dragHotZone, id, value, formatString, style, draggable, Event.current.GetTypeForControl(id) == EventType.MouseDown ? (float)NumericFieldDraggerUtility.CalculateFloatDragSensitivity(s_DragStartValue) : 0.0f); } internal static float DoFloatField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, float value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) { long dummy = 0; double doubleValue = value; DoNumberField(editor, position, dragHotZone, id, true, ref doubleValue, ref dummy, formatString, style, draggable, dragSensitivity); return MathUtils.ClampToFloat(doubleValue); } internal static int DoIntField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, int value, string formatString, GUIStyle style, bool draggable, float dragSensitivity) { double dummy = 0f; long longValue = value; DoNumberField(editor, position, dragHotZone, id, false, ref dummy, ref longValue, formatString, style, draggable, dragSensitivity); return MathUtils.ClampToInt(longValue); } internal static double DoDoubleField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, double value, string formatString, GUIStyle style, bool draggable) { return DoDoubleField(editor, position, dragHotZone, id, value, formatString, style, draggable, Event.current.GetTypeForControl(id) == EventType.MouseDown ? NumericFieldDraggerUtility.CalculateFloatDragSensitivity(s_DragStartValue) : 0.0); } internal static double DoDoubleField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, double value, string formatString, GUIStyle style, bool draggable, double dragSensitivity) { long dummy = 0; DoNumberField(editor, position, dragHotZone, id, true, ref value, ref dummy, formatString, style, draggable, dragSensitivity); return value; } internal static long DoLongField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, long value, string formatString, GUIStyle style, bool draggable, double dragSensitivity) { double dummy = 0f; DoNumberField(editor, position, dragHotZone, id, false, ref dummy, ref value, formatString, style, draggable, dragSensitivity); return value; } // allowed characters in a float field, that encompass: // - numbers, // - infinity/nan // - expressions // - expression evaluation functions internal static readonly string s_AllowedCharactersForFloat = UINumericFieldsUtils.k_AllowedCharactersForFloat; internal static readonly string s_AllowedCharactersForInt = UINumericFieldsUtils.k_AllowedCharactersForInt; static bool HasKeyboardFocus(int controlID) { // Every EditorWindow has its own keyboardControl state so we also need to // check if the current OS view has focus to determine if the control has actual key focus (gets the input) // and not just being a focused control in an unfocused window. return (GUIUtility.keyboardControl == controlID && EditorGUIUtility.HasCurrentWindowKeyFocus()); } internal struct NumberFieldValue { public NumberFieldValue(double v) { isDouble = true; doubleVal = v; longVal = 0; expression = null; success = false; } public NumberFieldValue(long v) { isDouble = false; doubleVal = 0; longVal = v; expression = null; success = false; } public bool isDouble; public double doubleVal; public long longVal; public ExpressionEvaluator.Expression expression; public bool success; public bool hasResult => success || expression != null; } internal static void DoNumberField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, string formatString, GUIStyle style, bool draggable, double dragSensitivity) { NumberFieldValue val = default; val.isDouble = isDouble; val.doubleVal = doubleVal; val.longVal = longVal; DoNumberField(editor, position, dragHotZone, id, ref val, formatString, style, draggable, dragSensitivity); if (val.success) { doubleVal = val.doubleVal; longVal = val.longVal; } } internal static void StringToNumericValue(in string str, ref NumberFieldValue value) { if (value.isDouble) StringToDouble(str, ref value); else StringToLong(str, ref value); } internal static void EvaluateExpressionOnNumberFieldValue(ref NumberFieldValue value) { if (value.isDouble) value.success = value.expression.Evaluate(ref value.doubleVal); else value.success = value.expression.Evaluate(ref value.longVal); } internal static void GetInitialValue(ref NumberFieldValue value) { if (value.isDouble) { double oldValue = default; if (UINumericFieldsUtils.TryConvertStringToDouble(s_OriginalText, out oldValue) && oldValue != value.doubleVal) { value.doubleVal = oldValue; return; } } else { long oldValue = default; if (UINumericFieldsUtils.TryConvertStringToLong(s_OriginalText, out oldValue) && oldValue != value.longVal) { value.longVal = oldValue; return; } } } internal static void UpdateNumberValueIfNeeded(ref NumberFieldValue value, in string str) { StringToNumericValue(str, ref value); if (!value.success && value.expression != null) { using (s_EvalExpressionMarker.Auto()) { GetInitialValue(ref value); EvaluateExpressionOnNumberFieldValue(ref value); } } GUI.changed = value.success || value.expression != null; } internal static void DoNumberField(RecycledTextEditor editor, Rect position, Rect dragHotZone, int id, ref NumberFieldValue value, string formatString, GUIStyle style, bool draggable, double dragSensitivity) { bool changed; string allowedCharacters = value.isDouble ? s_AllowedCharactersForFloat : s_AllowedCharactersForInt; if (draggable && GUI.enabled) { DragNumberValue(dragHotZone, id, ref value, dragSensitivity); } Event evt = Event.current; string str; if (HasKeyboardFocus(id) || (evt.type == EventType.MouseDown && evt.button == 0 && position.Contains(evt.mousePosition))) { if (!editor.IsEditingControl(id)) { str = s_RecycledCurrentEditingString = value.isDouble ? value.doubleVal.ToString(formatString, CultureInfo.InvariantCulture) : value.longVal.ToString(formatString, CultureInfo.InvariantCulture); } else { str = s_RecycledCurrentEditingString; if (evt.type == EventType.ValidateCommand && evt.commandName == EventCommandNames.UndoRedoPerformed) { str = value.isDouble ? value.doubleVal.ToString(formatString, CultureInfo.InvariantCulture) : value.longVal.ToString(formatString, CultureInfo.InvariantCulture); } } } else { str = value.isDouble ? value.doubleVal.ToString(formatString, CultureInfo.InvariantCulture) : value.longVal.ToString(formatString, CultureInfo.InvariantCulture); } str = DoTextField(editor, id, position, str, style, allowedCharacters, out changed, false, false, false); if (GUIUtility.keyboardControl == id && changed) { // If we are still actively editing, return the input values s_RecycledCurrentEditingString = str; UpdateNumberValueIfNeeded(ref value, str); } } internal static bool StringToDouble(string str, out double value) { NumberFieldValue v = default; StringToDouble(str, ref v); value = v.doubleVal; return v.success; } static void StringToDouble(string str, ref NumberFieldValue value) { value.success = UINumericFieldsUtils.TryConvertStringToDouble(str, out value.doubleVal, out value.expression); } internal static bool StringToLong(string str, out long value) { NumberFieldValue v = default; StringToLong(str, ref v); value = v.longVal; return v.success; } static void StringToLong(string str, ref NumberFieldValue value) { value.expression = null; value.success = UINumericFieldsUtils.TryConvertStringToLong(str, out value.longVal, out value.expression); } internal static int ArraySizeField(Rect position, GUIContent label, int value, GUIStyle style) { int id = GUIUtility.GetControlID(s_ArraySizeFieldHash, FocusType.Keyboard, position); BeginChangeCheck(); string str = DelayedTextFieldInternal(position, id, label, value.ToString(kIntFieldFormatString), "0123456789-", style); if (EndChangeCheck()) { try { value = int.Parse(str, CultureInfo.InvariantCulture.NumberFormat); } catch (FormatException) { } } return value; } internal static string DelayedTextFieldInternal(Rect position, string value, string allowedLetters, GUIStyle style) { int id = GUIUtility.GetControlID(s_DelayedTextFieldHash, FocusType.Keyboard, position); return DelayedTextFieldInternal(position, id, GUIContent.none, value, allowedLetters, style); } internal static string DelayedTextFieldInternal(Rect position, int id, GUIContent label, string value, string allowedLetters, GUIStyle style) { // Figure out which string should be shown: If we're currently editing we disregard the incoming value string str; if (HasKeyboardFocus(id)) { // If we just got focus, set up s_RecycledCurrentEditingString if (!s_DelayedTextEditor.IsEditingControl(id)) { str = s_RecycledCurrentEditingString = value; } else { str = s_RecycledCurrentEditingString; } Event evt = Event.current; if (evt.type == EventType.ValidateCommand && evt.commandName == EventCommandNames.UndoRedoPerformed) { str = value; } } else { str = value; } bool changed; bool wasChanged = GUI.changed; str = s_DelayedTextEditor.OnGUI(id, str, out changed); GUI.changed = false; if (!changed) { str = DoTextField(s_DelayedTextEditor, id, PrefixLabel(position, id, label), str, style, allowedLetters, out changed, false, false, false); GUI.changed = false; // If we are still actively editing, return the input values if (GUIUtility.keyboardControl == id) { if (!s_DelayedTextEditor.IsEditingControl(id)) { if ((value != str) && (!showMixedValue || (showMixedValue && k_MultiEditValueString != str))) { GUI.changed = true; value = str; } } else { s_RecycledCurrentEditingString = str; } } } else { GUI.changed = true; value = str; } GUI.changed |= wasChanged; return value; } internal static void DelayedTextFieldInternal(Rect position, int id, SerializedProperty property, string allowedLetters, GUIContent label, GUIStyle style) { label = BeginProperty(position, label, property); BeginChangeCheck(); string newValue = DelayedTextFieldInternal(position, id, label, property.stringValue, allowedLetters, style); if (EndChangeCheck()) property.stringValue = newValue; EndProperty(); } internal static void DelayedNumberFieldInternal(Rect position, Rect dragHotZone, int id, bool isDouble, ref double doubleVal, ref long longVal, string formatString, GUIStyle style, bool draggable, double dragSensitivity) { NumberFieldValue val = default; val.isDouble = isDouble; val.doubleVal = doubleVal; val.longVal = longVal; DelayedNumberFieldInternal(position, dragHotZone, id, ref val, formatString, style, draggable, dragSensitivity); if (val.success) { doubleVal = val.doubleVal; longVal = val.longVal; } } static void DelayedNumberFieldInternal(Rect position, Rect dragHotZone, int id, ref NumberFieldValue value, string formatString, GUIStyle style, bool draggable, double dragSensitivity) { string allowedCharacters = value.isDouble ? s_AllowedCharactersForFloat : s_AllowedCharactersForInt; Event evt = Event.current; string str; if (HasKeyboardFocus(id) || (evt.type == EventType.MouseDown && evt.button == 0 && position.Contains(evt.mousePosition))) { if (!s_DelayedTextEditor.IsEditingControl(id) && s_DragCandidateState == DragCandidateState.NotDragging) { str = s_RecycledCurrentEditingString = value.isDouble ? value.doubleVal.ToString(formatString, CultureInfo.InvariantCulture) : value.longVal.ToString(formatString, CultureInfo.InvariantCulture); } else { str = s_RecycledCurrentEditingString; if (evt.type == EventType.ValidateCommand && evt.commandName == EventCommandNames.UndoRedoPerformed) { str = value.isDouble ? value.doubleVal.ToString(formatString, CultureInfo.InvariantCulture) : value.longVal.ToString(formatString, CultureInfo.InvariantCulture); } } } else { str = value.isDouble ? value.doubleVal.ToString(formatString, CultureInfo.InvariantCulture) : value.longVal.ToString(formatString, CultureInfo.InvariantCulture); } if (draggable) { double dragDouble = 0; long dragLong = 0; bool isConverted = value.isDouble ? StringToDouble(str, out dragDouble) : StringToLong(str, out dragLong); if (isConverted) { DragNumberValue(dragHotZone, id, value.isDouble, ref dragDouble, ref dragLong, dragSensitivity); str = value.isDouble ? dragDouble.ToString(formatString, CultureInfo.InvariantCulture) : dragLong.ToString(formatString, CultureInfo.InvariantCulture); } } bool changed; bool wasChanged = GUI.changed; str = s_DelayedTextEditor.OnGUI(id, str, out changed); GUI.changed = false; if (!changed) { str = DoTextField(s_DelayedTextEditor, id, position, str, style, allowedCharacters, out changed, false, false, false); GUI.changed = false; // If we are still actively editing, return the input values if (GUIUtility.keyboardControl == id) { s_RecycledCurrentEditingString = str; if (!s_DelayedTextEditor.IsEditingControl(id) && s_DragCandidateState == DragCandidateState.NotDragging) { bool equalValues = false; if (value.isDouble) { equalValues = double.TryParse(str, out var strToDouble) && Math.Abs(value.doubleVal - strToDouble) < Double.Epsilon; } else { equalValues = str.Equals(value.longVal); } if (!equalValues && (!showMixedValue || (showMixedValue && k_MultiEditValueString != str))) { GUI.changed = true; if (value.isDouble) StringToDouble(str, ref value); else StringToLong(str, ref value); } } } } else { UpdateNumberValueIfNeeded(ref value, str); } GUI.changed |= wasChanged; } internal static float DelayedFloatFieldInternal(Rect position, GUIContent label, float value, GUIStyle style) { bool wasChanged = GUI.changed; int id = GUIUtility.GetControlID(s_DelayedTextFieldHash, FocusType.Keyboard, position); long dummy = 0; double doubleValue = value; Rect dragHotzone = new Rect(0, 0, 0, 0); bool draggable = SetDelayedDraggable(ref position, ref dragHotzone, label, id); BeginChangeCheck(); DelayedNumberFieldInternal(position, dragHotzone, id, true, ref doubleValue, ref dummy, kFloatFieldFormatString, style, draggable, Event.current.GetTypeForControl(id) == EventType.MouseDown ? (float)NumericFieldDraggerUtility.CalculateFloatDragSensitivity(s_DragStartValue) : 0.0f); if (EndChangeCheck()) { if ((float)doubleValue != value) return (float)doubleValue; GUI.changed = wasChanged; } return value; } internal static void DelayedFloatFieldInternal(Rect position, SerializedProperty property, GUIContent label) { label = BeginProperty(position, label, property); BeginChangeCheck(); float newValue = DelayedFloatFieldInternal(position, label, property.floatValue, EditorStyles.numberField); if (EndChangeCheck()) property.floatValue = newValue; EndProperty(); } internal static double DelayedDoubleFieldInternal(Rect position, GUIContent label, double value, GUIStyle style) { bool wasChanged = GUI.changed; int id = GUIUtility.GetControlID(s_DelayedTextFieldHash, FocusType.Keyboard, position); long dummy = 0; double newDoubleValue = value; Rect dragHotzone = new Rect(0, 0, 0, 0); bool draggable = SetDelayedDraggable(ref position, ref dragHotzone, label, id); BeginChangeCheck(); DelayedNumberFieldInternal(position, dragHotzone, id, true, ref newDoubleValue, ref dummy, kFloatFieldFormatString, style, draggable, Event.current.GetTypeForControl(id) == EventType.MouseDown ? (float)NumericFieldDraggerUtility.CalculateFloatDragSensitivity(s_DragStartValue) : 0.0f); if (EndChangeCheck()) { if (newDoubleValue != value) return newDoubleValue; GUI.changed = wasChanged; } return value; } internal static int DelayedIntFieldInternal(Rect position, GUIContent label, int value, GUIStyle style) { bool wasChanged = GUI.changed; int id = GUIUtility.GetControlID(s_DelayedTextFieldHash, FocusType.Keyboard, position); double dummy = 0; long longValue = value; Rect dragHotzone = new Rect(0, 0, 0, 0); bool draggable = SetDelayedDraggable(ref position, ref dragHotzone, label, id); BeginChangeCheck(); DelayedNumberFieldInternal(position, dragHotzone, id, false, ref dummy, ref longValue, kIntFieldFormatString, style, draggable, Event.current.GetTypeForControl(id) == EventType.MouseDown ? (float)NumericFieldDraggerUtility.CalculateIntDragSensitivity(value) : 0.0f); if (EndChangeCheck()) { if ((int)longValue != value) return (int)longValue; GUI.changed = wasChanged; } return value; } internal static void DelayedIntFieldInternal(Rect position, SerializedProperty property, GUIContent label) { label = BeginProperty(position, label, property); BeginChangeCheck(); int newValue = DelayedIntFieldInternal(position, label, property.intValue, EditorStyles.numberField); if (EndChangeCheck()) property.intValue = newValue; EndProperty(); } internal static bool SetDelayedDraggable(ref Rect position, ref Rect dragHotzone, GUIContent label, int id) { //Fields without labels are not considered draggable bool draggable = label != GUIContent.none; if (draggable) { dragHotzone = position; position = PrefixLabel(position, id, label); dragHotzone.xMax = position.x; } else { position = IndentedRect(position); } return draggable; } internal static int IntFieldInternal(Rect position, int value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); return DoIntField(s_RecycledEditor, IndentedRect(position), new Rect(0, 0, 0, 0), id, value, kIntFieldFormatString, style, false, NumericFieldDraggerUtility.CalculateIntDragSensitivity(value)); } // Make a text field for entering integers. internal static int IntFieldInternal(Rect position, GUIContent label, int value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); Rect position2 = PrefixLabel(position, id, label); position.xMax = position2.x; return DoIntField(s_RecycledEditor, position2, position, id, value, kIntFieldFormatString, style, true, NumericFieldDraggerUtility.CalculateIntDragSensitivity(value)); } internal static long LongFieldInternal(Rect position, long value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); return DoLongField(s_RecycledEditor, IndentedRect(position), new Rect(0, 0, 0, 0), id, value, kIntFieldFormatString, style, false, NumericFieldDraggerUtility.CalculateIntDragSensitivity(value)); } // Make a text field for entering integers. internal static long LongFieldInternal(Rect position, GUIContent label, long value, GUIStyle style) { NumberFieldValue v = new NumberFieldValue(value); LongFieldInternal(position, label, ref v, style); return v.longVal; } static void LongFieldInternal(Rect position, GUIContent label, ref NumberFieldValue value, GUIStyle style) { int id = GUIUtility.GetControlID(s_FloatFieldHash, FocusType.Keyboard, position); Rect position2 = PrefixLabel(position, id, label); position.xMax = position2.x; var dragSensitivity = NumericFieldDraggerUtility.CalculateIntDragSensitivity(value.longVal); DoNumberField(s_RecycledEditor, position2, position, id, ref value, kIntFieldFormatString, style, true, dragSensitivity); } public static float Slider(Rect position, float value, float leftValue, float rightValue) { int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position); return DoSlider(IndentedRect(position), EditorGUIUtility.DragZoneRect(position, false), id, value, leftValue, rightValue, kFloatFieldFormatString); } public static float Slider(Rect position, string label, float value, float leftValue, float rightValue) { return Slider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); } // Make a slider the user can drag to change a value between a min and a max. public static float Slider(Rect position, GUIContent label, float value, float leftValue, float rightValue) { return Slider(position, label, value, leftValue, rightValue, EditorStyles.numberField); } internal static float Slider(Rect position, GUIContent label, float value, float leftValue, float rightValue, GUIStyle textfieldStyle) { return PowerSlider(position, label, value, leftValue, rightValue, textfieldStyle, 1.0f); } internal static float Slider(Rect position, GUIContent label, float value, float sliderMin, float sliderMax, float textFieldMin, float textFieldMax) { return Slider(position, label, value, sliderMin, sliderMax, textFieldMin, textFieldMax, EditorStyles.numberField, GUI.skin.horizontalSlider, GUI.skin.horizontalSliderThumb, null, GUI.skin.horizontalSliderThumbExtent); } internal static float Slider(Rect position, GUIContent label, float value, float sliderMin, float sliderMax, float textFieldMin, float textFieldMax , GUIStyle textfieldStyle, GUIStyle sliderStyle, GUIStyle thumbStyle, Texture2D sliderBackground, GUIStyle thumbStyleExtent) { var id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position); var controlRect = PrefixLabel(position, id, label); var dragZone = LabelHasContent(label) ? EditorGUIUtility.DragZoneRect(position) : new Rect(); // Ensure dragzone is empty when we have no label return DoSlider(controlRect, dragZone, id, value, sliderMin, sliderMax, kFloatFieldFormatString, textFieldMin, textFieldMax, 1f, 1f, textfieldStyle, sliderStyle, thumbStyle, sliderBackground, thumbStyleExtent); } internal static float PowerSlider(Rect position, string label, float sliderValue, float leftValue, float rightValue, float power) { return PowerSlider(position, EditorGUIUtility.TempContent(label), sliderValue, leftValue, rightValue, power); } // Make a power slider the user can drag to change a value between a min and a max. internal static float PowerSlider(Rect position, GUIContent label, float sliderValue, float leftValue, float rightValue, float power) { return PowerSlider(position, label, sliderValue, leftValue, rightValue, EditorStyles.numberField, power); } internal static float PowerSlider(Rect position, GUIContent label, float sliderValue, float leftValue, float rightValue, GUIStyle textfieldStyle, float power) { int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position); Rect controlRect = PrefixLabel(position, id, label); Rect dragZone = LabelHasContent(label) ? EditorGUIUtility.DragZoneRect(position) : new Rect(); // Ensure dragzone is empty when we have no label return DoSlider(controlRect, dragZone, id, sliderValue, leftValue, rightValue, kFloatFieldFormatString, textfieldStyle, power); } public static int LogarithmicIntSlider(Rect position, string label, int sliderValue, int leftValue, int rightValue, int logbase, int textFieldMin, int textFieldMax) { return LogarithmicIntSlider(position, EditorGUIUtility.TempContent(label), sliderValue, leftValue, rightValue, logbase, textFieldMin, textFieldMax); } public static int LogarithmicIntSlider(Rect position, GUIContent label, int sliderValue, int leftValue, int rightValue, int logbase, int textFieldMin, int textFieldMax) { return LogarithmicIntSlider(position, label, sliderValue, leftValue, rightValue, EditorStyles.numberField, logbase, textFieldMin, textFieldMax); } internal static int LogarithmicIntSlider(Rect position, GUIContent label, int sliderValue, int leftValue, int rightValue, GUIStyle textfieldStyle, int logbase, int textFieldMin, int textFieldMax) { int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position); Rect controlRect = PrefixLabel(position, id, label); Rect dragZone = LabelHasContent(label) ? EditorGUIUtility.DragZoneRect(position) : new Rect(); // Ensure dragzone is empty when we have no label return Mathf.RoundToInt(DoSlider(controlRect, dragZone, id, (float) sliderValue, (float) leftValue, (float) rightValue, kIntFieldFormatString, power:1, logbase: logbase, textFieldMin: textFieldMin, textFieldMax: textFieldMax)); } private static float PowPreserveSign(float f, float p) { var result = Mathf.Pow(Mathf.Abs(f), p); return f < 0.0f ? -result : result; } internal static GenericMenu FillPropertyContextMenu(SerializedProperty property, SerializedProperty linkedProperty = null, GenericMenu menu = null, VisualElement element = null) { if (property == null) return null; if (linkedProperty != null && linkedProperty.serializedObject != property.serializedObject) linkedProperty = null; GenericMenu pm = menu ?? new GenericMenu(); var itargetobjects = property.serializedObject.targetObjectsCount; for (int icount = 0; icount < itargetobjects; icount++) { if (!property.serializedObject.targetObjects[icount]) return null; } // Since the menu items are invoked with delay, we can't assume a SerializedObject we don't own // will still be around at that time. Hence create our own copy. (case 1051734) SerializedObject serializedObjectCopy = new SerializedObject(property.serializedObject.targetObjects); SerializedProperty propertyWithPath = serializedObjectCopy.FindProperty(property.propertyPath); if (propertyWithPath == null) return null; // FillPropertyContextMenu is now always called when a right click is done on a property. // However we don't want those menu to be added when the property is disabled. if (GUI.enabled) { ScriptAttributeUtility.GetHandler(property).AddMenuItems(property, pm); SerializedProperty linkedPropertyWithPath = null; if (linkedProperty != null) { linkedPropertyWithPath = serializedObjectCopy.FindProperty(linkedProperty.propertyPath); ScriptAttributeUtility.GetHandler(linkedProperty).AddMenuItems(linkedProperty, pm); } // Would be nice to allow to set to value of a specific target for properties with children too, // but it's not currently supported. if (property.hasMultipleDifferentValues && !property.hasVisibleChildren) { TargetChoiceHandler.AddSetToValueOfTargetMenuItems(pm, propertyWithPath, TargetChoiceHandler.SetToValueOfTarget); } Object targetObject = property.serializedObject.targetObject; PropertyValueOriginInfo propertyOrigin = PrefabUtility.GetPropertyValueOriginInfo(property); if (propertyOrigin.asset != null) { pm.AddItem(new GUIContent("Go to " + propertyOrigin.contextMenuText + " in '" + propertyOrigin.asset.name + "'"), false, () => GoToPrefab(AssetDatabase.GetAssetPath(propertyOrigin.asset), PrefabUtility.GetGameObject(targetObject))); } bool shouldDisplayPrefabContextMenuItems = property.prefabOverride || (linkedProperty?.prefabOverride ?? false); // Only display the custom apply/revert menu for GameObjects/Components that are not part of a Prefab instance & variant. var shouldDisplayApplyRevertProviderContextMenuItems = targetObject is IApplyRevertPropertyContextMenuItemProvider; if (shouldDisplayPrefabContextMenuItems || shouldDisplayApplyRevertProviderContextMenuItems) { SerializedProperty[] properties; if (linkedProperty == null) properties = new SerializedProperty[] { propertyWithPath }; else properties = new SerializedProperty[] { propertyWithPath, linkedPropertyWithPath }; if (shouldDisplayApplyRevertProviderContextMenuItems) { var provider = targetObject as IApplyRevertPropertyContextMenuItemProvider; if (provider.TryGetApplyMethodForFieldName(propertyWithPath, out Action<SerializedProperty> applyMethod)) { pm.AddItem( new GUIContent() { text = $"Apply override to '{provider.GetSourceName(targetObject as Component)}' {provider.GetSourceTerm()}" }, false, (o) => applyMethod(propertyWithPath), properties); } if (provider.TryGetRevertMethodForFieldName(propertyWithPath, out Action<SerializedProperty> revertMethod)) { pm.AddItem( new GUIContent() { text = $"Revert {provider.GetSourceTerm()} override" }, false, (o) => revertMethod(propertyWithPath), properties); } } else if (shouldDisplayPrefabContextMenuItems) { bool samePropertyValueAsSource = false; Object source = PrefabUtility.GetCorrespondingObjectFromSource(targetObject); SerializedObject sourceSerializedObject = new SerializedObject(source); SerializedProperty sourceProperty = sourceSerializedObject.FindProperty(property.propertyPath); samePropertyValueAsSource = SerializedProperty.DataEquals(property, sourceProperty); PrefabUtility.HandleApplyRevertMenuItems( null, targetObject, (menuItemContent, sourceObject, _) => { // Add apply menu item for this apply target. TargetChoiceHandler.PropertyAndSourcePathInfo info = new TargetChoiceHandler.PropertyAndSourcePathInfo(); info.properties = properties; info.assetPath = AssetDatabase.GetAssetPath(sourceObject); GameObject rootObject = PrefabUtility.GetRootGameObject(sourceObject); if (EditorUtility.IsPersistent(targetObject) || !PrefabUtility.IsPartOfPrefabThatCanBeAppliedTo(rootObject) || !PrefabUtility.CanPropertyBeAppliedToTarget(property, rootObject)) pm.AddDisabledItem(menuItemContent); else pm.AddItem(menuItemContent, false, TargetChoiceHandler.ApplyPrefabPropertyOverride, info); }, (menuItemContent) => { // Add revert menu item. GUIContent content; if (samePropertyValueAsSource) { GameObject sourceRoot = PrefabUtility.GetRootGameObject(source); content = new GUIContent(string.Format(Styles.revertPropertyValueIdenticalToSource, sourceRoot.name)); } else { content = menuItemContent; } pm.AddItem(content, false, TargetChoiceHandler.RevertPrefabPropertyOverride, properties); }, false, property.serializedObject.targetObjectsCount ); } } } // Add copy/paste clipboard operations if available (the entries themselves // will check for GUI enablement; e.g. Copy should be there even for disabled // GUI but Paste should not). ClipboardContextMenu.SetupPropertyCopyPaste(propertyWithPath, menu: pm, evt: null); if (GUI.enabled) { // If property is an element in an array, show duplicate and delete menu options if (property.propertyPath.LastIndexOf(']') == property.propertyPath.Length - 1) { var parentArrayPropertyPath = property.propertyPath.Substring(0, property.propertyPath.LastIndexOf(".Array.data[", StringComparison.Ordinal)); var parentArrayProperty = property.serializedObject.FindProperty(parentArrayPropertyPath); var parentArrayIndex = -1; // Referencing the selected element in the array ensures that Duplicate/Delete // work correctly on non reordable lists, so we need to try and parse it's index out of the path string. try { // Strip the string up to the first .Array.data[ var parentArrayIndexString = property.propertyPath.Substring(property.propertyPath.LastIndexOf(".Array.data[", StringComparison.Ordinal) + 12); // Strip everything after the next ] parentArrayIndexString = parentArrayIndexString.Substring(0, parentArrayIndexString.IndexOf("]")); // Attempt to parse this into an Int32 parentArrayIndex = Int32.Parse(parentArrayIndexString); } catch { /*we can't parse an array index, so leave it -1*/ } if (!parentArrayProperty.isFixedBuffer) { if (pm.GetItemCount() > 0) { pm.AddSeparator(""); } pm.AddItem(EditorGUIUtility.TrTextContent("Duplicate Array Element"), false, (a) => { var list = ReorderableList.GetReorderableListFromSerializedProperty(parentArrayProperty); var listView = element?.GetFirstAncestorOfType<ListView>(); // If we have a ReorderableList associated with this property lets use list selection array // and apply this action to all selected elements thus having better integration with // ReorderableLists multi-selection features if (list != null && list.selectedIndices.Count > 0) { for (int i = list.selectedIndices.Count - 1; i >= 0; i--) { if (list.selectedIndices[i] >= parentArrayProperty.arraySize) continue; SerializedProperty resolvedProperty = parentArrayProperty.GetArrayElementAtIndex(list.selectedIndices[i]); if (resolvedProperty != null) { if (!TargetChoiceHandler.DuplicateArrayElement(resolvedProperty)) continue; } for (int j = i; j < list.selectedIndices.Count; j++) { list.m_Selection[j]++; } } if (list.onChangedCallback != null) list.onChangedCallback(list); ReorderableList.InvalidateExistingListCaches(); } else if (listView != null && listView.selectedIndices.Any()) { DuplicateListViewItems(listView, parentArrayProperty); } else // Non reorderable { if (parentArrayIndex >= 0 && parentArrayIndex < parentArrayProperty.arraySize) { SerializedProperty resolvedProperty = parentArrayProperty.GetArrayElementAtIndex(parentArrayIndex); if (resolvedProperty != null) { TargetChoiceHandler.DuplicateArrayElement(resolvedProperty); } } else { TargetChoiceHandler.DuplicateArrayElement(a); } } if(list != null) { if (list.onChangedCallback != null) list.onChangedCallback(list); ReorderableList.InvalidateExistingListCaches(); } EditorGUIUtility.editingTextField = false; }, propertyWithPath); pm.AddItem(EditorGUIUtility.TrTextContent("Delete Array Element"), false, (a) => { var list = ReorderableList.GetReorderableListFromSerializedProperty(parentArrayProperty); var listView = element?.GetFirstAncestorOfType<ListView>(); // If we have a ReorderableList associated with this property lets use list selection array // and apply this action to all selected elements thus having better integration with // ReorderableLists multi-selection features if (list != null && list.selectedIndices.Count > 0) { foreach (var selected in list.selectedIndices.Reverse<int>()) { if (selected >= parentArrayProperty.arraySize) continue; SerializedProperty resolvedProperty = parentArrayProperty.GetArrayElementAtIndex(selected); if (resolvedProperty != null) { if (!TargetChoiceHandler.DeleteArrayElement(resolvedProperty)) continue; } } list.m_Selection.Clear(); if (list.onChangedCallback != null) list.onChangedCallback(list); ReorderableList.InvalidateExistingListCaches(); } else if (listView != null && listView.selectedIndices.Any()) { DeleteListViewItems(listView, parentArrayProperty); } else // Non reorderable { if (parentArrayIndex >= 0 && parentArrayIndex < parentArrayProperty.arraySize) { SerializedProperty resolvedProperty = parentArrayProperty.GetArrayElementAtIndex(parentArrayIndex); if (resolvedProperty != null) { TargetChoiceHandler.DeleteArrayElement(resolvedProperty); } } else { TargetChoiceHandler.DeleteArrayElement(a); } } if(list != null) { list.m_Selection.Clear(); if (list.onChangedCallback != null) list.onChangedCallback(list); ReorderableList.InvalidateExistingListCaches(); } EditorGUIUtility.editingTextField = false; }, propertyWithPath); } } } // If shift is held down, show debug menu options // This menu is not excluded when the field is disabled // because it is nice to get information about the property even when it's disabled. if (Event.current.shift) { if (pm.GetItemCount() > 0) pm.AddSeparator(""); pm.AddItem(EditorGUIUtility.TrTextContent("Print Property Path"), false, e => Debug.Log(((SerializedProperty)e).propertyPath), propertyWithPath); } // If property is a reference and we're using VCS, add item to check it out // This menu is not excluded when the field is disabled // because it is nice to get information about the property even when it's disabled. if (propertyWithPath.propertyType == SerializedPropertyType.ObjectReference && VersionControlUtils.isVersionControlConnected) { var obj = propertyWithPath.objectReferenceValue; if (obj != null && !AssetDatabase.IsOpenForEdit(obj)) { if (pm.GetItemCount() > 0) pm.AddSeparator(""); pm.AddItem( new GUIContent(L10n.Tr("Check Out") + " '" + obj.name + "'"), false, o => AssetDatabase.MakeEditable(AssetDatabase.GetAssetOrScenePath((Object)o)), obj); } } // FillPropertyContextMenu is now always called when a right click is done on a property. // However we don't want those menu to be added when the property is disabled. if (GUI.enabled) { if (EditorApplication.contextualPropertyMenu != null) { if (pm.GetItemCount() > 0) pm.AddSeparator(""); EditorApplication.contextualPropertyMenu(pm, property); } } EditorGUIUtility.ContextualPropertyMenuCallback(pm, property); return pm; } internal static void DeleteListViewItems(BaseListView baseListView, SerializedProperty parentArrayProperty) { var previousSelectedIndices = new List<int>(baseListView.selectedIndices); previousSelectedIndices.Sort(); baseListView.ClearSelection(); for (int i = previousSelectedIndices.Count - 1; i >= 0; i--) { var index = previousSelectedIndices.ElementAt(i); if (index >= baseListView.itemsSource.Count) continue; SerializedProperty resolvedProperty = parentArrayProperty.GetArrayElementAtIndex(index); if (resolvedProperty != null) { if (!TargetChoiceHandler.DeleteArrayElement(resolvedProperty)) continue; } } } internal static void DuplicateListViewItems(BaseListView baseListView, SerializedProperty parentArrayProperty) { var previousSelectedIndices = new List<int>(baseListView.selectedIndices); previousSelectedIndices.Sort(); var newSelectedIndices = new List<int>(); baseListView.ClearSelection(); for (int i = previousSelectedIndices.Count - 1; i >= 0; i--) { var index = previousSelectedIndices.ElementAt(i); if (index >= baseListView.itemsSource.Count) continue; SerializedProperty resolvedProperty = parentArrayProperty.GetArrayElementAtIndex(index); if (resolvedProperty != null) { if (!TargetChoiceHandler.DuplicateArrayElement(resolvedProperty)) continue; } // need to update the rest of the selected indices as an element was added for (int j = i + 1; j < previousSelectedIndices.Count; j++) { previousSelectedIndices[j]++; } for (int j = 0; j < newSelectedIndices.Count; j++) { newSelectedIndices[j]++; } newSelectedIndices.Add(previousSelectedIndices[i] + 1); } baseListView.SetSelection(newSelectedIndices); } internal static void GoToPrefab(string assetPath, GameObject openedFromInstance) { // When this function is called from a Property Context Menu on the Overrides pop-up window, we need to make ensure that the correct GameObject // (i.e. the GameObject that the property belongs to) is selected when opening Prefab Mode by explicitly setting it as the active GameObject. if (EditorGUIUtility.comparisonViewMode != EditorGUIUtility.ComparisonViewMode.None) Selection.activeGameObject = openedFromInstance; PrefabStageUtility.OpenPrefab(assetPath, openedFromInstance, PrefabStage.Mode.InIsolation); } internal static void DoPropertyContextMenu(SerializedProperty property, SerializedProperty linkedProperty = null, GenericMenu menu = null) { GenericMenu pm = FillPropertyContextMenu(property, linkedProperty, menu); if (pm == null || pm.GetItemCount() == 0) { return; } Event.current.Use(); pm.ShowAsContext(); } public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue) { Slider(position, property, leftValue, rightValue, property.displayName); } public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, string label) { Slider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); } // Make a slider the user can drag to change a value between a min and a max. public static void Slider(Rect position, SerializedProperty property, float leftValue, float rightValue, GUIContent label) { label = BeginProperty(position, label, property); BeginChangeCheck(); float newValue = Slider(position, label, property.floatValue, leftValue, rightValue); if (EndChangeCheck()) { property.floatValue = newValue; } EndProperty(); } internal static void Slider(Rect position, SerializedProperty property, float sliderLeftValue, float sliderRightValue, float textLeftValue, float textRightValue, GUIContent label) { label = BeginProperty(position, label, property); BeginChangeCheck(); float newValue = Slider(position, label, property.floatValue, sliderLeftValue, sliderRightValue, textLeftValue, textRightValue); if (EndChangeCheck()) { property.floatValue = newValue; } EndProperty(); } internal static int IntSlider(Rect position, int value, int leftValue, int rightValue, float power = -1, float logbase = 1, GUIStyle textfieldStyle = null, GUIStyle sliderStyle = null, GUIStyle thumbStyle = null, Texture2D sliderBackground = null, GUIStyle thumbStyleExtent = null) { int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position); return Mathf.RoundToInt(DoSlider(IndentedRect(position), EditorGUIUtility.DragZoneRect(position), id, value, leftValue, rightValue, kIntFieldFormatString, power, logbase, textfieldStyle ?? EditorStyles.numberField, sliderStyle ?? GUI.skin.horizontalSlider, thumbStyle ?? GUI.skin.horizontalSliderThumb, sliderBackground, thumbStyleExtent ?? GUI.skin.horizontalSliderThumbExtent)); } public static int IntSlider(Rect position, int value, int leftValue, int rightValue) { int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position); return Mathf.RoundToInt(DoSlider(IndentedRect(position), EditorGUIUtility.DragZoneRect(position), id, value, leftValue, rightValue, kIntFieldFormatString)); } public static int IntSlider(Rect position, string label, int value, int leftValue, int rightValue) { return IntSlider(position, EditorGUIUtility.TempContent(label), value, leftValue, rightValue); } // Make a slider the user can drag to change an integer value between a min and a max. public static int IntSlider(Rect position, GUIContent label, int value, int leftValue, int rightValue) { int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position); return Mathf.RoundToInt(DoSlider(PrefixLabel(position, id, label), EditorGUIUtility.DragZoneRect(position), id, value, leftValue, rightValue, kIntFieldFormatString, EditorStyles.numberField)); } public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue) { IntSlider(position, property, leftValue, rightValue, property.displayName); } public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, string label) { IntSlider(position, property, leftValue, rightValue, EditorGUIUtility.TempContent(label)); } // Make a slider the user can drag to change a value between a min and a max. public static void IntSlider(Rect position, SerializedProperty property, int leftValue, int rightValue, GUIContent label) { label = BeginProperty(position, label, property); BeginChangeCheck(); int newValue = IntSlider(position, label, property.intValue, leftValue, rightValue); if (EndChangeCheck()) { property.intValue = newValue; } EndProperty(); } // Generic method for showing a left aligned and right aligned label within a rect internal static void DoTwoLabels(Rect rect, GUIContent leftLabel, GUIContent rightLabel, GUIStyle labelStyle) { if (Event.current.type != EventType.Repaint) return; TextAnchor oldAlignment = labelStyle.alignment; labelStyle.alignment = TextAnchor.UpperLeft; GUI.Label(rect, leftLabel, labelStyle); labelStyle.alignment = TextAnchor.UpperRight; GUI.Label(rect, rightLabel, labelStyle); labelStyle.alignment = oldAlignment; } internal static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString, float power = 1f, float logbase = 1f) { return DoSlider(position, dragZonePosition, id, value, left, right, formatString, power, logbase, EditorStyles.numberField, GUI.skin.horizontalSlider, GUI.skin.horizontalSliderThumb, null, GUI.skin.horizontalSliderThumbExtent); } internal static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString, float textFieldMin, float textFieldMax, float power = 1f, float logbase = 1f) { return DoSlider(position, dragZonePosition, id, value, left, right, formatString, textFieldMin, textFieldMax, power, logbase, EditorStyles.numberField, GUI.skin.horizontalSlider, GUI.skin.horizontalSliderThumb, null, GUI.skin.horizontalSliderThumbExtent); } internal static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString, GUIStyle textfieldStyle, float power = 1f, float logbase = 1f) { return DoSlider(position, dragZonePosition, id, value, left, right, formatString, power, logbase, textfieldStyle, GUI.skin.horizontalSlider, GUI.skin.horizontalSliderThumb, null, GUI.skin.horizontalSliderThumbExtent); } private static float DoSlider(Rect position, Rect dragZonePosition, int id, float value, float left, float right, string formatString, float power, float logbase, GUIStyle textfieldStyle, GUIStyle sliderStyle, GUIStyle thumbStyle, Texture2D sliderBackground, GUIStyle thumbStyleExtent) { return DoSlider(position, dragZonePosition, id, value, left, right, formatString, left, right, power, logbase, textfieldStyle, sliderStyle, thumbStyle, sliderBackground, thumbStyleExtent); } private static float DoSlider( Rect position, Rect dragZonePosition, int id, float value, float sliderMin, float sliderMax, string formatString, float textFieldMin , float textFieldMax, float power, float logbase, GUIStyle textfieldStyle, GUIStyle sliderStyle, GUIStyle thumbStyle, Texture2D sliderBackground, GUIStyle thumbStyleExtent ) { int sliderId = GUIUtility.GetControlID(s_SliderKnobHash, FocusType.Passive, position); // Map some nonsensical edge cases to avoid breaking the UI. // A slider with such a large range is basically useless, anyway. sliderMin = Mathf.Clamp(sliderMin, float.MinValue, float.MaxValue); sliderMax = Mathf.Clamp(sliderMax, float.MinValue, float.MaxValue); float w = position.width; if (w >= kSliderMinW + kSpacing + EditorGUIUtility.fieldWidth) { float sWidth = w - kSpacing - EditorGUIUtility.fieldWidth; BeginChangeCheck(); // While the text field is not being edited, we want to share the keyboard focus with the slider, so we temporarily set it to have focus if (GUIUtility.keyboardControl == id && !s_RecycledEditor.IsEditingControl(id)) { GUIUtility.keyboardControl = sliderId; } // Remap slider values according to power curve, if it's not identity var remapLeft = sliderMin; var remapRight = sliderMax; var newSliderValue = value; if (power != 1f) { remapLeft = PowPreserveSign(sliderMin, 1f / power); remapRight = PowPreserveSign(sliderMax, 1f / power); newSliderValue = PowPreserveSign(value, 1f / power); } else if (logbase != 1f) { remapLeft = Mathf.Log(sliderMin, logbase); remapRight = Mathf.Log(sliderMax, logbase); newSliderValue = Mathf.Log(value, logbase); } Rect sliderRect = new Rect(position.x, position.y, sWidth, position.height); if (sliderBackground != null && Event.current.type == EventType.Repaint) { var bgRect = sliderStyle.overflow.Add(sliderStyle.padding.Remove(sliderRect)); Graphics.DrawTexture(bgRect, sliderBackground, new Rect(.5f / sliderBackground.width, .5f / sliderBackground.height, 1 - 1f / sliderBackground.width, 1 - 1f / sliderBackground.height), 0, 0, 0, 0, new Color(0.5f, 0.5f, 0.5f, 0.5f)); } newSliderValue = GUI.Slider(sliderRect, newSliderValue, 0, remapLeft, remapRight, sliderStyle, showMixedValue ? GUI.skin.sliderMixed : thumbStyle, true, sliderId, showMixedValue ? GUI.skin.sliderMixed : thumbStyleExtent); if (power != 1f) { newSliderValue = PowPreserveSign(newSliderValue, power); newSliderValue = Mathf.Clamp(newSliderValue, Mathf.Min(sliderMin, sliderMax), Mathf.Max(sliderMin, sliderMax)); } else if (logbase != 1f) { newSliderValue = Mathf.Pow(logbase, newSliderValue); } // Do slider labels if present if (EditorGUIUtility.sliderLabels.HasLabels()) { Color orgColor = GUI.color; GUI.color = GUI.color * new Color(1f, 1f, 1f, 0.5f); float labelHeight = Mathf.Max(EditorStyles.miniLabel.CalcHeight(EditorGUIUtility.sliderLabels.leftLabel, 0), EditorStyles.miniLabel.CalcHeight(EditorGUIUtility.sliderLabels.rightLabel, 0)); Rect labelRect = new Rect(sliderRect.x, sliderRect.y + (sliderRect.height + thumbStyle.fixedHeight) / 2, sliderRect.width, labelHeight); DoTwoLabels(labelRect, EditorGUIUtility.sliderLabels.leftLabel, EditorGUIUtility.sliderLabels.rightLabel, EditorStyles.miniLabel); GUI.color = orgColor; EditorGUIUtility.sliderLabels.SetLabels(null, null); } // The keyboard control id that we want to retain is the "main" one that is used for the combined control, including the text field. // Whenever the keyboardControl is the sliderId after calling the slider function, we set it back to this main id, // regardless of whether it had keyboard focus before the function call, or just got it. if (GUIUtility.keyboardControl == sliderId || GUIUtility.hotControl == sliderId) { GUIUtility.keyboardControl = id; } if (GUIUtility.keyboardControl == id && Event.current.type == EventType.KeyDown && !s_RecycledEditor.IsEditingControl(id) && (Event.current.keyCode == KeyCode.LeftArrow || Event.current.keyCode == KeyCode.RightArrow)) { // Change by approximately 1/100 of entire range, or 1/10 if holding down shift // But round to nearest power of ten to get nice resulting numbers. float delta = MathUtils.GetClosestPowerOfTen(Mathf.Abs((sliderMax - sliderMin) * 0.01f)); if (formatString == kIntFieldFormatString && delta < 1) { delta = 1; } if (Event.current.shift) { delta *= 10; } // Increment or decrement by just over half the delta. // This means that e.g. if delta is 1, incrementing from 1.0 will go to 2.0, // but incrementing from 0.9 is going to 1.0 rather than 2.0. // This feels more right since 1.0 is the "next" one. if (Event.current.keyCode == KeyCode.LeftArrow) { newSliderValue -= delta * 0.5001f; } else { newSliderValue += delta * 0.5001f; } // Now round to a multiple of our delta value so we get a round end result instead of just a round delta. newSliderValue = MathUtils.RoundToMultipleOf(newSliderValue, delta); GUI.changed = true; Event.current.Use(); } if (EndChangeCheck()) { float valuesPerPixel = (sliderMax - sliderMin) / (sWidth - GUI.skin.horizontalSlider.padding.horizontal - GUI.skin.horizontalSliderThumb.fixedWidth); newSliderValue = MathUtils.RoundBasedOnMinimumDifference(newSliderValue, Mathf.Abs(valuesPerPixel)); value = Mathf.Clamp(newSliderValue, Mathf.Min(sliderMin, sliderMax), Mathf.Max(sliderMin, sliderMax)); if (s_RecycledEditor.IsEditingControl(id)) { s_RecycledEditor.EndEditing(); } } BeginChangeCheck(); var style = textfieldStyle ?? EditorStyles.numberField; position.x += sWidth + kSpacing; position.width = EditorGUIUtility.fieldWidth; // Centers the textfield if it has a specified height if (style.fixedHeight > 0) { position.y += (position.height - style.fixedHeight) / 2; } var newTextFieldValue = DoFloatField(s_RecycledEditor, position, dragZonePosition, id, value, formatString, style, true); if (EndChangeCheck()) { value = Mathf.Clamp(newTextFieldValue, Mathf.Min(textFieldMin, textFieldMax), Mathf.Max(textFieldMin, textFieldMax)); } } else { var style = textfieldStyle ?? EditorStyles.numberField; w = Mathf.Min(EditorGUIUtility.fieldWidth, w); position.x = position.xMax - w; position.width = w; // Centers the textfield if it has a specified height if (style.fixedHeight > 0) { position.y += (position.height - style.fixedHeight) / 2; } value = DoFloatField(s_RecycledEditor, position, dragZonePosition, id, value, formatString, style, true); value = Mathf.Clamp(value, Mathf.Min(textFieldMin, textFieldMax), Mathf.Max(textFieldMin, textFieldMax)); } return value; } [Obsolete("Switch the order of the first two parameters.")] public static void MinMaxSlider(GUIContent label, Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) { MinMaxSlider(position, label, ref minValue, ref maxValue, minLimit, maxLimit); } public static void MinMaxSlider(Rect position, string label, ref float minValue, ref float maxValue, float minLimit, float maxLimit) { MinMaxSlider(position, EditorGUIUtility.TempContent(label), ref minValue, ref maxValue, minLimit, maxLimit); } public static void MinMaxSlider(Rect position, GUIContent label, ref float minValue, ref float maxValue, float minLimit, float maxLimit) { int id = GUIUtility.GetControlID(s_MinMaxSliderHash, FocusType.Passive); DoMinMaxSlider(PrefixLabel(position, id, label), id, ref minValue, ref maxValue, minLimit, maxLimit); } // Make a special slider the user can use to specify a range between a min and a max. public static void MinMaxSlider(Rect position, ref float minValue, ref float maxValue, float minLimit, float maxLimit) { DoMinMaxSlider(IndentedRect(position), GUIUtility.GetControlID(s_MinMaxSliderHash, FocusType.Passive), ref minValue, ref maxValue, minLimit, maxLimit); } private static void DoMinMaxSlider(Rect position, int id, ref float minValue, ref float maxValue, float minLimit, float maxLimit) { float size = maxValue - minValue; BeginChangeCheck(); EditorGUIExt.DoMinMaxSlider(position, id, ref minValue, ref size, minLimit, maxLimit, minLimit, maxLimit, GUI.skin.horizontalSlider, EditorStyles.minMaxHorizontalSliderThumb, true); if (EndChangeCheck()) { maxValue = minValue + size; } } // The indent level of the field labels. public static int indentLevel { get { return ms_IndentLevel; } set { ms_IndentLevel = value; } } internal static float indent => indentLevel * kIndentPerLevel; public class IndentLevelScope : GUI.Scope { readonly int m_IndentOffset; public IndentLevelScope() : this(1) {} public IndentLevelScope(int increment) { m_IndentOffset = increment; indentLevel += m_IndentOffset; } protected override void CloseScope() { indentLevel -= m_IndentOffset; } } // Make a generic popup selection field. private static int PopupInternal(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, GUIStyle style) { return PopupInternal(position, label, selectedIndex, displayedOptions, null, style); } private static int PopupInternal(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, Func<int, bool> checkEnabled, GUIStyle style) { int id = GUIUtility.GetControlID(s_PopupHash, FocusType.Keyboard, position); if (label != null) position = PrefixLabel(position, id, label); return DoPopup(position, id, selectedIndex, displayedOptions, checkEnabled, style); } internal static int Popup(Rect position, GUIContent label, int selectedIndex, string[] displayedOptions, GUIStyle style) { return PopupInternal(position, label, selectedIndex, EditorGUIUtility.TempContent(displayedOptions), null, style); } internal static int Popup(Rect position, GUIContent label, int selectedIndex, string[] displayedOptions) { return Popup(position, label, selectedIndex, displayedOptions, EditorStyles.popup); } // Called from PropertyField private static void Popup(Rect position, SerializedProperty property, GUIContent label) { BeginChangeCheck(); int idx = Popup(position, label, property.hasMultipleDifferentValues ? -1 : property.enumValueIndex, EnumNamesCache.GetEnumLocalizedGUIContents(property)); if (EndChangeCheck()) { property.enumValueIndex = idx; } } // Should be called directly - based on int properties. internal static void Popup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, GUIContent label) { label = BeginProperty(position, label, property); BeginChangeCheck(); int idx = Popup(position, label, property.hasMultipleDifferentValues ? -1 : property.intValue, displayedOptions); if (EndChangeCheck()) { property.intValue = idx; } EndProperty(); } private static Func<Enum, bool> s_CurrentCheckEnumEnabled; private static EnumData s_CurrentEnumData; private static bool CheckCurrentEnumTypeEnabled(int value) { return s_CurrentCheckEnumEnabled(s_CurrentEnumData.values[value]); } // Make an enum popup selection field. private static Enum EnumPopupInternal(Rect position, GUIContent label, Enum selected, Func<Enum, bool> checkEnabled, bool includeObsolete, GUIStyle style) { return EnumPopupInternal(position, label, selected, selected.GetType(), checkEnabled, includeObsolete, style); } private static Enum EnumPopupInternal(Rect position, GUIContent label, Enum selected, Type enumType, Func<Enum, bool> checkEnabled, bool includeObsolete, GUIStyle style) { if (!enumType.IsEnum) { throw new ArgumentException("Parameter selected must be of type System.Enum", nameof(selected)); } var enumData = EnumDataUtility.GetCachedEnumData(enumType, !includeObsolete); var i = showMixedValue ? -1 : Array.IndexOf(enumData.values, selected); var options = EnumNamesCache.GetEnumTypeLocalizedGUIContents(enumType, enumData); s_CurrentCheckEnumEnabled = checkEnabled; s_CurrentEnumData = enumData; i = PopupInternal(position, label, i, options, checkEnabled == null ? (Func<int, bool>)null : CheckCurrentEnumTypeEnabled, style); s_CurrentCheckEnumEnabled = null; return (i < 0 || i >= enumData.flagValues.Length) ? selected : enumData.values[i]; } private static int EnumPopupInternal(Rect position, GUIContent label, int flagValue, Type enumType, Func<Enum, bool> checkEnabled, bool includeObsolete, GUIStyle style) { if (!enumType.IsEnum) { throw new ArgumentException("Parameter selected must be of type System.Enum", nameof(enumType)); } var enumData = EnumDataUtility.GetCachedEnumData(enumType, !includeObsolete); var i = showMixedValue ? -1 : Array.IndexOf(enumData.flagValues, flagValue); var options = EnumNamesCache.GetEnumTypeLocalizedGUIContents(enumType, enumData); s_CurrentCheckEnumEnabled = checkEnabled; s_CurrentEnumData = enumData; i = PopupInternal(position, label, i, options, checkEnabled == null ? (Func<int, bool>)null : CheckCurrentEnumTypeEnabled, style); s_CurrentCheckEnumEnabled = null; return (i < 0 || i >= enumData.flagValues.Length) ? flagValue : enumData.flagValues[i]; } private static int IntPopupInternal(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, GUIStyle style) { // value --> index int i; if (showMixedValue) { i = -1; } else if (optionValues != null) { for (i = 0; (i < optionValues.Length) && (selectedValue != optionValues[i]); ++i) { } } // value = index else { i = selectedValue; } i = PopupInternal(position, label, i, displayedOptions, style); if (optionValues == null) { return i; } // index --> value else if (i < 0 || i >= optionValues.Length) { return selectedValue; } else { return optionValues[i]; } } internal static void IntPopupInternal(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, GUIContent label) { label = BeginProperty(position, label, property); BeginChangeCheck(); int newValue = IntPopupInternal(position, label, property.intValue, displayedOptions, optionValues, EditorStyles.popup); if (EndChangeCheck()) property.intValue = newValue; EndProperty(); } internal static void SortingLayerField(Rect position, GUIContent label, SerializedProperty layerID, GUIStyle style, GUIStyle labelStyle) { using (new PropertyScope(position, null, layerID)) { int id = GUIUtility.GetControlID(s_SortingLayerFieldHash, FocusType.Keyboard, position); position = PrefixLabel(position, id, label, labelStyle); Event evt = Event.current; int selected = PopupCallbackInfo.GetSelectedValueForControl(id, -1); if (selected != -1) { int[] layerIDs = InternalEditorUtility.sortingLayerUniqueIDs; if (selected >= layerIDs.Length) { TagManagerInspector.ShowWithInitialExpansion(TagManagerInspector.InitialExpansionState.SortingLayers); } else { layerID.intValue = layerIDs[selected]; } } if (evt.type == EventType.MouseDown && position.Contains(evt.mousePosition) || evt.MainActionKeyForControl(id)) { int i = 0; int[] layerIDs = InternalEditorUtility.sortingLayerUniqueIDs; string[] layerNames = InternalEditorUtility.sortingLayerNames; for (i = 0; i < layerIDs.Length; i++) { if (layerIDs[i] == layerID.intValue) break; } ArrayUtility.Add(ref layerNames, ""); ArrayUtility.Add(ref layerNames, "Add Sorting Layer..."); DoPopup(position, id, i, EditorGUIUtility.TempContent(layerNames), style); } else if (Event.current.type == EventType.Repaint) { var layerName = layerID.hasMultipleDifferentValues ? mixedValueContent : EditorGUIUtility.TempContent(InternalEditorUtility.GetSortingLayerNameFromUniqueID(layerID.intValue)); showMixedValue = layerID.hasMultipleDifferentValues; BeginHandleMixedValueContentColor(); style.Draw(position, layerName, id, false); EndHandleMixedValueContentColor(); showMixedValue = false; } } } // sealed partial class for storing state for popup menus so we can get the info back to OnGUI from the user selection internal sealed class PopupCallbackInfo { // The global shared popup state public static PopupCallbackInfo instance = null; // Name of the command event sent from the popup menu to OnGUI when user has changed selection internal const string kPopupMenuChangedMessage = "PopupMenuChanged"; // The control ID of the popup menu that is currently displayed. // Used to pass selection changes back again... private readonly int m_ControlID = 0; // Which item was selected private int m_SelectedIndex = 0; // Which view should we send it to. private readonly GUIView m_SourceView; // *undoc* public PopupCallbackInfo(int controlID) { m_ControlID = controlID; m_SourceView = GUIView.current; } // *undoc* public static int GetSelectedValueForControl(int controlID, int selected) { Event evt = Event.current; if (evt.type == EventType.ExecuteCommand && evt.commandName == kPopupMenuChangedMessage) { if (instance == null) { Debug.LogError("Popup menu has no instance"); return selected; } if (instance.m_ControlID == controlID) { GUI.changed = showMixedValue || selected != instance.m_SelectedIndex; selected = instance.m_SelectedIndex; instance = null; evt.Use(); } } return selected; } internal void SetEnumValueDelegate(object userData, string[] options, int selected) { m_SelectedIndex = selected; if (m_SourceView) { m_SourceView.SendEvent(EditorGUIUtility.CommandEvent(kPopupMenuChangedMessage)); } } } internal static int DoPopup(Rect position, int controlID, int selected, GUIContent[] popupValues, GUIStyle style) { return DoPopup(position, controlID, selected, popupValues, null, style); } internal static int DoPopup(Rect position, int controlID, int selected, GUIContent[] popupValues, Func<int, bool> checkEnabled, GUIStyle style) { selected = PopupCallbackInfo.GetSelectedValueForControl(controlID, selected); GUIContent buttonContent; if (showMixedValue) { buttonContent = s_MixedValueContent; } else if (selected < 0 || selected >= popupValues.Length) { buttonContent = GUIContent.none; } else { buttonContent = new GUIContent(popupValues[selected]); buttonContent.text = EditorUtility.ParseMenuName(buttonContent.text); } Event evt = Event.current; switch (evt.type) { case EventType.Repaint: // @TODO: Remove this hack and make all editor styles use the default font instead Font originalFont = style.font; if (originalFont && EditorGUIUtility.GetBoldDefaultFont() && originalFont == EditorStyles.miniFont) { style.font = EditorStyles.miniBoldFont; } BeginHandleMixedValueContentColor(); style.Draw(position, buttonContent, controlID, false, position.Contains(Event.current.mousePosition)); EndHandleMixedValueContentColor(); style.font = originalFont; break; case EventType.MouseDown: if (evt.button == 0 && position.Contains(evt.mousePosition)) { if (Application.platform == RuntimePlatform.OSXEditor) { position.y = position.y - selected * 16 - 19; } PopupCallbackInfo.instance = new PopupCallbackInfo(controlID); EditorUtility.DisplayCustomMenu(position, popupValues, checkEnabled, showMixedValue ? -1 : selected, PopupCallbackInfo.instance.SetEnumValueDelegate, null, true); GUIUtility.keyboardControl = controlID; evt.Use(); } break; case EventType.KeyDown: if (evt.MainActionKeyForControl(controlID)) { if (Application.platform == RuntimePlatform.OSXEditor) { position.y = position.y - selected * 16 - 19; } PopupCallbackInfo.instance = new PopupCallbackInfo(controlID); EditorUtility.DisplayCustomMenu(position, popupValues, checkEnabled, showMixedValue ? -1 : selected, PopupCallbackInfo.instance.SetEnumValueDelegate, null); evt.Use(); } break; } return selected; } internal static string TagFieldInternal(Rect position, string tag, GUIStyle style) { position = IndentedRect(position); int id = GUIUtility.GetControlID(s_TagFieldHash, FocusType.Keyboard, position); Event evt = Event.current; int selected = PopupCallbackInfo.GetSelectedValueForControl(id, -1); if (selected != -1) { string[] tagValues = InternalEditorUtility.tags; if (selected >= tagValues.Length) { TagManagerInspector.ShowWithInitialExpansion(TagManagerInspector.InitialExpansionState.Tags); } else { tag = tagValues[selected]; } } if ((evt.type == EventType.MouseDown && position.Contains(evt.mousePosition)) || evt.MainActionKeyForControl(id)) { int i = 0; string[] tagValues = InternalEditorUtility.tags; for (i = 0; i < tagValues.Length; i++) { if (tagValues[i] == tag) { break; } } ArrayUtility.Add(ref tagValues, ""); ArrayUtility.Add(ref tagValues, L10n.Tr("Add Tag...")); DoPopup(position, id, i, EditorGUIUtility.TempContent(tagValues), style); return tag; } else if (Event.current.type == EventType.Repaint) { BeginHandleMixedValueContentColor(); style.Draw(position, showMixedValue ? s_MixedValueContent : EditorGUIUtility.TempContent(tag), id, false); EndHandleMixedValueContentColor(); } return tag; } // Make a tag selection field. internal static string TagFieldInternal(Rect position, GUIContent label, string tag, GUIStyle style) { int id = GUIUtility.GetControlID(s_TagFieldHash, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); Event evt = Event.current; int selected = PopupCallbackInfo.GetSelectedValueForControl(id, -1); if (selected != -1) { string[] tagValues = InternalEditorUtility.tags; if (selected >= tagValues.Length) { TagManagerInspector.ShowWithInitialExpansion(TagManagerInspector.InitialExpansionState.Tags); } else { tag = tagValues[selected]; } } if (evt.type == EventType.MouseDown && position.Contains(evt.mousePosition) || evt.MainActionKeyForControl(id)) { int i = 0; string[] tagValues = InternalEditorUtility.tags; for (i = 0; i < tagValues.Length; i++) { if (tagValues[i] == tag) { break; } } ArrayUtility.Add(ref tagValues, ""); ArrayUtility.Add(ref tagValues, L10n.Tr("Add Tag...")); DoPopup(position, id, i, EditorGUIUtility.TempContent(tagValues), style); return tag; } else if (Event.current.type == EventType.Repaint) { style.Draw(position, showMixedValue ? s_MixedValueContent : EditorGUIUtility.TempContent(tag), id, false, position.Contains(evt.mousePosition)); } return tag; } // Make a layer selection field. // // this one is slow, but we only have one of them (in the game object inspector), so we should be ok. // ARGH. This code is SO bad - I will refactor and repent after 2.5 - Nicholas internal static int LayerFieldInternal(Rect position, GUIContent label, int layer, GUIStyle style) { int id = GUIUtility.GetControlID(s_TagFieldHash, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); Event evt = Event.current; bool wasChangedBefore = GUI.changed; int selected = PopupCallbackInfo.GetSelectedValueForControl(id, -1); if (selected != -1) { if (selected >= InternalEditorUtility.layers.Length) { TagManagerInspector.ShowWithInitialExpansion(TagManagerInspector.InitialExpansionState.Layers); GUI.changed = wasChangedBefore; } else { int count = 0; for (int i = 0; i < 32; i++) { if (InternalEditorUtility.GetLayerName(i).Length != 0) { if (count == selected) { layer = i; break; } count++; } } } } if ((evt.type == EventType.MouseDown && position.Contains(evt.mousePosition)) || evt.MainActionKeyForControl(id)) { int count = 0; for (int i = 0; i < 32; i++) { if (InternalEditorUtility.GetLayerName(i).Length != 0) { if (i == layer) { break; } count++; } } string[] layers = InternalEditorUtility.GetLayersWithId(); ArrayUtility.Add(ref layers, ""); ArrayUtility.Add(ref layers, L10n.Tr("Add Layer...")); DoPopup(position, id, count, EditorGUIUtility.TempContent(layers), style); Event.current.Use(); return layer; } else if (evt.type == EventType.Repaint) { var layerFieldContent = showMixedValue ? s_MixedValueContent : EditorGUIUtility.TempContent(InternalEditorUtility.GetLayerName(layer)); style.Draw(position, layerFieldContent, id, false, position.Contains(evt.mousePosition)); } return layer; } internal static int MaskFieldInternal(Rect position, GUIContent label, int mask, string[] displayedOptions, GUIStyle style) { var id = GUIUtility.GetControlID(s_MaskField, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); return MaskFieldGUI.DoMaskField(position, id, mask, displayedOptions, style); } internal static int MaskFieldInternal(Rect position, GUIContent label, int mask, string[] displayedOptions, int[] optionValues, GUIStyle style) { var id = GUIUtility.GetControlID(s_MaskField, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); return MaskFieldGUI.DoMaskField(position, id, mask, displayedOptions, optionValues, style); } // Make a field for masks. internal static int MaskFieldInternal(Rect position, int mask, string[] displayedOptions, GUIStyle style) { var id = GUIUtility.GetControlID(s_MaskField, FocusType.Keyboard, position); return MaskFieldGUI.DoMaskField(IndentedRect(position), id, mask, displayedOptions, style); } public static Enum EnumFlagsField(Rect position, Enum enumValue) { return EnumFlagsField(position, enumValue, EditorStyles.popup); } public static Enum EnumFlagsField(Rect position, Enum enumValue, GUIStyle style) { return EnumFlagsField(position, GUIContent.none, enumValue, style); } public static Enum EnumFlagsField(Rect position, string label, Enum enumValue) { return EnumFlagsField(position, label, enumValue, EditorStyles.popup); } public static Enum EnumFlagsField(Rect position, string label, Enum enumValue, GUIStyle style) { return EnumFlagsField(position, EditorGUIUtility.TempContent(label), enumValue, style); } public static Enum EnumFlagsField(Rect position, GUIContent label, Enum enumValue) { return EnumFlagsField(position, label, enumValue, EditorStyles.popup); } public static Enum EnumFlagsField(Rect position, GUIContent label, Enum enumValue, GUIStyle style) { return EnumFlagsField(position, label, enumValue, false, style); } public static Enum EnumFlagsField(Rect position, GUIContent label, Enum enumValue, [DefaultValue("false")] bool includeObsolete, [DefaultValue("null")] GUIStyle style = null) { return EnumFlagsField(position, label, enumValue, includeObsolete, out _, out _, style ?? EditorStyles.popup); } // Internal version that also gives you back which flags were changed and what they were changed to. internal static Enum EnumFlagsField(Rect position, GUIContent label, Enum enumValue, bool includeObsolete, out int changedFlags, out bool changedToValue, GUIStyle style) { return EnumFlagsField(position, label, enumValue, enumValue.GetType(), includeObsolete, out changedFlags, out changedToValue, style); } internal static Enum EnumFlagsField(Rect position, GUIContent label, Enum enumValue, Type enumType, bool includeObsolete, out int changedFlags, out bool changedToValue, GUIStyle style) { if (!enumType.IsEnum) throw new ArgumentException("Parameter enumValue must be of type System.Enum", nameof(enumValue)); var enumData = EnumDataUtility.GetCachedEnumData(enumType, !includeObsolete); if (!enumData.serializable) // this is the same message used in SerializedPropertyEnumHelper.cpp throw new NotSupportedException(string.Format("Unsupported enum base type for {0}", enumType.Name)); var id = GUIUtility.GetControlID(s_EnumFlagsField, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); var flagsInt = EnumDataUtility.EnumFlagsToInt(enumData, enumValue); BeginChangeCheck(); flagsInt = MaskFieldGUI.DoMaskField(position, id, flagsInt, enumData.displayNames, enumData.flagValues, style, out changedFlags, out changedToValue); if (!EndChangeCheck()) return enumValue; return EnumDataUtility.IntToEnumFlags(enumType, flagsInt); } internal static int EnumFlagsField(Rect position, GUIContent label, int enumValue, Type enumType, bool includeObsolete, GUIStyle style) { if (!enumType.IsEnum) throw new ArgumentException("Specified enumType must be System.Enum", nameof(enumType)); var enumData = EnumDataUtility.GetCachedEnumData(enumType, !includeObsolete); if (!enumData.serializable) // this is the same message used in SerializedPropertyEnumHelper.cpp throw new NotSupportedException(string.Format("Unsupported enum base type for {0}", enumType.Name)); var id = GUIUtility.GetControlID(s_EnumFlagsField, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); int changedFlags; bool changedToValue; return MaskFieldGUI.DoMaskField(position, id, enumValue, enumData.displayNames, enumData.flagValues, style, out changedFlags, out changedToValue, enumType.GetEnumUnderlyingType()); } public static void ObjectField(Rect position, SerializedProperty property) { ObjectField(position, property, null, null, EditorStyles.objectField); } public static void ObjectField(Rect position, SerializedProperty property, GUIContent label) { ObjectField(position, property, null, label, EditorStyles.objectField); } public static void ObjectField(Rect position, SerializedProperty property, Type objType) { ObjectField(position, property, objType, null, EditorStyles.objectField); } public static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label) { ObjectField(position, property, objType, label, EditorStyles.objectField); } // We don't expose SerializedProperty overloads with custom GUIStyle parameters according to our guidelines, // but we have to provide it internally because ParticleSystem uses a style that's different from everything else. internal static void ObjectField(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style, ObjectFieldValidator validator = null) { label = BeginProperty(position, label, property); ObjectFieldInternal(position, property, objType, label, style, validator); EndProperty(); } // This version doesn't do BeginProperty / EndProperty. It should not be called directly. private static void ObjectFieldInternal(Rect position, SerializedProperty property, Type objType, GUIContent label, GUIStyle style, ObjectFieldValidator validator = null) { int id = GUIUtility.GetControlID(s_PPtrHash, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); bool allowSceneObjects = false; if (property != null) { // @TODO: Check all target objects. Object objectBeingEdited = property.serializedObject.targetObject; // Allow scene objects if the object being edited is NOT persistent if (objectBeingEdited != null && !EditorUtility.IsPersistent(objectBeingEdited)) { allowSceneObjects = true; } } DoObjectField(position, position, id, objType, property, validator, allowSceneObjects, style); } public static Object ObjectField(Rect position, Object obj, Type objType, Object targetBeingEdited) { int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, position); return DoObjectField(IndentedRect(position), IndentedRect(position), id, obj, targetBeingEdited, objType, null, true); } public static Object ObjectField(Rect position, Object obj, Type objType, bool allowSceneObjects) { int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, position); return DoObjectField(IndentedRect(position), IndentedRect(position), id, obj, null, objType, null, allowSceneObjects); } internal static Object ObjectField(Rect position, Object obj, Type objType, bool allowSceneObjects, GUIStyle style, GUIStyle buttonStyle) { int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, position); return DoObjectField(IndentedRect(position), IndentedRect(position), id, obj, null, objType, null, null, null, allowSceneObjects, style, buttonStyle); } [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] public static Object ObjectField(Rect position, Object obj, Type objType) { int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, position); return DoObjectField(position, position, id, obj, null, objType, null, true); } public static Object ObjectField(Rect position, string label, Object obj, Type objType, Object targetBeingEdited) { return ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, targetBeingEdited); } public static Object ObjectField(Rect position, string label, Object obj, Type objType, bool allowSceneObjects) { return ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, allowSceneObjects); } [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] public static Object ObjectField(Rect position, string label, Object obj, Type objType) { return ObjectField(position, EditorGUIUtility.TempContent(label), obj, objType, true); } static Rect GetObjectFieldThumbnailRect(Rect position, Type objType) { if (EditorGUIUtility.HasObjectThumbnail(objType) && position.height > kSingleLineHeight) { // Make object field with thumbnail quadratic and align to the right float size = Mathf.Min(position.width, position.height); position.height = size; position.xMin = position.xMax - size; } return position; } // Make an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker. public static Object ObjectField(Rect position, GUIContent label, Object obj, Type objType, Object targetBeingEdited) { int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); position = GetObjectFieldThumbnailRect(position, objType); return DoObjectField(position, position, id, obj, targetBeingEdited, objType, null, true); } // Make an object field. You can assign objects either by drag and drop objects or by selecting an object using the Object Picker. public static Object ObjectField(Rect position, GUIContent label, Object obj, Type objType, bool allowSceneObjects) { int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, position); position = PrefixLabel(position, id, label); position = GetObjectFieldThumbnailRect(position, objType); return DoObjectField(position, position, id, obj, null, objType, null, allowSceneObjects); } internal static void GetRectsForMiniThumbnailField(Rect position, out Rect thumbRect, out Rect labelRect) { thumbRect = IndentedRect(position); thumbRect.y -= (kObjectFieldMiniThumbnailHeight - kSingleLineHeight) * 0.5f; // center around EditorGUI.kSingleLineHeight thumbRect.height = kObjectFieldMiniThumbnailHeight; thumbRect.width = kObjectFieldMiniThumbnailWidth; float labelStartX = thumbRect.x + 2 * kIndentPerLevel; // label aligns with indent levels for being able to have the following labels align with this label labelRect = new Rect(labelStartX, position.y, thumbRect.x + EditorGUIUtility.labelWidth - labelStartX, position.height); } // Make a object field with the preview to the left and the label on the right thats fits on a single line height internal static Object MiniThumbnailObjectField(Rect position, GUIContent label, Object obj, Type objType) { int id = GUIUtility.GetControlID(s_ObjectFieldHash, FocusType.Keyboard, position); Rect thumbRect, labelRect; GetRectsForMiniThumbnailField(position, out thumbRect, out labelRect); HandlePrefixLabel(position, labelRect, label, id, EditorStyles.label); return DoObjectField(thumbRect, thumbRect, id, obj, null, objType, null, false); } [Obsolete("Check the docs for the usage of the new parameter 'allowSceneObjects'.")] public static Object ObjectField(Rect position, GUIContent label, Object obj, Type objType) { return ObjectField(position, label, obj, objType, true); } internal static GameObject GetGameObjectFromObject(Object obj) { var go = obj as GameObject; if (go == null && obj is Component) go = ((Component)obj).gameObject; return go; } internal static bool CheckForCrossSceneReferencing(Object obj1, Object obj2) { // If either object is not a component nor gameobject: cannot become a cross scene reference GameObject go = GetGameObjectFromObject(obj1); if (go == null) return false; GameObject go2 = GetGameObjectFromObject(obj2); if (go2 == null) return false; // If either object is a prefab: cannot become a cross scene reference if (EditorUtility.IsPersistent(go) || EditorUtility.IsPersistent(go2)) return false; // If either scene is invalid: cannot become a cross scene reference if (!go.scene.IsValid() || !go2.scene.IsValid()) return false; return go.scene != go2.scene; } private static bool ValidateObjectReferenceValue(SerializedProperty property, Object obj, ObjectFieldValidatorOptions options) { if ((options & ObjectFieldValidatorOptions.ExactObjectTypeValidation) == ObjectFieldValidatorOptions.ExactObjectTypeValidation) return property.ValidateObjectReferenceValueExact(obj); return property.ValidateObjectReferenceValue(obj); } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static Object ValidateObjectFieldAssignment(Object[] references, Type objType, SerializedProperty property, ObjectFieldValidatorOptions options) { if (references.Length > 0) { bool dragAssignment = DragAndDrop.objectReferences.Length > 0; bool isTextureRef = (references[0] != null && references[0] is Texture2D); if ((objType == typeof(Sprite)) && isTextureRef && dragAssignment) { return SpriteUtility.TextureToSprite(references[0] as Texture2D); } if (property != null) { if (references[0] != null && ValidateObjectReferenceValue(property, references[0], options)) { if (EditorSceneManager.preventCrossSceneReferences && CheckForCrossSceneReferencing(references[0], property.serializedObject.targetObject)) return null; if (objType != null) { if (references[0] is GameObject && typeof(Component).IsAssignableFrom(objType)) { GameObject go = (GameObject)references[0]; references = go.GetComponents(typeof(Component)); } foreach (Object i in references) { if (i != null && objType.IsAssignableFrom(i.GetType())) { return i; } } } else { return references[0]; } } // If array, test against the target arrayElementType, if not test against the target Type. string testElementType = property.type; if (property.type == "vector") testElementType = property.arrayElementType; if ((testElementType == "PPtr<Sprite>" || testElementType == "PPtr<$Sprite>") && isTextureRef && dragAssignment) { return SpriteUtility.TextureToSprite(references[0] as Texture2D); } } else { if (references[0] != null && references[0] is GameObject && typeof(Component).IsAssignableFrom(objType)) { GameObject go = (GameObject)references[0]; references = go.GetComponents(typeof(Component)); } foreach (Object i in references) { if (i != null && objType.IsAssignableFrom(i.GetType())) { return i; } } } } return null; } // Apply the indentLevel to a control rect public static Rect IndentedRect(Rect source) { float x = indent; return new Rect(source.x + x, source.y, source.width - x, source.height); } // Make an X & Y field for entering a [[Vector2]]. public static Vector2 Vector2Field(Rect position, string label, Vector2 value) { return Vector2Field(position, EditorGUIUtility.TempContent(label), value); } // Make an X & Y field for entering a [[Vector2]]. public static Vector2 Vector2Field(Rect position, GUIContent label, Vector2 value) { return Vector2Field(position, label, value, false); } internal static Vector2 Vector2Field(Rect position, GUIContent label, Vector2 value, bool setWideMode) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2, 0, setWideMode); position.height = kSingleLineHeight; return Vector2Field(position, value); } // Make an X & Y field for entering a [[Vector2]]. private static Vector2 Vector2Field(Rect position, Vector2 value) { s_Vector2Floats[0] = value.x; s_Vector2Floats[1] = value.y; position.height = kSingleLineHeight; BeginChangeCheck(); MultiFloatField(position, s_XYLabels, s_Vector2Floats); if (EndChangeCheck()) { value.x = s_Vector2Floats[0]; value.y = s_Vector2Floats[1]; } return value; } // Make an X, Y & Z field for entering a [[Vector3]]. public static Vector3 Vector3Field(Rect position, string label, Vector3 value) { return Vector3Field(position, EditorGUIUtility.TempContent(label), value); } // Make an X, Y & Z field for entering a [[Vector3]]. public static Vector3 Vector3Field(Rect position, GUIContent label, Vector3 value) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); position.height = kSingleLineHeight; return Vector3Field(position, value); } // Make an X, Y & Z field for entering a [[Vector3]]. private static Vector3 Vector3Field(Rect position, Vector3 value) { s_Vector3Floats[0] = value.x; s_Vector3Floats[1] = value.y; s_Vector3Floats[2] = value.z; position.height = kSingleLineHeight; BeginChangeCheck(); MultiFloatField(position, s_XYZLabels, s_Vector3Floats); if (EndChangeCheck()) { value.x = s_Vector3Floats[0]; value.y = s_Vector3Floats[1]; value.z = s_Vector3Floats[2]; } return value; } internal static Vector3 LinkedVector3Field(Rect position, GUIContent label, Vector3 value, ref bool proportionalScale) { int axisModified = 0;// use X as default modified axis return LinkedVector3Field(position, label, GUIContent.none, value, ref proportionalScale, value, 0, ref axisModified); } // Make an X, Y & Z field for entering a [[Vector3]], with a "lock" internal static Vector3 LinkedVector3Field(Rect position, GUIContent label, GUIContent toggleContent, Vector3 value, ref bool proportionalScale, Vector3 initialScale, uint mixedValues, ref int axisModified, SerializedProperty property = null, SerializedProperty proportionalScaleProperty = null) { GUIContent copy = label; Rect fullLabelRect = position; BeginChangeCheck(); if (proportionalScaleProperty != null) { BeginPropertyInternal(fullLabelRect, label, proportionalScaleProperty); } var scalePropertyId = -1; if (property != null) { label = BeginPropertyInternal(position, label, property); scalePropertyId = GUIUtility.keyboardControl; } SerializedProperty copiedProperty = property == null ? property : property.Copy(); var toggle = EditorStyles.toggle.CalcSize(GUIContent.none); int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3, toggle.x + kDefaultSpacing, false); var toggleRect = position; toggleRect.width = toggle.x; float toggleOffset = toggleRect.width + kDefaultSpacing; toggleRect.x -= toggleOffset; toggle.x -= toggleOffset; Styles.linkButton.alignment = TextAnchor.MiddleCenter; // In case we have a background overlay, make sure Constrain proportions toggle won't be affected Color currentColor = GUI.backgroundColor; GUI.backgroundColor = Color.white; bool previousProportionalScale = proportionalScale; proportionalScale = GUI.Toggle(toggleRect, proportionalScale, toggleContent, Styles.linkButton); if (proportionalScaleProperty != null && previousProportionalScale != proportionalScale) proportionalScaleProperty.boolValue = proportionalScale; GUI.backgroundColor = currentColor; position.x += toggle.x + kDefaultSpacing; position.width -= toggle.x + kDefaultSpacing; position.height = kSingleLineHeight; if (proportionalScaleProperty != null) { EndProperty(); } if (property != null) { // Note: due to how both the scale + constrainScale property drawn and handled in a custom fashion, the lastcontrolId never correspond // to the scaleProperty. Also s_PendingPropertyKeyboardHandling is nullifed by the constrainScale property. // Make it work for now but I feel this whole system is super brittle. // This will be hopefully fixed up when we use uitk to create these editors. var lastId = EditorGUIUtility.s_LastControlID; EditorGUIUtility.s_LastControlID = scalePropertyId; s_PendingPropertyKeyboardHandling = property; EndProperty(); EditorGUIUtility.s_LastControlID = lastId; } var newValue = LinkedVector3Field(position, value, proportionalScale, mixedValues, initialScale, ref axisModified, copiedProperty); return newValue; } static Vector3 LinkedVector3Field(Rect position, Vector3 value, bool proportionalScale) { int axisModified = 0;// Use X as default modified axis return LinkedVector3Field(position, value, proportionalScale, 0, value, ref axisModified); } // Make an X, Y & Z field for entering a [[Vector3]]. static Vector3 LinkedVector3Field(Rect position, Vector3 value, bool proportionalScale, uint mixedValues, Vector3 initialScale, ref int axisModified, SerializedProperty property = null) { Vector3 valueAfterChangeCheck = value; s_Vector3Floats[0] = value.x; s_Vector3Floats[1] = value.y; s_Vector3Floats[2] = value.z; position.height = kSingleLineHeight; const float kPrefixWidthOffset = 3.65f; LockingMultiFloatFieldInternal(position, proportionalScale, mixedValues, s_XYZLabels, s_Vector3Floats, new float[] {initialScale.x, initialScale.y, initialScale.z}, property, EditorGUI.CalcPrefixLabelWidth(s_XYZLabels[0]) + kPrefixWidthOffset); if (EndChangeCheck()) { valueAfterChangeCheck.x = s_Vector3Floats[0]; valueAfterChangeCheck.y = s_Vector3Floats[1]; valueAfterChangeCheck.z = s_Vector3Floats[2]; } return proportionalScale? ConstrainProportionsTransformScale.DoScaleProportions(valueAfterChangeCheck, value, ConstrainProportionsTransformScale.m_IsAnimationPreview? value : initialScale, ref axisModified) : valueAfterChangeCheck; } // Make an X, Y field - not public (use PropertyField instead) private static void Vector2Field(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2); position.height = kSingleLineHeight; SerializedProperty cur = property.Copy(); cur.Next(true); MultiPropertyFieldInternal(position, s_XYLabels, cur, PropertyVisibility.All); } // Make an X, Y and Z field - not public (use PropertyField instead) private static void Vector3Field(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); position.height = kSingleLineHeight; SerializedProperty cur = property.Copy(); cur.Next(true); MultiPropertyFieldInternal(position, s_XYZLabels, cur, PropertyVisibility.All); } // Make an X, Y and Z field for Quaternions - not public (use PropertyField instead) private static void QuaternionEulerField(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); position.height = kSingleLineHeight; Vector3 eulerValue = property.quaternionValue.eulerAngles; s_Vector3Floats[0] = Mathf.Floor(eulerValue.x / kQuaternionFloatPrecision) * kQuaternionFloatPrecision; s_Vector3Floats[1] = Mathf.Floor(eulerValue.y / kQuaternionFloatPrecision) * kQuaternionFloatPrecision; s_Vector3Floats[2] = Mathf.Floor(eulerValue.z / kQuaternionFloatPrecision) * kQuaternionFloatPrecision; BeginChangeCheck(); MultiFloatFieldInternal(position, s_XYZLabels, s_Vector3Floats); if (EndChangeCheck()) { property.quaternionValue = Quaternion.Euler(s_Vector3Floats[0], s_Vector3Floats[1], s_Vector3Floats[2]); } } // Make an X, Y, Z and W field - not public (use PropertyField instead) static void Vector4Field(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 4); position.height = kSingleLineHeight; SerializedProperty cur = property.Copy(); cur.Next(true); MultiPropertyFieldInternal(position, s_XYZWLabels, cur, PropertyVisibility.All); } // Make an X, Y, Z & W field for entering a [[Vector4]]. public static Vector4 Vector4Field(Rect position, string label, Vector4 value) { return Vector4Field(position, EditorGUIUtility.TempContent(label), value); } // Make an X, Y, Z & W field for entering a [[Vector4]]. public static Vector4 Vector4Field(Rect position, GUIContent label, Vector4 value) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 4); position.height = kSingleLineHeight; return Vector4FieldNoIndent(position, value); } private static Vector4 Vector4FieldNoIndent(Rect position, Vector4 value) { s_Vector4Floats[0] = value.x; s_Vector4Floats[1] = value.y; s_Vector4Floats[2] = value.z; s_Vector4Floats[3] = value.w; position.height = kSingleLineHeight; BeginChangeCheck(); MultiFloatField(position, s_XYZWLabels, s_Vector4Floats); if (EndChangeCheck()) { value.x = s_Vector4Floats[0]; value.y = s_Vector4Floats[1]; value.z = s_Vector4Floats[2]; value.w = s_Vector4Floats[3]; } return value; } // Make an X & Y int field for entering a [[Vector2Int]]. public static Vector2Int Vector2IntField(Rect position, string label, Vector2Int value) { return Vector2IntField(position, EditorGUIUtility.TempContent(label), value); } // Make an X & Y int field for entering a [[Vector2Int]]. public static Vector2Int Vector2IntField(Rect position, GUIContent label, Vector2Int value) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2); position.height = kSingleLineHeight; return Vector2IntField(position, value); } // Make an X & Y int field for entering a [[Vector2Int]]. private static Vector2Int Vector2IntField(Rect position, Vector2Int value) { s_Vector2Ints[0] = value.x; s_Vector2Ints[1] = value.y; position.height = kSingleLineHeight; BeginChangeCheck(); MultiIntField(position, s_XYLabels, s_Vector2Ints); if (EndChangeCheck()) { value.x = s_Vector2Ints[0]; value.y = s_Vector2Ints[1]; } return value; } // Make an X, Y int field - not public (use PropertyField instead) private static void Vector2IntField(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2); position.height = kSingleLineHeight; SerializedProperty cur = property.Copy(); cur.Next(true); MultiPropertyFieldInternal(position, s_XYLabels, cur, PropertyVisibility.All); } // Make an X, Y and Z int field for entering a [[Vector3Int]]. public static Vector3Int Vector3IntField(Rect position, string label, Vector3Int value) { return Vector3IntField(position, EditorGUIUtility.TempContent(label), value); } // Make an X, Y and Z int field for entering a [[Vector3Int]]. public static Vector3Int Vector3IntField(Rect position, GUIContent label, Vector3Int value) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); position.height = kSingleLineHeight; return Vector3IntField(position, value); } // Make an X, Y and Z int field for entering a [[Vector3Int]]. private static Vector3Int Vector3IntField(Rect position, Vector3Int value) { s_Vector3Ints[0] = value.x; s_Vector3Ints[1] = value.y; s_Vector3Ints[2] = value.z; position.height = kSingleLineHeight; BeginChangeCheck(); MultiIntField(position, s_XYZLabels, s_Vector3Ints); if (EndChangeCheck()) { value.x = s_Vector3Ints[0]; value.y = s_Vector3Ints[1]; value.z = s_Vector3Ints[2]; } return value; } // Make an X, Y and Z int field - not public (use PropertyField instead) private static void Vector3IntField(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); position.height = kSingleLineHeight; SerializedProperty cur = property.Copy(); cur.Next(true); MultiPropertyFieldInternal(position, s_XYZLabels, cur, PropertyVisibility.All); } public static Rect RectField(Rect position, Rect value) { return RectFieldNoIndent(IndentedRect(position), value); } private static Rect RectFieldNoIndent(Rect position, Rect value) { position.height = kSingleLineHeight; s_Vector2Floats[0] = value.x; s_Vector2Floats[1] = value.y; BeginChangeCheck(); // Right align the text var oldAlignment = EditorStyles.label.alignment; EditorStyles.label.alignment = TextAnchor.MiddleLeft; MultiFloatFieldInternal(position, s_XYLabels, s_Vector2Floats, kMiniLabelW); if (EndChangeCheck()) { value.x = s_Vector2Floats[0]; value.y = s_Vector2Floats[1]; } position.y += kSingleLineHeight + kVerticalSpacingMultiField; s_Vector2Floats[0] = value.width; s_Vector2Floats[1] = value.height; BeginChangeCheck(); MultiFloatFieldInternal(position, s_WHLabels, s_Vector2Floats, kMiniLabelW); if (EndChangeCheck()) { value.width = s_Vector2Floats[0]; value.height = s_Vector2Floats[1]; } EditorStyles.label.alignment = oldAlignment; return value; } public static Rect RectField(Rect position, string label, Rect value) { return RectField(position, EditorGUIUtility.TempContent(label), value); } // Make an X, Y, W & H field for entering a [[Rect]]. public static Rect RectField(Rect position, GUIContent label, Rect value) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2); return RectFieldNoIndent(position, value); } // Make an X, Y, W & H for Rect using SerializedProperty (not public) private static void RectField(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2); position.height = kSingleLineHeight; SerializedProperty cur = property.Copy(); cur.Next(true); // Right align the text var oldAlignment = EditorStyles.label.alignment; EditorStyles.label.alignment = TextAnchor.MiddleLeft; MultiPropertyFieldInternal(position, s_XYLabels, cur, PropertyVisibility.All, null, kMiniLabelW); position.y += kSingleLineHeight + kVerticalSpacingMultiField; MultiPropertyFieldInternal(position, s_WHLabels, cur, PropertyVisibility.All, null, kMiniLabelW); EditorStyles.label.alignment = oldAlignment; } public static RectInt RectIntField(Rect position, RectInt value) { position.height = kSingleLineHeight; s_Vector2Ints[0] = value.x; s_Vector2Ints[1] = value.y; BeginChangeCheck(); MultiIntField(position, s_XYLabels, s_Vector2Ints); if (EndChangeCheck()) { value.x = s_Vector2Ints[0]; value.y = s_Vector2Ints[1]; } position.y += kSingleLineHeight + 2; s_Vector2Ints[0] = value.width; s_Vector2Ints[1] = value.height; BeginChangeCheck(); MultiIntField(position, s_WHLabels, s_Vector2Ints); if (EndChangeCheck()) { value.width = s_Vector2Ints[0]; value.height = s_Vector2Ints[1]; } return value; } public static RectInt RectIntField(Rect position, string label, RectInt value) { return RectIntField(position, EditorGUIUtility.TempContent(label), value); } // Make an X, Y, W & H field for entering a [[Rect]]. public static RectInt RectIntField(Rect position, GUIContent label, RectInt value) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2); position.height = kSingleLineHeight; return RectIntField(position, value); } // Make an X, Y, W & H for RectInt using SerializedProperty (not public) private static void RectIntField(Rect position, SerializedProperty property, GUIContent label) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 2); position.height = kSingleLineHeight; SerializedProperty cur = property.Copy(); cur.Next(true); MultiPropertyFieldInternal(position, s_XYLabels, cur, PropertyVisibility.All, null, kMiniLabelW); position.y += kSingleLineHeight + kVerticalSpacingMultiField; MultiPropertyFieldInternal(position, s_WHLabels, cur, PropertyVisibility.All, null, kMiniLabelW); } private static Rect DrawBoundsFieldLabelsAndAdjustPositionForValues(Rect position, bool drawOutside, GUIContent firstContent, GUIContent secondContent) { const float kBoundsTextWidth = 53; if (drawOutside) position.xMin -= kBoundsTextWidth; GUI.Label(position, firstContent, EditorStyles.label); position.y += kSingleLineHeight + kVerticalSpacingMultiField; GUI.Label(position, secondContent, EditorStyles.label); position.y -= kSingleLineHeight + kVerticalSpacingMultiField; position.xMin += kBoundsTextWidth; return position; } public static Bounds BoundsField(Rect position, Bounds value) { return BoundsFieldNoIndent(IndentedRect(position), value, false); } public static Bounds BoundsField(Rect position, string label, Bounds value) { return BoundsField(position, EditorGUIUtility.TempContent(label), value); } // Make Center & Extents field for entering a [[Bounds]]. public static Bounds BoundsField(Rect position, GUIContent label, Bounds value) { if (!LabelHasContent(label)) return BoundsFieldNoIndent(IndentedRect(position), value, false); int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); if (EditorGUIUtility.wideMode) position.y += kSingleLineHeight + kVerticalSpacingMultiField; return BoundsFieldNoIndent(position, value, true); } private static Bounds BoundsFieldNoIndent(Rect position, Bounds value, bool isBelowLabel) { position.height = kSingleLineHeight; position = DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && isBelowLabel, s_CenterLabel, s_ExtentLabel); value.center = Vector3Field(position, value.center); position.y += kSingleLineHeight + kVerticalSpacingMultiField; value.extents = Vector3Field(position, value.extents); return value; } // private (use PropertyField) private static void BoundsField(Rect position, SerializedProperty property, GUIContent label) { bool hasLabel = LabelHasContent(label); if (hasLabel) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); if (EditorGUIUtility.wideMode) position.y += kSingleLineHeight + kVerticalSpacingMultiField; } position.height = kSingleLineHeight; position = DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && hasLabel, s_CenterLabel, s_ExtentLabel); SerializedProperty cur = property.Copy(); cur.Next(true); cur.Next(true); MultiPropertyFieldInternal(position, s_XYZLabels, cur, PropertyVisibility.All, null, kMiniLabelW); cur.Next(true); position.y += kSingleLineHeight + kVerticalSpacingMultiField; MultiPropertyFieldInternal(position, s_XYZLabels, cur, PropertyVisibility.All, null, kMiniLabelW); } public static BoundsInt BoundsIntField(Rect position, BoundsInt value) { return BoundsIntFieldNoIndent(IndentedRect(position), value, false); } public static BoundsInt BoundsIntField(Rect position, string label, BoundsInt value) { return BoundsIntField(position, EditorGUIUtility.TempContent(label), value); } public static BoundsInt BoundsIntField(Rect position, GUIContent label, BoundsInt value) { if (!LabelHasContent(label)) return BoundsIntFieldNoIndent(IndentedRect(position), value, false); int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); if (EditorGUIUtility.wideMode) position.y += kSingleLineHeight + kVerticalSpacingMultiField; return BoundsIntFieldNoIndent(position, value, true); } private static BoundsInt BoundsIntFieldNoIndent(Rect position, BoundsInt value, bool isBelowLabel) { position.height = kSingleLineHeight; position = DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && isBelowLabel, s_PositionLabel, s_SizeLabel); value.position = Vector3IntField(position, value.position); position.y += kSingleLineHeight + kVerticalSpacingMultiField; value.size = Vector3IntField(position, value.size); return value; } // private (use PropertyField) private static void BoundsIntField(Rect position, SerializedProperty property, GUIContent label) { bool hasLabel = LabelHasContent(label); if (hasLabel) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, 3); if (EditorGUIUtility.wideMode) position.y += kSingleLineHeight + kVerticalSpacingMultiField; } position.height = kSingleLineHeight; position = DrawBoundsFieldLabelsAndAdjustPositionForValues(position, EditorGUIUtility.wideMode && hasLabel, s_PositionLabel, s_SizeLabel); SerializedProperty cur = property.Copy(); cur.Next(true); cur.Next(true); MultiPropertyFieldInternal(position, s_XYZLabels, cur, PropertyVisibility.All); cur.Next(true); position.y += kSingleLineHeight + kVerticalSpacingMultiField; MultiPropertyFieldInternal(position, s_XYZLabels, cur, PropertyVisibility.All); } public static void MultiFloatField(Rect position, GUIContent label, GUIContent[] subLabels, float[] values) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, subLabels.Length); position.height = kSingleLineHeight; MultiFloatField(position, subLabels, values); } public static void MultiFloatField(Rect position, GUIContent[] subLabels, float[] values) { MultiFloatFieldInternal(position, subLabels, values); } internal static float GetLabelWidth(GUIContent Label, float prefixLabelWidth = -1) { float LabelWidth = EditorGUI.CalcPrefixLabelWidth(Label); if (LabelWidth > kMiniLabelW) return prefixLabelWidth > 0 ? prefixLabelWidth : LabelWidth; else return prefixLabelWidth > 0 ? prefixLabelWidth : kMiniLabelW; } internal static void MultiFloatFieldInternal(Rect position, GUIContent[] subLabels, float[] values, float prefixLabelWidth = -1) { int eCount = values.Length; float w = (position.width - (eCount - 1) * kSpacingSubLabel) / eCount; Rect nr = new Rect(position) {width = w}; float t = EditorGUIUtility.labelWidth; int l = indentLevel; indentLevel = 0; for (int i = 0; i < values.Length; i++) { EditorGUIUtility.labelWidth = GetLabelWidth(subLabels[i], prefixLabelWidth); values[i] = FloatField(nr, subLabels[i], values[i]); nr.x += w + kSpacingSubLabel; } EditorGUIUtility.labelWidth = t; indentLevel = l; } static void LockingMultiFloatFieldInternal(Rect position, bool locked, GUIContent[] subLabels, float[] values, float prefixLabelWidth = -1) { LockingMultiFloatFieldInternal(position, locked, 0, subLabels, values, null, null, prefixLabelWidth); } static void LockingMultiFloatFieldInternal(Rect position, bool locked, uint mixedValues, GUIContent[] subLabels, float[] values, float[] initialValues = null, SerializedProperty property = null, float prefixLabelWidth = -1) { int eCount = values.Length; float w = (position.width - (eCount - 1) * EditorGUI.kSpacingSubLabel) / eCount; Rect nr = new Rect(position) {width = w}; float t = EditorGUIUtility.labelWidth; int l = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; var guiEnabledState = GUI.enabled; bool hasMixedValues = mixedValues != 0; uint multiselectionLock = ConstrainProportionsTransformScale.GetMultiSelectionLockedFields(property?.serializedObject?.targetObjects); if (initialValues == null || ConstrainProportionsTransformScale.m_IsAnimationPreview) initialValues = values; // In animation preview mode we scale using last valid value instead of initialScale, make sure we won't lock fields on Vector3.zero bool forceEnableFields = ConstrainProportionsTransformScale.ShouldForceEnablePropertyFields(initialValues); bool mixedValueState = EditorGUI.showMixedValue; for (int i = 0; i < initialValues.Length; i++) { if (property != null) property.Next(true); EditorGUIUtility.labelWidth = prefixLabelWidth > 0 ? prefixLabelWidth : EditorGUI.CalcPrefixLabelWidth(subLabels[i]); if (guiEnabledState) { if (locked) { // If initial field value is 0, it must be locked not to break proportions GUI.enabled = forceEnableFields || !Mathf.Approximately(initialValues[i], 0) && (property != null && property.serializedObject.targetObjectsCount > 1 ? !ConstrainProportionsTransformScale.IsBit(multiselectionLock, i) : true); } else { GUI.enabled = true; } } if (hasMixedValues) EditorGUI.showMixedValue = ConstrainProportionsTransformScale.IsBit(mixedValues, i); if (property != null) { EditorGUI.PropertyField(nr, property, subLabels[i]); values[i] = property.floatValue; } else { values[i] = EditorGUI.FloatField(nr, subLabels[i], values[i]); } if (hasMixedValues) EditorGUI.showMixedValue = false; nr.x += w + EditorGUI.kSpacingSubLabel; } GUI.enabled = guiEnabledState; EditorGUI.showMixedValue = mixedValueState; EditorGUIUtility.labelWidth = t; EditorGUI.indentLevel = l; } public static void MultiIntField(Rect position, GUIContent[] subLabels, int[] values) { MultiIntFieldInternal(position, subLabels, values); } internal static void MultiIntFieldInternal(Rect position, GUIContent[] subLabels, int[] values) { int eCount = values.Length; float w = (position.width - (eCount - 1) * kSpacingSubLabel) / eCount; Rect nr = new Rect(position) {width = w}; float t = EditorGUIUtility.labelWidth; int l = indentLevel; indentLevel = 0; for (int i = 0; i < values.Length; i++) { EditorGUIUtility.labelWidth = GetLabelWidth(subLabels[i]); values[i] = IntField(nr, subLabels[i], values[i]); nr.x += w + kSpacingSubLabel; } EditorGUIUtility.labelWidth = t; indentLevel = l; } public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, GUIContent label) { MultiPropertyField(position, subLabels, valuesIterator, label, PropertyVisibility.OnlyVisible); } public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, GUIContent label, PropertyVisibility visibility) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); position = MultiFieldPrefixLabel(position, id, label, subLabels.Length); position.height = kSingleLineHeight; MultiPropertyField(position, subLabels, valuesIterator, visibility); } public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator) { MultiPropertyField(position, subLabels, valuesIterator, PropertyVisibility.OnlyVisible); } public static void MultiPropertyField(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, PropertyVisibility visibility) { MultiPropertyFieldInternal(position, subLabels, valuesIterator, visibility); } public enum PropertyVisibility { All, OnlyVisible } internal static void MultiPropertyFieldInternal(Rect position, GUIContent[] subLabels, SerializedProperty valuesIterator, PropertyVisibility visibility, bool[] disabledMask = null, float prefixLabelWidth = -1) { int eCount = subLabels.Length; float w = (position.width - (eCount - 1) * kSpacingSubLabel) / eCount; Rect nr = new Rect(position) {width = w}; float t = EditorGUIUtility.labelWidth; int l = indentLevel; indentLevel = 0; for (int i = 0; i < subLabels.Length; i++) { EditorGUIUtility.labelWidth = GetLabelWidth(subLabels[i], prefixLabelWidth); if (disabledMask != null) BeginDisabled(disabledMask[i]); PropertyField(nr, valuesIterator, subLabels[i]); if (disabledMask != null) EndDisabled(); nr.x += w + kSpacingSubLabel; switch (visibility) { case PropertyVisibility.All: valuesIterator.Next(false); break; case PropertyVisibility.OnlyVisible: valuesIterator.NextVisible(false); break; } } EditorGUIUtility.labelWidth = t; indentLevel = l; } // Make a property field that look like a multi property field (but is made up of individual properties) internal static void PropertiesField(Rect position, GUIContent label, SerializedProperty[] properties, GUIContent[] propertyLabels, float propertyLabelsWidth) { int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); Rect fieldPosition = PrefixLabel(position, id, label); fieldPosition.height = kSingleLineHeight; float oldLabelWidth = EditorGUIUtility.labelWidth; int oldIndentLevel = indentLevel; EditorGUIUtility.labelWidth = propertyLabelsWidth; indentLevel = 0; for (int i = 0; i < properties.Length; i++) { PropertyField(fieldPosition, properties[i], propertyLabels[i]); fieldPosition.y += kSingleLineHeight + kVerticalSpacingMultiField; } indentLevel = oldIndentLevel; EditorGUIUtility.labelWidth = oldLabelWidth; } internal static int CycleButton(Rect position, int selected, GUIContent[] options, GUIStyle style) { if (selected >= options.Length || selected < 0) { selected = 0; GUI.changed = true; } if (GUI.Button(position, options[selected], style)) { selected++; GUI.changed = true; if (selected >= options.Length) { selected = 0; } } return selected; } public static Color ColorField(Rect position, Color value) { int id = GUIUtility.GetControlID(s_ColorHash, FocusType.Keyboard, position); return DoColorField(IndentedRect(position), id, value, true, true, false); } internal static Color ColorField(Rect position, Color value, bool showEyedropper, bool showAlpha) { int id = GUIUtility.GetControlID(s_ColorHash, FocusType.Keyboard, position); return DoColorField(position, id, value, showEyedropper, showAlpha, false); } public static Color ColorField(Rect position, string label, Color value) { return ColorField(position, EditorGUIUtility.TempContent(label), value); } // Make a field for selecting a [[Color]]. public static Color ColorField(Rect position, GUIContent label, Color value) { int id = GUIUtility.GetControlID(s_ColorHash, FocusType.Keyboard, position); return DoColorField(PrefixLabel(position, id, label), id, value, true, true, false); } internal static Color ColorField(Rect position, GUIContent label, Color value, bool showEyedropper, bool showAlpha) { int id = GUIUtility.GetControlID(s_ColorHash, FocusType.Keyboard, position); return DoColorField(PrefixLabel(position, id, label), id, value, showEyedropper, showAlpha, false); } #pragma warning disable 612 [Obsolete("Use EditorGUI.ColorField(Rect position, GUIContent label, Color value, bool showEyedropper, bool showAlpha, bool hdr)")] public static Color ColorField(Rect position, GUIContent label, Color value, bool showEyedropper, bool showAlpha, bool hdr, ColorPickerHDRConfig hdrConfig) { return ColorField(position, label, value, showEyedropper, showAlpha, hdr); } #pragma warning restore 612 public static Color ColorField(Rect position, GUIContent label, Color value, bool showEyedropper, bool showAlpha, bool hdr) { int id = GUIUtility.GetControlID(s_ColorHash, FocusType.Keyboard, position); return DoColorField(PrefixLabel(position, id, label), id, value, showEyedropper, showAlpha, hdr); } const float kEyedropperSize = 20f; private static Color DoColorField(Rect position, int id, Color value, bool showEyedropper, bool showAlpha, bool hdr) { Event evt = Event.current; GUIStyle style = EditorStyles.colorField; Color origColor = value; value = showMixedValue ? Color.white : value; bool hovered = position.Contains(evt.mousePosition); bool hoveredEyedropper = new Rect(position.x + position.width - kEyedropperSize, position.y, kEyedropperSize, position.height).Contains(evt.mousePosition); var wasEnabled = GUI.enabled; var eventType = GetEventTypeForControlAllowDisabledContextMenuPaste(evt, id); switch (eventType) { case EventType.MouseDown: if (showEyedropper) { hovered ^= hoveredEyedropper; } if (hovered) { switch (evt.button) { case 0: // Left click: Show the ColorPicker GUIUtility.keyboardControl = id; showMixedValue = false; ColorPicker.Show(GUIView.current, value, showAlpha, hdr); GUIUtility.ExitGUI(); break; case 1: // Right click: Show color context menu // See ExecuteCommand section below to see handling for copy & paste GUIUtility.keyboardControl = id; var names = new[] {L10n.Tr("Copy"), L10n.Tr("Paste")}; var enabled = new[] {true, wasEnabled && Clipboard.hasColor}; var currentView = GUIView.current; EditorUtility.DisplayCustomMenu( new Rect(Event.current.mousePosition, Vector2.zero), names, enabled, null, delegate(object data, string[] options, int selected) { if (selected == 0) { Event e = EditorGUIUtility.CommandEvent(EventCommandNames.Copy); currentView.SendEvent(e); } else if (selected == 1) { Event e = EditorGUIUtility.CommandEvent(EventCommandNames.Paste); currentView.SendEvent(e); } }, null); evt.Use(); return origColor; } } if (showEyedropper) { if (hoveredEyedropper && wasEnabled) { GUIUtility.keyboardControl = id; EyeDropper.Start(GUIView.current); s_ColorPickID = id; GUIUtility.ExitGUI(); } } break; case EventType.Repaint: Rect position2; position2 = showEyedropper ? style.padding.Remove(position) : EditorStyles.colorPickerBox.padding.Remove(position); if (showEyedropper) { style.Draw(position, GUIContent.none, id, false, hovered); // Draw box outline and eyedropper icon } else { EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id, false, hovered); // Draw box outline } // Draw color field if (showEyedropper && s_ColorPickID == id) { Color c = EyeDropper.GetPickedColor(); c.a = value.a; if (hdr) c = c.linear; EditorGUIUtility.DrawColorSwatch(position2, c, showAlpha, hdr); } else { EditorGUIUtility.DrawColorSwatch(position2, value, showAlpha, hdr); } break; case EventType.ValidateCommand: switch (evt.commandName) { case EventCommandNames.UndoRedoPerformed: // Set color in ColorPicker in case an undo/redo has been made // when ColorPicker sends an event back to this control's GUIView, it someties retains keyboardControl if ((GUIUtility.keyboardControl == id || ColorPicker.originalKeyboardControl == id) && ColorPicker.visible) ColorPicker.color = value; break; case EventCommandNames.Copy: case EventCommandNames.Paste: evt.Use(); break; } break; case EventType.ExecuteCommand: // Cancel EyeDropper if we change focus. if (showEyedropper && Event.current.commandName == EventCommandNames.NewKeyboardFocus) { EyeDropper.End(); s_ColorPickID = 0; } // when ColorPicker sends an event back to this control's GUIView, it sometimes retains keyboardControl if (GUIUtility.keyboardControl == id || ColorPicker.originalKeyboardControl == id) { switch (evt.commandName) { case EventCommandNames.EyeDropperUpdate: HandleUtility.Repaint(); break; case EventCommandNames.EyeDropperClicked: GUI.changed = true; HandleUtility.Repaint(); Color c = EyeDropper.GetLastPickedColor(); c.a = value.a; s_ColorPickID = 0; return hdr ? c.linear : c; case EventCommandNames.EyeDropperCancelled: HandleUtility.Repaint(); s_ColorPickID = 0; break; case EventCommandNames.ColorPickerChanged: GUI.changed = true; HandleUtility.Repaint(); return ColorPicker.color; case EventCommandNames.Copy: Clipboard.colorValue = value; evt.Use(); break; case EventCommandNames.Paste: PasteColor(ref origColor, showAlpha, hdr); break; } } break; case EventType.KeyDown: if (evt.MainActionKeyForControl(id)) { evt.Use(); showMixedValue = false; ColorPicker.Show(GUIView.current, value, showAlpha, hdr); GUIUtility.ExitGUI(); } else if (evt.modifiers == EventModifiers.Control) { if (evt.keyCode == KeyCode.C) { Clipboard.colorValue = value; evt.Use(); } else if (evt.keyCode == KeyCode.V) { PasteColor(ref origColor, showAlpha, hdr); } } break; } return origColor; } private static void PasteColor(ref Color origColor, bool showAlpha, bool hdr) { if (Clipboard.hasColor) { Color pasted = Clipboard.colorValue; if (!hdr && pasted.maxColorComponent > 1f) pasted = pasted.RGBMultiplied(1f / pasted.maxColorComponent); // Do not change alpha if color field is not showing alpha if (!showAlpha) pasted.a = origColor.a; origColor = pasted; GUI.changed = true; Event.current.Use(); } } public static AnimationCurve CurveField(Rect position, AnimationCurve value) { int id = GUIUtility.GetControlID(s_CurveHash, FocusType.Keyboard, position); return DoCurveField(IndentedRect(position), id, value, kCurveColor, new Rect(), null); } public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value) { return CurveField(position, EditorGUIUtility.TempContent(label), value); } public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value) { int id = GUIUtility.GetControlID(s_CurveHash, FocusType.Keyboard, position); return DoCurveField(PrefixLabel(position, id, label), id, value, kCurveColor, new Rect(), null); } // Variants with settings public static AnimationCurve CurveField(Rect position, AnimationCurve value, Color color, Rect ranges) { int id = GUIUtility.GetControlID(s_CurveHash, FocusType.Keyboard, position); return DoCurveField(IndentedRect(position), id, value, color, ranges, null); } public static AnimationCurve CurveField(Rect position, string label, AnimationCurve value, Color color, Rect ranges) { return CurveField(position, EditorGUIUtility.TempContent(label), value, color, ranges); } // Make a field for editing an [[AnimationCurve]]. public static AnimationCurve CurveField(Rect position, GUIContent label, AnimationCurve value, Color color, Rect ranges) { int id = GUIUtility.GetControlID(s_CurveHash, FocusType.Keyboard, position); return DoCurveField(PrefixLabel(position, id, label), id, value, color, ranges, null); } public static void CurveField(Rect position, SerializedProperty property, Color color, Rect ranges) { CurveField(position, property, color, ranges, null); } // Make a field for editing an [[AnimationCurve]]. public static void CurveField(Rect position, SerializedProperty property, Color color, Rect ranges, GUIContent label) { label = BeginProperty(position, label, property); int id = GUIUtility.GetControlID(s_CurveHash, FocusType.Keyboard, position); DoCurveField(PrefixLabel(position, id, label), id, null, color, ranges, property); EndProperty(); } private static void SetCurveEditorWindowCurve(AnimationCurve value, SerializedProperty property, Color color) { if (property != null) { CurveEditorWindow.curve = property.hasMultipleDifferentValues ? new AnimationCurve() : property.animationCurveValue; } else { CurveEditorWindow.curve = value; } CurveEditorWindow.color = color; } internal static AnimationCurve DoCurveField(Rect position, int id, AnimationCurve value, Color color, Rect ranges, SerializedProperty property) { Event evt = Event.current; // Avoid crash problems caused by textures with zero or negative sizes! position.width = Mathf.Max(position.width, 2); position.height = Mathf.Max(position.height, 2); if (GUIUtility.keyboardControl == id && evt.type != EventType.Layout && GUIView.current == CurveEditorWindow.instance.delegateView) { if (s_CurveID != id) { s_CurveID = id; if (CurveEditorWindow.visible) { SetCurveEditorWindowCurve(value, property, color); ShowCurvePopup(ranges); } } else { if (CurveEditorWindow.visible && Event.current.type == EventType.Repaint) { SetCurveEditorWindowCurve(value, property, color); CurveEditorWindow.instance.Repaint(); } } } switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (evt.button == 0 && position.Contains(evt.mousePosition)) { s_CurveID = id; GUIUtility.keyboardControl = id; SetCurveEditorWindowCurve(value, property, color); ShowCurvePopup(ranges); evt.Use(); GUIUtility.ExitGUI(); } break; case EventType.Repaint: Rect position2 = position; position2.y += 1; position2.height -= 1; if (ranges != new Rect()) { EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, kCurveBGColor, ranges); } else { EditorGUIUtility.DrawCurveSwatch(position2, value, property, color, kCurveBGColor); } EditorStyles.colorPickerBox.Draw(position2, GUIContent.none, id, false); break; case EventType.ExecuteCommand: if (s_CurveID == id && GUIView.current == CurveEditorWindow.instance.delegateView) { switch (evt.commandName) { case CurveEditorWindow.CurveChangedCommand: GUI.changed = true; AnimationCurvePreviewCache.ClearCache(); HandleUtility.Repaint(); if (property != null) { property.animationCurveValue = CurveEditorWindow.curve; if (property.hasMultipleDifferentValues) { Debug.LogError("AnimationCurve SerializedProperty hasMultipleDifferentValues is true after writing."); } } return CurveEditorWindow.curve; } } break; case EventType.KeyDown: if (evt.MainActionKeyForControl(id)) { s_CurveID = id; SetCurveEditorWindowCurve(value, property, color); ShowCurvePopup(ranges); evt.Use(); GUIUtility.ExitGUI(); } break; } return value; } private static void ShowCurvePopup(Rect ranges) { CurveEditorSettings settings = new CurveEditorSettings(); if (ranges.width > 0 && ranges.height > 0 && ranges.width != Mathf.Infinity && ranges.height != Mathf.Infinity) { settings.hRangeMin = ranges.xMin; settings.hRangeMax = ranges.xMax; settings.vRangeMin = ranges.yMin; settings.vRangeMax = ranges.yMax; } CurveEditorWindow.instance.Show(GUIView.current, settings); } internal static Vector2 GetObjectIconDropDownSize(float width, float height) { return new Vector2(width + kDropDownArrowWidth / 2 + 2 * kDropDownArrowMargin, height + kDropDownArrowWidth / 2 + 2 * kDropDownArrowMargin); } internal static void ObjectIconDropDown(Rect position, Object[] targets, bool showLabelIcons, Texture2D nullIcon, SerializedProperty iconProperty) { if (s_IconTextureInactive == null) { s_IconTextureInactive = (Material)EditorGUIUtility.LoadRequired("Inspectors/InactiveGUI.mat"); } if (s_IconButtonStyle == null) { s_IconButtonStyle = new GUIStyle(EditorStyles.iconButton) { fixedWidth = 0, fixedHeight = 0 }; } if (DropdownButton(position, GUIContent.none, FocusType.Passive, s_IconButtonStyle)) { if (IconSelector.ShowAtPosition(targets, position, showLabelIcons)) { GUIUtility.ExitGUI(); } } if (Event.current.type == EventType.Repaint) { var contentPosition = position; contentPosition.xMin += kDropDownArrowMargin; contentPosition.xMax -= kDropDownArrowMargin + kDropDownArrowWidth / 2; contentPosition.yMin += kDropDownArrowMargin; contentPosition.yMax -= kDropDownArrowMargin + kDropDownArrowWidth / 2; Rect arrowRect = new Rect(contentPosition.x + contentPosition.width - kDropDownArrowWidth / 2, contentPosition.y + contentPosition.height - kDropDownArrowHeight / 2, kDropDownArrowWidth, kDropDownArrowHeight); Texture2D icon = null; if (!iconProperty.hasMultipleDifferentValues) { icon = AssetPreview.GetMiniThumbnail(targets[0]); } if (icon == null) { icon = nullIcon; } Vector2 iconSize = contentPosition.size; if (icon) { iconSize.x = Mathf.Min(icon.width, iconSize.x); iconSize.y = Mathf.Min(icon.height, iconSize.y); } Rect iconRect = new Rect(contentPosition.x + contentPosition.width / 2 - iconSize.x / 2, contentPosition.y + contentPosition.height / 2 - iconSize.y / 2 , iconSize.x, iconSize.y); GameObject obj = targets[0] as GameObject; bool isInactive = obj && (!EditorUtility.IsPersistent(targets[0]) && (!obj.activeSelf || !obj.activeInHierarchy)); if (isInactive) { var imageAspect = icon.width / (float)icon.height; Rect iconScreenRect = new Rect(); Rect sourceRect = new Rect(); GUI.CalculateScaledTextureRects(iconRect, ScaleMode.ScaleToFit, imageAspect, ref iconScreenRect, ref sourceRect); Graphics.DrawTexture(iconScreenRect, icon, sourceRect, 0, 0, 0, 0, new Color(.5f, .5f, .5f, 1f), s_IconTextureInactive); } else { GUI.DrawTexture(iconRect, icon, ScaleMode.ScaleToFit); } if (s_IconDropDown == null) { s_IconDropDown = EditorGUIUtility.IconContent("Icon Dropdown"); } GUIStyle.none.Draw(arrowRect, s_IconDropDown, false, false, false, false); } } // Titlebar without foldout public static void InspectorTitlebar(Rect position, Object[] targetObjs) { GUIStyle baseStyle = GUIStyle.none; int id = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); DoInspectorTitlebar(position, id, true, targetObjs, null, baseStyle); } public static bool InspectorTitlebar(Rect position, bool foldout, Object targetObj, bool expandable) { return InspectorTitlebar(position, foldout, new[] {targetObj}, expandable); } // foldable titlebar. public static bool InspectorTitlebar(Rect position, bool foldout, Object[] targetObjs, bool expandable) { GUIStyle baseStyle = EditorStyles.inspectorTitlebar; // Important to get controlId for the foldout first, so it gets keyboard focus before the toggle does. int id = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); DoInspectorTitlebar(position, id, foldout, targetObjs, null, baseStyle); foldout = DoObjectMouseInteraction(foldout, position, targetObjs, id); if (expandable) { Rect renderRect = GetInspectorTitleBarObjectFoldoutRenderRect(position, baseStyle); DoObjectFoldoutInternal(foldout, renderRect, id); } return foldout; } // foldable titlebar based on Editor. public static bool InspectorTitlebar(Rect position, bool foldout, Editor editor) { GUIStyle baseStyle = EditorStyles.inspectorTitlebar; // Important to get controlId for the foldout first, so it gets keyboard focus before the toggle does. int id = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); DoInspectorTitlebar(position, id, foldout, editor.targets, editor.enabledProperty, baseStyle); foldout = DoObjectMouseInteraction(foldout, position, editor.targets, id); if (editor.CanBeExpandedViaAFoldout()) { Rect renderRect = GetInspectorTitleBarObjectFoldoutRenderRect(position, baseStyle); DoObjectFoldoutInternal(foldout, renderRect, id); } return foldout; } static Rect GetIconRect(Rect position, GUIStyle baseStyle) { return new Rect(position.x + baseStyle.padding.left, position.y + (baseStyle.fixedHeight - kInspTitlebarIconWidth) / 2 + baseStyle.padding.top, kInspTitlebarIconWidth, kInspTitlebarIconWidth); } static Rect GetTextRect(Rect position, Rect iconRect, Rect settingsRect, GUIStyle baseStyle, GUIStyle textStyle) { return new Rect(iconRect.xMax + kInspTitlebarSpacing + kInspTitlebarSpacing + kInspTitlebarIconWidth, position.y + (baseStyle.fixedHeight - textStyle.fixedHeight) / 2 + baseStyle.padding.top, 100, textStyle.fixedHeight) { xMax = settingsRect.xMin - kInspTitlebarSpacing }; } static Rect GetSettingsRect(Rect position, GUIStyle baseStyle, GUIStyle iconButtonStyle) { Vector2 settingsElementSize = iconButtonStyle.CalcSize(GUIContents.titleSettingsIcon); return new Rect(position.xMax - baseStyle.padding.right - kInspTitlebarSpacing - kInspTitlebarIconWidth , position.y + (baseStyle.fixedHeight - settingsElementSize.y) / 2 + baseStyle.padding.top, settingsElementSize.x, settingsElementSize.y); } internal static bool EnableCheckBoxInTitlebar(Object targetObj) { if (targetObj is ScriptableObject && targetObj is not StateMachineBehaviour) return false; return true; } // Make an inspector-window-like titlebar. internal static void DoInspectorTitlebar(Rect position, int id, bool foldout, Object[] targetObjs, SerializedProperty enabledProperty, GUIStyle baseStyle) { GUIStyle textStyle = EditorStyles.inspectorTitlebarText; GUIStyle iconButtonStyle = EditorStyles.iconButton; Event evt = Event.current; bool pressed = GUIUtility.hotControl == id; bool hasFocus = GUIUtility.HasKeyFocus(id); bool hovered = position.Contains(evt.mousePosition); Rect iconRect = GetIconRect(position, baseStyle); Rect settingsRect = GetSettingsRect(position, baseStyle, iconButtonStyle); Rect textRect = GetTextRect(position, iconRect, settingsRect, baseStyle, textStyle); if (evt.type == EventType.Repaint) { baseStyle.Draw(position, GUIContent.none, hovered, pressed, foldout, hasFocus); } bool isAddedComponentAndEventIsRepaint = false; Component comp = targetObjs[0] as Component; if (ShouldDrawOverrideBackground(targetObjs, evt, comp)) { isAddedComponentAndEventIsRepaint = true; DrawOverrideBackgroundApplicable(position, true); } int enabled = -1; foreach (Object targetObj in targetObjs) { if (comp is MonoBehaviour) { enabled = 1; } else { int thisEnabled = EditorUtility.GetObjectEnabled(targetObj); if (enabled == -1) { if (EnableCheckBoxInTitlebar(targetObj)) enabled = thisEnabled; } else if (enabled != thisEnabled) { enabled = -2; // Early out: mix value mode break; } } } if (enabled != -1) { Rect toggleRect = iconRect; toggleRect.x = iconRect.xMax + kInspTitlebarSpacing; Rect combinedIconAndToggleRect = new Rect(iconRect.x, iconRect.y, toggleRect.xMax - iconRect.xMin, iconRect.height); if (enabledProperty != null) { enabledProperty.serializedObject.Update(); EditorGUI.PropertyField(toggleRect, enabledProperty, GUIContent.none); enabledProperty.serializedObject.ApplyModifiedProperties(); } // The codepath and usage where we do not have a SerializedProperty is more complicated while // providing less functionality. It does not display a line in the margin when the enabled // toggle has been overridden on a Prefab instance. // The stuff it's doing with AnimationMode, undo handling, and multi object editing // is all stuff that's also handled internally in SerializedProperty. // It's kept for backwards compatibility only, since InspectorTitlebar is public API. else { bool enabledState = enabled != 0; showMixedValue = enabled == -2; BeginChangeCheck(); Color previousColor = GUI.backgroundColor; bool animated = AnimationMode.IsPropertyAnimated(targetObjs[0], kEnabledPropertyName); if (animated) { Color animatedColor = AnimationMode.animatedPropertyColor; if (AnimationMode.InAnimationRecording()) animatedColor = AnimationMode.recordedPropertyColor; else if (AnimationMode.IsPropertyCandidate(targetObjs[0], kEnabledPropertyName)) animatedColor = AnimationMode.candidatePropertyColor; animatedColor.a *= GUI.color.a; GUI.backgroundColor = animatedColor; } int toggleId = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); enabledState = EditorGUIInternal.DoToggleForward(toggleRect, toggleId, enabledState, GUIContent.none, EditorStyles.toggle); if (animated) { GUI.backgroundColor = previousColor; } if (EndChangeCheck()) { Undo.RecordObjects(targetObjs, (enabledState ? "Enable" : "Disable") + " Component" + (targetObjs.Length > 1 ? "s" : "")); foreach (Object targetObj in targetObjs) { EditorUtility.SetObjectEnabled(targetObj, enabledState); } } showMixedValue = false; } if (combinedIconAndToggleRect.Contains(Event.current.mousePosition)) { // It's necessary to handle property context menu here in right mouse down because // component contextual menu will override this otherwise. if ((evt.type == EventType.MouseDown && evt.button == 1) || evt.type == EventType.ContextClick) { SerializedObject serializedObject = new SerializedObject(targetObjs); DoPropertyContextMenu(serializedObject.FindProperty(kEnabledPropertyName)); evt.Use(); } } } Rect headerItemRect = settingsRect; headerItemRect.x -= kInspTitlebarIconWidth + kInspTitlebarSpacing; headerItemRect = EditorGUIUtility.DrawEditorHeaderItems(headerItemRect, targetObjs, kInspTitlebarSpacing); textRect.xMax = headerItemRect.xMin - kInspTitlebarSpacing; if (evt.type == EventType.Repaint) { var icon = AssetPreview.GetMiniThumbnail(targetObjs[0]); GUIStyle.none.Draw(iconRect, EditorGUIUtility.TempContent(icon), iconRect.Contains(Event.current.mousePosition), false, false, false); if (isAddedComponentAndEventIsRepaint) GUIStyle.none.Draw(iconRect, EditorGUIUtility.TempContent(Styles.prefabOverlayAddedIcon), false, false, false, false); } // Temporarily set GUI.enabled = true to enable the Settings button. see Case 947218. var oldGUIEnabledState = GUI.enabled; GUI.enabled = true; switch (evt.type) { case EventType.MouseDown: if (EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None && settingsRect.Contains(evt.mousePosition)) { EditorUtility.DisplayObjectContextMenu(settingsRect, targetObjs, 0); evt.Use(); } break; case EventType.Repaint: textStyle.Draw(textRect, EditorGUIUtility.TempContent(ObjectNames.GetInspectorTitle(targetObjs[0], targetObjs.Length > 1)), hovered, pressed, foldout, hasFocus); if (EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None) { EditorStyles.optionsButtonStyle.Draw(settingsRect, GUIContent.none, id, foldout, settingsRect.Contains(Event.current.mousePosition)); } break; } GUI.enabled = oldGUIEnabledState; } internal static bool ShouldDrawOverrideBackground(Object[] targetObjs, Event evt, Component comp) { return evt.type == EventType.Repaint && targetObjs.Length == 1 && comp != null && EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None && PrefabUtility.GetCorrespondingConnectedObjectFromSource(comp.gameObject) != null && PrefabUtility.GetCorrespondingObjectFromSource(comp) == null; } internal static void RemovedComponentTitlebar(Rect position, GameObject instanceGo, Component sourceComponent) { GUIStyle baseStyle = EditorStyles.inspectorTitlebar; GUIStyle textStyle = EditorStyles.inspectorTitlebarText; GUIStyle iconButtonStyle = EditorStyles.iconButton; Rect iconRect = GetIconRect(position, baseStyle); Rect settingsRect = GetSettingsRect(position, baseStyle, iconButtonStyle); Rect textRect = GetTextRect(position, iconRect, settingsRect, baseStyle, textStyle); textRect.xMax = settingsRect.xMin - kInspTitlebarSpacing; Event evt = Event.current; bool openMenu = false; Rect openMenuRect = new Rect(); if (position.Contains(Event.current.mousePosition)) { // It's necessary to handle property context menu here in right mouse down because // component contextual menu will override this otherwise. if ((evt.type == EventType.MouseDown && evt.button == 1) || evt.type == EventType.ContextClick) openMenu = true; } Rect headerItemRect = settingsRect; headerItemRect.x -= kInspTitlebarIconWidth + kInspTitlebarSpacing; textRect.xMax = headerItemRect.xMin - kInspTitlebarSpacing; int id = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); switch (evt.type) { case EventType.MouseDown: if (settingsRect.Contains(evt.mousePosition)) { openMenu = true; openMenuRect = settingsRect; } break; case EventType.Repaint: baseStyle.Draw(position, GUIContent.none, false, false, false, false); if (EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None) DrawOverrideBackgroundApplicable(position, true); EditorStyles.optionsButtonStyle.Draw(settingsRect, GUIContent.none, id, false, settingsRect.Contains(Event.current.mousePosition)); var icon = AssetPreview.GetMiniThumbnail(sourceComponent); using (new DisabledScope(true)) { GUIStyle.none.Draw(iconRect, EditorGUIUtility.TempContent(icon), false, false, false, false); } GUIStyle.none.Draw(iconRect, EditorGUIUtility.TempContent(Styles.prefabOverlayRemovedIcon), false, false, false, false); position = baseStyle.padding.Remove(position); using (new DisabledScope(true)) { textStyle.Draw(textRect, EditorGUIUtility.TempContent(ObjectNames.GetInspectorTitle(sourceComponent) + " (Removed)"), false, false, false, false); } break; } if (openMenu) { GenericMenu menu = new GenericMenu(); PrefabUtility.HandleApplyRevertMenuItems( "Removed Component", instanceGo, (menuItemContent, sourceObject, _) => { TargetChoiceHandler.ObjectInstanceAndSourceInfo info = new TargetChoiceHandler.ObjectInstanceAndSourceInfo(); info.instanceObject = instanceGo; Component componentToRemove = sourceComponent; while (componentToRemove.gameObject != sourceObject) { componentToRemove = PrefabUtility.GetCorrespondingObjectFromSource(componentToRemove); if (componentToRemove == null) return; } info.correspondingObjectInSource = componentToRemove; if (!PrefabUtility.IsPartOfPrefabThatCanBeAppliedTo(componentToRemove) || EditorUtility.IsPersistent(instanceGo)) menu.AddDisabledItem(menuItemContent); else menu.AddItem(menuItemContent, false, TargetChoiceHandler.ApplyPrefabRemovedComponent, info); }, (menuItemContent) => { TargetChoiceHandler.ObjectInstanceAndSourceInfo info = new TargetChoiceHandler.ObjectInstanceAndSourceInfo(); info.instanceObject = instanceGo; info.correspondingObjectInSource = sourceComponent; menu.AddItem(menuItemContent, false, TargetChoiceHandler.RevertPrefabRemovedComponent, info); } ); if (openMenuRect == new Rect()) menu.ShowAsContext(); else menu.DropDown(settingsRect); evt.Use(); } } internal static bool ToggleTitlebar(Rect position, GUIContent label, bool foldout, ref bool toggleValue) { // Important to get controlId for the foldout first, so it gets keyboard focus before the toggle does. int id = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); GUIStyle baseStyle = EditorStyles.inspectorTitlebar; GUIStyle textStyle = EditorStyles.inspectorTitlebarText; GUIStyle foldoutStyle = EditorStyles.titlebarFoldout; Rect toggleRect = new Rect(position.x + baseStyle.padding.left, position.y + baseStyle.padding.top, kInspTitlebarIconWidth, kInspTitlebarIconWidth); Rect textRect = new Rect(toggleRect.xMax + kInspTitlebarSpacing, toggleRect.y, 200, kInspTitlebarIconWidth); int toggleId = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); toggleValue = EditorGUIInternal.DoToggleForward(toggleRect, toggleId, toggleValue, GUIContent.none, EditorStyles.toggle); if (Event.current.type == EventType.Repaint) { baseStyle.Draw(position, GUIContent.none, id, foldout); foldoutStyle.Draw(GetInspectorTitleBarObjectFoldoutRenderRect(position, baseStyle), GUIContent.none, id, foldout); position = baseStyle.padding.Remove(position); textStyle.Draw(textRect, label, id, foldout); } return EditorGUIInternal.DoToggleForward(IndentedRect(position), id, foldout, GUIContent.none, GUIStyle.none); } internal static bool FoldoutTitlebar(Rect position, GUIContent label, bool foldout, bool skipIconSpacing) { return FoldoutTitlebar(position, label, foldout, skipIconSpacing, EditorStyles.inspectorTitlebar, EditorStyles.inspectorTitlebarText); } internal static bool FoldoutTitlebar(Rect position, GUIContent label, bool foldout, bool skipIconSpacing, GUIStyle baseStyle, GUIStyle textStyle) { // Important to get controlId for the foldout first, so it gets keyboard focus before the toggle does. int id = GUIUtility.GetControlID(s_TitlebarHash, FocusType.Keyboard, position); switch (Event.current.type) { case EventType.KeyDown: if (GUIUtility.keyboardControl == id) { KeyCode kc = Event.current.keyCode; if (kc == KeyCode.LeftArrow && foldout || (kc == KeyCode.RightArrow && foldout == false)) { foldout = !foldout; GUI.changed = true; Event.current.Use(); return foldout; } } break; case EventType.Repaint: GUIStyle foldoutStyle = EditorStyles.titlebarFoldout; var textPositionX = position.x + baseStyle.padding.left + (skipIconSpacing ? 0 : (kInspTitlebarIconWidth + kInspTitlebarSpacing)); Rect textRect = new Rect(textPositionX, position.y + baseStyle.padding.top, Mathf.Max(EditorGUIUtility.labelWidth, position.xMax - textPositionX), kInspTitlebarIconWidth); bool hovered = position.Contains(Event.current.mousePosition); baseStyle.Draw(position, GUIContent.none, id, foldout, hovered); foldoutStyle.Draw(GetInspectorTitleBarObjectFoldoutRenderRect(position, baseStyle), GUIContent.none, id, foldout, hovered); position = baseStyle.padding.Remove(position); textStyle.Draw(textRect, EditorGUIUtility.TempContent(label.text), id, foldout, hovered); break; default: break; } return EditorGUIInternal.DoToggleForward(IndentedRect(position), id, foldout, GUIContent.none, GUIStyle.none); } [EditorHeaderItem(typeof(Object), -1000)] internal static bool HelpIconButton(Rect position, Object[] objs) { var obj = objs[0]; bool isDevBuild = Unsupported.IsSourceBuild(); // For efficiency, only check in development builds if this script is a user script. bool monoBehaviourFallback = !isDevBuild; if (!monoBehaviourFallback) { monoBehaviourFallback = HelpButtonCache.IsObjectPartOfTargetAssemblies(obj); } bool hasHelp = HelpButtonCache.HasHelpForObject(obj, monoBehaviourFallback); if (hasHelp || isDevBuild) { // Help button should not be disabled at any time. For example VCS system disables // inspectors and it wouldn't make sense to prevent users from getting help because // he didn't check out the file yet. bool wasEditorDisabled = GUI.enabled; GUI.enabled = true; GUIContent content = GUIContent.Temp(GUIContents.helpIcon.image); // Only build the tooltip string if the cursor is over our help button rect if (position.Contains(Event.current.mousePosition)) { string helpTopic = Help.GetNiceHelpNameForObject(obj, monoBehaviourFallback); if (isDevBuild && !hasHelp) { bool isScript = obj is MonoBehaviour; string pageName = (isScript ? "script-" : "sealed partial class-") + helpTopic; content.tooltip = string.Format(@"Could not find Reference page for {0} ({1}).\nDocs for this object is missing or all docs are missing.\nThis warning only shows up in development builds.", helpTopic, pageName); } else { content.tooltip = string.Format("Open Reference for {0}.", ObjectNames.NicifyVariableName(helpTopic)); } } Color oldColor = GUI.color; if (isDevBuild && !hasHelp) GUI.color = Color.yellow; GUIStyle helpIconStyle = EditorStyles.iconButton; if (GUI.Button(position, content, helpIconStyle)) { Help.ShowHelpForObject(obj); } GUI.color = oldColor; GUI.enabled = wasEditorDisabled; return true; } return false; } // Make a label with a foldout arrow to the left of it. internal static bool FoldoutInternal(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, GUIStyle style) { Rect origPosition = position; position = style.margin.Remove(position); if (EditorGUIUtility.hierarchyMode) { int offset = (EditorStyles.foldout.padding.left - EditorStyles.label.padding.left); position.xMin -= offset; } int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, position); EventType eventType = Event.current.type; // special case test, so we are able to receive mouse events when we are disabled. This allows the foldout to still be expanded/contracted when disabled. if (!GUI.enabled && GUIClip.enabled && (Event.current.rawType == EventType.MouseDown || Event.current.rawType == EventType.MouseDrag || Event.current.rawType == EventType.MouseUp)) { eventType = Event.current.rawType; } Rect clickRect = position; if (!toggleOnLabelClick) { clickRect.width = style.padding.left; clickRect.x += indent; } switch (eventType) { case EventType.MouseDown: // If the mouse is inside the button, we say that we're the hot control if (clickRect.Contains(Event.current.mousePosition) && Event.current.button == 0) { GUIUtility.keyboardControl = GUIUtility.hotControl = id; Event.current.Use(); } break; case EventType.MouseUp: if (GUIUtility.hotControl == id) { GUIUtility.hotControl = 0; // If we got the mousedown, the mouseup is ours as well // (no matter if the click was in the button or not) Event.current.Use(); // toggle the passed-in value if the mouse was over the button & return true if (clickRect.Contains(Event.current.mousePosition)) { GUI.changed = true; return !foldout; } } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { Event.current.Use(); } break; case EventType.Repaint: EditorStyles.foldoutSelected.Draw(position, GUIContent.none, id, s_DragUpdatedOverID == id); Rect drawRect = new Rect(position.x + indent, position.y, EditorGUIUtility.labelWidth - indent, position.height); // If mixed values, indicate it in the collapsed foldout field so it's easy to see at a glance if anything // in the Inspector has different values. Don't show it when expanded, since the difference will be visible further down. if (showMixedValue && !foldout) { style.Draw(drawRect, content, id, false); BeginHandleMixedValueContentColor(); Rect fieldPosition = origPosition; fieldPosition.xMin += EditorGUIUtility.labelWidth; EditorStyles.label.Draw(fieldPosition, s_MixedValueContent, id, false); EndHandleMixedValueContentColor(); } else { style.Draw(drawRect, content, id, foldout); } break; case EventType.KeyDown: if (GUIUtility.keyboardControl == id) { KeyCode kc = Event.current.keyCode; if (kc == KeyCode.LeftArrow && foldout || (kc == KeyCode.RightArrow && foldout == false)) { foldout = !foldout; GUI.changed = true; Event.current.Use(); } } break; case EventType.DragUpdated: if (s_DragUpdatedOverID == id) { if (position.Contains(Event.current.mousePosition)) { if (Time.realtimeSinceStartup > s_FoldoutDestTime) { foldout = true; Event.current.Use(); } } else { s_DragUpdatedOverID = 0; } } else { if (position.Contains(Event.current.mousePosition)) { s_DragUpdatedOverID = id; s_FoldoutDestTime = Time.realtimeSinceStartup + kFoldoutExpandTimeout; Event.current.Use(); } } break; case EventType.DragExited: if (s_DragUpdatedOverID == id) { s_DragUpdatedOverID = 0; Event.current.Use(); } break; } return foldout; } // Make a progress bar. public static void ProgressBar(Rect position, float value, string text) { ProgressBar(position, value, GUIContent.Temp(text), false, EditorStyles.progressBarBack, EditorStyles.progressBarBar, EditorStyles.progressBarText); } internal static bool ProgressBar(Rect position, float value, GUIContent content, bool textOnBar, GUIStyle progressBarBackgroundStyle, GUIStyle progressBarStyle, GUIStyle progressBarTextStyle) { bool mouseHover = position.Contains(Event.current.mousePosition); int id = GUIUtility.GetControlID(s_ProgressBarHash, FocusType.Keyboard, position); Event evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (mouseHover) { Event.current.Use(); return true; } break; case EventType.Repaint: progressBarBackgroundStyle.Draw(position, mouseHover, false, false, false); if (value > 0.0f) { value = Mathf.Clamp01(value); var barRect = new Rect(position); barRect.width *= value; if (barRect.width >= 1f) progressBarStyle.Draw(barRect, GUIContent.none, mouseHover, false, false, false); } else if (value == -1.0f) { float barWidth = position.width * 0.2f; float halfBarWidth = barWidth / 2.0f; float cos = Mathf.Cos((float)EditorApplication.timeSinceStartup * 2f); float rb = position.x + halfBarWidth; float re = position.xMax - halfBarWidth; float scale = (re - rb) / 2f; float cursor = scale * cos; var barRect = new Rect(position.x + cursor + scale, position.y, barWidth, position.height); progressBarStyle.Draw(barRect, GUIContent.none, mouseHover, false, false, false); } var contentTextToDisplay = content; var contentWidth = progressBarTextStyle.CalcSize(contentTextToDisplay).x; if (contentWidth > position.width) { int numberOfVisibleCharacters = (int)((position.width / contentWidth) * content.text.Length); // we iterate in case we encounter a weird string like ________..............._________ (with big characters in the outside and small in the inside) int i = 0; do { int numberOfVisibleCharactersBySide = numberOfVisibleCharacters / 2 - 2 - i; //-2 to account for the ..., we reduce each iteration to fit contentTextToDisplay.text = content.text.Substring(0, numberOfVisibleCharactersBySide) + "..." + content.text.Substring(content.text.Length - numberOfVisibleCharactersBySide, numberOfVisibleCharactersBySide); ++i; } while (progressBarTextStyle.CalcSize(contentTextToDisplay).x > position.width); } progressBarTextStyle.Draw(position, contentTextToDisplay, mouseHover, false, false, false); break; } return false; } // Make a help box with a message to the user. public static void HelpBox(Rect position, string message, MessageType type) { HelpBox(position, EditorGUIUtility.TempContent(message, EditorGUIUtility.GetHelpIcon(type))); } public static void HelpBox(Rect position, GUIContent content) { GUI.Label(position, content, EditorStyles.helpBox); } internal static bool LabelHasContent(GUIContent label) { if (label == null) { return true; } // @TODO: find out why checking for GUIContent.none doesn't work return label.text != string.Empty || label.image != null; } internal static void PrepareCurrentPrefixLabel(int controlId) { if (s_HasPrefixLabel) { if (!string.IsNullOrEmpty(s_PrefixLabel.text)) { Color curColor = GUI.color; GUI.color = s_PrefixGUIColor; HandlePrefixLabel(s_PrefixTotalRect, s_PrefixRect, s_PrefixLabel, controlId, s_PrefixStyle); GUI.color = curColor; } s_HasPrefixLabel = false; } } internal static bool IsLabelHighlightEnabled() { return s_LabelHighlightContext != null && s_LabelHighlightContext.Length > 1; } internal static void BeginLabelHighlight(string searchContext, Color searchHighlightSelectionColor, Color searchHighlightColor) { if (searchContext != null && searchContext.Trim() == "") { searchContext = null; } s_LabelHighlightContext = searchContext; s_LabelHighlightSelectionColor = searchHighlightSelectionColor; s_LabelHighlightColor = searchHighlightColor; } internal static void EndLabelHighlight() { s_LabelHighlightContext = null; } internal static bool DrawLabelHighlight(Rect position, GUIContent label, GUIStyle style) { if (!IsLabelHighlightEnabled() || !SearchUtils.MatchSearchGroups(s_LabelHighlightContext, label.text, out var startHighlight, out var endHighlight)) return false; const bool isActive = false; const bool hasKeyboardFocus = true; // This ensure we draw the selection text over the label. const bool drawAsComposition = false; // Override text color when in label highlight regardless of the GUIStyleState var oldFocusedTextColor = style.focused.textColor; style.focused.textColor = s_LabelHighlightColor; style.DrawWithTextSelection(position, label, isActive, hasKeyboardFocus, startHighlight, endHighlight + 1, drawAsComposition, s_LabelHighlightSelectionColor); style.focused.textColor = oldFocusedTextColor; return true; } // Draw a prefix label and select the corresponding control if the label is clicked. // If no id or an id of 0 is specified, the id of the next control will be used. // For regular inline controls, the PrefixLabel method should be used, // but HandlePrefixLabel can be used for customized label placement. internal static void HandlePrefixLabelInternal(Rect totalPosition, Rect labelPosition, GUIContent label, int id, GUIStyle style) { // If we don't know the controlID at this time, delay the handling of the prefix label until the next GUIUtility.GetControlID if (id == 0 && label != null) { s_PrefixLabel.text = label.text; s_PrefixLabel.image = label.image; s_PrefixLabel.tooltip = label.tooltip; s_PrefixTotalRect = totalPosition; s_PrefixRect = labelPosition; s_PrefixStyle = style; s_PrefixGUIColor = GUI.color; s_HasPrefixLabel = true; return; } // Control highlighting if (Highlighter.searchMode == HighlightSearchMode.PrefixLabel || Highlighter.searchMode == HighlightSearchMode.Auto) { if (label != null) Highlighter.Handle(totalPosition, label.text); } switch (Event.current.type) { case EventType.Repaint: labelPosition.width += 1; Color oldColor = GUI.backgroundColor; GUI.backgroundColor = Color.white; if (!EditorGUI.DrawLabelHighlight(labelPosition, label, style)) style.DrawPrefixLabel(labelPosition, label, id); GUI.backgroundColor = oldColor; break; case EventType.MouseDown: if (Event.current.button == 0 && labelPosition.Contains(Event.current.mousePosition)) { if (EditorGUIUtility.CanHaveKeyboardFocus(id)) { GUIUtility.keyboardControl = id; } EditorGUIUtility.editingTextField = false; HandleUtility.Repaint(); } break; } } // Make a label in front of some control. public static Rect PrefixLabel(Rect totalPosition, GUIContent label) { return PrefixLabel(totalPosition, 0, label, EditorStyles.label); } public static Rect PrefixLabel(Rect totalPosition, GUIContent label, GUIStyle style) { return PrefixLabel(totalPosition, 0, label, style); } public static Rect PrefixLabel(Rect totalPosition, int id, GUIContent label) { return PrefixLabel(totalPosition, id, label, EditorStyles.label); } public static Rect PrefixLabel(Rect totalPosition, int id, GUIContent label, GUIStyle style) { if (!LabelHasContent(label)) { return IndentedRect(totalPosition); } Rect labelPosition = new Rect(totalPosition.x + indent, totalPosition.y, EditorGUIUtility.labelWidth - indent, lineHeight); Rect fieldPosition = new Rect(totalPosition.x + EditorGUIUtility.labelWidth + kPrefixPaddingRight, totalPosition.y, totalPosition.width - EditorGUIUtility.labelWidth - kPrefixPaddingRight, totalPosition.height); HandlePrefixLabel(totalPosition, labelPosition, label, id, style); return fieldPosition; } internal static bool UseVTMaterial(Texture texture) { if (PlayerSettings.GetVirtualTexturingSupportEnabled() == false) return false; Texture2D tex2d = texture as Texture2D; int tileSize = VirtualTexturing.EditorHelpers.tileSize; return tex2d != null && tex2d.vtOnly && tex2d.width > tileSize && tex2d.height > tileSize; } internal static Rect MultiFieldPrefixLabel(Rect totalPosition, int id, GUIContent label, int columns) { return MultiFieldPrefixLabel(totalPosition, id, label, columns, 0, false); } internal static Rect MultiFieldPrefixLabel(Rect totalPosition, int id, GUIContent label, int columns, float labelWidthIndent, bool setWideMode) { if (!LabelHasContent(label)) { return IndentedRect(totalPosition); } if (EditorGUIUtility.wideMode || setWideMode) { Rect labelPosition = new Rect(totalPosition.x + indent, totalPosition.y, EditorGUIUtility.labelWidth - indent - labelWidthIndent, kSingleLineHeight); Rect fieldPosition = totalPosition; fieldPosition.xMin += EditorGUIUtility.labelWidth + kPrefixPaddingRight; // If there are 2 columns we use the same column widths as if there had been 3 columns // in order to make columns line up neatly. if (columns == 2) { float columnWidth = (fieldPosition.width - (3 - 1) * kSpacingSubLabel) / 3f; fieldPosition.xMax -= (columnWidth + kSpacingSubLabel); } HandlePrefixLabel(totalPosition, labelPosition, label, id); return fieldPosition; } else { Rect labelPosition = new Rect(totalPosition.x + indent, totalPosition.y, totalPosition.width - indent, kSingleLineHeight); Rect fieldPosition = totalPosition; fieldPosition.xMin += indent + kIndentPerLevel; fieldPosition.yMin += kSingleLineHeight + kVerticalSpacingMultiField; HandlePrefixLabel(totalPosition, labelPosition, label, id); return fieldPosition; } } public class PropertyScope : GUI.Scope { public GUIContent content { get; protected set; } public PropertyScope(Rect totalPosition, GUIContent label, SerializedProperty property) { content = BeginProperty(totalPosition, label, property); } protected override void CloseScope() { EndProperty(); } } // Create a Property wrapper, useful for making regular GUI controls work with [[SerializedProperty]]. public static GUIContent BeginProperty(Rect totalPosition, GUIContent label, SerializedProperty property) { return BeginPropertyInternal(totalPosition, label, property); } // Create a Property wrapper, useful for making regular GUI controls work with [[SerializedProperty]]. internal static GUIContent BeginPropertyInternal(Rect totalPosition, GUIContent label, SerializedProperty property) { if (s_PendingPropertyKeyboardHandling != null) { DoPropertyFieldKeyboardHandling(s_PendingPropertyKeyboardHandling); } // Properties can be nested, so A BeginProperty may not be followed by its corresponding EndProperty // before there have been one or more pairs of BeginProperty/EndProperty in between. // The keyboard handling for a property (that handles duplicate and delete commands for array items) // uses EditorGUI.lastControlID so it has to be executed for a property before any possible child // properties are handled. However, it can't be done in it's own BeginProperty, because the controlID // for the property is not yet known at that point. For that reason we mark the keyboard handling as // pending and handle it either the next BeginProperty call (for the first child property) or if there's // no child properties, then in the matching EndProperty call. s_PendingPropertyKeyboardHandling = property; if (property == null) { string error = (label == null ? "" : label.text + ": ") + "SerializedProperty is null"; HelpBox(totalPosition, "null", MessageType.Error); throw new NullReferenceException(error); } if (Highlighter.IsSearchingForIdentifier()) Highlighter.HighlightIdentifier(totalPosition, property.propertyPath); s_PropertyFieldTempContent.text = (label == null) ? property.localizedDisplayName : label.text; // no necessary to be translated. s_PropertyFieldTempContent.tooltip = (label == null || string.IsNullOrEmpty(label.tooltip)) ? property.tooltip : label.tooltip; s_PropertyFieldTempContent.image = label?.image; // In inspector debug mode & when holding down alt. Show the property path of the property. if (Event.current.alt && property.serializedObject.inspectorMode != InspectorMode.Normal) { s_PropertyFieldTempContent.tooltip = s_PropertyFieldTempContent.text = property.propertyPath; } bool wasBoldDefaultFont = EditorGUIUtility.GetBoldDefaultFont(); var so = property.serializedObject; if (so.HasAnyInstantiatedPrefabsWithValidAsset() && EditorGUIUtility.comparisonViewMode != EditorGUIUtility.ComparisonViewMode.Original) { PropertyGUIData parentData = s_PropertyStack.Count > 0 ? s_PropertyStack.Peek() : new PropertyGUIData(); bool linkedProperties = parentData.totalPosition == totalPosition; var hasPrefabOverride = property.prefabOverride; if (!linkedProperties || hasPrefabOverride) EditorGUIUtility.SetBoldDefaultFont(hasPrefabOverride); if (Event.current.type == EventType.Repaint && hasPrefabOverride && !property.isDefaultOverride && !property.isDrivenRectTransformProperty) { Rect highlightRect = totalPosition; highlightRect.xMin += EditorGUI.indent; if (!PrefabUtility.CanPropertyBeAppliedToSource(property)) DrawOverrideBackgroundNonApplicable(highlightRect, false); else DrawOverrideBackgroundApplicable(highlightRect, false); } } if (Event.current.type == EventType.Repaint && EditorApplication.isPlaying && SerializedObject.GetLivePropertyFeatureGlobalState()) { var component = property.serializedObject.targetObject as Component; var isLiveProperty = (component != null && !component.gameObject.scene.isSubScene) || property.isLiveModified; if (isLiveProperty) { EditorGUIUtility.SetBoldDefaultFont(true); Rect highlightRect = totalPosition; highlightRect.xMin += EditorGUI.indent; DrawLivePropertyBackground(highlightRect, false); } } s_PropertyStack.Push(new PropertyGUIData(property, totalPosition, wasBoldDefaultFont, GUI.enabled, GUI.backgroundColor)); EditorGUIUtility.BeginPropertyCallback(totalPosition, property); if (GUIDebugger.active && Event.current.type != EventType.Layout) { var targetObjectTypeName = property.serializedObject.targetObject != null ? property.serializedObject.targetObject.GetType().AssemblyQualifiedName : null; GUIDebugger.LogBeginProperty(targetObjectTypeName, property.propertyPath, totalPosition); } showMixedValue = property.hasMultipleDifferentValues; if (property.isAnimated) { Color animatedColor = AnimationMode.animatedPropertyColor; if (AnimationMode.InAnimationRecording()) animatedColor = AnimationMode.recordedPropertyColor; else if (property.isCandidate) animatedColor = AnimationMode.candidatePropertyColor; animatedColor.a *= GUI.backgroundColor.a; GUI.backgroundColor = animatedColor; } else if (PrefabUtility.IsPropertyBeingDrivenByPrefabStage(property)) { GUI.enabled = false; if (isCollectingTooltips) s_PropertyFieldTempContent.tooltip = PrefabStage.s_PrefabInContextPreviewValuesTooltip; } GUI.enabled &= property.editable; return s_PropertyFieldTempContent; } // Ends a Property wrapper started with ::ref::BeginProperty. public static void EndProperty() { if (GUIDebugger.active && Event.current.type != EventType.Layout) { GUIDebugger.LogEndProperty(); } showMixedValue = false; PropertyGUIData data = s_PropertyStack.Pop(); PropertyGUIData parentData = s_PropertyStack.Count > 0 ? s_PropertyStack.Peek() : new PropertyGUIData(); bool linkedProperties = parentData.totalPosition == data.totalPosition; // Context menu // Handle context menu in EndProperty instead of BeginProperty. This ensures that child properties // get the event rather than parent properties when clicking inside the child property rects, but the menu can // still be invoked for the parent property by clicking inside the parent rect but outside the child rects. var oldEnable = GUI.enabled; GUI.enabled = true; // Event.current.type will never return ContextClick if the GUI is disabled. if (Event.current.type == EventType.ContextClick && data.totalPosition.Contains(Event.current.mousePosition)) { GUI.enabled = oldEnable; if (linkedProperties) DoPropertyContextMenu(data.property, parentData.property); else DoPropertyContextMenu(data.property); } GUI.enabled = oldEnable; EditorGUIUtility.SetBoldDefaultFont(data.wasBoldDefaultFont); GUI.enabled = data.wasEnabled; GUI.backgroundColor = data.color; if (s_PendingPropertyKeyboardHandling != null) { DoPropertyFieldKeyboardHandling(s_PendingPropertyKeyboardHandling); } // Wait with deleting the property until the property stack is empty in order to avoid // deleting a property in the middle of GUI calls that's dependent on it existing. if (s_PendingPropertyDelete != null && s_PropertyStack.Count == 0) { // For SerializedProperty iteration reasons, if the property we delete is the current property, // we have to delete on the actual iterator property rather than a copy of it, // otherwise we get an error next time we call NextVisible on the iterator property. if (s_PendingPropertyDelete.propertyPath == data.property.propertyPath) { data.property.DeleteCommand(); } else { s_PendingPropertyDelete.DeleteCommand(); } s_PendingPropertyDelete = null; } } internal static void DrawOverrideBackground(Rect position, Color color, bool fixupRectForHeadersAndBackgrounds = false) { if (fixupRectForHeadersAndBackgrounds) { // Tweaks to match the specifics of how the horizontal lines between components are drawn. position.yMin += 2; position.yMax += 1; } DrawMarginLineForRect(position, color); } internal static void DrawOverrideBackgroundApplicable(Rect position, bool fixupRectForHeadersAndBackgrounds = false) { DrawOverrideBackground(position, k_OverrideMarginColor, fixupRectForHeadersAndBackgrounds); } internal static void DrawOverrideBackgroundNonApplicable(Rect position, bool fixupRectForHeadersAndBackgrounds = false) { DrawOverrideBackground(position, k_OverrideMarginColorNotApplicable, fixupRectForHeadersAndBackgrounds); } internal static void DrawMarginLineForRect(Rect position, Color color) { if (Event.current.type != EventType.Repaint) return; position.x = EditorGUIUtility.leftMarginCoord - Mathf.Max(0f, GUIClip.topmostRect.xMin); position.width = 2; Graphics.DrawTexture(position, EditorGUIUtility.whiteTexture, new Rect(), 0, 0, 0, 0, color, guiTextureClipVerticallyMaterial); } internal static void DrawLivePropertyBackground(Rect position, bool fixupRectForHeadersAndBackgrounds = false) { if (fixupRectForHeadersAndBackgrounds) { // Tweaks to match the specifics of how the horizontal lines between components are drawn. position.yMin += 2; position.yMax += 1; } DrawMarginLineForRect(position, EditorGUIUtility.isProSkin? k_LiveModifiedMarginDarkThemeColor : k_LiveModifiedMarginLightThemeColor); } private static SerializedProperty s_PendingPropertyKeyboardHandling = null; private static SerializedProperty s_PendingPropertyDelete = null; private static void DoPropertyFieldKeyboardHandling(SerializedProperty property) { s_PendingPropertyKeyboardHandling = null; // Only interested in processing commands if our field has keyboard focus if (GUIUtility.keyboardControl != EditorGUIUtility.s_LastControlID) return; var evt = Event.current; // Only interested in validate/execute keyboard shortcut commands if (evt.type != EventType.ExecuteCommand && evt.type != EventType.ValidateCommand) return; var isExecute = Event.current.type == EventType.ExecuteCommand; // Delete if (evt.commandName == EventCommandNames.Delete || evt.commandName == EventCommandNames.SoftDelete) { if (isExecute) { // Wait with deleting the property until the property stack is empty. See EndProperty. s_PendingPropertyDelete = property.Copy(); } evt.Use(); } // Duplicate if (evt.commandName == EventCommandNames.Duplicate) { if (isExecute) property.DuplicateCommand(); evt.Use(); } // Copy & Paste if (evt.commandName == EventCommandNames.Copy || evt.commandName == EventCommandNames.Paste) { if (evt.commandName == EventCommandNames.Paste) GUI.changed = true; ClipboardContextMenu.SetupPropertyCopyPaste(property, menu: null, evt: evt); } } internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label, GUIStyle style) { LayerMaskField(position, unchecked((uint)property.intValue), property, label, style); } // Make a field for layer masks. internal static void LayerMaskField(Rect position, SerializedProperty property, GUIContent label) { LayerMaskField(position, unchecked((uint)property.intValue), property, label, EditorStyles.layerMaskField); } internal static LayerMask LayerMaskField(Rect position, LayerMask layers, GUIContent label) { return unchecked((int)LayerMaskField(position, unchecked((uint)layers.value), null, label, EditorStyles.layerMaskField)); } internal static uint LayerMaskField(Rect position, UInt32 layers, GUIContent label) { return LayerMaskField(position, layers, null, label, EditorStyles.layerMaskField); } private static string[] s_LayerNames; private static int[] s_LayerValues; internal static uint LayerMaskField(Rect position, UInt32 layers, SerializedProperty property, GUIContent label, GUIStyle style) { int id = GUIUtility.GetControlID(s_LayerMaskField, FocusType.Keyboard, position); if (label != null) { position = PrefixLabel(position, id, label); } TagManager.GetDefinedLayers(ref s_LayerNames, ref s_LayerValues); EditorGUI.BeginChangeCheck(); var newValue = MaskFieldGUI.DoMaskField(position, id, unchecked((int)layers), s_LayerNames, s_LayerValues, style); if (EditorGUI.EndChangeCheck() && property != null) property.intValue = newValue; return unchecked((uint)newValue); } // Helper function for helping with debugging the editor internal static void ShowRepaints() { if (!Unsupported.IsDeveloperMode() || !s_ShowRepaintDots) return; Color temp = GUI.color; GUI.color = new Color(UnityEngine.Random.value * .6f + .4f, UnityEngine.Random.value * .6f + .4f, UnityEngine.Random.value * .6f + .4f, 1f); var size = new Vector2(Styles.repaintDot.width, Styles.repaintDot.height); GUI.Label(new Rect(Vector2.zero, EditorGUIUtility.PixelsToPoints(size)), Styles.repaintDot); GUI.color = temp; } // Draws the alpha channel of a texture within a rectangle. internal static void DrawTextureAlphaInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel) { var mat = UseVTMaterial(image) ? alphaVTMaterial : alphaMaterial; DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect, mipLevel, ColorWriteMask.All, 0); } // Draws texture transparently using the alpha channel. internal static void DrawTextureTransparentInternal(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel, ColorWriteMask colorWriteMask, float exposure) { if (imageAspect == 0f && image == null) { Debug.LogError("Please specify an image or a imageAspect"); return; } if (imageAspect == 0f) imageAspect = image.width / (float)image.height; DrawTransparencyCheckerTexture(position, scaleMode, imageAspect); if (image != null) { var mat = UseVTMaterial(image) ? transparentVTMaterial : transparentMaterial; DrawPreviewTexture(position, image, mat, scaleMode, imageAspect, mipLevel, colorWriteMask, exposure); } } internal static void DrawTransparencyCheckerTexture(Rect position, ScaleMode scaleMode, float imageAspect) { Rect screenRect = new Rect(); Rect sourceRect = new Rect(); GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref screenRect, ref sourceRect); GUI.DrawTextureWithTexCoords( screenRect, transparentCheckerTexture, new Rect( screenRect.width * -.5f / transparentCheckerTexture.width, screenRect.height * -.5f / transparentCheckerTexture.height, screenRect.width / transparentCheckerTexture.width, screenRect.height / transparentCheckerTexture.height), false); } // Draws the texture within a rectangle. internal static void DrawPreviewTextureInternal(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect, float mipLevel, ColorWriteMask colorWriteMask, float exposure) { if (Event.current.type == EventType.Repaint) { if (imageAspect == 0) imageAspect = image.width / (float)image.height; Color colorMask = new Color(1, 1, 1, 1); if ((colorWriteMask & ColorWriteMask.Red) == 0) colorMask.r = 0; if ((colorWriteMask & ColorWriteMask.Green) == 0) colorMask.g = 0; if ((colorWriteMask & ColorWriteMask.Blue) == 0) colorMask.b = 0; if ((colorWriteMask & ColorWriteMask.Alpha) == 0) colorMask.a = 0; if (mat == null) mat = GetMaterialForSpecialTexture(image, UseVTMaterial(image) ? colorVTMaterial : colorMaterial); mat.SetColor("_ColorMask", colorMask); mat.SetFloat("_Mip", mipLevel); mat.SetFloat("_Exposure", exposure); mat.SetInt("_SNormFormat", UnityEngine.Experimental.Rendering.GraphicsFormatUtility.IsSNormFormat(image.graphicsFormat) ? 1 : 0); RenderTexture rt = image as RenderTexture; bool manualResolve = (rt != null) && rt.bindTextureMS; if (manualResolve) { var desc = rt.descriptor; desc.bindMS = false; desc.msaaSamples = 1; RenderTexture resolved = RenderTexture.GetTemporary(desc); resolved.Create(); rt.ResolveAntiAliasedSurface(resolved); image = resolved; } Rect screenRect = new Rect(), sourceRect = new Rect(); GUI.CalculateScaledTextureRects(position, scaleMode, imageAspect, ref screenRect, ref sourceRect); Texture2D t2d = image as Texture2D; if (t2d != null && TextureUtil.GetUsageMode(image) == TextureUsageMode.AlwaysPadded) { // In case of always padded textures, only show the non-padded area sourceRect.width *= (float)t2d.width / TextureUtil.GetGPUWidth(t2d); sourceRect.height *= (float)t2d.height / TextureUtil.GetGPUHeight(t2d); } Graphics.DrawTexture(screenRect, image, sourceRect, 0, 0, 0, 0, GUI.color, mat); //Start streaming in content for the next preview draw calls. The first draw might not have texture content to render with. //StreamTexture is called after the draw call because the VT stack might not have been created yet otherwise. StreamTexture(image, mat, mipLevel); if (manualResolve) { RenderTexture.ReleaseTemporary(image as RenderTexture); } } } internal static void StreamTexture(Texture texture, Material mat, float mipLevel) { if (UseVTMaterial(texture)) { const string stackName = "Stack";//keep in sync with preview shader stack name int stackNameId = Shader.PropertyToID(stackName); Texture2D t2d = texture as Texture2D; //Request a higher mipmap first to make sure we have (low res) data as soon as possible const int fallbackResolution = 256; int minDimension = Mathf.Min(texture.width, texture.height); if (minDimension > fallbackResolution) { float factor = (float)minDimension / (float)fallbackResolution; int fallbackMipLevel = (int)Math.Ceiling(Math.Log(factor, 2)); if (fallbackMipLevel > (int)mipLevel) VirtualTexturing.Streaming.RequestRegion(mat, stackNameId, new Rect(0, 0, 1, 1), fallbackMipLevel, 2); //make sure the 128x128 mip is also requested to always have a fallback. Needed for mini thumbnails } if (mipLevel >= 0) //otherwise we don't know what mip will be sampled in the shader { VirtualTexturing.Streaming.RequestRegion(mat, stackNameId, new Rect(0, 0, 1, 1), (int)mipLevel, 1); } } } // This will return appriopriate material to use with the texture according to its usage mode internal static Material GetMaterialForSpecialTexture(Texture t, Material defaultMat = null, bool manualTex2Linear = false, bool useVTMaterialWhenPossible = true) { bool useVT = useVTMaterialWhenPossible && UseVTMaterial(t); // i am not sure WHY do we check that (i would guess this is api user error and exception make sense, not "return something") if (t == null) return null; TextureUsageMode usage = TextureUtil.GetUsageMode(t); TextureFormat format = TextureUtil.GetTextureFormat(t); if (usage == TextureUsageMode.RealtimeLightmapRGBM || usage == TextureUsageMode.BakedLightmapRGBM || usage == TextureUsageMode.RGBMEncoded) return lightmapRGBMMaterial; else if (usage == TextureUsageMode.BakedLightmapDoubleLDR) return lightmapDoubleLDRMaterial; else if (usage == TextureUsageMode.BakedLightmapFullHDR) return lightmapFullHDRMaterial; else if (TextureUtil.IsNormalMapUsageMode(usage)) { var normalMat = useVT ? normalmapVTMaterial : normalmapMaterial; normalMat.SetFloat("_IsPlainNormalmap", usage == TextureUsageMode.NormalmapPlain && format != TextureFormat.BC5 ? 1.0f : 0.0f); normalMat.SetFloat("_ManualTex2Linear", manualTex2Linear ? 1.0f : 0.0f); return normalMat; } else if (GraphicsFormatUtility.IsAlphaOnlyFormat(format)) { var alphaOnlyMat = useVT ? alphaVTMaterial : alphaMaterial; alphaOnlyMat.SetFloat("_ManualTex2Linear", manualTex2Linear ? 1.0f : 0.0f); return alphaOnlyMat; } if (defaultMat != null) { defaultMat.SetInt("_SNormFormat", UnityEngine.Experimental.Rendering.GraphicsFormatUtility.IsSNormFormat(t.graphicsFormat) ? 1 : 0); } return defaultMat; } internal static Texture2D transparentCheckerTexture { get { if (EditorGUIUtility.isProSkin) { return EditorGUIUtility.LoadRequired("Previews/Textures/textureCheckerDark.png") as Texture2D; } else { return EditorGUIUtility.LoadRequired("Previews/Textures/textureChecker.png") as Texture2D; } } } // before we had preview materials as static vars, but these go null on domain reload, leaking memory // so now we keep them in native land // we load shaders from assets and create materials once (in native), and managed code queries them when needed internal static Material colorMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.Color); } } internal static Material colorVTMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.ColorVT); } } internal static Material alphaMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.Alpha); } } internal static Material alphaVTMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.AlphaVT); } } internal static Material transparentMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.Transparent); } } internal static Material transparentVTMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.TransparentVT); } } internal static Material normalmapMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.Normalmap); } } internal static Material normalmapVTMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.NormalmapVT); } } internal static Material lightmapRGBMMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.LightmapRGBM); } } internal static Material lightmapDoubleLDRMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.LightmapDoubleLDR); } } internal static Material lightmapFullHDRMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.LightmapFullHDR); } } internal static Material guiTextureClipVerticallyMaterial { get { return EditorGUIUtility.GetPreviewMaterial(PreviewMaterialType.GUITextureClipVertically); } } internal static void SetExpandedRecurse(SerializedProperty property, bool expanded) { SerializedProperty search = property.Copy(); int depth = search.depth; HashSet<long> visited = null; bool visitChild; do { visitChild = true; if (search.propertyType == SerializedPropertyType.ManagedReference) { // Managed reference objects can form a cyclical graph, so need to track visited objects if (visited == null) visited = new HashSet<long>(); long refId = search.managedReferenceId; if (!visited.Add(refId)) { visitChild = false; continue; } } if (depth == search.depth || search.hasVisibleChildren) { search.isExpanded = expanded; } } while (search.NextVisible(visitChild) && search.depth > depth); } // Get the height needed for a ::ref::PropertyField control, not including its children and not taking custom PropertyDrawers into account. internal static float GetSinglePropertyHeight(SerializedProperty property, GUIContent label) { if (property == null) return kSingleLineHeight; return GetPropertyHeight(property.propertyType, label); } // Get the height needed for a simple builtin control type. public static float GetPropertyHeight(SerializedPropertyType type, GUIContent label) { if (type == SerializedPropertyType.Vector3 || type == SerializedPropertyType.Vector2 || type == SerializedPropertyType.Vector4 || type == SerializedPropertyType.Vector3Int || type == SerializedPropertyType.Vector2Int || type == SerializedPropertyType.Quaternion) { return (!LabelHasContent(label) || EditorGUIUtility.wideMode ? 0f : kStructHeaderLineHeight + kVerticalSpacingMultiField) + kSingleLineHeight; } if (type == SerializedPropertyType.Rect || type == SerializedPropertyType.RectInt) { return (!LabelHasContent(label) || EditorGUIUtility.wideMode ? 0f : kStructHeaderLineHeight + kVerticalSpacingMultiField) + kSingleLineHeight * 2 + kVerticalSpacingMultiField; } // Bounds field has label on its own line even in wide mode because the words "center" and "extends" // would otherwise eat too much of the label space. if (type == SerializedPropertyType.Bounds || type == SerializedPropertyType.BoundsInt) { return (!LabelHasContent(label) ? 0f : kStructHeaderLineHeight + kVerticalSpacingMultiField) + kSingleLineHeight * 2 + kVerticalSpacingMultiField; } return kSingleLineHeight; } // Get the height needed for a ::ref::PropertyField control. internal static float GetPropertyHeightInternal(SerializedProperty property, GUIContent label, bool includeChildren) { return ScriptAttributeUtility.GetHandler(property).GetHeight(property, label, includeChildren); } [Obsolete("CanCacheInspectorGUI has been deprecated and is no longer used.", false)] public static bool CanCacheInspectorGUI(SerializedProperty property) { return false; } internal static bool HasVisibleChildFields(SerializedProperty property, bool isUIElements = false) { switch (property.propertyType) { case SerializedPropertyType.Vector3: case SerializedPropertyType.Vector2: case SerializedPropertyType.Vector3Int: case SerializedPropertyType.Vector2Int: case SerializedPropertyType.Rect: case SerializedPropertyType.RectInt: case SerializedPropertyType.Bounds: case SerializedPropertyType.BoundsInt: case SerializedPropertyType.Hash128: return false; } if (PropertyHandler.UseReorderabelListControl(property)) return false; return property.hasVisibleChildren; } // Make a field for [[SerializedProperty]]. internal static bool PropertyFieldInternal(Rect position, SerializedProperty property, GUIContent label, bool includeChildren) { return ScriptAttributeUtility.GetHandler(property).OnGUI(position, property, label, includeChildren); } static readonly string s_ArrayMultiInfoFormatString = EditorGUIUtility.TrTextContent("This field cannot display arrays with more than {0} elements when multiple objects are selected.").text; static readonly GUIContent s_ArrayMultiInfoContent = new GUIContent(); static ProfilerMarker s_EvalExpressionMarker = new ProfilerMarker("Inspector.EvaluateMultiExpression"); internal static bool DefaultPropertyField(Rect position, SerializedProperty property, GUIContent label) { label = BeginPropertyInternal(position, label, property); SerializedPropertyType type = property.propertyType; bool childrenAreExpanded = false; // Should we inline? All one-line vars as well as Vector2, Vector3, Rect and Bounds properties are inlined. if (!HasVisibleChildFields(property)) { bool canUseExpression = ConstrainProportionsTransformScale.CanUseMathExpressions(property); switch (type) { case SerializedPropertyType.Integer: { BeginChangeCheck(); NumberFieldValue val = new NumberFieldValue(property.longValue); LongField(position, label, ref val); if (EndChangeCheck() && val.hasResult) { if (val.expression != null) { using (s_EvalExpressionMarker.Auto()) { var originalValues = s_RecycledEditor.GetOriginalLongValues(); var values = property.allLongValues; for (var i = 0; i < values.Length; ++i) { values[i] = originalValues[i]; if(canUseExpression) val.expression.Evaluate(ref values[i], i, values.Length); } property.allLongValues = values; } } else { property.longValue = val.longVal; } } break; } case SerializedPropertyType.Float: { BeginChangeCheck(); NumberFieldValue val = new NumberFieldValue(property.doubleValue); // Necessary to check for float type to get correct string formatting for float and double. bool isFloat = property.numericType == SerializedPropertyNumericType.Float; if (isFloat) FloatField(position, label, ref val); else DoubleField(position, label, ref val); if (EndChangeCheck() && val.hasResult) { if (val.expression != null) { using (s_EvalExpressionMarker.Auto()) { var originalValues = s_RecycledEditor.GetOriginalDoubleValues(); var values = property.allDoubleValues; bool changed = false; for (var i = 0; i < values.Length; ++i) { values[i] = originalValues[i]; if (canUseExpression && val.expression.Evaluate(ref values[i], i, values.Length)) { if (isFloat) values[i] = MathUtils.ClampToFloat(values[i]); changed = true; } } if (changed) property.allDoubleValues = values; } } else { if (isFloat) val.doubleVal = MathUtils.ClampToFloat(val.doubleVal); property.doubleValue = val.doubleVal; } } break; } case SerializedPropertyType.String: { BeginChangeCheck(); string newValue = TextField(position, label, property.stringValue); if (EndChangeCheck()) { property.stringValue = newValue; } break; } // Multi @todo: Needs style work case SerializedPropertyType.Boolean: { BeginChangeCheck(); bool newValue = Toggle(position, label, property.boolValue); if (EndChangeCheck()) { property.boolValue = newValue; } break; } case SerializedPropertyType.Color: { BeginChangeCheck(); bool showAlpha = true; bool hdr = false; var propertyFieldInfo = ScriptAttributeUtility.GetFieldInfoFromProperty(property, out var propertyType); if (propertyFieldInfo != null) { var attributes = propertyFieldInfo.GetCustomAttributes<ColorUsageAttribute>(false).ToArray(); if (attributes.Length > 0) { var attribute = attributes[0]; showAlpha = attribute.showAlpha; hdr = attribute.hdr; } } Color newColor = ColorField(position, label, property.colorValue, true, showAlpha, hdr); if (EndChangeCheck()) { property.colorValue = newColor; } break; } case SerializedPropertyType.ArraySize: { BeginChangeCheck(); int newValue = ArraySizeField(position, label, property.intValue, EditorStyles.numberField); if (EndChangeCheck()) { property.intValue = newValue; } break; } case SerializedPropertyType.FixedBufferSize: { IntField(position, label, property.intValue); break; } case SerializedPropertyType.Enum: { EnumPopup(position, property, label); break; } // Multi @todo: Needs testing for texture types case SerializedPropertyType.ObjectReference: { ObjectFieldInternal(position, property, null, label, EditorStyles.objectField); break; } case SerializedPropertyType.LayerMask: { TagManager.GetDefinedLayers(ref m_FlagNames, ref m_FlagValues); MaskFieldGUI.GetMaskButtonValue(property.intValue, m_FlagNames, m_FlagValues, out var toggleLabel, out var toggleLabelMixed); if (label != null) position = PrefixLabel(position, label, EditorStyles.label); var toggleLabelContent = property.hasMultipleDifferentValues ? mixedValueContent : MaskFieldGUI.DoMixedLabel(toggleLabel, toggleLabelMixed, position, EditorStyles.layerMaskField); bool toggled = DropdownButton(position, toggleLabelContent, FocusType.Keyboard, EditorStyles.layerMaskField); if (toggled) { PopupWindowWithoutFocus.Show(position, new MaskFieldDropDown(property)); GUIUtility.ExitGUI(); } break; } case SerializedPropertyType.RenderingLayerMask: { var names = RenderingLayerMask.GetDefinedRenderingLayerNames(); var values = RenderingLayerMask.GetDefinedRenderingLayerValues(); MaskFieldGUI.GetMaskButtonValue((int) property.uintValue, names, values, out var toggleLabel, out var toggleLabelMixed); if (label != null) position = PrefixLabel(position, label, EditorStyles.label); var toggleLabelContent = property.hasMultipleDifferentValues ? mixedValueContent : MaskFieldGUI.DoMixedLabel(toggleLabel, toggleLabelMixed, position, EditorStyles.layerMaskField); bool toggled = DropdownButton(position, toggleLabelContent, FocusType.Keyboard, EditorStyles.layerMaskField); if (toggled) { PopupWindowWithoutFocus.Show(position, new MaskFieldDropDown(property)); GUIUtility.ExitGUI(); } break; } case SerializedPropertyType.Character: { char[] value = { (char)property.intValue }; bool wasChanged = GUI.changed; GUI.changed = false; string newValue = TextField(position, label, new string(value)); if (GUI.changed) { if (newValue.Length == 1) { property.intValue = newValue[0]; } // Value didn't get changed after all else { GUI.changed = false; } } GUI.changed |= wasChanged; break; } case SerializedPropertyType.AnimationCurve: { int id = GUIUtility.GetControlID(s_CurveHash, FocusType.Keyboard, position); DoCurveField(PrefixLabel(position, id, label), id, null, kCurveColor, new Rect(), property); break; } case SerializedPropertyType.Gradient: { int id = GUIUtility.GetControlID(s_CurveHash, FocusType.Keyboard, position); DoGradientField(PrefixLabel(position, id, label), id, null, property, false, ColorSpace.Gamma); break; } case SerializedPropertyType.Vector3: { Vector3Field(position, property, label); break; } case SerializedPropertyType.Vector4: { Vector4Field(position, property, label); break; } case SerializedPropertyType.Vector2: { Vector2Field(position, property, label); break; } case SerializedPropertyType.Vector2Int: { Vector2IntField(position, property, label); break; } case SerializedPropertyType.Vector3Int: { Vector3IntField(position, property, label); break; } case SerializedPropertyType.Rect: { RectField(position, property, label); break; } case SerializedPropertyType.RectInt: { RectIntField(position, property, label); break; } case SerializedPropertyType.Bounds: { BoundsField(position, property, label); break; } case SerializedPropertyType.BoundsInt: { BoundsIntField(position, property, label); break; } case SerializedPropertyType.Hash128: { BeginChangeCheck(); string newValue = TextField(position, label, property.hash128Value.ToString()); if (EndChangeCheck()) { property.hash128Value = Hash128.Parse(newValue); } break; } default: { int genericID = GUIUtility.GetControlID(s_GenericField, FocusType.Keyboard, position); PrefixLabel(position, genericID, label); break; } } } else if (type == SerializedPropertyType.Quaternion) { QuaternionEulerField(position, property, label); } // Handle Foldout else { Event tempEvent = new Event(Event.current); // Handle the actual foldout first, since that's the one that supports keyboard control. // This makes it work more consistent with PrefixLabel. childrenAreExpanded = property.isExpanded; bool newChildrenAreExpanded = childrenAreExpanded; using (new DisabledScope(!property.editable)) { GUIStyle foldoutStyle = (DragAndDrop.activeControlID == -10) ? EditorStyles.foldoutPreDrop : EditorStyles.foldout; newChildrenAreExpanded = Foldout(position, childrenAreExpanded, s_PropertyFieldTempContent, true, foldoutStyle); } if (childrenAreExpanded && property.isArray && property.minArraySize > property.serializedObject.maxArraySizeForMultiEditing && property.serializedObject.isEditingMultipleObjects) { Rect boxRect = position; boxRect.xMin += EditorGUIUtility.labelWidth - indent; s_ArrayMultiInfoContent.text = s_ArrayMultiInfoContent.tooltip = string.Format(s_ArrayMultiInfoFormatString, property.serializedObject.maxArraySizeForMultiEditing); LabelField(boxRect, GUIContent.none, s_ArrayMultiInfoContent, EditorStyles.helpBox); } if (newChildrenAreExpanded != childrenAreExpanded) { // Recursive set expanded if (Event.current.alt) { SetExpandedRecurse(property, newChildrenAreExpanded); } // Expand one element only else { property.isExpanded = newChildrenAreExpanded; } } childrenAreExpanded = newChildrenAreExpanded; // Check for drag & drop events here, to add objects to an array by dragging to the foldout. // The event may have already been used by the Foldout control above, but we want to also use it here, // so we use the event copy we made prior to calling the Foldout method. // We need to use last s_LastControlID here to ensure we do not break duplicate functionality (fix for case 598389) // If we called GetControlID here s_LastControlID would be incremented and would not longer be in sync with GUIUtililty.keyboardFocus that // is used for duplicating (See DoPropertyFieldKeyboardHandling) int id = EditorGUIUtility.s_LastControlID; switch (tempEvent.type) { case EventType.DragExited: if (GUI.enabled) { HandleUtility.Repaint(); } break; case EventType.DragUpdated: case EventType.DragPerform: if (position.Contains(tempEvent.mousePosition) && GUI.enabled) { Object[] references = DragAndDrop.objectReferences; // Check each single object, so we can add multiple objects in a single drag. Object[] oArray = new Object[1]; bool didAcceptDrag = false; foreach (Object o in references) { oArray[0] = o; Object validatedObject = ValidateObjectFieldAssignment(oArray, null, property, ObjectFieldValidatorOptions.None); if (validatedObject != null) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (tempEvent.type == EventType.DragPerform) { property.AppendFoldoutPPtrValue(validatedObject); didAcceptDrag = true; DragAndDrop.activeControlID = 0; } else { DragAndDrop.activeControlID = id; } } } if (didAcceptDrag) { GUI.changed = true; DragAndDrop.AcceptDrag(); } } break; } } EndProperty(); return childrenAreExpanded; } internal static void DrawLegend(Rect position, Color color, string label, bool enabled) { position = new Rect(position.x + 2, position.y + 2, position.width - 2, position.height - 2); Color oldCol = GUI.backgroundColor; GUI.backgroundColor = enabled ? color : new Color(0.5f, 0.5f, 0.5f, 0.45f); GUI.Label(position, label, "ProfilerPaneSubLabel"); GUI.backgroundColor = oldCol; } internal static string TextFieldDropDown(Rect position, string text, string[] dropDownElement) { return TextFieldDropDown(position, GUIContent.none, text, dropDownElement); } internal static string TextFieldDropDown(Rect position, GUIContent label, string text, string[] dropDownElement) { int id = GUIUtility.GetControlID(s_TextFieldDropDownHash, FocusType.Keyboard, position); return DoTextFieldDropDown(PrefixLabel(position, id, label), id, text, dropDownElement, false); } internal static string DelayedTextFieldDropDown(Rect position, string text, string[] dropDownElement) { return DelayedTextFieldDropDown(position, GUIContent.none, text, dropDownElement); } internal static string DelayedTextFieldDropDown(Rect position, GUIContent label, string text, string[] dropDownElement) { int id = GUIUtility.GetControlID(s_TextFieldDropDownHash, FocusType.Keyboard, position); return DoTextFieldDropDown(PrefixLabel(position, id, label), id, text, dropDownElement, true); } public static bool DropdownButton(Rect position, GUIContent content, FocusType focusType) { return DropdownButton(position, content, focusType, EditorStyles.miniPullDown); } public static bool DropdownButton(Rect position, GUIContent content, FocusType focusType, GUIStyle style) { int id = GUIUtility.GetControlID(s_DropdownButtonHash, focusType, position); return DropdownButton(id, position, content, style); } // A button that returns true on mouse down - like a popup button internal static bool DropdownButton(int id, Rect position, GUIContent content, GUIStyle style) { Event evt = Event.current; switch (evt.type) { case EventType.Repaint: var hovered = position.Contains(Event.current.mousePosition); if (showMixedValue) { BeginHandleMixedValueContentColor(); style.Draw(position, s_MixedValueContent, id, false, hovered); EndHandleMixedValueContentColor(); } else style.Draw(position, content, id, false, hovered); break; case EventType.MouseDown: if (GUIUtility.HitTest(position, evt) && evt.button == 0) { GUI.GrabMouseControl(id); Event.current.Use(); return true; } break; case EventType.MouseUp: if (GUI.HasMouseControl(id)) { GUI.ReleaseMouseControl(); Event.current.Use(); } break; case EventType.KeyDown: if (GUIUtility.keyboardControl == id && evt.character == ' ') { Event.current.Use(); return true; } break; } return false; } internal static bool isCollectingTooltips { get { return s_CollectingToolTips; } set { s_CollectingToolTips = value; } } internal static bool s_CollectingToolTips; internal static int AdvancedPopup(Rect rect, int selectedIndex, string[] displayedOptions) { return StatelessAdvancedDropdown.DoSearchablePopup(rect, selectedIndex, displayedOptions, "MiniPullDown"); } internal static int AdvancedPopup(Rect rect, int selectedIndex, string[] displayedOptions, GUIStyle style) { return StatelessAdvancedDropdown.DoSearchablePopup(rect, selectedIndex, displayedOptions, style); } internal static int AdvancedLazyPopup(Rect rect, string displayedOption, int selectedIndex, Func<Tuple<int, string[]>> displayedOptionsFunc, GUIStyle style) { return StatelessAdvancedDropdown.DoLazySearchablePopup(rect, displayedOption, selectedIndex, displayedOptionsFunc, style); } // Draws the alpha channel of a texture within a rectangle. public static void DrawTextureAlpha(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect, [DefaultValue("-1")] float mipLevel) { DrawTextureAlphaInternal(position, image, scaleMode, imageAspect, mipLevel); } [ExcludeFromDocs] public static void DrawTextureAlpha(Rect position, Texture image) { DrawTextureAlphaInternal(position, image, ScaleMode.StretchToFill, 0, -1); } [ExcludeFromDocs] public static void DrawTextureAlpha(Rect position, Texture image, ScaleMode scaleMode) { DrawTextureAlphaInternal(position, image, scaleMode, 0, -1); } [ExcludeFromDocs] public static void DrawTextureAlpha(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) { DrawTextureAlphaInternal(position, image, scaleMode, imageAspect, -1); } // Draws texture transparently using the alpha channel. public static void DrawTextureTransparent(Rect position, Texture image, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect, [DefaultValue("-1")] float mipLevel, [DefaultValue("ColorWriteMask.All")] ColorWriteMask colorWriteMask, [DefaultValue("0")] float exposure) { DrawTextureTransparentInternal(position, image, scaleMode, imageAspect, mipLevel, colorWriteMask, exposure); } [ExcludeFromDocs] public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode) { DrawTextureTransparent(position, image, scaleMode, 0); } [ExcludeFromDocs] public static void DrawTextureTransparent(Rect position, Texture image) { DrawTextureTransparent(position, image, ScaleMode.StretchToFill, 0); } [ExcludeFromDocs] public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode, float imageAspect) { DrawTextureTransparent(position, image, scaleMode, imageAspect, -1); } [ExcludeFromDocs] public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel) { DrawTextureTransparent(position, image, scaleMode, imageAspect, mipLevel, ColorWriteMask.All); } [ExcludeFromDocs] public static void DrawTextureTransparent(Rect position, Texture image, ScaleMode scaleMode, float imageAspect, float mipLevel, ColorWriteMask colorWriteMask) { DrawTextureTransparent(position, image, scaleMode, imageAspect, mipLevel, colorWriteMask, 0); } // Draws the texture within a rectangle. public static void DrawPreviewTexture(Rect position, Texture image, [DefaultValue("null")] Material mat, [DefaultValue("ScaleMode.StretchToFill")] ScaleMode scaleMode, [DefaultValue("0")] float imageAspect, [DefaultValue("-1")] float mipLevel, [DefaultValue("ColorWriteMask.All")] ColorWriteMask colorWriteMask, [DefaultValue("0")] float exposure) { DrawPreviewTextureInternal(position, image, mat, scaleMode, imageAspect, mipLevel, colorWriteMask, exposure); } [ExcludeFromDocs] public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect, float mipLevel, ColorWriteMask colorWriteMask) { DrawPreviewTexture(position, image, mat, scaleMode, imageAspect, mipLevel, colorWriteMask, 0); } [ExcludeFromDocs] public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect, float mipLevel) { DrawPreviewTexture(position, image, mat, scaleMode, imageAspect, mipLevel, ColorWriteMask.All); } [ExcludeFromDocs] public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode, float imageAspect) { DrawPreviewTexture(position, image, mat, scaleMode, imageAspect, -1); } [ExcludeFromDocs] public static void DrawPreviewTexture(Rect position, Texture image, Material mat, ScaleMode scaleMode) { DrawPreviewTexture(position, image, mat, scaleMode, 0); } [ExcludeFromDocs] public static void DrawPreviewTexture(Rect position, Texture image, Material mat) { DrawPreviewTexture(position, image, mat, ScaleMode.StretchToFill, 0); } [ExcludeFromDocs] public static void DrawPreviewTexture(Rect position, Texture image) { DrawPreviewTexture(position, image, null, ScaleMode.StretchToFill, 0); } [ExcludeFromDocs] public static void LabelField(Rect position, string label) { LabelField(position, label, EditorStyles.label); } public static void LabelField(Rect position, string label, [DefaultValue("EditorStyles.label")] GUIStyle style) { LabelField(position, GUIContent.none, EditorGUIUtility.TempContent(label), style); } [ExcludeFromDocs] public static void LabelField(Rect position, GUIContent label) { LabelField(position, label, EditorStyles.label); } public static void LabelField(Rect position, GUIContent label, [DefaultValue("EditorStyles.label")] GUIStyle style) { LabelField(position, GUIContent.none, label, style); } [ExcludeFromDocs] public static void LabelField(Rect position, string label, string label2) { LabelField(position, label, label2, EditorStyles.label); } public static void LabelField(Rect position, string label, string label2, [DefaultValue("EditorStyles.label")] GUIStyle style) { LabelField(position, new GUIContent(label), EditorGUIUtility.TempContent(label2), style); } [ExcludeFromDocs] public static void LabelField(Rect position, GUIContent label, GUIContent label2) { LabelField(position, label, label2, EditorStyles.label); } public static void LabelField(Rect position, GUIContent label, GUIContent label2, [DefaultValue("EditorStyles.label")] GUIStyle style) { LabelFieldInternal(position, label, label2, style); } public static bool LinkButton(Rect position, string label) { return LinkButton(position, EditorGUIUtility.TempContent(label)); } public static bool LinkButton(Rect position, GUIContent label) { Handles.color = EditorStyles.linkLabel.normal.textColor; Handles.DrawLine(new Vector3(position.xMin + EditorStyles.linkLabel.padding.left, position.yMax), new Vector3(position.xMax - EditorStyles.linkLabel.padding.right, position.yMax)); Handles.color = Color.white; EditorGUIUtility.AddCursorRect(position, MouseCursor.Link); return GUI.Button(position, label, EditorStyles.linkLabel); } [ExcludeFromDocs] public static bool ToggleLeft(Rect position, string label, bool value) { GUIStyle labelStyle = EditorStyles.label; return ToggleLeft(position, label, value, labelStyle); } public static bool ToggleLeft(Rect position, string label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) { return ToggleLeft(position, EditorGUIUtility.TempContent(label), value, labelStyle); } [ExcludeFromDocs] public static bool ToggleLeft(Rect position, GUIContent label, bool value) { return ToggleLeft(position, label, value, EditorStyles.label); } public static bool ToggleLeft(Rect position, GUIContent label, bool value, [DefaultValue("EditorStyles.label")] GUIStyle labelStyle) { return ToggleLeftInternal(position, label, value, labelStyle); } [ExcludeFromDocs] public static string TextField(Rect position, string text) { return TextField(position, text, EditorStyles.textField); } public static string TextField(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return TextFieldInternal(position, text, style); } [ExcludeFromDocs] public static string TextField(Rect position, string label, string text) { return TextField(position, label, text, EditorStyles.textField); } public static string TextField(Rect position, string label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return TextField(position, EditorGUIUtility.TempContent(label), text, style); } [ExcludeFromDocs] public static string TextField(Rect position, GUIContent label, string text) { return TextField(position, label, text, EditorStyles.textField); } public static string TextField(Rect position, GUIContent label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return TextFieldInternal(position, label, text, style); } [ExcludeFromDocs] public static string DelayedTextField(Rect position, string text) { return DelayedTextField(position, text, EditorStyles.textField); } public static string DelayedTextField(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return DelayedTextField(position, GUIContent.none, text, style); } [ExcludeFromDocs] public static string DelayedTextField(Rect position, string label, string text) { return DelayedTextField(position, label, text, EditorStyles.textField); } public static string DelayedTextField(Rect position, string label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return DelayedTextField(position, EditorGUIUtility.TempContent(label), text, style); } [ExcludeFromDocs] public static string DelayedTextField(Rect position, GUIContent label, string text) { return DelayedTextField(position, label, text, EditorStyles.textField); } public static string DelayedTextField(Rect position, GUIContent label, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { int id = GUIUtility.GetControlID(s_TextFieldHash, FocusType.Keyboard, position); return DelayedTextFieldInternal(position, id, label, text, null, style); } [ExcludeFromDocs] public static void DelayedTextField(Rect position, SerializedProperty property) { DelayedTextField(position, property, null); } public static void DelayedTextField(Rect position, SerializedProperty property, [DefaultValue("null")] GUIContent label) { DelayedTextFieldHelper(position, property, label, EditorStyles.textField); } internal static void DelayedTextFieldHelper(Rect position, SerializedProperty property, GUIContent label, GUIStyle style) { int id = GUIUtility.GetControlID(s_TextFieldHash, FocusType.Keyboard, position); DelayedTextFieldInternal(position, id, property, null, label, style); } [ExcludeFromDocs] public static string DelayedTextField(Rect position, GUIContent label, int controlId, string text) { return DelayedTextField(position, label, controlId, text, EditorStyles.textField); } public static string DelayedTextField(Rect position, GUIContent label, int controlId, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return DelayedTextFieldInternal(position, controlId, label, text, null, style); } [ExcludeFromDocs] public static string TextArea(Rect position, string text) { return TextArea(position, text, EditorStyles.textField); } public static string TextArea(Rect position, string text, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return TextAreaInternal(position, text, style); } [ExcludeFromDocs] public static void SelectableLabel(Rect position, string text) { SelectableLabel(position, text, EditorStyles.label); } public static void SelectableLabel(Rect position, string text, [DefaultValue("EditorStyles.label")] GUIStyle style) { SelectableLabelInternal(position, text, style); } [ExcludeFromDocs] public static string PasswordField(Rect position, string password) { return PasswordField(position, password, EditorStyles.textField); } public static string PasswordField(Rect position, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return PasswordFieldInternal(position, password, style); } [ExcludeFromDocs] public static string PasswordField(Rect position, string label, string password) { return PasswordField(position, label, password, EditorStyles.textField); } public static string PasswordField(Rect position, string label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return PasswordField(position, EditorGUIUtility.TempContent(label), password, style); } [ExcludeFromDocs] public static string PasswordField(Rect position, GUIContent label, string password) { return PasswordField(position, label, password, EditorStyles.textField); } public static string PasswordField(Rect position, GUIContent label, string password, [DefaultValue("EditorStyles.textField")] GUIStyle style) { return PasswordFieldInternal(position, label, password, style); } [ExcludeFromDocs] public static float FloatField(Rect position, float value) { return FloatField(position, value, EditorStyles.numberField); } public static float FloatField(Rect position, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return FloatFieldInternal(position, value, style); } [ExcludeFromDocs] public static float FloatField(Rect position, string label, float value) { return FloatField(position, label, value, EditorStyles.numberField); } public static float FloatField(Rect position, string label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return FloatField(position, EditorGUIUtility.TempContent(label), value, style); } internal static void FloatField(Rect position, GUIContent label, ref NumberFieldValue value) { FloatFieldInternal(position, label, ref value, EditorStyles.numberField); } [ExcludeFromDocs] public static float FloatField(Rect position, GUIContent label, float value) { return FloatField(position, label, value, EditorStyles.numberField); } public static float FloatField(Rect position, GUIContent label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return FloatFieldInternal(position, label, value, style); } [ExcludeFromDocs] public static float DelayedFloatField(Rect position, float value) { return DelayedFloatField(position, value, EditorStyles.numberField); } public static float DelayedFloatField(Rect position, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedFloatField(position, GUIContent.none, value, style); } [ExcludeFromDocs] public static float DelayedFloatField(Rect position, string label, float value) { return DelayedFloatField(position, label, value, EditorStyles.numberField); } public static float DelayedFloatField(Rect position, string label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedFloatField(position, EditorGUIUtility.TempContent(label), value, style); } [ExcludeFromDocs] public static float DelayedFloatField(Rect position, GUIContent label, float value) { return DelayedFloatField(position, label, value, EditorStyles.numberField); } public static float DelayedFloatField(Rect position, GUIContent label, float value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedFloatFieldInternal(position, label, value, style); } [ExcludeFromDocs] public static void DelayedFloatField(Rect position, SerializedProperty property) { DelayedFloatField(position, property, null); } public static void DelayedFloatField(Rect position, SerializedProperty property, [DefaultValue("null")] GUIContent label) { DelayedFloatFieldInternal(position, property, label); } [ExcludeFromDocs] public static double DoubleField(Rect position, double value) { return DoubleField(position, value, EditorStyles.numberField); } public static double DoubleField(Rect position, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DoubleFieldInternal(position, value, style); } [ExcludeFromDocs] public static double DoubleField(Rect position, string label, double value) { return DoubleField(position, label, value, EditorStyles.numberField); } public static double DoubleField(Rect position, string label, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DoubleField(position, EditorGUIUtility.TempContent(label), value, style); } [ExcludeFromDocs] public static double DoubleField(Rect position, GUIContent label, double value) { return DoubleField(position, label, value, EditorStyles.numberField); } public static double DoubleField(Rect position, GUIContent label, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DoubleFieldInternal(position, label, value, style); } static void DoubleField(Rect position, GUIContent label, ref NumberFieldValue value) { DoubleFieldInternal(position, label, ref value, EditorStyles.numberField); } [ExcludeFromDocs] public static double DelayedDoubleField(Rect position, double value) { return DelayedDoubleField(position, value, EditorStyles.numberField); } public static double DelayedDoubleField(Rect position, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedDoubleFieldInternal(position, null, value, style); } [ExcludeFromDocs] public static double DelayedDoubleField(Rect position, string label, double value) { return DelayedDoubleField(position, label, value, EditorStyles.numberField); } public static double DelayedDoubleField(Rect position, string label, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedDoubleField(position, EditorGUIUtility.TempContent(label), value, style); } [ExcludeFromDocs] public static double DelayedDoubleField(Rect position, GUIContent label, double value) { return DelayedDoubleField(position, label, value, EditorStyles.numberField); } public static double DelayedDoubleField(Rect position, GUIContent label, double value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedDoubleFieldInternal(position, label, value, style); } [ExcludeFromDocs] public static int IntField(Rect position, int value) { return IntField(position, value, EditorStyles.numberField); } public static int IntField(Rect position, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return IntFieldInternal(position, value, style); } [ExcludeFromDocs] public static int IntField(Rect position, string label, int value) { return IntField(position, label, value, EditorStyles.numberField); } public static int IntField(Rect position, string label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return IntField(position, EditorGUIUtility.TempContent(label), value, style); } [ExcludeFromDocs] public static int IntField(Rect position, GUIContent label, int value) { return IntField(position, label, value, EditorStyles.numberField); } public static int IntField(Rect position, GUIContent label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return IntFieldInternal(position, label, value, style); } [ExcludeFromDocs] public static int DelayedIntField(Rect position, int value) { return DelayedIntField(position, value, EditorStyles.numberField); } public static int DelayedIntField(Rect position, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedIntField(position, GUIContent.none, value, style); } [ExcludeFromDocs] public static int DelayedIntField(Rect position, string label, int value) { return DelayedIntField(position, label, value, EditorStyles.numberField); } public static int DelayedIntField(Rect position, string label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedIntField(position, EditorGUIUtility.TempContent(label), value, style); } [ExcludeFromDocs] public static int DelayedIntField(Rect position, GUIContent label, int value) { return DelayedIntField(position, label, value, EditorStyles.numberField); } public static int DelayedIntField(Rect position, GUIContent label, int value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return DelayedIntFieldInternal(position, label, value, style); } [ExcludeFromDocs] public static void DelayedIntField(Rect position, SerializedProperty property) { DelayedIntField(position, property, null); } public static void DelayedIntField(Rect position, SerializedProperty property, [DefaultValue("null")] GUIContent label) { DelayedIntFieldInternal(position, property, label); } [ExcludeFromDocs] public static long LongField(Rect position, long value) { return LongField(position, value, EditorStyles.numberField); } public static long LongField(Rect position, long value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return LongFieldInternal(position, value, style); } [ExcludeFromDocs] public static long LongField(Rect position, string label, long value) { return LongField(position, label, value, EditorStyles.numberField); } public static long LongField(Rect position, string label, long value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return LongField(position, EditorGUIUtility.TempContent(label), value, style); } [ExcludeFromDocs] public static long LongField(Rect position, GUIContent label, long value) { return LongField(position, label, value, EditorStyles.numberField); } static void LongField(Rect position, GUIContent label, ref NumberFieldValue value) { LongFieldInternal(position, label, ref value, EditorStyles.numberField); } public static long LongField(Rect position, GUIContent label, long value, [DefaultValue("EditorStyles.numberField")] GUIStyle style) { return LongFieldInternal(position, label, value, style); } [ExcludeFromDocs] public static int Popup(Rect position, int selectedIndex, string[] displayedOptions) { return Popup(position, selectedIndex, displayedOptions, EditorStyles.popup); } public static int Popup(Rect position, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return DoPopup(IndentedRect(position), GUIUtility.GetControlID(s_PopupHash, FocusType.Keyboard, position), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); } [ExcludeFromDocs] public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions) { return Popup(position, selectedIndex, displayedOptions, EditorStyles.popup); } public static int Popup(Rect position, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return DoPopup(IndentedRect(position), GUIUtility.GetControlID(s_PopupHash, FocusType.Keyboard, position), selectedIndex, displayedOptions, style); } [ExcludeFromDocs] public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions) { return Popup(position, label, selectedIndex, displayedOptions, EditorStyles.popup); } public static int Popup(Rect position, string label, int selectedIndex, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return PopupInternal(position, EditorGUIUtility.TempContent(label), selectedIndex, EditorGUIUtility.TempContent(displayedOptions), style); } [ExcludeFromDocs] public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions) { return Popup(position, label, selectedIndex, displayedOptions, EditorStyles.popup); } public static int Popup(Rect position, GUIContent label, int selectedIndex, GUIContent[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return PopupInternal(position, label, selectedIndex, displayedOptions, style); } [ExcludeFromDocs] public static Enum EnumPopup(Rect position, Enum selected) { return EnumPopup(position, selected, EditorStyles.popup); } public static Enum EnumPopup(Rect position, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return EnumPopup(position, GUIContent.none, selected, style); } [ExcludeFromDocs] public static Enum EnumPopup(Rect position, string label, Enum selected) { return EnumPopup(position, label, selected, EditorStyles.popup); } public static Enum EnumPopup(Rect position, string label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return EnumPopup(position, EditorGUIUtility.TempContent(label), selected, style); } [ExcludeFromDocs] public static Enum EnumPopup(Rect position, GUIContent label, Enum selected) { return EnumPopup(position, label, selected, EditorStyles.popup); } public static Enum EnumPopup(Rect position, GUIContent label, Enum selected, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return EnumPopupInternal(position, label, selected, null, false, style); } public static Enum EnumPopup(Rect position, GUIContent label, Enum selected, [DefaultValue("null")] Func<Enum, bool> checkEnabled, [DefaultValue("false")] bool includeObsolete = false, [DefaultValue("null")] GUIStyle style = null) { return EnumPopupInternal(position, label, selected, checkEnabled, includeObsolete, style ?? EditorStyles.popup); } private static void EnumPopup(Rect position, SerializedProperty property, GUIContent label) { Type type; ScriptAttributeUtility.GetFieldInfoFromProperty(property, out type); if (type != null && type.IsEnum) { BeginChangeCheck(); int value = EnumNamesCache.IsEnumTypeUsingFlagsAttribute(type) ? EnumFlagsField(position, label, property.intValue, type, false, EditorStyles.popup) : EnumPopupInternal(position, label, property.intValue, type, null, false, EditorStyles.popup); if (EndChangeCheck()) { // When the flag is a negative we need to convert it or it will be clamped. Type enumType = type.GetEnumUnderlyingType(); if (value < 0 && (enumType == typeof(uint) || enumType == typeof(ushort) || enumType == typeof(byte))) { property.longValue = (uint)value; } else { property.intValue = value; } } } else { BeginChangeCheck(); int idx = Popup(position, label, property.enumValueIndex, EnumNamesCache.GetEnumLocalizedGUIContents(property)); if (EndChangeCheck()) { property.enumValueIndex = idx; } } } [ExcludeFromDocs] public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues) { return IntPopup(position, selectedValue, displayedOptions, optionValues, EditorStyles.popup); } public static int IntPopup(Rect position, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return IntPopup(position, GUIContent.none, selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); } [ExcludeFromDocs] public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) { return IntPopup(position, selectedValue, displayedOptions, optionValues, EditorStyles.popup); } public static int IntPopup(Rect position, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return IntPopup(position, GUIContent.none, selectedValue, displayedOptions, optionValues, style); } [ExcludeFromDocs] public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues) { return IntPopup(position, label, selectedValue, displayedOptions, optionValues, EditorStyles.popup); } public static int IntPopup(Rect position, GUIContent label, int selectedValue, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return IntPopupInternal(position, label, selectedValue, displayedOptions, optionValues, style); } [ExcludeFromDocs] public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues) { IntPopup(position, property, displayedOptions, optionValues, null); } public static void IntPopup(Rect position, SerializedProperty property, GUIContent[] displayedOptions, int[] optionValues, [DefaultValue("null")] GUIContent label) { IntPopupInternal(position, property, displayedOptions, optionValues, label); } [ExcludeFromDocs] public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues) { return IntPopup(position, label, selectedValue, displayedOptions, optionValues, EditorStyles.popup); } public static int IntPopup(Rect position, string label, int selectedValue, string[] displayedOptions, int[] optionValues, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return IntPopupInternal(position, EditorGUIUtility.TempContent(label), selectedValue, EditorGUIUtility.TempContent(displayedOptions), optionValues, style); } [ExcludeFromDocs] public static string TagField(Rect position, string tag) { return TagField(position, tag, EditorStyles.popup); } public static string TagField(Rect position, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return TagFieldInternal(position, EditorGUIUtility.TempContent(string.Empty), tag, style); } [ExcludeFromDocs] public static string TagField(Rect position, string label, string tag) { return TagField(position, label, tag, EditorStyles.popup); } public static string TagField(Rect position, string label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return TagFieldInternal(position, EditorGUIUtility.TempContent(label), tag, style); } [ExcludeFromDocs] public static string TagField(Rect position, GUIContent label, string tag) { return TagField(position, label, tag, EditorStyles.popup); } public static string TagField(Rect position, GUIContent label, string tag, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return TagFieldInternal(position, label, tag, style); } [ExcludeFromDocs] public static int LayerField(Rect position, int layer) { return LayerField(position, layer, EditorStyles.popup); } public static int LayerField(Rect position, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return LayerFieldInternal(position, GUIContent.none, layer, style); } [ExcludeFromDocs] public static int LayerField(Rect position, string label, int layer) { return LayerField(position, label, layer, EditorStyles.popup); } public static int LayerField(Rect position, string label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return LayerFieldInternal(position, EditorGUIUtility.TempContent(label), layer, style); } [ExcludeFromDocs] public static int LayerField(Rect position, GUIContent label, int layer) { return LayerField(position, label, layer, EditorStyles.popup); } public static int LayerField(Rect position, GUIContent label, int layer, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return LayerFieldInternal(position, label, layer, style); } [ExcludeFromDocs] public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions) { return MaskField(position, label, mask, displayedOptions, EditorStyles.popup); } public static int MaskField(Rect position, GUIContent label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return MaskFieldInternal(position, label, mask, displayedOptions, style); } [ExcludeFromDocs] public static int MaskField(Rect position, string label, int mask, string[] displayedOptions) { return MaskField(position, label, mask, displayedOptions, EditorStyles.popup); } public static int MaskField(Rect position, string label, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return MaskFieldInternal(position, GUIContent.Temp(label), mask, displayedOptions, style); } [ExcludeFromDocs] public static int MaskField(Rect position, int mask, string[] displayedOptions) { return MaskField(position, mask, displayedOptions, EditorStyles.popup); } public static int MaskField(Rect position, int mask, string[] displayedOptions, [DefaultValue("EditorStyles.popup")] GUIStyle style) { return MaskFieldInternal(position, mask, displayedOptions, style); } [ExcludeFromDocs] public static bool Foldout(Rect position, bool foldout, string content) { return Foldout(position, foldout, content, EditorStyles.foldout); } public static bool Foldout(Rect position, bool foldout, string content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { return FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), false, style); } [ExcludeFromDocs] public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick) { return Foldout(position, foldout, content, toggleOnLabelClick, EditorStyles.foldout); } public static bool Foldout(Rect position, bool foldout, string content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { return FoldoutInternal(position, foldout, EditorGUIUtility.TempContent(content), toggleOnLabelClick, style); } [ExcludeFromDocs] public static bool Foldout(Rect position, bool foldout, GUIContent content) { return Foldout(position, foldout, content, EditorStyles.foldout); } public static bool Foldout(Rect position, bool foldout, GUIContent content, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { return FoldoutInternal(position, foldout, content, false, style); } [ExcludeFromDocs] public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick) { return Foldout(position, foldout, content, toggleOnLabelClick, EditorStyles.foldout); } public static bool Foldout(Rect position, bool foldout, GUIContent content, bool toggleOnLabelClick, [DefaultValue("EditorStyles.foldout")] GUIStyle style) { return FoldoutInternal(position, foldout, content, toggleOnLabelClick, style); } [ExcludeFromDocs] public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, int id) { HandlePrefixLabel(totalPosition, labelPosition, label, id, EditorStyles.label); } [ExcludeFromDocs] public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label) { HandlePrefixLabel(totalPosition, labelPosition, label, 0, EditorStyles.label); } internal static float CalcPrefixLabelWidth(GUIContent label, GUIStyle style = null) { if (style == null) style = EditorStyles.label; return style.CalcSize(label).x; } public static void HandlePrefixLabel(Rect totalPosition, Rect labelPosition, GUIContent label, [DefaultValue("0")] int id, [DefaultValue("EditorStyles.label")] GUIStyle style) { HandlePrefixLabelInternal(totalPosition, labelPosition, label, id, style); } public static float GetPropertyHeight(SerializedProperty property, bool includeChildren) { return GetPropertyHeightInternal(property, null, includeChildren); } [ExcludeFromDocs] public static float GetPropertyHeight(SerializedProperty property, GUIContent label) { return GetPropertyHeight(property, label, true); } [ExcludeFromDocs] public static float GetPropertyHeight(SerializedProperty property) { return GetPropertyHeight(property, null, true); } public static float GetPropertyHeight(SerializedProperty property, [DefaultValue("null")] GUIContent label, [DefaultValue("true")] bool includeChildren) { return GetPropertyHeightInternal(property, label, includeChildren); } [ExcludeFromDocs] public static bool PropertyField(Rect position, SerializedProperty property) { // Allow reorderable list to include children by default to keep similar behaviour to old arrays return PropertyField(position, property, PropertyHandler.UseReorderabelListControl(property)); } public static bool PropertyField(Rect position, SerializedProperty property, [DefaultValue("false")] bool includeChildren) { return PropertyFieldInternal(position, property, null, includeChildren); } [ExcludeFromDocs] public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label) { // Allow reorderable list to include children by default to keep similar behaviour to old arrays return PropertyField(position, property, label, PropertyHandler.UseReorderabelListControl(property)); } public static bool PropertyField(Rect position, SerializedProperty property, GUIContent label, [DefaultValue("false")] bool includeChildren) { return PropertyFieldInternal(position, property, label, includeChildren); } internal static class EnumNamesCache { static Dictionary<Type, GUIContent[]> s_EnumTypeLocalizedGUIContents = new Dictionary<Type, GUIContent[]>(); static Dictionary<int, GUIContent[]> s_SerializedPropertyEnumLocalizedGUIContents = new Dictionary<int, GUIContent[]>(); static Dictionary<Type, bool> s_IsEnumTypeUsingFlagsAttribute = new Dictionary<Type, bool>(); static Dictionary<Type, string[]> s_SerializedPropertyEnumDisplayNames = new Dictionary<Type, string[]>(); static Dictionary<Type, string[]> s_SerializedPropertyEnumNames = new Dictionary<Type, string[]>(); internal static GUIContent[] GetEnumTypeLocalizedGUIContents(Type enumType, EnumData enumData) { GUIContent[] result; if (s_EnumTypeLocalizedGUIContents.TryGetValue(enumType, out result)) { return result; } else { // Build localized data and add to cache using (new LocalizationGroup(enumType)) { UnityEngine.EnumDataUtility.HandleInspectorOrderAttribute(enumType, ref enumData); result = EditorGUIUtility.TrTempContent(enumData.displayNames, enumData.tooltip); s_EnumTypeLocalizedGUIContents[enumType] = result; return result; } } } internal static GUIContent[] GetEnumLocalizedGUIContents(SerializedProperty property) { if (property.serializedObject.targetObject == null) return EditorGUIUtility.TempContent(property.enumLocalizedDisplayNames); var propertyHash = property.hashCodeForPropertyPathWithoutArrayIndex; var typeHash = property.serializedObject.targetObject.GetType().GetHashCode(); var hashCode = typeHash ^ propertyHash; GUIContent[] result; if (s_SerializedPropertyEnumLocalizedGUIContents.TryGetValue(hashCode, out result)) { return result; } result = EditorGUIUtility.TempContent(property.enumLocalizedDisplayNames); s_SerializedPropertyEnumLocalizedGUIContents[hashCode] = result; return result; } internal static string[] GetEnumDisplayNames(SerializedProperty property) { Type enumType; ScriptAttributeUtility.GetFieldInfoFromProperty(property, out enumType); // For native properties, like Camera.m_ClearFlags, the enumType returned will be null. // So we can't use it for the dict key below. Need to early out. // Case: 1388694 if (enumType == null) return property.enumDisplayNames; string[] result; if (!s_SerializedPropertyEnumDisplayNames.TryGetValue(enumType, out result)) { result = property.enumDisplayNames; s_SerializedPropertyEnumDisplayNames.Add(enumType, result); } return result; } internal static string[] GetEnumNames(SerializedProperty property) { Type enumType; ScriptAttributeUtility.GetFieldInfoFromProperty(property, out enumType); string[] result; if (!s_SerializedPropertyEnumNames.TryGetValue(enumType, out result)) { result = property.enumNames; s_SerializedPropertyEnumNames.Add(enumType, result); } return result; } internal static bool IsEnumTypeUsingFlagsAttribute(Type type) { bool result; if (s_IsEnumTypeUsingFlagsAttribute.TryGetValue(type, out result)) return result; // GetCustomAttributes allocates a new List on every call so we cache the result result = type.GetCustomAttributes(typeof(FlagsAttribute), false).Length > 0; s_IsEnumTypeUsingFlagsAttribute[type] = result; return result; } } static class HelpButtonCache { static Dictionary<Type, bool> s_TypeIsPartOfTargetAssembliesMap = new Dictionary<Type, bool>(); static Dictionary<Type, bool> s_ObjectHasHelp = new Dictionary<Type, bool>(); internal static bool HasHelpForObject(Object obj, bool monoBehaviourFallback) { if (obj == null) return false; bool result; if (s_ObjectHasHelp.TryGetValue(obj.GetType(), out result)) { return result; } else { // Calc result and cache it result = Help.HasHelpForObject(obj, monoBehaviourFallback); s_ObjectHasHelp[obj.GetType()] = result; return result; } } internal static bool IsObjectPartOfTargetAssemblies(Object obj) { if (obj == null) return false; var type = obj.GetType(); bool result; if (s_TypeIsPartOfTargetAssembliesMap.TryGetValue(type, out result)) { return result; } else { // Calc result and cache it result = false; EditorCompilation.TargetAssemblyInfo[] allTargetAssemblies = EditorCompilationInterface.GetTargetAssemblyInfos(); string assemblyName = obj.GetType().Assembly.ManifestModule.Name; for (int i = 0; i < allTargetAssemblies.Length; ++i) { if (assemblyName == allTargetAssemblies[i].Name) { result = true; break; } } s_TypeIsPartOfTargetAssembliesMap[type] = result; return result; } } } } }
UnityCsReference/Editor/Mono/EditorGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/EditorGUI.cs", "repo_id": "UnityCsReference", "token_count": 203005 }
303
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Serialization; using UnityEngine.Bindings; using UnityObject = UnityEngine.Object; using RefId = System.Int64; namespace UnityEditor { //Must match declaration in EditorSerializationUtility.h [NativeType(Header = "Editor/Src/Utility/EditorSerializationUtility.h")] public readonly struct ManagedReferenceMissingType : IEquatable<ManagedReferenceMissingType>, IComparable<ManagedReferenceMissingType> { public readonly String assemblyName { get { return m_AssemblyName; } } public readonly String className { get { return m_ClassName; } } public readonly String namespaceName { get { return m_NamespaceName; } } public readonly RefId referenceId { get { return m_ReferenceId; } } public readonly String serializedData { get { return m_SerializedData; } } public bool Equals(ManagedReferenceMissingType other) { return referenceId == other.referenceId; } public int CompareTo(ManagedReferenceMissingType other) { return referenceId.CompareTo(other.referenceId); } #pragma warning disable CS0649 [NativeName("assemblyName")] private readonly String m_AssemblyName; [NativeName("className")] private readonly String m_ClassName; [NativeName("namespaceName")] private readonly String m_NamespaceName; [NativeName("referenceId")] private readonly RefId m_ReferenceId; [NativeName("serializedData")] private readonly String m_SerializedData; #pragma warning restore CS0649 }; [NativeHeader("Editor/Src/Utility/EditorSerializationUtility.h")] public sealed class SerializationUtility { // Must match the same declarations in "Runtime/Serialize/ReferenceId.h" [System.Obsolete("Use Serialization.ManagedReferenceUtility.RefIdUnknown instead. (UnityUpgradable) -> [UnityEngine] UnityEngine.Serialization.ManagedReferenceUtility.RefIdUnknown", false)] public const RefId RefIdUnknown = -1; [System.Obsolete("Use Serialization.ManagedReferenceUtility.RefIdNull instead. (UnityUpgradable) -> [UnityEngine] UnityEngine.Serialization.ManagedReferenceUtility.RefIdNull", false)] public const RefId RefIdNull = -2; [System.Obsolete("Use Serialization.ManagedReferenceUtility.SetManagedReferenceIdForObject instead. (UnityUpgradable) -> [UnityEngine] UnityEngine.Serialization.ManagedReferenceUtility.SetManagedReferenceIdForObject(*)", false)] public static bool SetManagedReferenceIdForObject(UnityObject obj, object scriptObj, RefId refId) { return ManagedReferenceUtility.SetManagedReferenceIdForObject(obj, scriptObj, refId); } [System.Obsolete("Use Serialization.ManagedReferenceUtility::GetManagedReferenceIdForObject instead. (UnityUpgradable) -> [UnityEngine] UnityEngine.Serialization.ManagedReferenceUtility.GetManagedReferenceIdForObject(*)", false)] public static RefId GetManagedReferenceIdForObject(UnityObject obj, object scriptObj) { return ManagedReferenceUtility.GetManagedReferenceIdForObject(obj, scriptObj); } [System.Obsolete("Use Serialization.ManagedReferenceUtility::GetManagedReference instead. (UnityUpgradable) -> [UnityEngine] UnityEngine.Serialization.ManagedReferenceUtility.GetManagedReference(*)", false)] public static object GetManagedReference(UnityObject obj, RefId id) { return ManagedReferenceUtility.GetManagedReference(obj, id); } [System.Obsolete("Use Serialization.ManagedReferenceUtility::GetManagedReferencesIds instead. (UnityUpgradable) -> [UnityEngine] UnityEngine.Serialization.ManagedReferenceUtility.GetManagedReferenceIds(*)", false)] public static RefId[] GetManagedReferenceIds(UnityObject obj) { return ManagedReferenceUtility.GetManagedReferenceIds(obj); } [NativeMethod("HasManagedReferencesWithMissingTypes")] static extern bool HasManagedReferencesWithMissingTypesInternal(UnityObject obj); public static bool HasManagedReferencesWithMissingTypes(UnityObject obj) { return HasManagedReferencesWithMissingTypesInternal(obj); } [NativeMethod("GetManagedReferencesWithMissingTypes")] static extern ManagedReferenceMissingType[] GetManagedReferencesWithMissingTypesInternal(UnityObject obj); public static ManagedReferenceMissingType[] GetManagedReferencesWithMissingTypes(UnityObject obj) { return GetManagedReferencesWithMissingTypesInternal(obj); } [NativeMethod("ClearAllManagedReferencesWithMissingTypes")] static extern bool ClearAllManagedReferencesWithMissingTypesInternal(UnityObject obj); public static bool ClearAllManagedReferencesWithMissingTypes(UnityObject obj) { return ClearAllManagedReferencesWithMissingTypesInternal(obj); } [NativeMethod("ClearManagedReferenceWithMissingType")] static extern bool ClearManagedReferenceWithMissingTypeInternal(UnityObject obj, RefId id); public static bool ClearManagedReferenceWithMissingType(UnityObject obj, RefId id) { return ClearManagedReferenceWithMissingTypeInternal(obj, id); } internal static extern void SuppressMissingTypeWarning(string className); }; }
UnityCsReference/Editor/Mono/EditorSerializationUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/EditorSerializationUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1914 }
304
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using UnityEditor.Profiling; namespace UnityEditor { /// <summary> /// Use this to enhance C# events with editor performance trackers. This can be used as a replacement of a C# event without changing /// the public API. Using editor performance trackers means that the pop-up progress bar will provide more helpful information. /// </summary> /// <remarks> /// Like C# events, adding and removing subscribers is thread-safe. Invoking the event however should only happen on the main thread /// (because of the performance trackers). /// /// Using this type will give your performance trackers sensible names and cache them. Like regular C# events, adding and removing /// subscribers may cause garbage allocations. /// </remarks> /// <example> /// <code> /// public static class Events { /// public static event SomeDelegate MyEvent; /// /// private static void InvokeEvent() { /// MyEvent?.Invoke(1, 2, 3); /// } /// } /// </code> /// can be rewritten to this: /// <code> /// public static class Events { /// public static event SomeDelegate MyEvent { /// add => m_MyEvent.Add(value); /// remove => m_MyEvent.Remove(value); /// } /// private static EventWithPerformanceTracker&lt;SomeDelegate&gt; m_MyEvent = /// new EventWithPerformanceTracker&lt;SomeDelegate&gt;($"{nameof(Events)}.{nameof(MyEvent)}"); /// /// private static void InvokeEvent() { /// foreach (var evt in m_Event) { /// // A performance tracker for this delegate is active here! /// evt.Invoke(1, 2, 3); /// } /// } /// } /// </code> /// </example> /// <typeparam name="T">The delegate type for this event.</typeparam> struct EventWithPerformanceTracker<T> where T : Delegate { private readonly string m_Scope; // This is either a reference to a delegate or a reference to a list. This mirrors the implementation of // multicast delegates in .NET. This needs to be a class to make thread-safe add/remove work. private DelegateWithHandle m_Delegate; public EventWithPerformanceTracker(string scope) { m_Scope = scope; m_Delegate = null; } /// <summary> /// Returns whether this event has any subscribers. /// </summary> public bool hasSubscribers => m_Delegate != null && m_Delegate.isNonEmpty; /// <summary> /// Add a subscriber to this event. This is equivalent to using += on a C# event. /// </summary> /// <param name="value"></param> public void Add(T value) { // Thread-safe method to subscribe to this event. The implementation closely mirrors the compiler-generated code for events. // see https://sharplab.io/#v2:CYLg1APgAgTAjAWAFBQMwAJboMLoN7LpGYYCmAbqQHYAumcMAPAJa0B86AopbQLIDchYkKJpMAFnS8AFAEp8I9AF9kSoA=== var del = m_Delegate; while (true) { var del2 = del; var value2 = DelegateWithHandle.Add(del2, value); del = Interlocked.CompareExchange(ref m_Delegate, value2, del2); if (del == del2) { break; } } } /// <summary> /// Remove a subscriber from this event. This is equivalent to using -= on a C# event. /// </summary> /// <param name="value"></param> public void Remove(T value) { var del = m_Delegate; while (true) { var del2 = del; var value2 = DelegateWithHandle.Remove(del2, value); del = Interlocked.CompareExchange(ref m_Delegate, value2, del2); if (del == del2) { break; } } } public Enumerator GetEnumerator() => new Enumerator(this); internal struct Enumerator : IEnumerator<T> { private readonly DelegateWithHandle m_Delegate; private readonly string m_Scope; private readonly int m_Length; private int m_ActivePerformanceTracker; private int m_CurrentIndex; internal Enumerator(EventWithPerformanceTracker<T> evt) { m_Length = evt.m_Delegate?.length ?? 0; m_Scope = evt.m_Scope; m_ActivePerformanceTracker = -1; m_CurrentIndex = -1; m_Delegate = evt.m_Delegate; } public void Dispose() { if (m_ActivePerformanceTracker >= 0) EditorPerformanceTracker.StopTracker(m_ActivePerformanceTracker); } public bool MoveNext() { if (m_ActivePerformanceTracker >= 0) EditorPerformanceTracker.StopTracker(m_ActivePerformanceTracker); m_CurrentIndex++; m_ActivePerformanceTracker = m_CurrentIndex < m_Length ? m_Delegate.StartTrackerAt(m_CurrentIndex, m_Scope) : -1; return m_CurrentIndex < m_Length; } public void Reset() => throw new NotImplementedException(); public T Current => m_Delegate.GetDelegateAt(m_CurrentIndex); object IEnumerator.Current => (this as IEnumerator<T>).Current; } internal static EventWithPerformanceTracker.Entry BuildDelegate(string scope, T del) { if (del == null) { return default; } var ls = del.GetInvocationList(); switch (ls.Length) { case 0: return default; case 1: return new EventWithPerformanceTracker.Entry(del, EventWithPerformanceTracker.GetPerformanceTrackerHandleForEvent(scope, del)); default: { var entries = new EventWithPerformanceTracker.Entry[ls.Length]; for (int i = 0; i < entries.Length; i++) entries[i] = new EventWithPerformanceTracker.Entry(ls[i] as T, EventWithPerformanceTracker.GetPerformanceTrackerHandleForEvent(scope, ls[i])); return new EventWithPerformanceTracker.Entry(entries); } } } private class DelegateWithHandle { private EventWithPerformanceTracker.Entry m_DelegateOrList; private DelegateWithHandle() {} private DelegateWithHandle(EventWithPerformanceTracker.Entry entry) { m_DelegateOrList = entry; } public bool isNonEmpty => m_DelegateOrList.Reference != null; internal int length => m_DelegateOrList.length; internal int StartTrackerAt(int idx, string scope) { // We have to lazily initialize the tracker because subscription might happen from any thread // but we can only create editor performance trackers from the main thread. ref var handle = ref m_DelegateOrList.Reference is EventWithPerformanceTracker.Entry[] list ? ref list[idx].EditorPerformanceTrackerHandle : ref m_DelegateOrList.EditorPerformanceTrackerHandle; if (handle == EditorPerformanceTracker.InvalidTrackerHandle) handle = EventWithPerformanceTracker.GetPerformanceTrackerHandleForEvent(scope, GetDelegateAt(idx)); EditorPerformanceTracker.TryStartTrackerByHandle(handle, out var token); return token; } internal T GetDelegateAt(int idx) => (m_DelegateOrList.Reference is EventWithPerformanceTracker.Entry[] list ? list[idx].Reference : m_DelegateOrList.Reference) as T; internal static DelegateWithHandle Add(DelegateWithHandle dwh, T del) { if (dwh == null) { return new DelegateWithHandle(new EventWithPerformanceTracker.Entry(del)); } switch (dwh.m_DelegateOrList.Reference) { case null: return new DelegateWithHandle(new EventWithPerformanceTracker.Entry(del)); case EventWithPerformanceTracker.Entry[] list: { // This may seem wasteful, but mirrors the C# implementation of delegates. This is important // to make thread-safe events work without locking, and also to support re-entrant events. var newList = new EventWithPerformanceTracker.Entry[list.Length + 1]; int n = list.Length; for (int i = 0; i < n; i++) newList[i] = list[i]; newList[n] = new EventWithPerformanceTracker.Entry(del); return new DelegateWithHandle(new EventWithPerformanceTracker.Entry(newList)); } default: { var newList = new EventWithPerformanceTracker.Entry[2]; newList[0] = dwh.m_DelegateOrList; newList[1] = new EventWithPerformanceTracker.Entry(del); return new DelegateWithHandle(new EventWithPerformanceTracker.Entry(newList)); } } } private static DelegateWithHandle RemoveAt(EventWithPerformanceTracker.Entry[] array, int idx) { if (array.Length == 1) return null; if (array.Length == 2) { return new DelegateWithHandle(array[1 - idx]); } int n = array.Length; var newArray = new EventWithPerformanceTracker.Entry[n - 1]; for (int k = 0; k < idx; k++) { newArray[k] = array[k]; } for (int k = idx + 1; k < n; k++) { newArray[k - 1] = array[k]; } return new DelegateWithHandle(new EventWithPerformanceTracker.Entry(newArray)); } internal static DelegateWithHandle Remove(DelegateWithHandle dwh, T del) { if (dwh == null) return null; switch (dwh.m_DelegateOrList.Reference) { case null: return dwh; case EventWithPerformanceTracker.Entry[] list: { for (int i = list.Length - 1; i >= 0; i--) { if ((list[i].Reference as T) == del) { return RemoveAt(list, i); } } return dwh; } default: { if ((dwh.m_DelegateOrList.Reference as T) == del) return null; return dwh; } } } } } static class EventWithPerformanceTracker { internal struct Entry { internal ulong EditorPerformanceTrackerHandle; internal readonly object Reference; public Entry(Delegate del, ulong trackerHandle = EditorPerformanceTracker.InvalidTrackerHandle) { Reference = del; EditorPerformanceTrackerHandle = trackerHandle; } public Entry(Entry[] entries) { Reference = entries; EditorPerformanceTrackerHandle = EditorPerformanceTracker.InvalidTrackerHandle; } internal int length { get { if (Reference == null) return 0; if (Reference is Entry[] list) return list.Length; return 1; } } } internal static string GetPerformanceTrackerName(string scope, Delegate d) { if (d.Method.DeclaringType != null) { if (Attribute.IsDefined(d.Method.DeclaringType, typeof(CompilerGeneratedAttribute))) { // find the outermost type var type = d.Method.DeclaringType; while (type.DeclaringType != null) { type = type.DeclaringType; } return $"{scope}: callback in {type.FullName}"; } return $"{scope}: {d.Method.DeclaringType.FullName}.{d.Method.Name}"; } return scope; } internal static ulong GetPerformanceTrackerHandleForEvent(string scope, Delegate d) { var declaringType = d.Method.DeclaringType; if (declaringType != null) { return EditorPerformanceTracker.GetOrCreateTrackerHandle(GetPerformanceTrackerName(scope, d), declaringType); } return EditorPerformanceTracker.GetOrCreateTrackerHandle(GetPerformanceTrackerName(scope, d)); } } /// <summary> /// Use this to add editor performance trackers to events that are implemented via raw delegates instead of proper /// C# events. Using editor performance trackers means that the pop-up progress bar will provide more helpful information. /// </summary> /// <remarks> /// This delegate should only be invoked on the main thread (because of the performance trackers). /// /// The implementation of this type assumes that the delegate it is wrapping changes infrequently compared to how often /// it is invoked. Invoking the delegate is cheap, but (as with C# delegates) changing the delegate can cause additional /// work as we need to recompute the performance markers. /// </remarks> /// <example> /// <code> /// public static class Events { /// public static SomeDelegate MyPoorlyImplementedEvent; /// /// private static void InvokeEvent() { /// MyPoorlyImplementedEvent?.Invoke(1, 2, 3); /// } /// } /// </code> /// can be rewritten to this: /// <code> /// public static class Events { /// public static SomeDelegate MyPoorlyImplementedEvent; /// private static DelegateWithPerformanceTracker&lt;SomeDelegate&gt; m_MyPoorlyImplementedEvent = /// new DelegateWithPerformanceTracker&lt;SomeDelegate&gt;($"{nameof(Events)}.{nameof(MyPoorlyImplementedEvent)}"); /// /// private static void InvokeEvent() { /// foreach (var evt in m_MyPoorlyImplementedEvent.UpdateAndInvoke(MyPoorlyImplementedEvent)) { /// evt.Invoke(1, 2, 3); /// } /// } /// } /// </code> /// </example> /// <typeparam name="T">The delegate type.</typeparam> struct DelegateWithPerformanceTracker<T> where T : Delegate { private readonly string m_Scope; // We follow the same pattern as in EventWithPerformanceTracker to allow for re-entrant events. private EventWithPerformanceTracker.Entry m_Delegates; private T m_CachedDelegate; public DelegateWithPerformanceTracker(string scope) { m_Scope = scope; m_Delegates = default; m_CachedDelegate = null; } /// <summary> /// Update the delegate wrapped by this tracker and acquire an enumerator for invoking it via iteration. /// </summary> /// <param name="value"></param> /// <returns></returns> public Invoker UpdateAndInvoke(T value) { if (!ReferenceEquals(m_CachedDelegate, value)) { m_CachedDelegate = value; m_Delegates = EventWithPerformanceTracker<T>.BuildDelegate(m_Scope, value); } return new Invoker(ref m_Delegates); } internal readonly struct Invoker { private readonly EventWithPerformanceTracker.Entry m_Delegates; public Enumerator GetEnumerator() => new Enumerator(in this); public Invoker(ref EventWithPerformanceTracker.Entry dlg) { m_Delegates = dlg; } internal struct Enumerator : IEnumerator<T> { private readonly EventWithPerformanceTracker.Entry m_Delegates; private readonly int m_Length; private int m_ActivePerformanceTracker; private int m_CurrentIndex; internal Enumerator(in Invoker evt) { m_Delegates = evt.m_Delegates; m_Length = evt.m_Delegates.length; m_ActivePerformanceTracker = -1; m_CurrentIndex = -1; } public void Dispose() { if (m_ActivePerformanceTracker >= 0) EditorPerformanceTracker.StopTracker(m_ActivePerformanceTracker); } public bool MoveNext() { if (m_ActivePerformanceTracker >= 0) EditorPerformanceTracker.StopTracker(m_ActivePerformanceTracker); m_CurrentIndex++; if (m_CurrentIndex < m_Length) { ulong handle; if (m_Length == 1) handle = m_Delegates.EditorPerformanceTrackerHandle; else handle = (m_Delegates.Reference as EventWithPerformanceTracker.Entry[])[m_CurrentIndex].EditorPerformanceTrackerHandle; EditorPerformanceTracker.TryStartTrackerByHandle(handle, out m_ActivePerformanceTracker); } else m_ActivePerformanceTracker = -1; return m_CurrentIndex < m_Length; } public void Reset() => throw new NotImplementedException(); public T Current { get { if (m_Length == 1) return m_Delegates.Reference as T; return (m_Delegates.Reference as EventWithPerformanceTracker.Entry[])[m_CurrentIndex].Reference as T; } } object IEnumerator.Current => (this as IEnumerator<T>).Current; } } } }
UnityCsReference/Editor/Mono/EventWithPerformanceTracker.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/EventWithPerformanceTracker.cs", "repo_id": "UnityCsReference", "token_count": 9395 }
305
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngineInternal; namespace UnityEditor { [System.Obsolete("LightmapBakeQuality has been deprecated.", false)] public enum LightmapBakeQuality { High = 0, Low = 1, } public partial class LightmapEditorSettings { [System.Obsolete("LightmapEditorSettings.aoContrast has been deprecated.", false)] public static float aoContrast { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.aoAmount has been deprecated.", false)] public static float aoAmount { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.lockAtlas has been deprecated.", false)] public static bool lockAtlas { get { return false; } set {} } [System.Obsolete("LightmapEditorSettings.skyLightColor has been deprecated.", false)] public static Color skyLightColor { get { return Color.black; } set {} } [System.Obsolete("LightmapEditorSettings.skyLightIntensity has been deprecated.", false)] public static float skyLightIntensity { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.quality has been deprecated.", false)] public static LightmapBakeQuality quality { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.bounceBoost has been deprecated.", false)] public static float bounceBoost { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.finalGatherRays has been deprecated.", false)] public static int finalGatherRays { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.finalGatherContrastThreshold has been deprecated.", false)] public static float finalGatherContrastThreshold { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.finalGatherGradientThreshold has been deprecated.", false)] public static float finalGatherGradientThreshold { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.finalGatherInterpolationPoints has been deprecated.", false)] public static int finalGatherInterpolationPoints { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.lastUsedResolution has been deprecated.", false)] public static float lastUsedResolution { get { return 0; } set {} } [System.Obsolete("LightmapEditorSettings.bounceIntensity has been deprecated.", false)] public static float bounceIntensity { get { return 0; } set {} } [System.Obsolete("resolution is now called realtimeResolution (UnityUpgradable) -> realtimeResolution", false)] public static float resolution { get { return realtimeResolution; } set { realtimeResolution = value; } } [System.Obsolete("GIBakeBackend has been renamed to Lightmapper. (UnityUpgradable)", true)] public enum GIBakeBackend { Radiosity = 0, PathTracer = 1 } [System.Obsolete("The giBakeBackend property has been renamed to lightmapper. (UnityUpgradable) -> lightmapper", false)] public static GIBakeBackend giBakeBackend { get { if (lightmapper == Lightmapper.ProgressiveCPU) return GIBakeBackend.PathTracer; else return GIBakeBackend.Radiosity; } set { if (value == GIBakeBackend.PathTracer) lightmapper = Lightmapper.ProgressiveCPU; else lightmapper = Lightmapper.Enlighten; } } [System.Obsolete("PathTracerSampling has been renamed to Sampling. (UnityUpgradable) -> UnityEditor.LightmapEditorSettings/Sampling", false)] public enum PathTracerSampling { Auto = 0, Fixed = 1 } [System.Obsolete("The giPathTracerSampling property has been renamed to sampling. (UnityUpgradable) -> sampling", false)] public static PathTracerSampling giPathTracerSampling { get { if (sampling == Sampling.Auto) return PathTracerSampling.Auto; else return PathTracerSampling.Fixed; } set { if (value == PathTracerSampling.Auto) sampling = Sampling.Auto; else sampling = Sampling.Fixed; } } [System.Obsolete("PathTracerFilter has been renamed to FilterType. (UnityUpgradable) -> UnityEditor.LightmapEditorSettings/FilterType", false)] public enum PathTracerFilter { Gaussian = 0, ATrous = 1 } [System.Obsolete("The giPathTracerFilter property has been deprecated. There are three independent properties to set individual filter types for direct, indirect and AO GI textures: filterTypeDirect, filterTypeIndirect and filterTypeAO.")] public static PathTracerFilter giPathTracerFilter { get { if (LightmapEditorSettings.filterTypeDirect == FilterType.Gaussian) return PathTracerFilter.Gaussian; else return PathTracerFilter.ATrous; } set { LightmapEditorSettings.filterTypeDirect = FilterType.Gaussian; LightmapEditorSettings.filterTypeIndirect = FilterType.Gaussian; LightmapEditorSettings.filterTypeAO = FilterType.Gaussian; } } [System.Obsolete("LightmapEditorSettings.maxAtlasWidth is now called maxAtlasSize (UnityUpgradable) -> maxAtlasSize", false)] public static int maxAtlasWidth { get { return maxAtlasSize; } set { maxAtlasSize = value; } } private static int m_MaxAtlasHeight = 1024; [System.Obsolete("LightmapEditorSettings.maxAtlasHeight has been deprecated. Only square atlases are supported, please use the maxAtlasSize instead. ")] public static int maxAtlasHeight { get { return m_MaxAtlasHeight; } set { m_MaxAtlasHeight = value; } } } }
UnityCsReference/Editor/Mono/GI/LightmapEditorSettingsDeprecated.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GI/LightmapEditorSettingsDeprecated.cs", "repo_id": "UnityCsReference", "token_count": 3197 }
306
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { public sealed partial class EditorGUILayout { internal static float AngularDial( GUIContent label, float angle, Texture thumbTexture, GUIStyle background, GUIStyle thumb, params GUILayoutOption[] options ) { var hasLabel = label != null && label != GUIContent.none; var height = background == null || background.fixedHeight == 0 ? EditorGUIUtility.singleLineHeight : background.fixedHeight; var minWidth = (hasLabel ? EditorGUIUtility.labelWidth : 0f) + (background != null ? background.fixedWidth : 0f); var maxWidth = kLabelFloatMaxW; var rect = GUILayoutUtility.GetRect(minWidth, maxWidth, height, height, background, options); s_LastRect = rect; return EditorGUI.AngularDial(rect, label, angle, thumbTexture, background, thumb); } } public sealed partial class EditorGUI { internal static float AngularDial( Rect rect, GUIContent label, float angle, Texture thumbTexture, GUIStyle background, GUIStyle thumb ) { var id = GUIUtility.GetControlID(FocusType.Passive); var evt = Event.current; if (label != null && label != GUIContent.none) rect = PrefixLabel(rect, id, label); var diameter = Mathf.Min(rect.width, rect.height); var thumbDimensions = thumb == null || thumb == GUIStyle.none ? Vector2.zero : thumb.CalcSize(GUIContent.Temp(thumbTexture)); var thumbSize = Mathf.Max(thumbDimensions.x, thumbDimensions.y); switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (rect.Contains(evt.mousePosition)) { var p = evt.mousePosition - rect.center; var r = Mathf.Sqrt(p.x * p.x + p.y * p.y); if (r < diameter * 0.5f && r > diameter * 0.5f - thumbSize) return UseAngularDialEventAndGetAngle(id, evt, rect.center, angle); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) return UseAngularDialEventAndGetAngle(id, evt, rect.center, angle); break; case EventType.MouseUp: if (GUIUtility.hotControl == id) { GUIUtility.hotControl = 0; return UseAngularDialEventAndGetAngle(id, evt, rect.center, angle); } break; case EventType.Repaint: var hover = false; if (rect.Contains(evt.mousePosition)) { var p = evt.mousePosition - rect.center; var r = Mathf.Sqrt(p.x * p.x + p.y * p.y); hover = r<diameter * 0.5f && r> diameter * 0.5f - thumbSize; } var active = GUIUtility.hotControl == id; if (background != null && background != GUIStyle.none) background.Draw(rect, hover, active, false, false); if (thumb != null && thumb != GUIStyle.none) { var thumbCenterRadius = diameter * 0.5f - thumbSize * 0.5f; // negate angle since gui space goes top to bottom var radians = -Mathf.Deg2Rad * angle; var thumbCenter = new Vector2(Mathf.Cos(radians), Mathf.Sin(radians)) * thumbCenterRadius + rect.center; var size = thumb.CalcSize(GUIContent.none); if (thumb.fixedWidth == 0f) size.x = Mathf.Max(size.x, thumbSize); if (thumb.fixedHeight == 0f) size.y = Mathf.Max(size.y, thumbSize); var thumbRect = new Rect { size = size, center = thumbCenter }; thumbRect.center = thumbCenter; thumb.Draw(thumbRect, thumbTexture, thumbRect.Contains(evt.mousePosition), active, false, false); } break; } return angle; } private static float UseAngularDialEventAndGetAngle(int id, Event evt, Vector2 center, float angle) { GUIUtility.hotControl = evt.type == EventType.MouseUp ? 0 : id; EditorGUIUtility.keyboardControl = 0; GUI.changed = true; evt.Use(); var normalized = (evt.mousePosition - center).normalized; // negate angle since gui space goes top to bottom var newAngle = -Mathf.Rad2Deg * Mathf.Acos(normalized.x) * Mathf.Sign(Vector2.Dot(Vector2.up, normalized)); // accumulate delta angle to allow for multiple revolutions return angle + Mathf.DeltaAngle(angle, newAngle); } } }
UnityCsReference/Editor/Mono/GUI/AngularDial.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/AngularDial.cs", "repo_id": "UnityCsReference", "token_count": 2793 }
307
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; namespace UnityEditor { class DragRectGUI { static int dragRectHash = "DragRect".GetHashCode(); static int s_DragCandidateState = 0; static float s_DragSensitivity = 1.0f; public static int DragRect(Rect position, int value, int minValue, int maxValue) { Event evt = Event.current; int id = GUIUtility.GetControlID(dragRectHash, FocusType.Passive, position); switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (position.Contains(evt.mousePosition) && evt.button == 0) { GUIUtility.hotControl = id; s_DragCandidateState = 1; evt.Use(); } break; case EventType.MouseUp: if (GUIUtility.hotControl == id && s_DragCandidateState != 0) { GUIUtility.hotControl = 0; s_DragCandidateState = 0; evt.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { switch (s_DragCandidateState) { case 1: value += (int)(HandleUtility.niceMouseDelta * s_DragSensitivity); GUI.changed = true; evt.Use(); if (value < minValue) value = minValue; else if (value > maxValue) value = maxValue; break; } } break; case EventType.Repaint: EditorGUIUtility.AddCursorRect(position, MouseCursor.SlideArrow); break; } return value; } } }
UnityCsReference/Editor/Mono/GUI/DragRect.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/DragRect.cs", "repo_id": "UnityCsReference", "token_count": 1396 }
308
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditorInternal; namespace UnityEditor { public sealed partial class EditorGUILayout { // Gradient versions public static Gradient GradientField(Gradient value, params GUILayoutOption[] options) { Rect r = s_LastRect = GUILayoutUtility.GetRect(EditorGUIUtility.fieldWidth, kLabelFloatMaxW, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.colorField, options); return EditorGUI.GradientField(r, value); } public static Gradient GradientField(string label, Gradient value, params GUILayoutOption[] options) { Rect r = s_LastRect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.colorField, options); return EditorGUI.GradientField(r, label, value); } public static Gradient GradientField(GUIContent label, Gradient value, params GUILayoutOption[] options) { Rect r = s_LastRect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.colorField, options); return EditorGUI.GradientField(r, label, value); } public static Gradient GradientField(GUIContent label, Gradient value, bool hdr, params GUILayoutOption[] options) { Rect r = s_LastRect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.colorField, options); return EditorGUI.GradientField(r, label, value, hdr); } // SerializedProperty versions internal static Gradient GradientField(SerializedProperty value, params GUILayoutOption[] options) { Rect r = s_LastRect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.colorField, options); return EditorGUI.GradientField(r, value); } internal static Gradient GradientField(string label, SerializedProperty value, params GUILayoutOption[] options) { Rect r = s_LastRect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.colorField, options); return EditorGUI.GradientField(r, label, value); } internal static Gradient GradientField(GUIContent label, SerializedProperty value, params GUILayoutOption[] options) { Rect r = s_LastRect = GUILayoutUtility.GetRect(kLabelFloatMinW, kLabelFloatMaxW, EditorGUI.kSingleLineHeight, EditorGUI.kSingleLineHeight, EditorStyles.colorField, options); return EditorGUI.GradientField(r, label, value); } } public sealed partial class EditorGUI { static readonly int s_GradientHash = "s_GradientHash".GetHashCode(); static int s_GradientID; // Gradient versions public static Gradient GradientField(Rect position, Gradient gradient) { int id = EditorGUIUtility.GetControlID(s_GradientHash, FocusType.Keyboard, position); return DoGradientField(position, id, gradient, null, false, ColorSpace.Gamma); } public static Gradient GradientField(Rect position, string label, Gradient gradient) { return GradientField(position, EditorGUIUtility.TempContent(label), gradient); } public static Gradient GradientField(Rect position, GUIContent label, Gradient gradient) { return GradientField(position, label, gradient, false); } public static Gradient GradientField(Rect position, GUIContent label, Gradient gradient, bool hdr) { return GradientField(position, label, gradient, hdr, ColorSpace.Gamma); } public static Gradient GradientField(Rect position, GUIContent label, Gradient gradient, bool hdr, ColorSpace colorSpace) { int id = EditorGUIUtility.GetControlID(s_GradientHash, FocusType.Keyboard, position); return DoGradientField(PrefixLabel(position, id, label), id, gradient, null, hdr, colorSpace); } // SerializedProperty versions internal static Gradient GradientField(Rect position, SerializedProperty property) { return GradientField(position, property, false); } internal static Gradient GradientField(Rect position, SerializedProperty property, bool hdr) { return GradientField(position, property, hdr, ColorSpace.Gamma); } internal static Gradient GradientField(Rect position, SerializedProperty property, bool hdr, ColorSpace colorSpace) { int id = EditorGUIUtility.GetControlID(s_GradientHash, FocusType.Keyboard, position); return DoGradientField(position, id, null, property, hdr, colorSpace); } internal static Gradient GradientField(Rect position, string label, SerializedProperty property) { return GradientField(position, EditorGUIUtility.TempContent(label), property); } internal static Gradient GradientField(Rect position, GUIContent label, SerializedProperty property) { int id = EditorGUIUtility.GetControlID(s_GradientHash, FocusType.Keyboard, position); return DoGradientField(PrefixLabel(position, id, label), id, null, property, false, ColorSpace.Gamma); } internal static Gradient DoGradientField(Rect position, int id, Gradient value, SerializedProperty property, bool hdr, ColorSpace space) { Event evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.MouseDown: if (position.Contains(evt.mousePosition)) { if (evt.button == 0) { s_GradientID = id; GUIUtility.keyboardControl = id; Gradient gradient = property != null ? property.gradientValue : value; GradientPicker.Show(gradient, hdr, space); GUIUtility.ExitGUI(); } else if (evt.button == 1) { if (property != null) GradientContextMenu.Show(property.Copy()); // TODO: make work for Gradient value } } break; case EventType.Repaint: { Rect r2 = new Rect(position.x + 1, position.y + 1, position.width - 2, position.height - 2); // Adjust for box drawn on top if (property != null) GradientEditor.DrawGradientSwatch(r2, property, Color.white, space); else GradientEditor.DrawGradientSwatch(r2, value, Color.white, space); EditorStyles.colorPickerBox.Draw(position, GUIContent.none, id); break; } case EventType.ExecuteCommand: if (s_GradientID == id && evt.commandName == GradientPicker.GradientPickerChangedCommand) { GUI.changed = true; GradientPreviewCache.ClearCache(); HandleUtility.Repaint(); if (property != null) property.gradientValue = GradientPicker.gradient; return GradientPicker.gradient; } break; case EventType.ValidateCommand: if (s_GradientID == id && evt.commandName == EventCommandNames.UndoRedoPerformed) { if (property != null) GradientPicker.SetCurrentGradient(property.gradientValue); GradientPreviewCache.ClearCache(); return value; } break; case EventType.KeyDown: if (GUIUtility.keyboardControl == id && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)) { Event.current.Use(); Gradient gradient = property != null ? property.gradientValue : value; GradientPicker.Show(gradient, hdr, space); GUIUtility.ExitGUI(); } break; } return value; } } }
UnityCsReference/Editor/Mono/GUI/GradientField.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/GradientField.cs", "repo_id": "UnityCsReference", "token_count": 4101 }
309
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor.Compilation; using UnityEditor.Scripting; namespace UnityEditor { [InitializeOnLoad] internal class ManagedDebuggerWindow : PopupWindowContent { private readonly GUIContent m_CodeOptimizationTitleContent; private readonly GUIContent m_CodeOptimizationTextContent; private readonly GUIContent m_CodeOptimizationButtonContent; private readonly GUIStyle m_WindowStyle; private readonly CodeOptimization m_CodeOptimization; private float m_TextRectHeight; private const int k_FieldCount = 2; private const int k_FrameWidth = 11; private const int k_WindowWidth = 290; private const int k_WindowHeight = (int)EditorGUI.kSingleLineHeight * k_FieldCount + k_FrameWidth * 2; static ManagedDebuggerWindow() { SubscribeToDebuggerAttached(); } public ManagedDebuggerWindow(CodeOptimization codeOptimization) { m_CodeOptimization = codeOptimization; if (CodeOptimization.Debug == m_CodeOptimization) { m_CodeOptimizationTitleContent = EditorGUIUtility.TrTextContent("Mode: Debug"); m_CodeOptimizationButtonContent = EditorGUIUtility.TrTextContent("Switch to release mode"); m_CodeOptimizationTextContent = (!EditorUtility.scriptCompilationFailed) ? EditorGUIUtility.TrTextContentWithIcon("Release mode disables C# debugging but improves C# performance.\nSwitching to release mode will recompile and reload all scripts.", EditorGUIUtility.GetHelpIcon(MessageType.Info)) : EditorGUIUtility.TrTextContentWithIcon("All compiler errors must be fixed before switching to release mode.", EditorGUIUtility.GetHelpIcon(MessageType.Error)); } else { m_CodeOptimizationTitleContent = EditorGUIUtility.TrTextContent("Mode: Release"); m_CodeOptimizationButtonContent = EditorGUIUtility.TrTextContent("Switch to debug mode"); m_CodeOptimizationTextContent = (!EditorUtility.scriptCompilationFailed) ? EditorGUIUtility.TrTextContentWithIcon("Debug mode enables C# debugging but reduces C# performance.\nSwitching to debug mode will recompile and reload all scripts.", EditorGUIUtility.GetHelpIcon(MessageType.Info)) : EditorGUIUtility.TrTextContentWithIcon("All compiler errors must be fixed before switching to debug mode.", EditorGUIUtility.GetHelpIcon(MessageType.Error)); } m_TextRectHeight = EditorStyles.helpBox.CalcHeight(m_CodeOptimizationTextContent, k_WindowWidth); m_WindowStyle = new GUIStyle { padding = new RectOffset(10, 10, 10, 10) }; } public override void OnGUI(Rect rect) { var exit = false; GUILayout.BeginArea(rect, m_WindowStyle); GUILayout.BeginHorizontal(); GUILayout.Label(m_CodeOptimizationTitleContent, EditorStyles.boldLabel); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); EditorGUILayout.LabelField(GUIContent.none, m_CodeOptimizationTextContent, EditorStyles.helpBox); GUILayout.EndHorizontal(); using (new EditorGUI.DisabledScope(EditorUtility.scriptCompilationFailed)) { GUILayout.BeginHorizontal(); if (GUILayout.Button(m_CodeOptimizationButtonContent)) { ToggleDebugState(m_CodeOptimization); exit = true; } GUILayout.EndHorizontal(); } GUILayout.EndArea(); exit |= Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape; if (exit) { editorWindow.Close(); GUIUtility.ExitGUI(); } } public override Vector2 GetWindowSize() { return new Vector2(k_WindowWidth, k_WindowHeight + m_TextRectHeight); } private static void OnDebuggerAttached(bool debuggerAttached) { if (debuggerAttached) { if (CodeOptimization.Release == CompilationPipeline.codeOptimization) { if (EditorUtility.scriptCompilationFailed) { EditorUtility.DisplayDialog( "C# Debugger Attached", "All compiler errors must be fixed before switching to debug mode.", "Ok"); ManagedDebugger.Disconnect(); } else { int option = EditorUtility.DisplayDialogComplex( "C# Debugger Attached", @"You are trying to attach a debugger, but Debug Mode is switched off in your project. When Unity is in Debug Mode, C# performance is reduced, but you can attach a debugger. Switching to Debug Mode also recompiles and reloads all scripts. You can enable Debug Mode temporarily for this Editor session, switch it on for all projects until further notice, or cancel attaching the debugger. If you switch it on for all projects, you can change it later in the ""Code Optimization on Startup"" setting in the Preferences window.", "Enable debugging for this session", "Cancel", "Enable debugging for all projects"); if (option == 0) { ToggleDebugState(CompilationPipeline.codeOptimization); } else if (option == 2) { EditorPrefs.SetBool("ScriptDebugInfoEnabled", true); ToggleDebugState(CompilationPipeline.codeOptimization); } else { ManagedDebugger.Disconnect(); } } } } AppStatusBar.StatusChanged(); } private static void SubscribeToDebuggerAttached() { ManagedDebugger.debuggerAttached += OnDebuggerAttached; } private static void ToggleDebugState(CodeOptimization codeOptimization) { if (CodeOptimization.Debug == codeOptimization) { CompilationPipeline.codeOptimization = CodeOptimization.Release; } else { CompilationPipeline.codeOptimization = CodeOptimization.Debug; } } } }
UnityCsReference/Editor/Mono/GUI/ManagedDebuggerWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/ManagedDebuggerWindow.cs", "repo_id": "UnityCsReference", "token_count": 3237 }
310
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEditor.StyleSheets; using UnityEngine; namespace UnityEditor { [Serializable] internal class ScalableGUIContent { [Serializable] struct TextureResource { public float pixelsPerPoint; public string resourcePath; } [SerializeField] private List<TextureResource> m_TextureResources = new List<TextureResource>(2); [SerializeField] private string m_CurrentResourcePath; [SerializeField] private GUIContent m_GuiContent; public string text => asGUIContent()?.text; public Texture image => asGUIContent()?.image; public string tooltip => asGUIContent()?.tooltip; public ScalableGUIContent(string resourceName) : this(string.Empty, string.Empty, resourceName) { } public ScalableGUIContent(string text, string tooltip, string resourceName) { m_GuiContent = !string.IsNullOrEmpty(text) || !string.IsNullOrEmpty(tooltip) ? EditorGUIUtility.TextContent(string.Format("{0}|{1}", text, tooltip)) : new GUIContent(); // TODO: make this more sophisticated when/if we have more granular support for different DPI levels m_TextureResources.Add(new TextureResource { pixelsPerPoint = 1f, resourcePath = resourceName}); m_TextureResources.Add(new TextureResource { pixelsPerPoint = 2f, resourcePath = string.Format("{0}@2x", resourceName)}); } public static implicit operator GUIContent(ScalableGUIContent gc) { return gc.asGUIContent(); } private GUIContent asGUIContent() { var dpi = EditorGUIUtility.pixelsPerPoint; var resourcePath = m_CurrentResourcePath; var resourceDpi = 1.0f; var normalResourcePath = m_TextureResources[0].resourcePath; for (int i = 0, count = m_TextureResources.Count; i < count; ++i) { var currentResource = m_TextureResources[i]; resourcePath = currentResource.resourcePath; resourceDpi = currentResource.pixelsPerPoint; if (resourceDpi >= dpi) break; } if (resourcePath != m_CurrentResourcePath) { Texture2D loadedResource = EditorGUIUtility.LoadIconRequired(normalResourcePath); loadedResource.pixelsPerPoint = resourceDpi; m_GuiContent.image = loadedResource; m_CurrentResourcePath = resourcePath; } if (resourceDpi != GUIUtility.pixelsPerPoint) { Texture2D image = m_GuiContent.image as Texture2D; if (image != null) { image.filterMode = FilterMode.Bilinear; } } return m_GuiContent; } } }
UnityCsReference/Editor/Mono/GUI/ScalableGUIContent.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/ScalableGUIContent.cs", "repo_id": "UnityCsReference", "token_count": 1408 }
311
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEngine.SceneManagement; using UnityEditor.SceneManagement; using UnityEditorInternal; using UnityEngine.Assertions; using Object = UnityEngine.Object; namespace UnityEditor { // Implements dragging behavior for HierarchyProperty based data: Assets or GameObjects internal class AssetsTreeViewDragging : TreeViewDragging { public AssetsTreeViewDragging(TreeViewController treeView) : base(treeView) { } public override bool CanStartDrag(TreeViewItem targetItem, List<int> draggedItemIDs, Vector2 mouseDownPosition) { // Prevent dragging of immutable root folder foreach (var draggedItemID in draggedItemIDs) { var path = AssetDatabase.GetAssetPath(draggedItemID); if (AssetDatabase.IsValidFolder(path) && !AssetDatabase.TryGetAssetFolderInfo(path, out _, out _)) return false; } return true; } public override void StartDrag(TreeViewItem draggedItem, List<int> draggedItemIDs) { DragAndDrop.PrepareStartDrag(); DragAndDrop.objectReferences = ProjectWindowUtil.GetDragAndDropObjects(draggedItem.id, draggedItemIDs); DragAndDrop.paths = ProjectWindowUtil.GetDragAndDropPaths(draggedItem.id, draggedItemIDs); if (DragAndDrop.objectReferences.Length > 1) DragAndDrop.StartDrag("<Multiple>"); else { string title = ObjectNames.GetDragAndDropTitle(InternalEditorUtility.GetObjectFromInstanceID(draggedItem.id)); DragAndDrop.StartDrag(title); } } public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, DropPosition dropPos) { var dragToInstanceId = parentItem?.id ?? 0; return DragAndDrop.DropOnProjectBrowserWindow(dragToInstanceId, AssetDatabase.GetAssetPath(dragToInstanceId), perform); } } internal class GameObjectsTreeViewDragging : TreeViewDragging { public delegate DragAndDropVisualMode CustomDraggingDelegate(GameObjectTreeViewItem parentItem, GameObjectTreeViewItem targetItem, DropPosition dropPos, bool perform); CustomDraggingDelegate m_CustomDragHandling; const string kSceneHeaderDragString = "SceneHeaderList"; public Transform parentForDraggedObjectsOutsideItems { get; set; } public GameObjectsTreeViewDragging(TreeViewController treeView) : base(treeView) {} public void SetCustomDragHandler(CustomDraggingDelegate handler) { m_CustomDragHandling = handler; } public override void StartDrag(TreeViewItem draggedItem, List<int> draggedItemIDs) { DragAndDrop.PrepareStartDrag(); if ((Event.current.control || Event.current.command) && !draggedItemIDs.Contains(draggedItem.id)) { draggedItemIDs.Add(draggedItem.id); } // Ensure correct order for hierarchy items (to preserve visible order when dropping at new location) draggedItemIDs = m_TreeView.SortIDsInVisiblityOrder(draggedItemIDs); if (!draggedItemIDs.Contains(draggedItem.id)) draggedItemIDs = new List<int> { draggedItem.id }; Object[] draggedObjReferences = ProjectWindowUtil.GetDragAndDropObjects(draggedItem.id, draggedItemIDs); DragAndDrop.objectReferences = draggedObjReferences; // After introducing multi-scene, UnityEngine.Scene can be selected in HierarchyWindow. // UnityEngine.Scene is not a UnityEngine.Object. // So DragAndDrop.objectReferences can't cover this case. List<Scene> draggedScenes = GetDraggedScenes(draggedItemIDs); if (draggedScenes != null) { DragAndDrop.SetGenericData(kSceneHeaderDragString, draggedScenes); List<string> paths = new List<string>(); foreach (Scene scene in draggedScenes) { if (scene.path.Length > 0) paths.Add(scene.path); } DragAndDrop.paths = paths.ToArray(); } string title; if (draggedItemIDs.Count > 1) title = "<Multiple>"; else { if (draggedObjReferences.Length == 1) title = ObjectNames.GetDragAndDropTitle(draggedObjReferences[0]); else if (draggedScenes != null && draggedScenes.Count == 1) title = draggedScenes[0].path; else { title = "Unhandled dragged item"; Debug.LogError("Unhandled dragged item"); } } DragAndDrop.StartDrag(title); dataSource.SetupChildParentReferencesIfNeeded(); } GameObjectTreeViewDataSource dataSource { get { return (GameObjectTreeViewDataSource)m_TreeView.data; } } public override DragAndDropVisualMode DoDrag(TreeViewItem parentItem, TreeViewItem targetItem, bool perform, DropPosition dropPos) { var hierarchyTargetItem = targetItem as GameObjectTreeViewItem; // Allow client to handle drag if (m_CustomDragHandling != null) { DragAndDropVisualMode dragResult = m_CustomDragHandling(parentItem as GameObjectTreeViewItem, hierarchyTargetItem, dropPos, perform); if (dragResult != DragAndDropVisualMode.None) return dragResult; } // Scene dragging logic DragAndDropVisualMode dragSceneResult = DoDragScenes(parentItem as GameObjectTreeViewItem, hierarchyTargetItem, perform, dropPos); if (dragSceneResult != DragAndDropVisualMode.None) return dragSceneResult; if (targetItem != null && !IsDropTargetUserModifiable(hierarchyTargetItem, dropPos)) return DragAndDropVisualMode.Rejected; var option = HierarchyDropFlags.None; var searchActive = !string.IsNullOrEmpty(dataSource.searchString); if (searchActive) option |= HierarchyDropFlags.SearchActive; if (parentItem == null || targetItem == null) { // Here we are dragging outside any treeview items: if (parentForDraggedObjectsOutsideItems != null) { // Use specific parent for DragAndDropForwarding return DragAndDrop.DropOnHierarchyWindow(0, option, parentForDraggedObjectsOutsideItems, perform); } else { // Simulate drag upon the last loaded scene in the hierarchy (adds as last root sibling of the last scene) Scene lastScene = dataSource.GetLastScene(); if (!lastScene.IsValid()) return DragAndDropVisualMode.Rejected; option |= HierarchyDropFlags.DropUpon; return DragAndDrop.DropOnHierarchyWindow(lastScene.handle, option, null, perform); } } // Here we are hovering over items var draggingUpon = dropPos == TreeViewDragging.DropPosition.Upon; if (searchActive && !draggingUpon) { return DragAndDropVisualMode.None; } if (draggingUpon) { option |= HierarchyDropFlags.DropUpon; } else { if (dropPos == TreeViewDragging.DropPosition.Above) { option |= HierarchyDropFlags.DropAbove; } option |= HierarchyDropFlags.DropBetween; } bool isDroppingBetweenParentAndFirstChild = parentItem != null && targetItem != parentItem && dropPos == DropPosition.Above && parentItem.children[0] == targetItem; if (isDroppingBetweenParentAndFirstChild) { option |= HierarchyDropFlags.DropAfterParent; } int gameObjectOrSceneInstanceID = GetDropTargetInstanceID(hierarchyTargetItem, dropPos); if (gameObjectOrSceneInstanceID == 0) return DragAndDropVisualMode.Rejected; if (perform && SubSceneGUI.IsUsingSubScenes() && !IsValidSubSceneDropTarget(gameObjectOrSceneInstanceID, dropPos, DragAndDrop.objectReferences)) return DragAndDropVisualMode.Rejected; GameObject go = EditorUtility.InstanceIDToObject(gameObjectOrSceneInstanceID) as GameObject; if (go != null) { DragAndDropVisualMode visualMode; if (PrefabReplaceUtility.GetDragVisualModeAndShowMenuWithReplaceMenuItemsWhenNeeded(go, draggingUpon, perform, true, true, out visualMode)) { return visualMode; } } return DragAndDrop.DropOnHierarchyWindow(gameObjectOrSceneInstanceID, option, null, perform); } int GetDropTargetInstanceID(GameObjectTreeViewItem hierarchyTargetItem, DropPosition dropPosition) { if (SubSceneGUI.IsUsingSubScenes()) { var gameObjectDropTarget = hierarchyTargetItem.objectPPTR as GameObject; if (gameObjectDropTarget != null) { if (dropPosition == DropPosition.Above) return hierarchyTargetItem.id; if (SubSceneGUI.IsSubSceneHeader(gameObjectDropTarget)) { Scene subScene = SubSceneGUI.GetSubScene(gameObjectDropTarget); if (subScene.IsValid()) return subScene.handle; else return 0; } } } return hierarchyTargetItem.id; } bool IsValidSubSceneDropTarget(int dropTargetGameObjectOrSceneInstanceID, DropPosition dropPosition, Object[] draggedObjects) { if (draggedObjects == null || draggedObjects.Length == 0) return false; Transform parentForDrop = GetTransformParentForDrop(dropTargetGameObjectOrSceneInstanceID, dropPosition); if (parentForDrop == null) { // Drop is on a root scene which is always allowed return true; } foreach (var obj in draggedObjects) { var gameObject = obj as GameObject; if (gameObject == null) continue; // Require all dragged objects to be valid (since native cannot filter out invalid sub scene drags currently) if (SubSceneGUI.IsChildOrSameAsOtherTransform(parentForDrop, gameObject.transform)) return false; } // Valid drop target for current dragged objects return true; } Transform GetTransformParentForDrop(int gameObjectOrSceneInstanceID, DropPosition dropPosition) { var obj = EditorUtility.InstanceIDToObject(gameObjectOrSceneInstanceID); if (obj != null) { // Find transform parent from GameObject var go = obj as GameObject; if (go == null) throw new InvalidOperationException("Unexpected UnityEngine.Object type in Hierarchy " + obj.GetType()); switch (dropPosition) { case DropPosition.Upon: return go.transform; case DropPosition.Below: case DropPosition.Above: if (go.transform.parent == null) { var subSceneInfo = SubSceneGUI.GetSubSceneInfo(go.scene); if (subSceneInfo.isValid) return subSceneInfo.transform; } return go.transform.parent; default: throw new InvalidOperationException("Unhandled enum " + dropPosition); } } else { // Find transform parent from Scene var scene = EditorSceneManager.GetSceneByHandle(gameObjectOrSceneInstanceID); var subSceneInfo = SubSceneGUI.GetSubSceneInfo(scene); if (subSceneInfo.isValid) return subSceneInfo.transform; return null; // root scene has no transform parent } } static bool IsDropTargetUserModifiable(GameObjectTreeViewItem targetItem, DropPosition dropPos) { if (targetItem.isSceneHeader && !targetItem.scene.isLoaded) return false; switch (dropPos) { case DropPosition.Upon: if (targetItem.objectPPTR != null) return IsUserModifiable(targetItem.objectPPTR); break; case DropPosition.Below: case DropPosition.Above: var targetParent = targetItem.parent as GameObjectTreeViewItem; if (targetParent != null && targetParent.objectPPTR != null) return IsUserModifiable(targetParent.objectPPTR); break; default: throw new ArgumentOutOfRangeException(nameof(dropPos), dropPos, null); } return true; } static bool IsUserModifiable(Object obj) { return (obj.hideFlags & HideFlags.NotEditable) == 0; } public override void DragCleanup(bool revertExpanded) { DragAndDrop.SetGenericData(kSceneHeaderDragString, null); base.DragCleanup(revertExpanded); } private List<Scene> GetDraggedScenes(List<int> draggedItemIDs) { List<Scene> scenes = new List<Scene>(); foreach (int id in draggedItemIDs) { Scene scene = EditorSceneManager.GetSceneByHandle(id); if (!SceneHierarchy.IsSceneHeaderInHierarchyWindow(scene)) return null; scenes.Add(scene); } return scenes; } private DragAndDropVisualMode DoDragScenes(GameObjectTreeViewItem parentItem, GameObjectTreeViewItem targetItem, bool perform, DropPosition dropPos) { // We allow dragging SceneAssets on any game object in the Hierarchy to make it easy to drag in a Scene from // the project browser. If dragging on a game object (not a sceneheader) we place the dropped scene // below the game object's scene // Case: 1 List<Scene> scenes = DragAndDrop.GetGenericData(kSceneHeaderDragString) as List<Scene>; bool reorderExistingScenes = (scenes != null); // Case: 2 bool insertNewScenes = false; if (!reorderExistingScenes && DragAndDrop.objectReferences.Length > 0) { int sceneAssetCount = 0; foreach (var dragged in DragAndDrop.objectReferences) { if (dragged is SceneAsset) sceneAssetCount++; } insertNewScenes = (sceneAssetCount == DragAndDrop.objectReferences.Length); } // Early out if not case 1 or 2 if (!reorderExistingScenes && !insertNewScenes) return DragAndDropVisualMode.None; if (perform) { List<Scene> scenesToBeMoved = null; if (insertNewScenes) { List<Scene> insertedScenes = new List<Scene>(); foreach (var sceneAsset in DragAndDrop.objectReferences) { string scenePath = AssetDatabase.GetAssetPath(sceneAsset); Scene scene = SceneManager.GetSceneByPath(scenePath); if (SceneHierarchy.IsSceneHeaderInHierarchyWindow(scene)) m_TreeView.Frame(scene.handle, true, true); else { bool unloaded = Event.current.alt; if (unloaded) scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.AdditiveWithoutLoading); else scene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive); if (SceneHierarchy.IsSceneHeaderInHierarchyWindow(scene)) insertedScenes.Add(scene); } } if (targetItem != null) scenesToBeMoved = insertedScenes; // Select added scenes and frame last scene if (insertedScenes.Count > 0) { Selection.instanceIDs = insertedScenes.Select(x => x.handle).ToArray(); m_TreeView.Frame(insertedScenes.Last().handle, true, false); } } else // reorderExistingScenes scenesToBeMoved = scenes; if (scenesToBeMoved != null) { if (targetItem != null) { Scene dstScene = targetItem.scene; if (SceneHierarchy.IsSceneHeaderInHierarchyWindow(dstScene)) { if (!targetItem.isSceneHeader || dropPos == DropPosition.Upon) dropPos = DropPosition.Below; if (dropPos == DropPosition.Above) { for (int i = 0; i < scenesToBeMoved.Count; i++) EditorSceneManager.MoveSceneBefore(scenesToBeMoved[i], dstScene); } else if (dropPos == DropPosition.Below) { for (int i = scenesToBeMoved.Count - 1; i >= 0; i--) EditorSceneManager.MoveSceneAfter(scenesToBeMoved[i], dstScene); } } } else { Scene dstScene = SceneManager.GetSceneAt(SceneManager.sceneCount - 1); for (int i = scenesToBeMoved.Count - 1; i >= 0; i--) EditorSceneManager.MoveSceneAfter(scenesToBeMoved[i], dstScene); } } } return DragAndDropVisualMode.Move; } } } // namespace UnityEditor
UnityCsReference/Editor/Mono/GUI/TreeView/AssetOrGameObjectTreeViewDragging.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/AssetOrGameObjectTreeViewDragging.cs", "repo_id": "UnityCsReference", "token_count": 9572 }
312
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor.IMGUI.Controls { public partial class TreeView { internal class TreeViewControlDataSource : LazyTreeViewDataSource { readonly TreeView m_Owner; public TreeViewControlDataSource(TreeViewController treeView, TreeView owner) : base(treeView) { m_Owner = owner; // The user should just create the visible rows, we create the hidden root showRootItem = false; } public override void ReloadData() { // Clear root item to ensure client gets a call to BuildRoot every time Reload is called m_RootItem = null; base.ReloadData(); } void ValidateRootItem() { if (m_RootItem == null) { throw new NullReferenceException("BuildRoot should set a valid root item."); } if (m_RootItem.depth != -1) { Debug.LogError("BuildRoot should ensure the root item has a depth == -1. The visible items start at depth == 0."); m_RootItem.depth = -1; } if (m_RootItem.children == null && !m_Owner.m_OverriddenMethods.hasBuildRows) { throw new InvalidOperationException("TreeView: 'rootItem.children == null'. Did you forget to add children? If you intend to only create the list of rows (not the full tree) then you need to override: BuildRows, GetAncestors and GetDescendantsThatHaveChildren."); } } public override void FetchData() { // Set before BuildRoot and BuildRows so we can call GetRows in them without recursion m_NeedRefreshRows = false; // Root if (m_RootItem == null) { m_RootItem = m_Owner.BuildRoot(); ValidateRootItem(); } // Rows m_Rows = m_Owner.BuildRows(m_RootItem); if (m_Rows == null) throw new NullReferenceException("RefreshRows should set valid list of rows."); // Custom row rects if (m_Owner.m_OverriddenMethods.hasGetCustomRowHeight) m_Owner.m_GUI.RefreshRowRects(m_Rows); } public void SearchFullTree(string search, List<TreeViewItem> result) { if (string.IsNullOrEmpty(search)) throw new ArgumentException("Invalid search: cannot be null or empty", "search"); if (result == null) throw new ArgumentException("Invalid list: cannot be null", "result"); var stack = new Stack<TreeViewItem>(); stack.Push(m_RootItem); while (stack.Count > 0) { TreeViewItem current = stack.Pop(); if (current.children != null) { foreach (var child in current.children) { if (child != null) { if (m_Owner.DoesItemMatchSearch(child, search)) result.Add(child); stack.Push(child); } } } } result.Sort((x, y) => EditorUtility.NaturalCompare(x.displayName, y.displayName)); } protected override void GetParentsAbove(int id, HashSet<int> ancestors) { foreach (var ancestor in m_Owner.GetAncestors(id)) ancestors.Add(ancestor); } protected override void GetParentsBelow(int id, HashSet<int> children) { foreach (var child in m_Owner.GetDescendantsThatHaveChildren(id)) children.Add(child); } public override bool IsExpandable(TreeViewItem item) { return m_Owner.CanChangeExpandedState(item); } public override bool CanBeMultiSelected(TreeViewItem item) { return m_Owner.CanMultiSelect(item); } public override bool CanBeParent(TreeViewItem item) { return m_Owner.CanBeParent(item); } public override bool IsRenamingItemAllowed(TreeViewItem item) { return m_Owner.CanRename(item); } } } }
UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDataSource.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlDataSource.cs", "repo_id": "UnityCsReference", "token_count": 2587 }
313
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.ComponentModel; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor.TreeViewExamples { class TestGUICustomItemHeights : TreeViewGUIWithCustomItemsHeights { internal class Styles { public static GUIStyle foldout = "IN Foldout"; } private float m_Column1Width = 300; protected Rect m_DraggingInsertionMarkerRect; public TestGUICustomItemHeights(TreeViewController treeView) : base(treeView) { m_FoldoutWidth = Styles.foldout.fixedWidth; } protected override Vector2 GetSizeOfRow(TreeViewItem item) { return new Vector2(m_TreeView.GetTotalRect().width, item.hasChildren ? 20 : 36f); } public override void BeginRowGUI() { // Reset m_DraggingInsertionMarkerRect.x = -1; } public override void EndRowGUI() { base.EndRowGUI(); // Draw row marker when dragging if (m_DraggingInsertionMarkerRect.x >= 0 && Event.current.type == EventType.Repaint) { Rect insertionRect = m_DraggingInsertionMarkerRect; insertionRect.height = 2f; insertionRect.y -= insertionRect.height / 2; if (!m_TreeView.dragging.drawRowMarkerAbove) insertionRect.y += m_DraggingInsertionMarkerRect.height; EditorGUI.DrawRect(insertionRect, Color.white); } } public override void OnRowGUI(Rect rowRect, TreeViewItem item, int row, bool selected, bool focused) { rowRect.height -= 1f; Rect column1Rect = rowRect; Rect column2Rect = rowRect; column1Rect.width = m_Column1Width; column1Rect.xMin += GetFoldoutIndent(item); column2Rect.xMin += m_Column1Width + 1; float indent = GetFoldoutIndent(item); Rect tmpRect = rowRect; int itemControlID = TreeViewController.GetItemControlID(item); bool isDropTarget = false; if (m_TreeView.dragging != null) isDropTarget = m_TreeView.dragging.GetDropTargetControlID() == itemControlID && m_TreeView.data.CanBeParent(item); bool showFoldout = m_TreeView.data.IsExpandable(item); Color selectedColor = new Color(0.0f, 0.22f, 0.44f); Color normalColor = new Color(0.1f, 0.1f, 0.1f); EditorGUI.DrawRect(column1Rect, selected ? selectedColor : normalColor); EditorGUI.DrawRect(column2Rect, selected ? selectedColor : normalColor); if (isDropTarget) { EditorGUI.DrawRect(new Rect(rowRect.x, rowRect.y, 3, rowRect.height), Color.yellow); } if (Event.current.type == EventType.Repaint) { Rect labelRect = column1Rect; labelRect.xMin += m_FoldoutWidth; GUI.Label(labelRect, item.displayName, EditorStyles.largeLabel); if (rowRect.height > 20f) { labelRect.y += 16f; GUI.Label(labelRect, "Ut tincidunt tortor. Donec nonummy, enim in lacinia pulvinar", EditorStyles.miniLabel); } } // Draw foldout (after text content above to ensure drop down icon is rendered above selection highlight) if (showFoldout) { tmpRect.x = indent; tmpRect.width = m_FoldoutWidth; EditorGUI.BeginChangeCheck(); bool newExpandedValue = GUI.Toggle(tmpRect, m_TreeView.data.IsExpanded(item), GUIContent.none, Styles.foldout); if (EditorGUI.EndChangeCheck()) { m_TreeView.UserInputChangedExpandedState(item, row, newExpandedValue); } } } } }
UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestGUICustom.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestGUICustom.cs", "repo_id": "UnityCsReference", "token_count": 1957 }
314
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Scripting; using UnityEngine.UIElements; namespace UnityEditor { class GUIViewDebuggerWindow : EditorWindow { enum InstructionType { Draw, Clip, Layout, NamedControl, Property, Unified, } internal static class Styles { public static readonly string defaultWindowPopupText = "<Please Select>"; public static readonly GUIContent inspectedWindowLabel = EditorGUIUtility.TrTextContent("Inspected View: "); public static readonly GUIContent pickStyleLabel = EditorGUIUtility.TrTextContent("Pick Style"); public static readonly GUIContent pickingStyleLabel = EditorGUIUtility.TrTextContent("Picking "); public static readonly GUIStyle listItem = "PR Label"; public static readonly GUIStyle listItemBackground = "CN EntryBackOdd"; public static readonly GUIStyle listBackgroundStyle = "ScrollViewAlt"; public static readonly GUIStyle boxStyle = "CN Box"; public static readonly GUIStyle messageStyle = "CN Message"; public static readonly GUIStyle stackframeStyle = "CN StacktraceStyle"; public static readonly GUIStyle stacktraceBackground = "CN StacktraceBackground"; public static readonly GUIStyle centeredText = "CN CenteredText"; public static readonly Color contentHighlighterColor = new Color(0.62f, 0.77f, 0.90f, 0.5f); public static readonly Color paddingHighlighterColor = new Color(0.76f, 0.87f, 0.71f, 0.5f); } static GUIViewDebuggerWindow s_ActiveInspector; static EditorWindow GetEditorWindow(GUIView view) { var hostView = view as HostView; if (hostView != null) return hostView.actualView; return null; } static string GetViewName(GUIView view) { var editorWindow = GetEditorWindow(view); if (editorWindow != null) return editorWindow.titleContent.text; return view.GetType().Name; } public GUIView inspected { get { if (m_Inspected != null || m_InspectedEditorWindow == null) return m_Inspected; // continue inspecting the same window if its dock area is destroyed by e.g., docking or undocking it return inspected = m_InspectedEditorWindow.m_Parent; } private set { if (m_Inspected != value) { ClearInstructionHighlighter(); m_Inspected = value; if (m_Inspected != null) { m_InspectedEditorWindow = (m_Inspected is HostView) ? ((HostView)m_Inspected).actualView : null; if (!m_StylePicker.IsPicking) GUIViewDebuggerHelper.DebugWindow(m_Inspected); m_Inspected.Repaint(); } else { m_InspectedEditorWindow = null; GUIViewDebuggerHelper.StopDebugging(); } if (instructionModeView != null) instructionModeView.ClearRowSelection(); OnInspectedViewChanged(); } } } [SerializeField] GUIView m_Inspected; EditorWindow m_InspectedEditorWindow; ElementHighlighter m_Highlighter; StylePicker m_StylePicker; public IBaseInspectView instructionModeView { get { return m_InstructionModeView; } } IBaseInspectView m_InstructionModeView; protected GUIViewDebuggerWindow() { m_InstructionModeView = new StyleDrawInspectView(this); m_Highlighter = new ElementHighlighter(); m_StylePicker = new StylePicker(this, m_Highlighter); m_StylePicker.CanInspectView = CanInspectView; } public void ClearInstructionHighlighter() { if (m_StylePicker != null && !m_StylePicker.IsPicking) m_Highlighter.ClearElement(); } public void HighlightInstruction(GUIView view, Rect instructionRect, GUIStyle style) { if (!m_ShowHighlighter) return; ClearInstructionHighlighter(); var visualElement = view.windowBackend.visualTree as VisualElement; if (visualElement == null) return; m_Highlighter.HighlightElement(visualElement, instructionRect, style); } InstructionType instructionType { get { return m_InstructionType; } set { if (m_InstructionType != value || m_InstructionModeView == null) { m_InstructionType = value; switch (m_InstructionType) { case InstructionType.Clip: m_InstructionModeView = new GUIClipInspectView(this); break; case InstructionType.Draw: m_InstructionModeView = new StyleDrawInspectView(this); break; case InstructionType.Layout: m_InstructionModeView = new GUILayoutInspectView(this); break; case InstructionType.NamedControl: m_InstructionModeView = new GUINamedControlInspectView(this); break; case InstructionType.Property: m_InstructionModeView = new GUIPropertyInspectView(this); break; case InstructionType.Unified: m_InstructionModeView = new UnifiedInspectView(this); break; } m_InstructionModeView.UpdateInstructions(); } } } [SerializeField] InstructionType m_InstructionType = InstructionType.Draw; [SerializeField] bool m_ShowHighlighter = true; [SerializeField] private bool m_InspectOptimizedGUIBlocks = false; //TODO: figure out proper minimum values and make sure the window also has compatible minimum size readonly SplitterState m_InstructionListDetailSplitter = SplitterState.FromRelative(new float[] { 30, 70 }, new float[] { 32, 32 }, null); [RequiredByNativeCode] [MenuItem("Window/Analysis/IMGUI Debugger", false, 20002, false)] static void InitDebuggerWindow() { // Get existing open window or if none, make a new one: if (s_ActiveInspector == null) { GUIViewDebuggerWindow window = (GUIViewDebuggerWindow)GetWindow(typeof(GUIViewDebuggerWindow)); s_ActiveInspector = window; } s_ActiveInspector.Show(); } void OnEnable() { titleContent = EditorGUIUtility.TrTextContent("IMGUI Debugger"); GUIViewDebuggerHelper.onViewInstructionsChanged += OnInspectedViewChanged; GUIViewDebuggerHelper.onDebuggingViewchanged += OnDebuggedViewChanged; GUIView serializedInspected = m_Inspected; inspected = null; inspected = serializedInspected; m_InstructionModeView = null; instructionType = m_InstructionType; } void OnDestroy() { if (m_StylePicker != null) { m_StylePicker.StopExploreStyle(); m_StylePicker = null; } } void OnDisable() { GUIViewDebuggerHelper.onViewInstructionsChanged -= OnInspectedViewChanged; GUIViewDebuggerHelper.onDebuggingViewchanged -= OnDebuggedViewChanged; inspected = null; if (m_StylePicker != null) m_StylePicker.StopExploreStyle(); } void OnBecameVisible() { OnShowOverlayChanged(); } void OnBecameInvisible() { ClearInstructionHighlighter(); } void OnGUI() { HandleStylePicking(); DoToolbar(); ShowDrawInstructions(); } private bool m_FlushingOptimizedGUIBlock; void OnDebuggedViewChanged(GUIView view, bool isDebugged) { if (!m_StylePicker.IsPicking && isDebugged && inspected != view) { inspected = view; } } void OnInspectedViewChanged() { if (m_InspectOptimizedGUIBlocks && !m_FlushingOptimizedGUIBlock) { var inspector = m_InspectedEditorWindow as InspectorWindow; if (inspector != null && inspector.tracker != null) { m_FlushingOptimizedGUIBlock = true; foreach (var editor in inspector.tracker.activeEditors) editor.isInspectorDirty = true; inspector.Repaint(); } } m_FlushingOptimizedGUIBlock = false; RefreshData(); Repaint(); } void HandleStylePicking() { if (m_StylePicker != null && m_StylePicker.IsPicking) { m_StylePicker.OnGUI(); if (Event.current.type == EventType.Ignore || Event.current.type == EventType.MouseUp) { m_StylePicker.StopExploreStyle(); } if (m_StylePicker.ExploredView != null && inspected != m_StylePicker.ExploredView) { inspected = m_StylePicker.ExploredView; } } } void DoToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar); DoWindowPopup(); DoInspectTypePopup(); DoInstructionOverlayToggle(); DoOptimizedGUIBlockToggle(); DoStylePicker(); GUILayout.EndHorizontal(); } bool CanInspectView(GUIView view) { if (view == null) return false; EditorWindow editorWindow = GetEditorWindow(view); if (editorWindow == null) return true; if (editorWindow == this) return false; return true; } void DoWindowPopup() { string selectedName = inspected == null ? Styles.defaultWindowPopupText : GetViewName(inspected); GUILayout.Label(Styles.inspectedWindowLabel, GUILayout.ExpandWidth(false)); Rect popupPosition = GUILayoutUtility.GetRect(GUIContent.Temp(selectedName), EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(true)); if (GUI.Button(popupPosition, GUIContent.Temp(selectedName), EditorStyles.toolbarDropDown)) { List<GUIView> views = new List<GUIView>(); GUIViewDebuggerHelper.GetViews(views); List<GUIContent> options = new List<GUIContent>(views.Count + 1); options.Add(EditorGUIUtility.TrTextContent("None")); int selectedIndex = 0; List<GUIView> selectableViews = new List<GUIView>(views.Count + 1); for (int i = 0; i < views.Count; ++i) { GUIView view = views[i]; //We can't inspect ourselves, otherwise we get infinite recursion. //Also avoid the InstructionOverlay if (!CanInspectView(view)) continue; GUIContent label = new GUIContent(string.Format("{0}. {1}", options.Count, GetViewName(view))); options.Add(label); selectableViews.Add(view); if (view == inspected) selectedIndex = selectableViews.Count; } //TODO: convert this to a Unity Window style popup. This way we could highlight the window on hover ;) EditorUtility.DisplayCustomMenu(popupPosition, options.ToArray(), selectedIndex, OnWindowSelected, selectableViews); } } void DoInspectTypePopup() { EditorGUI.BeginChangeCheck(); var newInstructionType = (InstructionType)EditorGUILayout.EnumPopup(m_InstructionType, EditorStyles.toolbarDropDown); if (EditorGUI.EndChangeCheck()) instructionType = newInstructionType; } void DoInstructionOverlayToggle() { EditorGUI.BeginChangeCheck(); m_ShowHighlighter = GUILayout.Toggle(m_ShowHighlighter, GUIContent.Temp("Show Overlay"), EditorStyles.toolbarButton); if (EditorGUI.EndChangeCheck()) { OnShowOverlayChanged(); } } void DoOptimizedGUIBlockToggle() { EditorGUI.BeginChangeCheck(); m_InspectOptimizedGUIBlocks = GUILayout.Toggle(m_InspectOptimizedGUIBlocks, GUIContent.Temp("Force Inspect Optimized GUI Blocks"), EditorStyles.toolbarButton); if (EditorGUI.EndChangeCheck()) OnInspectedViewChanged(); } void DoStylePicker() { var pickerRect = GUILayoutUtility.GetRect(Styles.pickStyleLabel, EditorStyles.toolbarButtonRight); if (!m_StylePicker.IsPicking && Event.current.isMouse && Event.current.type == EventType.MouseDown && pickerRect.Contains(Event.current.mousePosition)) { m_StylePicker.StartExploreStyle(); } GUI.Toggle(pickerRect, m_StylePicker.IsPicking, m_StylePicker.IsPicking ? Styles.pickingStyleLabel : Styles.pickStyleLabel, EditorStyles.toolbarButtonRight); } void OnShowOverlayChanged() { if (m_ShowHighlighter == false) { ClearInstructionHighlighter(); } else { if (inspected != null) { instructionModeView.ShowOverlay(); } } } void OnWindowSelected(object userdata, string[] options, int selected) { selected--; inspected = selected < 0 ? null : ((List<GUIView>)userdata)[selected]; } void RefreshData() { instructionModeView.UpdateInstructions(); } void ShowDrawInstructions() { if (inspected == null) { ClearInstructionHighlighter(); return; } SplitterGUILayout.BeginHorizontalSplit(m_InstructionListDetailSplitter); instructionModeView.DrawInstructionList(); EditorGUILayout.BeginVertical(); { if (m_StylePicker.IsPicking && m_StylePicker.ExploredDrawInstructionIndex != -1 && m_InstructionType == InstructionType.Draw) { m_InstructionModeView.ClearRowSelection(); m_InstructionModeView.SelectRow(m_StylePicker.ExploredDrawInstructionIndex); } instructionModeView.DrawSelectedInstructionDetails(position.width - m_InstructionListDetailSplitter.realSizes[0]); } EditorGUILayout.EndVertical(); SplitterGUILayout.EndHorizontalSplit(); EditorGUIUtility.DrawHorizontalSplitter(new Rect(m_InstructionListDetailSplitter.realSizes[0] + 1, EditorGUI.kWindowToolbarHeight, 1, position.height)); } } //This needs to match ManagedStackFrameToMono in native [StructLayout(LayoutKind.Sequential)] struct StackFrame { public uint lineNumber; public string sourceFile; public string methodName; public string signature; public string moduleName; //TODO: we only get "Mono JIT Code" or "wrapper something", can we get the actual assembly name? } internal static partial class GUIViewDebuggerHelper { internal static event Action onViewInstructionsChanged = null; internal static event Action<GUIView, bool> onDebuggingViewchanged = null; [RequiredByNativeCode] private static void CallOnViewInstructionsChanged() { onViewInstructionsChanged?.Invoke(); } [RequiredByNativeCode] private static void CallDebuggingViewChanged(GUIView view, bool isBeingDebugged) { onDebuggingViewchanged?.Invoke(view, isBeingDebugged); } } }
UnityCsReference/Editor/Mono/GUIDebugger/GUIViewDebuggerWindow.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GUIDebugger/GUIViewDebuggerWindow.cs", "repo_id": "UnityCsReference", "token_count": 8555 }
315
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using System; using System.Text; using UnityEngine.Scripting; using System.Globalization; namespace UnityEditor { internal class GameViewGUI { private static string FormatNumber(long num) { if (num < 1000) return num.ToString(CultureInfo.InvariantCulture.NumberFormat); if (num < 1000000) return (num * 0.001).ToString("f1", CultureInfo.InvariantCulture.NumberFormat) + "k"; return (num * 0.000001).ToString("f1", CultureInfo.InvariantCulture.NumberFormat) + "M"; } private static int m_FrameCounter = 0; private static float m_ClientTimeAccumulator = 0.0f; private static float m_RenderTimeAccumulator = 0.0f; private static float m_MaxTimeAccumulator = 0.0f; private static float m_ClientFrameTime = 0.0f; private static float m_RenderFrameTime = 0.0f; private static float m_MaxFrameTime = 0.0f; private static GUIContent s_GraphicsText = EditorGUIUtility.TextContent("Graphics:"); // Create label style from scene skin; add rich text support private static GUIStyle s_LabelStyle; private static GUIStyle labelStyle { get { if (s_LabelStyle == null) { s_LabelStyle = new GUIStyle("label"); s_LabelStyle.richText = true; } return s_LabelStyle; } } // Time per frame varies wildly, so we average a bit and display that. private static void UpdateFrameTime() { if (Event.current.type != EventType.Repaint) return; float frameTime = UnityStats.frameTime; float renderTime = UnityStats.renderTime; m_ClientTimeAccumulator += frameTime; m_RenderTimeAccumulator += renderTime; if (Application.targetFrameRate <= 0 || !Unsupported.IsEditorPlayerLoopWaiting()) m_MaxTimeAccumulator += Mathf.Max(frameTime, renderTime); else m_MaxTimeAccumulator += Unsupported.GetFrameTimeCalculatedForEachEditorPlayerLoop(); ++m_FrameCounter; bool needsTime = m_ClientFrameTime == 0.0f && m_RenderFrameTime == 0.0f; bool resetTime = m_FrameCounter > 30 || m_ClientTimeAccumulator > 0.3f || m_RenderTimeAccumulator > 0.3f; if (needsTime || resetTime) { m_ClientFrameTime = m_ClientTimeAccumulator / m_FrameCounter; m_RenderFrameTime = m_RenderTimeAccumulator / m_FrameCounter; m_MaxFrameTime = m_MaxTimeAccumulator / m_FrameCounter; } if (resetTime) { m_ClientTimeAccumulator = 0.0f; m_RenderTimeAccumulator = 0.0f; m_MaxTimeAccumulator = 0.0f; m_FrameCounter = 0; } } private static string FormatDb(float vol) { if (vol == 0.0f) return "-\u221E dB"; return UnityString.Format("{0:F1} dB", 20.0f * Mathf.Log10(vol)); } [RequiredByNativeCode] public static void GameViewStatsGUI() { var evt = Event.current; if (evt.type != EventType.Layout && evt.type != EventType.Repaint) return; float w = 300, h = 229; GUILayout.BeginArea(new Rect(GUIView.current.position.width - w - 10, 27, w, h), "Statistics", GUI.skin.window); // Audio stats bool audioOutputSuspended = UnityStats.audioOutputSuspended; GUILayout.Label((audioOutputSuspended) ? "Audio (suspended):" : "Audio:", EditorStyles.boldLabel); using (new EditorGUI.DisabledScope(audioOutputSuspended)) { StringBuilder audioStats = new StringBuilder(400); float audioLevel = UnityStats.audioLevel; audioStats.Append(" Level: " + FormatDb(audioLevel) + (EditorUtility.audioMasterMute ? " (MUTED)\n" : "\n")); audioStats.Append(UnityString.Format(" Clipping: {0:F1}%", 100.0f * UnityStats.audioClippingAmount)); GUILayout.Label(audioStats.ToString()); } GUI.Label(new Rect(170, 40, 120, 20), UnityString.Format("DSP load: {0:F1}%", 100.0f * UnityStats.audioDSPLoad)); GUI.Label(new Rect(170, 53, 120, 20), UnityString.Format("Stream load: {0:F1}%", 100.0f * UnityStats.audioStreamLoad)); EditorGUILayout.Space(); // Graphics stats Rect graphicsLabelRect = GUILayoutUtility.GetRect(s_GraphicsText, EditorStyles.boldLabel); GUI.Label(graphicsLabelRect, s_GraphicsText, EditorStyles.boldLabel); // Time stats UpdateFrameTime(); string timeStats = UnityString.Format("- FPS (Playmode Off)"); if (EditorApplication.isPlaying) { timeStats = UnityString.Format("{0:F1} FPS ({1:F1}ms)", 1.0f / Mathf.Max(m_MaxFrameTime, 1.0e-5f), m_MaxFrameTime * 1000.0f); } GUI.Label(new Rect(170, graphicsLabelRect.y, 120, 20), timeStats); int screenBytes = UnityStats.screenBytes; int batchesSavedByDynamicBatching = UnityStats.dynamicBatchedDrawCalls - UnityStats.dynamicBatches; int batchesSavedByStaticBatching = UnityStats.staticBatchedDrawCalls - UnityStats.staticBatches; int batchesSavedByInstancing = UnityStats.instancedBatchedDrawCalls - UnityStats.instancedBatches; StringBuilder gfxStats = new StringBuilder(400); if (m_ClientFrameTime > m_RenderFrameTime) gfxStats.Append(UnityString.Format(" CPU: main <b>{0:F1}</b>ms render thread {1:F1}ms\n", m_ClientFrameTime * 1000.0f, m_RenderFrameTime * 1000.0f)); else gfxStats.Append(UnityString.Format(" CPU: main {0:F1}ms render thread <b>{1:F1}</b>ms\n", m_ClientFrameTime * 1000.0f, m_RenderFrameTime * 1000.0f)); gfxStats.Append(UnityString.Format(" Batches: <b>{0}</b> \tSaved by batching: {1}\n", UnityStats.batches, batchesSavedByDynamicBatching + batchesSavedByStaticBatching + batchesSavedByInstancing)); gfxStats.Append(UnityString.Format(" Tris: {0} \tVerts: {1} \n", FormatNumber(UnityStats.trianglesLong), FormatNumber(UnityStats.verticesLong))); gfxStats.Append(UnityString.Format(" Screen: {0} - {1}\n", UnityStats.screenRes, EditorUtility.FormatBytes(screenBytes))); gfxStats.Append(UnityString.Format(" SetPass calls: {0} \tShadow casters: {1} \n", UnityStats.setPassCalls, UnityStats.shadowCasters)); gfxStats.Append(UnityString.Format(" Visible skinned meshes: {0}\n", UnityStats.visibleSkinnedMeshes)); gfxStats.Append(UnityString.Format(" Animation components playing: {0} \n", UnityStats.animationComponentsPlaying)); gfxStats.Append(UnityString.Format(" Animator components playing: {0}", UnityStats.animatorComponentsPlaying)); GUILayout.Label(gfxStats.ToString(), labelStyle); GUILayout.EndArea(); } } }
UnityCsReference/Editor/Mono/GameView/GameviewGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/GameView/GameviewGUI.cs", "repo_id": "UnityCsReference", "token_count": 3357 }
316
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace UnityEditor { [Serializable] class SnapSettings { public const bool defaultGridSnapEnabled = true; public const float defaultRotation = 15f; public const float defaultScale = 1f; [SerializeField] bool m_SnapToGrid = defaultGridSnapEnabled; [SerializeField] float m_Rotation = defaultRotation; [SerializeField] float m_Scale = defaultScale; public bool snapToGrid { get => m_SnapToGrid; set => m_SnapToGrid = value; } public float rotation { get { return m_Rotation; } set { m_Rotation = value; } } public float scale { get { return m_Scale; } set { m_Scale = value; } } } }
UnityCsReference/Editor/Mono/Grids/SnapSettings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Grids/SnapSettings.cs", "repo_id": "UnityCsReference", "token_count": 450 }
317
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.Internal; namespace UnityEditor { // Grid drawing params for Handles.DrawCamera. [StructLayout(LayoutKind.Sequential)] struct DrawGridParameters { public int gridID; public Vector3 pivot; public Color color; public Vector2 size; } public sealed partial class Handles { // Color of the X axis handle internal static PrefColor s_XAxisColor = new PrefColor("Scene/X Axis", 219f / 255, 62f / 255, 29f / 255, .93f); public static Color xAxisColor { get { return s_XAxisColor; } } // Color of the Y axis handle internal static PrefColor s_YAxisColor = new PrefColor("Scene/Y Axis", 154f / 255, 243f / 255, 72f / 255, .93f); public static Color yAxisColor { get { return s_YAxisColor; } } // Color of the Z axis handle internal static PrefColor s_ZAxisColor = new PrefColor("Scene/Z Axis", 58f / 255, 122f / 255, 248f / 255, .93f); public static Color zAxisColor { get { return s_ZAxisColor; } } // Color of the Constrain Proportions scale handles internal static PrefColor constrainProportionsScaleHandleColor = new PrefColor("Scene/Constrain Proportions Scale Handle", 190f / 255, 190f / 255, 190f / 255, 1f); // Color of the center handle internal static PrefColor s_CenterColor = new PrefColor("Scene/Center Axis", .8f, .8f, .8f, .93f); public static Color centerColor { get { return s_CenterColor; } } // color for handles the currently active handle internal static PrefColor s_SelectedColor = new PrefColor("Scene/Selected Axis", 246f / 255, 242f / 255, 50f / 255, .89f); public static Color selectedColor { get { return s_SelectedColor; } } // color for handles the currently hovered handle internal static PrefColor s_PreselectionColor = new PrefColor("Scene/Preselection Highlight", 201f / 255, 200f / 255, 144f / 255, 0.89f); public static Color preselectionColor { get { return s_PreselectionColor; } } // soft color for general stuff - used to draw e.g. the arc selection while dragging internal static PrefColor s_SecondaryColor = new PrefColor("Scene/Guide Line", .5f, .5f, .5f, .2f); public static Color secondaryColor { get { return s_SecondaryColor; } } // internal color for static handles internal static Color staticColor = new Color(.5f, .5f, .5f, 0f); // internal blend ratio for static colors internal static float staticBlend = 0.6f; static PrefColor s_ElementColor => new PrefColor("Scene/Element Default", 0f, 224f / 255f, 1f, 1f); static PrefColor s_ElementPreselectionColor => new PrefColor("Scene/Element Preselection", 1f, 207f / 255f, 112f / 255f, 1f); static PrefColor s_ElementSelectionColor => new PrefColor("Scene/Element Selection", 1f, 182f / 255f, 40f / 255f, 1f); public static Color elementColor => s_ElementColor; public static Color elementPreselectionColor => s_ElementPreselectionColor; public static Color elementSelectionColor => s_ElementSelectionColor; internal static float backfaceAlphaMultiplier = 0.2f; internal static Color s_ColliderHandleColor = new Color(145f, 244f, 139f, 210f) / 255; internal static Color s_ColliderHandleColorDisabled = new Color(84, 200f, 77f, 140f) / 255; internal static Color s_BoundingBoxHandleColor = new Color(255, 255, 255, 150) / 255; // Should match s_ColliderHandleColor to start unless the user overrides the color. As Gizmos are drawn from CPP there is no way currently to hook the ColliderHandleColor up properly. public static Color UIColliderHandleColor { get { return s_UIColliderHandleColor; } } internal static PrefColor s_UIColliderHandleColor = new PrefColor("Scene/UI Collider Handle", 145f / 255, 244f / 255, 139f / 255, 210f / 255); internal readonly static GUIContent s_StaticLabel = EditorGUIUtility.TrTextContent("Static"); internal readonly static GUIContent s_PrefabLabel = EditorGUIUtility.TrTextContent("Prefab"); internal static int s_SliderHash = "SliderHash".GetHashCode(); internal static int s_Slider2DHash = "Slider2DHash".GetHashCode(); internal static int s_FreeRotateHandleHash = "FreeRotateHandleHash".GetHashCode(); internal static int s_RadiusHandleHash = "RadiusHandleHash".GetHashCode(); internal static int s_xAxisMoveHandleHash = "xAxisFreeMoveHandleHash".GetHashCode(); internal static int s_yAxisMoveHandleHash = "yAxisFreeMoveHandleHash".GetHashCode(); internal static int s_zAxisMoveHandleHash = "zAxisFreeMoveHandleHash".GetHashCode(); internal static int s_FreeMoveHandleHash = "FreeMoveHandleHash".GetHashCode(); internal static int s_xzAxisMoveHandleHash = "xzAxisFreeMoveHandleHash".GetHashCode(); internal static int s_xyAxisMoveHandleHash = "xyAxisFreeMoveHandleHash".GetHashCode(); internal static int s_yzAxisMoveHandleHash = "yzAxisFreeMoveHandleHash".GetHashCode(); internal static int s_xAxisScaleHandleHash = "xAxisScaleHandleHash".GetHashCode(); internal static int s_yAxisScaleHandleHash = "yAxisScaleHandleHash".GetHashCode(); internal static int s_zAxisScaleHandleHash = "zAxisScaleHandleHash".GetHashCode(); internal static int s_ScaleSliderHash = "ScaleSliderHash".GetHashCode(); internal static int s_ScaleValueHandleHash = "ScaleValueHandleHash".GetHashCode(); internal static int s_DiscHash = "DiscHash".GetHashCode(); internal static int s_ButtonHash = "ButtonHash".GetHashCode(); static readonly int kPropUseGuiClip = Shader.PropertyToID("_UseGUIClip"); static readonly int kPropHandleZTest = Shader.PropertyToID("_HandleZTest"); static readonly int kPropColor = Shader.PropertyToID("_Color"); static readonly int kPropArcCenterRadius = Shader.PropertyToID("_ArcCenterRadius"); static readonly int kPropArcNormalAngle = Shader.PropertyToID("_ArcNormalAngle"); static readonly int kPropArcFromCount = Shader.PropertyToID("_ArcFromCount"); static readonly int kPropArcThicknessSides = Shader.PropertyToID("_ArcThicknessSides"); static readonly int kPropHandlesMatrix = Shader.PropertyToID("_HandlesMatrix"); public struct DrawingScope : IDisposable { private bool m_Disposed; public Color originalColor { get { return m_OriginalColor; } } private Color m_OriginalColor; public Matrix4x4 originalMatrix { get { return m_OriginalMatrix; } } private Matrix4x4 m_OriginalMatrix; public DrawingScope(Color color) : this(color, Handles.matrix) {} public DrawingScope(Matrix4x4 matrix) : this(Handles.color, matrix) {} public DrawingScope(Color color, Matrix4x4 matrix) { m_Disposed = false; m_OriginalColor = Handles.color; m_OriginalMatrix = Handles.matrix; Handles.matrix = matrix; Handles.color = color; } public void Dispose() { if (m_Disposed) return; m_Disposed = true; Handles.color = m_OriginalColor; Handles.matrix = m_OriginalMatrix; } } internal static Mesh cubeMesh { get { if (s_CubeMesh == null) Init(); return s_CubeMesh; } } internal static Mesh coneMesh { get { if (s_ConeMesh == null) Init(); return s_ConeMesh; } } internal static Mesh cylinderMesh { get { if (s_CylinderMesh == null) Init(); return s_CylinderMesh; } } internal static Mesh sphereMesh { get { if (s_SphereMesh == null) Init(); return s_SphereMesh; } } internal static Mesh quadMesh { get { if (s_QuadMesh == null) Init(); return s_QuadMesh; } } internal static int s_xRotateHandleHash = "xRotateHandleHash".GetHashCode(); internal static int s_yRotateHandleHash = "yRotateHandleHash".GetHashCode(); internal static int s_zRotateHandleHash = "zRotateHandleHash".GetHashCode(); internal static int s_cameraAxisRotateHandleHash = "cameraAxisRotateHandleHash".GetHashCode(); internal static int s_xyzRotateHandleHash = "xyzRotateHandleHash".GetHashCode(); internal static int s_xScaleHandleHash = "xScaleHandleHash".GetHashCode(); internal static int s_yScaleHandleHash = "yScaleHandleHash".GetHashCode(); internal static int s_zScaleHandleHash = "zScaleHandleHash".GetHashCode(); internal static int s_xyzScaleHandleHash = "xyzScaleHandleHash".GetHashCode(); private static Color lineTransparency = new Color(1, 1, 1, 0.75f); internal static SavedFloat s_LineThickness = new SavedFloat("SceneView.handleLineThickness", 2.0f); public static float lineThickness => s_LineThickness.value; // When hovering over some handle axis/control, this is the indication that it would // get picked on mouse press: // Color gets a bit more bright and less opaque, internal static Color s_HoverIntensity = new Color(1.0f, 1.0f, 1.0f, 1.33f); // Handle lines get more thick, internal static float s_HoverExtraThickness = 1.0f; // 3D handle elements (caps) get slightly larger. internal static float s_HoverExtraScale = 1.05f; // When axis is looking away from camera, fade it out along 25 -> 15 degrees range static readonly float kCameraViewLerpStart1 = Mathf.Cos(Mathf.Deg2Rad * 25.0f); static readonly float kCameraViewLerpEnd1 = Mathf.Cos(Mathf.Deg2Rad * 15.0f); // When axis is looking towards the camera, fade it out along 170 -> 175 degrees range static readonly float kCameraViewLerpStart2 = Mathf.Cos(Mathf.Deg2Rad * 170.0f); static readonly float kCameraViewLerpEnd2 = Mathf.Cos(Mathf.Deg2Rad * 175.0f); // Hide & disable axis if they have faded out more than 60% internal const float kCameraViewThreshold = 0.6f; // The function for calling AddControl in Layout event and draw the handle in Repaint event. public delegate void CapFunction(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType); public delegate float SizeFunction(Vector3 position); static PrefColor[] s_AxisColor = { s_XAxisColor, s_YAxisColor, s_ZAxisColor }; static Vector3[] s_AxisVector = { Vector3.right, Vector3.up, Vector3.forward }; internal static Color s_DisabledHandleColor = new Color(0.5f, 0.5f, 0.5f, 0.5f); internal static Color GetColorByAxis(int axis) { return s_AxisColor[axis]; } internal static Color ToActiveColorSpace(Color color) { return (QualitySettings.activeColorSpace == ColorSpace.Linear) ? color.linear : color; } static Vector3 GetAxisVector(int axis) { return s_AxisVector[axis]; } internal static bool IsHovering(int controlID, Event evt) { return controlID == HandleUtility.nearestControl && GUIUtility.hotControl == 0 && !Tools.viewToolActive; } static internal void SetupHandleColor(int controlID, Event evt, out Color prevColor, out float thickness) { prevColor = Handles.color; thickness = Handles.lineThickness; if (controlID == GUIUtility.hotControl) { Handles.color = Handles.selectedColor; } else if (IsHovering(controlID, evt)) { var col = Handles.color * s_HoverIntensity; // make sure colors never go outside of 0..1 range col.r = Mathf.Clamp01(col.r); col.g = Mathf.Clamp01(col.g); col.b = Mathf.Clamp01(col.b); col.a = Mathf.Clamp01(col.a); Handles.color = col; thickness += s_HoverExtraThickness; } } static void Swap(ref Vector3 v, int[] indices, int a, int b) { var f = v[a]; v[a] = v[b]; v[b] = f; var t = indices[a]; indices[a] = indices[b]; indices[b] = t; } // Given view direction in handle space, calculate // back-to-front order in which handle axes should be drawn. // The array should be [3] size, and will contain axis indices // from (0,1,2) set. static void CalcDrawOrder(Vector3 viewDir, int[] ordering) { ordering[0] = 0; ordering[1] = 1; ordering[2] = 2; // essentially an unrolled bubble sort for 3 elements if (viewDir.y > viewDir.x) Swap(ref viewDir, ordering, 1, 0); if (viewDir.z > viewDir.y) Swap(ref viewDir, ordering, 2, 1); if (viewDir.y > viewDir.x) Swap(ref viewDir, ordering, 1, 0); } private static bool BeginLineDrawing(Matrix4x4 matrix, bool dottedLines, int mode) { if (Event.current.type != EventType.Repaint) return false; Color col = color * lineTransparency; if (dottedLines) HandleUtility.ApplyDottedWireMaterial(zTest); else HandleUtility.ApplyWireMaterial(zTest); GL.PushMatrix(); GL.MultMatrix(matrix); GL.Begin(mode); GL.Color(col); return true; } private static void EndLineDrawing() { GL.End(); GL.PopMatrix(); } public static void DrawPolyLine(params Vector3[] points) { if (!BeginLineDrawing(matrix, false, GL.LINE_STRIP)) return; for (int i = 0; i < points.Length; i++) { GL.Vertex(points[i]); } EndLineDrawing(); } [ExcludeFromDocs] public static void DrawLine(Vector3 p1, Vector3 p2) { DrawLine(p1, p2, false); } internal static void DrawLine(Vector3 p1, Vector3 p2, bool dottedLine) { if (!BeginLineDrawing(matrix, dottedLine, GL.LINES)) return; GL.Vertex(p1); GL.Vertex(p2); EndLineDrawing(); } static float ThicknessToPixels(float thickness) { var halfThicknessPixels = thickness * EditorGUIUtility.pixelsPerPoint * 0.5f; if (halfThicknessPixels < 0.9f) halfThicknessPixels = 0; return halfThicknessPixels; } public static void DrawLine(Vector3 p1, Vector3 p2, [DefaultValue("0.0f")] float thickness) { if (Event.current.type != EventType.Repaint) return; thickness = ThicknessToPixels(thickness); if (thickness <= 0) { DrawLine(p1, p2); return; } var mat = SetupArcMaterial(); if (mat == null) // can't do thick lines { DrawLine(p1, p2); return; } mat.SetVector(kPropArcCenterRadius, new Vector4(p1.x, p1.y, p1.z, 0)); mat.SetVector(kPropArcFromCount, new Vector4(p2.x, p2.y, p2.z, 0)); mat.SetVector(kPropArcThicknessSides, new Vector4(thickness, kArcSides, 0, 0)); mat.SetPass(1); var indexBuffer = HandleUtility.GetArcIndexBuffer(kArcSegments, kArcSides); Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, kArcSides * 6); } public static void DrawLines(Vector3[] lineSegments) { if (!BeginLineDrawing(matrix, false, GL.LINES)) return; try { for (int i = 0; i < lineSegments.Length; i += 2) { var p1 = lineSegments[i + 0]; var p2 = lineSegments[i + 1]; GL.Vertex(p1); GL.Vertex(p2); } } finally { EndLineDrawing(); } } public static void DrawLines(Vector3[] points, int[] segmentIndices) { if (!BeginLineDrawing(matrix, false, GL.LINES)) return; try { for (int i = 0; i < segmentIndices.Length; i += 2) { var p1 = points[segmentIndices[i + 0]]; var p2 = points[segmentIndices[i + 1]]; GL.Vertex(p1); GL.Vertex(p2); } } finally { EndLineDrawing(); } } public static void DrawDottedLine(Vector3 p1, Vector3 p2, float screenSpaceSize) { if (!BeginLineDrawing(matrix, true, GL.LINES)) return; var dashSize = screenSpaceSize * EditorGUIUtility.pixelsPerPoint; GL.MultiTexCoord(1, p1); GL.MultiTexCoord2(2, dashSize, 0); GL.Vertex(p1); GL.MultiTexCoord(1, p1); GL.MultiTexCoord2(2, dashSize, 0); GL.Vertex(p2); EndLineDrawing(); } public static void DrawDottedLines(Vector3[] lineSegments, float screenSpaceSize) { if (!BeginLineDrawing(matrix, true, GL.LINES)) return; var dashSize = screenSpaceSize * EditorGUIUtility.pixelsPerPoint; try { for (int i = 0; i < lineSegments.Length; i += 2) { var p1 = lineSegments[i + 0]; var p2 = lineSegments[i + 1]; GL.MultiTexCoord(1, p1); GL.MultiTexCoord2(2, dashSize, 0); GL.Vertex(p1); GL.MultiTexCoord(1, p1); GL.MultiTexCoord2(2, dashSize, 0); GL.Vertex(p2); } } finally { EndLineDrawing(); } } public static void DrawDottedLines(Vector3[] points, int[] segmentIndices, float screenSpaceSize) { if (!BeginLineDrawing(matrix, true, GL.LINES)) return; var dashSize = screenSpaceSize * EditorGUIUtility.pixelsPerPoint; try { for (int i = 0; i < segmentIndices.Length; i += 2) { var p1 = points[segmentIndices[i + 0]]; var p2 = points[segmentIndices[i + 1]]; GL.MultiTexCoord(1, p1); GL.MultiTexCoord2(2, dashSize, 0); GL.Vertex(p1); GL.MultiTexCoord(1, p1); GL.MultiTexCoord2(2, dashSize, 0); GL.Vertex(p2); } } finally { EndLineDrawing(); } } public static void DrawWireCube(Vector3 center, Vector3 size) { if (Event.current.type != EventType.Repaint || lineTransparency.a <= 0) return; HandleUtility.ApplyWireMaterial(zTest); GL.PushMatrix(); GL.MultMatrix(matrix); GL.Begin(GL.LINE_STRIP); GL.Color(color * lineTransparency); Vector3 p1, p2, p3, p6, p7, p8; { Vector3 halfsize = size * 0.5f; GL.Vertex(center + new Vector3(-halfsize.x, -halfsize.y, -halfsize.z)); p1 = center + new Vector3(-halfsize.x, halfsize.y, -halfsize.z); GL.Vertex(p1); p2 = center + new Vector3(halfsize.x, halfsize.y, -halfsize.z); GL.Vertex(p2); p3 = center + new Vector3(halfsize.x, -halfsize.y, -halfsize.z); GL.Vertex(p3); GL.Vertex(center + new Vector3(-halfsize.x, -halfsize.y, -halfsize.z)); GL.Vertex(center + new Vector3(-halfsize.x, -halfsize.y, halfsize.z)); p6 = center + new Vector3(-halfsize.x, halfsize.y, halfsize.z); GL.Vertex(p6); p7 = center + new Vector3(halfsize.x, halfsize.y, halfsize.z); GL.Vertex(p7); p8 = center + new Vector3(halfsize.x, -halfsize.y, halfsize.z); GL.Vertex(p8); GL.Vertex(center + new Vector3(-halfsize.x, -halfsize.y, halfsize.z)); } GL.End(); GL.Begin(GL.LINES); GL.Color(color * lineTransparency); GL.Vertex(p1); GL.Vertex(p6); GL.Vertex(p2); GL.Vertex(p7); GL.Vertex(p3); GL.Vertex(p8); GL.End(); GL.PopMatrix(); } public static bool ShouldRenderGizmos() { var playModeView = PlayModeView.GetRenderingView(); SceneView sv = SceneView.currentDrawingSceneView; if (playModeView != null) return playModeView.IsShowingGizmos(); if (sv != null) return sv.drawGizmos; return false; } public static void DrawGizmos(Camera camera) { if (ShouldRenderGizmos()) Internal_DoDrawGizmos(camera); } // Make a 3D slider public static Vector3 Slider(Vector3 position, Vector3 direction) { return Slider(position, direction, HandleUtility.GetHandleSize(position), ArrowHandleCap, -1); } public static Vector3 Slider(Vector3 position, Vector3 direction, float size, CapFunction capFunction, float snap) { int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Passive); return UnityEditorInternal.Slider1D.Do(id, position, direction, size, capFunction, snap); } public static Vector3 Slider(int controlID, Vector3 position, Vector3 direction, float size, CapFunction capFunction, float snap) { return UnityEditorInternal.Slider1D.Do(controlID, position, direction, size, capFunction, snap); } public static Vector3 Slider(int controlID, Vector3 position, Vector3 offset, Vector3 direction, float size, CapFunction capFunction, float snap) { return UnityEditorInternal.Slider1D.Do(controlID, position, offset, direction, direction, size, capFunction, snap); } [Obsolete("Rotation parameter is obsolete. (UnityUpgradable) -> !1")] public static Vector3 FreeMoveHandle(Vector3 position, Quaternion rotation, float size, Vector3 snap, CapFunction capFunction) { int id = GUIUtility.GetControlID(s_FreeMoveHandleHash, FocusType.Passive); return UnityEditorInternal.FreeMove.Do(id, position, rotation, size, snap, capFunction); } [Obsolete("Rotation parameter is obsolete. (UnityUpgradable) -> !2")] public static Vector3 FreeMoveHandle(int controlID, Vector3 position, Quaternion rotation, float size, Vector3 snap, CapFunction capFunction) { return UnityEditorInternal.FreeMove.Do(controlID, position, rotation, size, snap, capFunction); } public static Vector3 FreeMoveHandle(Vector3 position, float size, Vector3 snap, CapFunction capFunction) { int id = GUIUtility.GetControlID(s_FreeMoveHandleHash, FocusType.Passive); return UnityEditorInternal.FreeMove.Do(id, position, size, snap, capFunction); } public static Vector3 FreeMoveHandle(int controlID, Vector3 position, float size, Vector3 snap, CapFunction capFunction) { return UnityEditorInternal.FreeMove.Do(controlID, position, size, snap, capFunction); } // Make a single-float draggable handle. public static float ScaleValueHandle(float value, Vector3 position, Quaternion rotation, float size, CapFunction capFunction, float snap) { int id = GUIUtility.GetControlID(s_ScaleValueHandleHash, FocusType.Passive); return UnityEditorInternal.SliderScale.DoCenter(id, value, position, rotation, size, capFunction, snap); } public static float ScaleValueHandle(int controlID, float value, Vector3 position, Quaternion rotation, float size, CapFunction capFunction, float snap) { return UnityEditorInternal.SliderScale.DoCenter(controlID, value, position, rotation, size, capFunction, snap); } // Make a 3D Button. public static bool Button(Vector3 position, Quaternion direction, float size, float pickSize, CapFunction capFunction) { int id = GUIUtility.GetControlID(s_ButtonHash, FocusType.Passive); return UnityEditorInternal.Button.Do(id, position, direction, size, pickSize, capFunction); } internal static bool Button(int controlID, Vector3 position, Quaternion direction, float size, float pickSize, CapFunction capFunction) { return UnityEditorInternal.Button.Do(controlID, position, direction, size, pickSize, capFunction); } internal static bool Button(int controlID, Vector3 position, Quaternion direction, float size, float pickSize, CapFunction capFunction, bool checkMouseProximity) { return UnityEditorInternal.Button.Do(controlID, position, direction, size, pickSize, capFunction, checkMouseProximity); } // Draw a cube. Pass this into handle functions. public static void CubeHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToCube(position, rotation, size)); break; case (EventType.Repaint): Graphics.DrawMeshNow(cubeMesh, StartCapDraw(position, rotation, size)); break; } } // Draw a Sphere. Pass this into handle functions. public static void SphereHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: // TODO: Create DistanceToCube HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(position, size)); break; case (EventType.Repaint): Graphics.DrawMeshNow(sphereMesh, StartCapDraw(position, rotation, size)); break; } } // Draw a Cone. Pass this into handle functions. public static void ConeHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToCone(position, rotation, size)); break; case EventType.Repaint: Graphics.DrawMeshNow(coneMesh, StartCapDraw(position, rotation, size)); break; } } // Draw a Cylinder. Pass this into handle functions. public static void CylinderHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: // TODO: Create DistanceToCylinder HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(position, size)); break; case (EventType.Repaint): Graphics.DrawMeshNow(cylinderMesh, StartCapDraw(position, rotation, size)); break; } } // Draw a camera-facing Rectangle. Pass this into handle functions. static Vector3[] s_RectangleHandlePointsCache = new Vector3[5]; public static void RectangleHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { RectangleHandleCap(controlID, position, rotation, new Vector2(size, size), eventType); } internal static void RectangleHandleCap(int controlID, Vector3 position, Quaternion rotation, Vector2 size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: // TODO: Create DistanceToRectangle HandleUtility.AddControl(controlID, HandleUtility.DistanceToRectangleInternal(position, rotation, size)); break; case (EventType.Repaint): Vector3 sideways = rotation * new Vector3(size.x, 0, 0); Vector3 up = rotation * new Vector3(0, size.y, 0); s_RectangleHandlePointsCache[0] = position + sideways + up; s_RectangleHandlePointsCache[1] = position + sideways - up; s_RectangleHandlePointsCache[2] = position - sideways - up; s_RectangleHandlePointsCache[3] = position - sideways + up; s_RectangleHandlePointsCache[4] = position + sideways + up; Handles.DrawPolyLine(s_RectangleHandlePointsCache); break; } } internal static void RectangleHandleCapWorldSpace(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { RectangleHandleCapWorldSpace(controlID, position, rotation, new Vector2(size, size), eventType); } internal static void RectangleHandleCapWorldSpace(int controlID, Vector3 position, Quaternion rotation, Vector2 size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToRectangleInternalWorldSpace(position, rotation, size)); break; case (EventType.Repaint): Vector3 sideways = rotation * new Vector3(size.x, 0, 0); Vector3 up = rotation * new Vector3(0, size.y, 0); s_RectangleHandlePointsCache[0] = position + sideways + up; s_RectangleHandlePointsCache[1] = position + sideways - up; s_RectangleHandlePointsCache[2] = position - sideways - up; s_RectangleHandlePointsCache[3] = position - sideways + up; s_RectangleHandlePointsCache[4] = position + sideways + up; Handles.DrawPolyLine(s_RectangleHandlePointsCache); break; } } // Draw a camera-facing dot. Pass this into handle functions. public static void DotHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToRectangle(position, rotation, size)); break; case (EventType.Repaint): // Only apply matrix to the position because DotCap is camera facing position = matrix.MultiplyPoint(position); Vector3 sideways = (Camera.current == null ? Vector3.right : Camera.current.transform.right) * size; Vector3 up = (Camera.current == null ? Vector3.up : Camera.current.transform.up) * size; Color col = color * new Color(1, 1, 1, 0.99f); HandleUtility.ApplyWireMaterial(Handles.zTest); GL.Begin(GL.QUADS); GL.Color(col); GL.Vertex(position + sideways + up); GL.Vertex(position + sideways - up); GL.Vertex(position - sideways - up); GL.Vertex(position - sideways + up); GL.End(); break; } } // Draw a camera-facing Circle. Pass this into handle functions. public static void CircleHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToRectangle(position, rotation, size)); break; case (EventType.Repaint): StartCapDraw(position, rotation, size); Vector3 forward = rotation * new Vector3(0, 0, 1); Handles.DrawWireDisc(position, forward, size); break; } } // Draw an arrow like those used by the move tool. public static void ArrowHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { ArrowHandleCap(controlID, position, rotation, size, eventType, Vector3.zero); } internal static void ArrowHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType, Vector3 coneOffset) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: { Vector3 direction = rotation * Vector3.forward; HandleUtility.AddControl(controlID, HandleUtility.DistanceToLine(position, position + (direction + coneOffset) * (size * .9f))); HandleUtility.AddControl(controlID, HandleUtility.DistanceToCone(position + (direction + coneOffset) * size, rotation, size * .2f)); break; } case EventType.Repaint: { Vector3 direction = rotation * Vector3.forward; float thickness = Handles.lineThickness; float coneSize = size * .2f; if (IsHovering(controlID, Event.current)) { thickness += s_HoverExtraThickness; coneSize *= s_HoverExtraScale; } var camera = Camera.current; var viewDir = camera != null ? camera.transform.forward : -direction; var facingAway = Vector3.Dot(viewDir, direction) < 0.0f; var conePos = position + (direction + coneOffset) * size; var linePos = position + (direction + coneOffset) * (size * .9f); // draw line vs cone in the appropriate order based on viewing // direction, for correct transparency sorting if (facingAway) { DrawLine(position, linePos, thickness); ConeHandleCap(controlID, conePos, rotation, coneSize, eventType); } else { ConeHandleCap(controlID, conePos, rotation, coneSize, eventType); DrawLine(position, linePos, thickness); } break; } } } // Draw a camera facing selection frame. public static void DrawSelectionFrame(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { if (eventType != EventType.Repaint) return; Handles.StartCapDraw(position, rotation, size); Vector3 sideways = rotation * new Vector3(size, 0, 0); Vector3 up = rotation * new Vector3(0, size, 0); var point1 = position - sideways + up; var point2 = position + sideways + up; var point3 = position + sideways - up; var point4 = position - sideways - up; Handles.DrawLine(point1, point2); Handles.DrawLine(point2, point3); Handles.DrawLine(point3, point4); Handles.DrawLine(point4, point1); } internal static Color GetFadedAxisColor(Color col, float fade, int id) { // never fade out axes that are being hover-highlighted or currently interacted with if (id != 0 && id == GUIUtility.hotControl || id == HandleUtility.nearestControl) fade = 0; col = Color.Lerp(col, Color.clear, fade); return col; } internal static float GetCameraViewLerpForWorldAxis(Vector3 viewVector, Vector3 axis) { var dot = Vector3.Dot(viewVector, axis); var l1 = Mathf.InverseLerp(kCameraViewLerpStart1, kCameraViewLerpEnd1, dot); var l2 = Mathf.InverseLerp(kCameraViewLerpStart2, kCameraViewLerpEnd2, dot); return Mathf.Max(l1, l2); } internal static Vector3 GetCameraViewFrom(Vector3 position, Matrix4x4 matrix) { Camera camera = Camera.current; return camera.orthographic ? matrix.MultiplyVector(camera.transform.forward).normalized : matrix.MultiplyVector(position - camera.transform.position).normalized; } // Make a 3D Scene view position handle. public static Vector3 PositionHandle(Vector3 position, Quaternion rotation) { return DoPositionHandle(position, rotation); } public static Vector3 PositionHandle(PositionHandleIds ids, Vector3 position, Quaternion rotation) { return DoPositionHandle(ids, position, rotation); } // Make a Scene view rotation handle. public static Quaternion RotationHandle(Quaternion rotation, Vector3 position) { return DoRotationHandle(rotation, position); } public static Quaternion RotationHandle(RotationHandleIds ids, Quaternion rotation, Vector3 position) { return DoRotationHandle(ids, rotation, position, RotationHandleParam.Default); } // Make a Scene view scale handle public static Vector3 ScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation) { return DoScaleHandle(scale, position, rotation, HandleUtility.GetHandleSize(position)); } // Make a Scene view scale handle public static Vector3 ScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size) { return DoScaleHandle(scale, position, rotation, size, false); } internal static Vector3 ScaleHandle(Vector3 scale, Vector3 position, Quaternion rotation, float size, bool isProportionalScale) { return DoScaleHandle(scale, position, rotation, size, isProportionalScale); } ///*listonly* public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius, bool handlesOnly) { return DoRadiusHandle(rotation, position, radius, handlesOnly); } // Make a Scene view radius handle public static float RadiusHandle(Quaternion rotation, Vector3 position, float radius) { return DoRadiusHandle(rotation, position, radius, false); } // Make a Scene View cone handle internal static Vector2 ConeHandle(Quaternion rotation, Vector3 position, Vector2 angleAndRange, float angleScale, float rangeScale, bool handlesOnly) { return DoConeHandle(rotation, position, angleAndRange, angleScale, rangeScale, handlesOnly); } // Make a Scene View cone frustrum handle internal static Vector3 ConeFrustrumHandle(Quaternion rotation, Vector3 position, Vector3 radiusAngleRange, ConeHandles showHandles = ConeHandles.All) { return DoConeFrustrumHandle(rotation, position, radiusAngleRange, showHandles); } // Slide a handle in a 2D plane public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, Vector2 snap) { return Slider2D(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, false); } public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 offset, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, Vector2 snap, [DefaultValue("false")] bool drawHelper) { return UnityEditorInternal.Slider2D.Do(id, handlePos, offset, handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, drawHelper); } /// *listonly* public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, Vector2 snap) { return Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, false); } public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, Vector2 snap, [DefaultValue("false")] bool drawHelper) { int id = GUIUtility.GetControlID(s_Slider2DHash, FocusType.Passive); return UnityEditorInternal.Slider2D.Do(id, handlePos, new Vector3(0, 0, 0), handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, drawHelper); } /// *listonly* public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, Vector2 snap) { return Slider2D(id, handlePos, handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, false); } public static Vector3 Slider2D(int id, Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, Vector2 snap, [DefaultValue("false")] bool drawHelper) { return UnityEditorInternal.Slider2D.Do(id, handlePos, new Vector3(0, 0, 0), handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, drawHelper); } /// *listonly* public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, float snap) { return Slider2D(handlePos, handleDir, slideDir1, slideDir2, handleSize, capFunction, snap, false); } public static Vector3 Slider2D(Vector3 handlePos, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, CapFunction capFunction, float snap, [DefaultValue("false")] bool drawHelper) { int id = GUIUtility.GetControlID(s_Slider2DHash, FocusType.Passive); return Slider2D(id, handlePos, new Vector3(0, 0, 0), handleDir, slideDir1, slideDir2, handleSize, capFunction, new Vector2(snap, snap), drawHelper); } // Make an unconstrained rotation handle. public static Quaternion FreeRotateHandle(int id, Quaternion rotation, Vector3 position, float size) { return UnityEditorInternal.FreeRotate.Do(id, rotation, position, size); } public static Quaternion FreeRotateHandle(Quaternion rotation, Vector3 position, float size) { int id = GUIUtility.GetControlID(s_FreeRotateHandleHash, FocusType.Passive); return UnityEditorInternal.FreeRotate.Do(id, rotation, position, size); } // Make a directional scale slider public static float ScaleSlider(int id, float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) { return UnityEditorInternal.SliderScale.DoAxis(id, scale, position, direction, rotation, size, snap); } public static float ScaleSlider(float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) { int id = GUIUtility.GetControlID(s_ScaleSliderHash, FocusType.Passive); return UnityEditorInternal.SliderScale.DoAxis(id, scale, position, direction, rotation, size, snap); } // Make a 3D disc that can be dragged with the mouse public static Quaternion Disc(int id, Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap) { return UnityEditorInternal.Disc.Do(id, rotation, position, axis, size, cutoffPlane, snap); } public static Quaternion Disc(Quaternion rotation, Vector3 position, Vector3 axis, float size, bool cutoffPlane, float snap) { int id = GUIUtility.GetControlID(s_DiscHash, FocusType.Passive); return UnityEditorInternal.Disc.Do(id, rotation, position, axis, size, cutoffPlane, snap); } internal static void SetupIgnoreRaySnapObjects() { HandleUtility.ignoreRaySnapObjects = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.Deep); } // If snapping is active, return a new value rounded to the nearest increment of snap. public static float SnapValue(float value, float snap) { if (EditorSnapSettings.incrementalSnapActive) return Snapping.Snap(value, snap); return value; } // If snapping is active, return a new value rounded to the nearest increment of snap. public static Vector2 SnapValue(Vector2 value, Vector2 snap) { if (EditorSnapSettings.incrementalSnapActive) return Snapping.Snap(value, snap); return value; } // If snapping is active, return a new value rounded to the nearest increment of snap. public static Vector3 SnapValue(Vector3 value, Vector3 snap) { if (EditorSnapSettings.incrementalSnapActive) return Snapping.Snap(value, snap); return value; } // Snap all transform positions to the grid public static void SnapToGrid(Transform[] transforms, SnapAxis axis = SnapAxis.All) { if (transforms != null && transforms.Length > 0) { foreach (var t in transforms) { if (t != null) t.position = Snapping.Snap(t.position, Vector3.Scale(GridSettings.size, new SnapAxisFilter(axis))); } } } // Snap all positions to the grid public static void SnapToGrid(Vector3[] positions, SnapAxis axis = SnapAxis.All) { if (positions != null && positions.Length > 0) { for(int i = 0; i<positions.Length; i++) { positions[i] = Snapping.Snap(positions[i], Vector3.Scale(GridSettings.size, new SnapAxisFilter(axis))); } } } // The camera used for deciding where 3D handles end up public Camera currentCamera { get { return Camera.current; } set { Internal_SetCurrentCamera(value); } } internal static Color realHandleColor { get { return color * new Color(1, 1, 1, .5f) + (lighting ? new Color(0, 0, 0, .5f) : new Color(0, 0, 0, 0)); } } // Draw two-shaded wire-disc that is fully shadowed internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, float radius) { Color col = Handles.color; Color origCol = col; col.a *= backfaceAlphaMultiplier; Handles.color = col; Handles.DrawWireDisc(position, axis, radius); Handles.color = origCol; } // Draw two-shaded wire-disc with from and degrees specifying the lit part and the rest being shadowed internal static void DrawTwoShadedWireDisc(Vector3 position, Vector3 axis, Vector3 from, float degrees, float radius) { Handles.DrawWireArc(position, axis, from, degrees, radius); Color col = Handles.color; Color origCol = col; col.a *= backfaceAlphaMultiplier; Handles.color = col; Handles.DrawWireArc(position, axis, from, degrees - 360, radius); Handles.color = origCol; } // Sets up matrix internal static Matrix4x4 StartCapDraw(Vector3 position, Quaternion rotation, float size) { Shader.SetGlobalColor("_HandleColor", realHandleColor); Shader.SetGlobalFloat("_HandleSize", size); Matrix4x4 mat = matrix * Matrix4x4.TRS(position, rotation, Vector3.one); Shader.SetGlobalMatrix("_ObjectToWorld", mat); HandleUtility.handleMaterial.SetFloat("_HandleZTest", (float)zTest); HandleUtility.handleMaterial.SetPass(0); return mat; } // Draw a camera-facing Rectangle. Pass this into handle functions. static Vector3[] s_RectangleCapPointsCache = new Vector3[5]; internal static void RectangleCap(int controlID, Vector3 position, Quaternion rotation, Vector2 size) { if (Event.current.type != EventType.Repaint) return; Vector3 sideways = rotation * new Vector3(size.x, 0, 0); Vector3 up = rotation * new Vector3(0, size.y, 0); s_RectangleCapPointsCache[0] = position + sideways + up; s_RectangleCapPointsCache[1] = position + sideways - up; s_RectangleCapPointsCache[2] = position - sideways - up; s_RectangleCapPointsCache[3] = position - sideways + up; s_RectangleCapPointsCache[4] = position + sideways + up; Handles.DrawPolyLine(s_RectangleCapPointsCache); } // Draw a camera facing selection frame. public static void SelectionFrame(int controlID, Vector3 position, Quaternion rotation, float size) { if (Event.current.type != EventType.Repaint) return; Handles.StartCapDraw(position, rotation, size); Vector3 sideways = rotation * new Vector3(size, 0, 0); Vector3 up = rotation * new Vector3(0, size, 0); var point1 = position - sideways + up; var point2 = position + sideways + up; var point3 = position + sideways - up; var point4 = position - sideways - up; Handles.DrawLine(point1, point2); Handles.DrawLine(point2, point3); Handles.DrawLine(point3, point4); Handles.DrawLine(point4, point1); } /// *listonly* public static void DrawAAPolyLine(Color[] colors, Vector3[] points) { DoDrawAAPolyLine(colors, points, -1, null, 2, 0.75f); } /// *listonly* public static void DrawAAPolyLine(float width, Color[] colors, Vector3[] points) { DoDrawAAPolyLine(colors, points, -1, null, width, 0.75f); } /// *listonly* public static void DrawAAPolyLine(params Vector3[] points) { DoDrawAAPolyLine(null, points, -1, null, 2, 0.75f); } /// *listonly* public static void DrawAAPolyLine(float width, params Vector3[] points) { DoDrawAAPolyLine(null, points, -1, null, width, 0.75f); } /// *listonly* public static void DrawAAPolyLine(Texture2D lineTex, params Vector3[] points) { DoDrawAAPolyLine(null, points, -1, lineTex, lineTex.height / 2, 0.99f); } /// *listonly* public static void DrawAAPolyLine(float width, int actualNumberOfPoints, params Vector3[] points) { DoDrawAAPolyLine(null, points, actualNumberOfPoints, null, width, 0.75f); } // Draw anti-aliased line specified with point array and width. public static void DrawAAPolyLine(Texture2D lineTex, float width, params Vector3[] points) { DoDrawAAPolyLine(null, points, -1, lineTex, width, 0.99f); } static void DoDrawAAPolyLine(Color[] colors, Vector3[] points, int actualNumberOfPoints, Texture2D lineTex, float width, float alpha) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(zTest); Color defaultColor = new Color(1, 1, 1, alpha); Internal_DrawAAPolyLine(colors, points, defaultColor, actualNumberOfPoints, lineTex, width, matrix); } // Draw anti-aliased convex polygon specified with point array. public static void DrawAAConvexPolygon(params Vector3[] points) { DoDrawAAConvexPolygon(points, -1, 1.0f); } static void DoDrawAAConvexPolygon(Vector3[] points, int actualNumberOfPoints, float alpha) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(zTest); Color defaultColor = new Color(1, 1, 1, alpha) * color; Internal_DrawAAConvexPolygon(points, defaultColor, actualNumberOfPoints, matrix); } // Draw textured bezier line through start and end points with the given tangents. To get an anti-aliased effect use a texture that is 1x2 pixels with one transparent white pixel and one opaque white pixel. The bezier curve will be swept using this texture. public static void DrawBezier(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, Color color, Texture2D texture, float width) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(zTest); Internal_DrawBezier(startPosition, endPosition, startTangent, endTangent, color, texture, width, matrix); } // Draw the outline of a flat disc in 3D space. [ExcludeFromDocs] public static void DrawWireDisc(Vector3 center, Vector3 normal, float radius) { DrawWireDisc(center, normal, radius, 0.0f); } public static void DrawWireDisc(Vector3 center, Vector3 normal, float radius, [DefaultValue("0.0f")] float thickness) { Vector3 tangent = Vector3.Cross(normal, Vector3.up); if (tangent.sqrMagnitude < .001f) tangent = Vector3.Cross(normal, Vector3.right); DrawWireArc(center, normal, tangent, 360, radius, thickness); } private static readonly Vector3[] s_WireArcPoints = new Vector3[60]; // Draw a circular arc in 3D space. [ExcludeFromDocs] public static void DrawWireArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) { DrawWireArc(center, normal, from, angle, radius, 0.0f); } static Material SetupArcMaterial() { var mat = HandleUtility.handleArcMaterial; if (!mat.shader.isSupported) // can happen when editor is actually using OpenGL ES 2 (no instancing) return null; var col = color * lineTransparency; mat.SetFloat(kPropUseGuiClip, Camera.current ? 0.0f : 1.0f); mat.SetFloat(kPropHandleZTest, (float)zTest); mat.SetColor(kPropColor, col); mat.SetMatrix(kPropHandlesMatrix, matrix); return mat; } const int kArcSegments = 60; const int kArcSides = 8; public static void DrawWireArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius, [DefaultValue("0.0f")] float thickness) { if (Event.current.type != EventType.Repaint) return; thickness = ThicknessToPixels(thickness); var mat = SetupArcMaterial(); if (mat == null) // can't do arcs or thick lines (only on GLES2), fallback to thin arc via CPU path { SetDiscSectionPoints(s_WireArcPoints, center, normal, from, angle, radius); DrawPolyLine(s_WireArcPoints); return; } mat.SetVector(kPropArcCenterRadius, new Vector4(center.x, center.y, center.z, radius)); mat.SetVector(kPropArcNormalAngle, new Vector4(normal.x, normal.y, normal.z, angle * Mathf.Deg2Rad)); mat.SetVector(kPropArcFromCount, new Vector4(from.x, from.y, from.z, kArcSegments)); mat.SetVector(kPropArcThicknessSides, new Vector4(thickness, kArcSides, 0, 0)); mat.SetPass(0); if (thickness <= 0.0f) Graphics.DrawProceduralNow(MeshTopology.LineStrip, kArcSegments); else { var indexBuffer = HandleUtility.GetArcIndexBuffer(kArcSegments, kArcSides); Graphics.DrawProceduralNow(MeshTopology.Triangles, indexBuffer, indexBuffer.count); } } public static void DrawSolidRectangleWithOutline(Rect rectangle, Color faceColor, Color outlineColor) { Vector3[] points = { new Vector3(rectangle.xMin, rectangle.yMin, 0.0f), new Vector3(rectangle.xMax, rectangle.yMin, 0.0f), new Vector3(rectangle.xMax, rectangle.yMax, 0.0f), new Vector3(rectangle.xMin, rectangle.yMax, 0.0f) }; Handles.DrawSolidRectangleWithOutline(points, faceColor, outlineColor); } // Draw a solid outlined rectangle in 3D space. public static void DrawSolidRectangleWithOutline(Vector3[] verts, Color faceColor, Color outlineColor) { if (Event.current.type != EventType.Repaint) return; HandleUtility.ApplyWireMaterial(zTest); GL.PushMatrix(); GL.MultMatrix(matrix); // Triangles (Draw it twice to ensure render of both front and back faces) if (faceColor.a > 0) { Color col = faceColor * color; GL.Begin(GL.TRIANGLES); for (int i = 0; i < 2; i++) { GL.Color(col); GL.Vertex(verts[i * 2 + 0]); GL.Vertex(verts[i * 2 + 1]); GL.Vertex(verts[(i * 2 + 2) % 4]); GL.Vertex(verts[i * 2 + 0]); GL.Vertex(verts[(i * 2 + 2) % 4]); GL.Vertex(verts[i * 2 + 1]); } GL.End(); } // Outline if (outlineColor.a > 0) { //HandleUtility.ApplyWireMaterial (); Color col = outlineColor * color; GL.Begin(GL.LINES); GL.Color(col); for (int i = 0; i < 4; i++) { GL.Vertex(verts[i]); GL.Vertex(verts[(i + 1) % 4]); } GL.End(); } GL.PopMatrix(); } // Draw a solid flat disc in 3D space. public static void DrawSolidDisc(Vector3 center, Vector3 normal, float radius) { Vector3 tangent = Vector3.Cross(normal, Vector3.up); if (tangent.sqrMagnitude < .001f) tangent = Vector3.Cross(normal, Vector3.right); DrawSolidArc(center, normal, tangent, 360, radius); } // Draw a circular sector (pie piece) in 3D space. public static void DrawSolidArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius) { if (Event.current.type != EventType.Repaint) return; SetDiscSectionPoints(s_WireArcPoints, center, normal, from, angle, radius); Shader.SetGlobalColor("_HandleColor", color * new Color(1, 1, 1, .5f)); Shader.SetGlobalFloat("_HandleSize", 1); HandleUtility.ApplyWireMaterial(zTest); // Draw it twice to ensure backface culling doesn't hide any of the faces GL.PushMatrix(); GL.MultMatrix(matrix); GL.Begin(GL.TRIANGLES); for (int i = 1, count = s_WireArcPoints.Length; i < count; ++i) { GL.Color(color); GL.Vertex(center); GL.Vertex(s_WireArcPoints[i - 1]); GL.Vertex(s_WireArcPoints[i]); GL.Vertex(center); GL.Vertex(s_WireArcPoints[i]); GL.Vertex(s_WireArcPoints[i - 1]); } GL.End(); GL.PopMatrix(); } internal static Mesh s_CubeMesh, s_SphereMesh, s_ConeMesh, s_CylinderMesh, s_QuadMesh; internal static void Init() { if (!s_CubeMesh) { GameObject handleGo = (GameObject)EditorGUIUtility.Load("SceneView/HandlesGO.fbx"); if (!handleGo) { Debug.Log("Couldn't find SceneView/HandlesGO.fbx"); } // @TODO: temp workaround to make it not render in the scene handleGo.SetActive(false); const string k_AssertMessage = "mesh is null. A problem has occurred with `SceneView/HandlesGO.fbx`"; foreach (Transform t in handleGo.transform) { var meshFilter = t.GetComponent<MeshFilter>(); switch (t.name) { case "Cube": s_CubeMesh = meshFilter.sharedMesh; Debug.AssertFormat(s_CubeMesh != null, k_AssertMessage); break; case "Sphere": s_SphereMesh = meshFilter.sharedMesh; Debug.AssertFormat(s_SphereMesh != null, k_AssertMessage); break; case "Cone": s_ConeMesh = meshFilter.sharedMesh; Debug.AssertFormat(s_ConeMesh != null, k_AssertMessage); break; case "Cylinder": s_CylinderMesh = meshFilter.sharedMesh; Debug.AssertFormat(s_CylinderMesh != null, k_AssertMessage); break; case "Quad": s_QuadMesh = meshFilter.sharedMesh; Debug.AssertFormat(s_QuadMesh != null, k_AssertMessage); break; } } } } /// *listonly* public static void Label(Vector3 position, string text) { Label(position, EditorGUIUtility.TempContent(text), GUI.skin.label); } /// *listonly* public static void Label(Vector3 position, Texture image) { Label(position, EditorGUIUtility.TempContent(image), GUI.skin.label); } /// *listonly* public static void Label(Vector3 position, GUIContent content) { Label(position, content, GUI.skin.label); } /// *listonly* public static void Label(Vector3 position, string text, GUIStyle style) { Label(position, EditorGUIUtility.TempContent(text), style); } // Make a text label positioned in 3D space. public static void Label(Vector3 position, GUIContent content, GUIStyle style) { Vector3 screenPoint = HandleUtility.WorldToGUIPointWithDepth(position); if (screenPoint.z < 0) return; //label is behind camera Handles.BeginGUI(); GUI.Label(HandleUtility.WorldPointToSizedRect(position, content, style), content, style); Handles.EndGUI(); } // Returns actual rectangle where the camera will be rendered internal static Rect GetCameraRect(Rect position) { Rect screenRect = GUIClip.Unclip(position); Rect cameraRect = new Rect(screenRect.xMin, Screen.height - screenRect.yMax, screenRect.width, screenRect.height); return cameraRect; } // Get the size of the main playModeView window public static Vector2 GetMainGameViewSize() { return PlayModeView.GetMainPlayModeViewTargetSize(); } public static void DrawOutline(int[] parentRenderers, int[] childRenderers, Color parentNodeColor, Color childNodeColor, float fillOpacity = 0) { if(Event.current.type != EventType.Repaint) return; Internal_DrawOutline(parentNodeColor, childNodeColor, 0, parentRenderers, childRenderers, OutlineDrawMode.SelectionOutline, fillOpacity, fillOpacity); Internal_FinishDrawingCamera(Camera.current, true); } public static void DrawOutline(int[] renderers, Color color, float fillOpacity = 0) => DrawOutline(renderers, null, color, color, fillOpacity); public static void DrawOutline(Renderer[] renderers, Color parentNodeColor, Color childNodeColor, float fillOpacity = 0) { int[] parentRenderers, childRenderers; HandleUtility.FilterRendererIDs(renderers, out parentRenderers, out childRenderers); DrawOutline(parentRenderers, childRenderers, parentNodeColor, childNodeColor, fillOpacity); } public static void DrawOutline(Renderer[] renderers, Color color, float fillOpacity = 0) => DrawOutline(renderers, color, color, fillOpacity); public static void DrawOutline(GameObject[] objects, Color parentNodeColor, Color childNodeColor, float fillOpacity = 0) { int[] parentRenderers, childRenderers; HandleUtility.FilterInstanceIDs(objects, out parentRenderers, out childRenderers); DrawOutline(parentRenderers, childRenderers, parentNodeColor, childNodeColor, fillOpacity); } public static void DrawOutline(GameObject[] objects, Color color, float fillOpacity = 0) { var index = 0; var ids = new int[objects.Length]; foreach (var go in objects) if (go.TryGetComponent(out Renderer renderer)) ids[index++] = renderer.GetInstanceID(); DrawOutline(ids, null, color, color, fillOpacity); } public static void DrawOutline(List<GameObject> objects, Color parentNodeColor, Color childNodeColor, float fillOpacity = 0) { int[] parentRenderers, childRenderers; HandleUtility.FilterInstanceIDs((GameObject[])NoAllocHelpers.ExtractArrayFromList(objects), out parentRenderers, out childRenderers); DrawOutline(parentRenderers, childRenderers, parentNodeColor, childNodeColor, fillOpacity); } public static void DrawOutline(List<GameObject> objects, Color color, float fillOpacity = 0) { var index = 0; var ids = new int[objects.Count]; foreach (var go in objects) { if (go.TryGetComponent(out Renderer renderer)) ids[index++] = renderer.GetInstanceID(); } DrawOutline(ids, null, color, color, fillOpacity); } internal static void DrawOutlineOrWireframeInternal(Color parentNodeColor, Color childNodeColor, float outlineAlpha, int[] parentRenderers, int[] childRenderers, OutlineDrawMode outlineMode) { // RenderOutline will swap color.a and outlineAlpha so we reverse it here to preserve correct behavior wrt Color settings in Preferences var parentOutlineAlpha = parentNodeColor.a; var childOutlineAlpha = childNodeColor.a; parentNodeColor.a = outlineAlpha; childNodeColor.a = outlineAlpha; Internal_DrawOutline(parentNodeColor, childNodeColor, 0, parentRenderers, childRenderers, outlineMode, parentOutlineAlpha, childOutlineAlpha); } internal static void DrawSubmeshOutline(Color parentNodeColor, Color childNodeColor, float outlineAlpha, int submeshOutlineMaterialId) { int[] parentRenderers, childRenderers; HandleUtility.FilterInstanceIDs(Selection.gameObjects, out parentRenderers, out childRenderers); // RenderOutline will swap color.a and outlineAlpha so we reverse it here to preserve correct behavior wrt Color settings in Preferences var parentOutlineAlpha = parentNodeColor.a; var childOutlineAlpha = childNodeColor.a; parentNodeColor.a = outlineAlpha; childNodeColor.a = outlineAlpha; Internal_DrawOutline(parentNodeColor, childNodeColor, submeshOutlineMaterialId, parentRenderers, childRenderers, OutlineDrawMode.SelectionOutline, parentOutlineAlpha, childOutlineAlpha); Internal_FinishDrawingCamera(Camera.current, true); } // Clears the camera. public static void ClearCamera(Rect position, Camera camera) { Event evt = Event.current; if (camera.targetTexture == null) { Rect screenRect = GUIClip.Unclip(position); screenRect = EditorGUIUtility.PointsToPixels(screenRect); Rect cameraRect = new Rect(screenRect.xMin, Screen.height - screenRect.yMax, screenRect.width, screenRect.height); camera.pixelRect = cameraRect; } else { camera.rect = new Rect(0, 0, 1, 1); } if (evt.type == EventType.Repaint) Internal_ClearCamera(camera); else Internal_SetCurrentCamera(camera); } internal static void DrawCameraImpl(Rect position, Camera camera, DrawCameraMode drawMode, bool drawGrid, DrawGridParameters gridParam, bool finish, bool renderGizmos = true, bool renderSelection = true, GameObject[] filter = null ) { Event evt = Event.current; if (evt.type == EventType.Repaint) { if (camera.targetTexture == null) { Rect screenRect = GUIClip.Unclip(position); screenRect = EditorGUIUtility.PointsToPixels(screenRect); camera.pixelRect = new Rect(screenRect.xMin, Screen.height - screenRect.yMax, screenRect.width, screenRect.height); } else { camera.rect = new Rect(0, 0, 1, 1); } if (drawMode == DrawCameraMode.Normal) { RenderTexture temp = camera.targetTexture; camera.targetTexture = RenderTexture.active; camera.Render(); camera.targetTexture = temp; } else { if (drawGrid) Internal_DrawCameraWithGrid(camera, drawMode, ref gridParam, renderGizmos, renderSelection); else Internal_DrawCameraWithFilter(camera, drawMode, renderGizmos, renderSelection, filter); // VR scene cameras finish drawing with each eye render if (finish && camera.cameraType != CameraType.VR) Internal_FinishDrawingCamera(camera, renderGizmos); } } else Internal_SetCurrentCamera(camera); } // Draws a camera inside a rectangle. // It also sets up the (for now, anyways) undocumented Event.current.mouseRay and Event.current.lastMouseRay for handleutility functions. // internal static void DrawCamera(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam) { DrawCameraImpl(position, camera, drawMode, true, gridParam, true); } internal static void DrawCameraStep1(Rect position, Camera camera, DrawCameraMode drawMode, DrawGridParameters gridParam, bool drawGizmos, bool drawSelection) { DrawCameraImpl(position, camera, drawMode, true, gridParam, false, drawGizmos, drawSelection); } internal static void DrawCameraStep2(Camera camera, DrawCameraMode drawMode, bool drawGizmos) { if (Event.current.type == EventType.Repaint && drawMode != DrawCameraMode.Normal) Internal_FinishDrawingCamera(camera, drawGizmos); } // Draws a camera inside a rectangle. // It also sets up the (for now, anyways) undocumented Event.current.mouseRay and Event.current.lastMouseRay for handleutility functions. // public static void DrawCamera(Rect position, Camera camera) { DrawCamera(position, camera, DrawCameraMode.Normal); } public static void DrawCamera(Rect position, Camera camera, [DefaultValue("UnityEditor.DrawCameraMode.Normal")] DrawCameraMode drawMode) { DrawCamera(position, camera, drawMode, true); } public static void DrawCamera(Rect position, Camera camera, [DefaultValue("UnityEditor.DrawCameraMode.Normal")] DrawCameraMode drawMode, bool drawGizmos) { DrawGridParameters nullGridParam = new DrawGridParameters(); DrawCameraImpl(position, camera, drawMode, false, nullGridParam, true, drawGizmos); } internal enum CameraFilterMode { Off = 0, ShowFiltered = 1 } /// *listonly* public static void SetCamera(Camera camera) { if (Event.current == null) return; if (Event.current.type == EventType.Repaint) Internal_SetupCamera(camera); else Internal_SetCurrentCamera(camera); } // Set the current camera so all Handles and Gizmos are draw with its settings. public static void SetCamera(Rect position, Camera camera) { if (camera.targetTexture == null) { Rect screenRect = GUIClip.Unclip(position); screenRect = EditorGUIUtility.PointsToPixels(screenRect); Rect cameraRect = new Rect(screenRect.xMin, Screen.height - screenRect.yMax, screenRect.width, screenRect.height); camera.pixelRect = cameraRect; } Event evt = Event.current; if (evt.type == EventType.Repaint) Internal_SetupCamera(camera); else Internal_SetCurrentCamera(camera); } ///*listonly* public static void BeginGUI() { if (Camera.current && Event.current.type == EventType.Repaint) { GUIClip.Reapply(); } } // Begin a 2D GUI block inside the 3D handle GUI. [Obsolete("Please use BeginGUI() with GUILayout.BeginArea(position) / GUILayout.EndArea()")] public static void BeginGUI(Rect position) { GUILayout.BeginArea(position); } // End a 2D GUI block and get back to the 3D handle GUI. public static void EndGUI() { Camera cam = Camera.current; if (cam && Event.current.type == EventType.Repaint) Internal_SetupCamera(cam); } internal static void ShowSceneViewLabel(Vector3 pos, GUIContent label) { Handles.color = Color.white; Handles.zTest = UnityEngine.Rendering.CompareFunction.Always; GUIStyle style = "SC ViewAxisLabel"; style.alignment = TextAnchor.MiddleLeft; style.fixedWidth = 0; Handles.BeginGUI(); Rect rect = HandleUtility.WorldPointToSizedRect(pos, label, style); rect.x += 10; rect.y += 10; GUI.Label(rect, label, style); Handles.EndGUI(); } public static Vector3[] MakeBezierPoints(Vector3 startPosition, Vector3 endPosition, Vector3 startTangent, Vector3 endTangent, int division) { if (division < 1) throw new ArgumentOutOfRangeException("division", "Must be greater than zero"); return Internal_MakeBezierPoints(startPosition, endPosition, startTangent, endTangent, division); } public static void DrawTexture3DSDF(Texture texture, [DefaultValue("1.0f")] float stepScale = 1.0f, [DefaultValue("0.0f")] float surfaceOffset = 0.0f, [DefaultValue("null")] Gradient customColorRamp = null) { Vector3 localScale = new Vector3(matrix.GetColumn(0).magnitude, matrix.GetColumn(1).magnitude, matrix.GetColumn(2).magnitude); Texture3DPreview.PrepareSDFPreview(Texture3DPreview.Materials.SDF, texture, localScale, stepScale, surfaceOffset, customColorRamp); Texture3DPreview.Materials.SDF.SetPass(0); Graphics.DrawMeshNow(cubeMesh, matrix); } public static void DrawTexture3DSlice(Texture texture, Vector3 slicePositions, [DefaultValue("FilterMode.Bilinear")] FilterMode filterMode = FilterMode.Bilinear, [DefaultValue("false")] bool useColorRamp = false, [DefaultValue("null")] Gradient customColorRamp = null) { Vector3 localScale = new Vector3(matrix.GetColumn(0).magnitude, matrix.GetColumn(1).magnitude, matrix.GetColumn(2).magnitude); Texture3DPreview.PrepareSlicePreview(Texture3DPreview.Materials.Slice, texture, slicePositions, filterMode, useColorRamp, customColorRamp); Texture3DPreview.Materials.Slice.SetPass(0); Graphics.DrawMeshNow(cubeMesh, matrix); } public static void DrawTexture3DVolume(Texture texture, [DefaultValue("1.0f")] float opacity = 1.0f, [DefaultValue("1.0f")] float qualityModifier = 1.0f, [DefaultValue("FilterMode.Bilinear")] FilterMode filterMode = FilterMode.Bilinear, [DefaultValue("false")] bool useColorRamp = false, [DefaultValue("null")] Gradient customColorRamp = null) { Vector3 localScale = new Vector3(matrix.GetColumn(0).magnitude, matrix.GetColumn(1).magnitude, matrix.GetColumn(2).magnitude); int sampleCount = Texture3DPreview.PrepareVolumePreview(Texture3DPreview.Materials.Volume, texture, localScale, opacity, filterMode, useColorRamp, customColorRamp, Camera.current, matrix, qualityModifier); Texture3DPreview.Materials.Volume.SetPass(0); Graphics.DrawProceduralNow(MeshTopology.Quads, 4, sampleCount); } } }
UnityCsReference/Editor/Mono/Handles/Handles.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Handles/Handles.cs", "repo_id": "UnityCsReference", "token_count": 36246 }
318
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace UnityEditor { [NativeHeader("Editor/Src/HomeWindow/HomeWindow.h")] static class HomeWindow { // NOTE: Keep in sync with enum in Editor/Src/HomeWindow/HomeWindow.h public enum HomeMode { Login, License, Launching, NewProjectOnly, OpenProjectOnly, ManageLicense, Welcome, Tutorial, Logout } [NativeMethod("StaticShow")] public static extern bool Show(HomeMode mode); } }
UnityCsReference/Editor/Mono/HomeWindow.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/HomeWindow.bindings.cs", "repo_id": "UnityCsReference", "token_count": 330 }
319
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { internal class AnimationClipInfoProperties { SerializedProperty m_Property; public AnimationClipInfoProperties(SerializedProperty prop) { m_Property = prop; Editor.AssignCachedProperties(this, prop); } #pragma warning disable 0649 [CacheProperty("name")] SerializedProperty m_Name; [CacheProperty("takeName")] SerializedProperty m_TakeName; [CacheProperty("internalID")] SerializedProperty m_InternalId; [CacheProperty("firstFrame")] SerializedProperty m_FirstFrame; [CacheProperty("lastFrame")] SerializedProperty m_LastFrame; [CacheProperty("wrapMode")] SerializedProperty m_WrapMode; [CacheProperty("loop")] SerializedProperty m_Loop; [CacheProperty("orientationOffsetY")] SerializedProperty m_OrientationOffsetY; [CacheProperty("level")] SerializedProperty m_Level; [CacheProperty("cycleOffset")] SerializedProperty m_CycleOffset; [CacheProperty("additiveReferencePoseFrame")] SerializedProperty m_AdditiveReferencePoseFrame; [CacheProperty("hasAdditiveReferencePose")] SerializedProperty m_HasAdditiveReferencePose; [CacheProperty("loopTime")] SerializedProperty m_LoopTime; [CacheProperty("loopBlend")] SerializedProperty m_LoopBlend; [CacheProperty("loopBlendOrientation")] SerializedProperty m_LoopBlendOrientation; [CacheProperty("loopBlendPositionY")] SerializedProperty m_LoopBlendPositionY; [CacheProperty("loopBlendPositionXZ")] SerializedProperty m_LoopBlendPositionXZ; [CacheProperty("keepOriginalOrientation")] SerializedProperty m_KeepOriginalOrientation; [CacheProperty("keepOriginalPositionY")] SerializedProperty m_KeepOriginalPositionY; [CacheProperty("keepOriginalPositionXZ")] SerializedProperty m_KeepOriginalPositionXZ; [CacheProperty("heightFromFeet")] SerializedProperty m_HeightFromFeet; [CacheProperty("mirror")] SerializedProperty m_Mirror; [CacheProperty("maskType")] SerializedProperty m_MaskType; [CacheProperty("maskSource")] SerializedProperty m_MaskSource; [CacheProperty("bodyMask")] SerializedProperty m_BodyMask; [CacheProperty("transformMask")] SerializedProperty m_TransformMask; [CacheProperty("curves")] SerializedProperty m_Curves; [CacheProperty("events")] SerializedProperty m_Events; #pragma warning restore 0649 public string name { get { return m_Name.stringValue; } set { m_Name.stringValue = value; } } public string takeName { get { return m_TakeName.stringValue; } set { m_TakeName.stringValue = value; } } public long internalID { get { return m_InternalId.longValue; } set { m_InternalId.longValue = value; } } public float firstFrame { get { return m_FirstFrame.floatValue; } set { m_FirstFrame.floatValue = value; } } public float lastFrame { get { return m_LastFrame.floatValue; } set { m_LastFrame.floatValue = value; } } public int wrapMode { get { return m_WrapMode.intValue; } set { m_WrapMode.intValue = value; } } public bool loop { get { return m_Loop.boolValue; } set { m_Loop.boolValue = value; } } // Mecanim animation properties public float orientationOffsetY { get { return m_OrientationOffsetY.floatValue; } set { m_OrientationOffsetY.floatValue = value; } } public float level { get { return m_Level.floatValue; } set { m_Level.floatValue = value; } } public float cycleOffset { get { return m_CycleOffset.floatValue; } set { m_CycleOffset.floatValue = value; } } public float additiveReferencePoseFrame { get { return m_AdditiveReferencePoseFrame.floatValue; } set { m_AdditiveReferencePoseFrame.floatValue = value; } } public bool hasAdditiveReferencePose { get { return m_HasAdditiveReferencePose.boolValue; } set { m_HasAdditiveReferencePose.boolValue = value; } } public bool loopTime { get { return m_LoopTime.boolValue; } set { m_LoopTime.boolValue = value; } } public bool loopBlend { get { return m_LoopBlend.boolValue; } set { m_LoopBlend.boolValue = value; } } public bool loopBlendOrientation { get { return m_LoopBlendOrientation.boolValue; } set { m_LoopBlendOrientation.boolValue = value; } } public bool loopBlendPositionY { get { return m_LoopBlendPositionY.boolValue; } set { m_LoopBlendPositionY.boolValue = value; } } public bool loopBlendPositionXZ { get { return m_LoopBlendPositionXZ.boolValue; } set { m_LoopBlendPositionXZ.boolValue = value; } } public bool keepOriginalOrientation { get { return m_KeepOriginalOrientation.boolValue; } set { m_KeepOriginalOrientation.boolValue = value; } } public bool keepOriginalPositionY { get { return m_KeepOriginalPositionY.boolValue; } set { m_KeepOriginalPositionY.boolValue = value; } } public bool keepOriginalPositionXZ { get { return m_KeepOriginalPositionXZ.boolValue; } set { m_KeepOriginalPositionXZ.boolValue = value; } } public bool heightFromFeet { get { return m_HeightFromFeet.boolValue; } set { m_HeightFromFeet.boolValue = value; } } public bool mirror { get { return m_Mirror.boolValue; } set { m_Mirror.boolValue = value; } } public ClipAnimationMaskType maskType { get { return (ClipAnimationMaskType)m_MaskType.intValue; } set { m_MaskType.intValue = (int)value; } } public AvatarMask maskSource { get { return (AvatarMask)m_MaskSource.objectReferenceValue; } set { m_MaskSource.objectReferenceValue = value; } } public SerializedProperty maskTypeProperty => m_MaskType; public SerializedProperty maskSourceProperty => m_MaskSource; public SerializedProperty bodyMaskProperty => m_BodyMask; public SerializedProperty transformMaskProperty => m_TransformMask; public void ApplyModifiedProperties() { m_Property.serializedObject.ApplyModifiedProperties(); } public bool MaskNeedsUpdating() { AvatarMask mask = maskSource; if (mask == null) return false; using (SerializedObject source = new SerializedObject(mask)) { if (!SerializedProperty.DataEquals(bodyMaskProperty, source.FindProperty("m_Mask"))) return true; if (!SerializedProperty.DataEquals(transformMaskProperty, source.FindProperty("m_Elements"))) return true; } return false; } public void MaskFromClip(AvatarMask mask) { SerializedProperty bodyMask = bodyMaskProperty; if (bodyMask != null && bodyMask.isArray) { for (AvatarMaskBodyPart i = 0; i < AvatarMaskBodyPart.LastBodyPart; i++) { mask.SetHumanoidBodyPartActive(i, bodyMask.GetArrayElementAtIndex((int)i).intValue != 0); } } var transformMask = transformMaskProperty; if (transformMask != null && transformMask.isArray) { if (transformMask.arraySize > 0 && (mask.transformCount != transformMask.arraySize)) mask.transformCount = transformMask.arraySize; int size = transformMask.arraySize; if (size == 0) return; SerializedProperty prop = transformMask.GetArrayElementAtIndex(0); for (int i = 0; i < size; i++) { SerializedProperty pathProperty = prop.FindPropertyRelative("m_Path"); SerializedProperty weightProperty = prop.FindPropertyRelative("m_Weight"); mask.SetTransformPath(i, pathProperty.stringValue); mask.SetTransformActive(i, weightProperty.floatValue > 0.5); prop.Next(false); } } } public void MaskToClip(AvatarMask mask) { SerializedProperty bodyMask = bodyMaskProperty; if (bodyMask != null && bodyMask.isArray) { for (AvatarMaskBodyPart i = 0; i < AvatarMaskBodyPart.LastBodyPart; i++) { if ((int)i >= bodyMask.arraySize) bodyMask.InsertArrayElementAtIndex((int)i); bodyMask.GetArrayElementAtIndex((int)i).intValue = mask.GetHumanoidBodyPartActive(i) ? 1 : 0; } } SerializedProperty transformMask = transformMaskProperty; ModelImporter.UpdateTransformMask(mask, transformMask); } public void ClearCurves() { SerializedProperty curves = m_Curves; if (curves != null && curves.isArray) { curves.ClearArray(); } } public int GetCurveCount() { int ret = 0; SerializedProperty curves = m_Curves; if (curves != null && curves.isArray) { ret = curves.arraySize; } return ret; } public SerializedProperty GetCurveProperty(int index) { SerializedProperty ret = null; SerializedProperty curves = m_Curves; if (curves != null && curves.isArray) { ret = curves.GetArrayElementAtIndex(index).FindPropertyRelative("curve"); } return ret; } public string GetCurveName(int index) { string ret = ""; SerializedProperty curves = m_Curves; if (curves != null && curves.isArray) { ret = curves.GetArrayElementAtIndex(index).FindPropertyRelative("name").stringValue; } return ret; } public void SetCurveName(int index, string name) { SerializedProperty curves = m_Curves; if (curves != null && curves.isArray) { curves.GetArrayElementAtIndex(index).FindPropertyRelative("name").stringValue = name; } } public AnimationCurve GetCurve(int index) { AnimationCurve ret = null; SerializedProperty curve = GetCurveProperty(index); if (curve != null) { ret = curve.animationCurveValue; } return ret; } public void SetCurve(int index, AnimationCurve curveValue) { SerializedProperty curve = GetCurveProperty(index); if (curve != null) { curve.animationCurveValue = curveValue; } } public void AddCurve() { SerializedProperty curves = m_Curves; if (curves != null && curves.isArray) { curves.InsertArrayElementAtIndex(curves.arraySize); curves.GetArrayElementAtIndex(curves.arraySize - 1).FindPropertyRelative("name").stringValue = "Curve"; AnimationCurve newCurve = new AnimationCurve(new Keyframe(0, 0), new Keyframe(1, 0)); newCurve.preWrapMode = WrapMode.Default; newCurve.postWrapMode = WrapMode.Default; curves.GetArrayElementAtIndex(curves.arraySize - 1).FindPropertyRelative("curve").animationCurveValue = newCurve; } } public void RemoveCurve(int index) { SerializedProperty curves = m_Curves; if (curves != null && curves.isArray) { curves.DeleteArrayElementAtIndex(index); } } public AnimationEvent GetEvent(int index) { AnimationEvent evt = new AnimationEvent(); SerializedProperty events = m_Events; if (events != null && events.isArray) { if (index < events.arraySize) { evt.floatParameter = events.GetArrayElementAtIndex(index).FindPropertyRelative("floatParameter").floatValue; evt.functionName = events.GetArrayElementAtIndex(index).FindPropertyRelative("functionName").stringValue; evt.intParameter = events.GetArrayElementAtIndex(index).FindPropertyRelative("intParameter").intValue; evt.objectReferenceParameter = events.GetArrayElementAtIndex(index).FindPropertyRelative("objectReferenceParameter").objectReferenceValue; evt.stringParameter = events.GetArrayElementAtIndex(index).FindPropertyRelative("data").stringValue; evt.time = events.GetArrayElementAtIndex(index).FindPropertyRelative("time").floatValue; } else { Debug.LogWarning("Invalid Event Index"); } } return evt; } public void SetEvent(int index, AnimationEvent animationEvent) { SerializedProperty events = m_Events; if (events != null && events.isArray) { if (index < events.arraySize) { events.GetArrayElementAtIndex(index).FindPropertyRelative("floatParameter").floatValue = animationEvent.floatParameter; events.GetArrayElementAtIndex(index).FindPropertyRelative("functionName").stringValue = animationEvent.functionName; events.GetArrayElementAtIndex(index).FindPropertyRelative("intParameter").intValue = animationEvent.intParameter; events.GetArrayElementAtIndex(index).FindPropertyRelative("objectReferenceParameter").objectReferenceValue = animationEvent.objectReferenceParameter; events.GetArrayElementAtIndex(index).FindPropertyRelative("data").stringValue = animationEvent.stringParameter; events.GetArrayElementAtIndex(index).FindPropertyRelative("time").floatValue = animationEvent.time; } else { Debug.LogWarning("Invalid Event Index"); } } } public void ClearEvents() { SerializedProperty events = m_Events; if (events != null && events.isArray) { events.ClearArray(); } } public int GetEventCount() { int ret = 0; SerializedProperty curves = m_Events; if (curves != null && curves.isArray) { ret = curves.arraySize; } return ret; } public void AddEvent(float time) { SerializedProperty events = m_Events; if (events != null && events.isArray) { events.InsertArrayElementAtIndex(events.arraySize); events.GetArrayElementAtIndex(events.arraySize - 1).FindPropertyRelative("functionName").stringValue = "NewEvent"; events.GetArrayElementAtIndex(events.arraySize - 1).FindPropertyRelative("time").floatValue = time; } } public void RemoveEvent(int index) { SerializedProperty events = m_Events; if (events != null && events.isArray) { events.DeleteArrayElementAtIndex(index); } } public void SetEvents(AnimationEvent[] newEvents) { SerializedProperty events = m_Events; if (events != null && events.isArray) { events.ClearArray(); foreach (AnimationEvent evt in newEvents) { events.InsertArrayElementAtIndex(events.arraySize); SetEvent(events.arraySize - 1, evt); } } } public AnimationEvent[] GetEvents() { AnimationEvent[] ret = new AnimationEvent[GetEventCount()]; SerializedProperty events = m_Events; if (events != null && events.isArray) { for (int i = 0; i < GetEventCount(); ++i) { ret[i] = GetEvent(i); } } return ret; } public void AssignToPreviewClip(AnimationClip clip) { AnimationClipSettings info = new AnimationClipSettings(); info.startTime = firstFrame / clip.frameRate; info.stopTime = lastFrame / clip.frameRate; info.orientationOffsetY = orientationOffsetY; info.level = level; info.cycleOffset = cycleOffset; info.loopTime = loopTime; info.loopBlend = loopBlend; info.loopBlendOrientation = loopBlendOrientation; info.loopBlendPositionY = loopBlendPositionY; info.loopBlendPositionXZ = loopBlendPositionXZ; info.keepOriginalOrientation = keepOriginalOrientation; info.keepOriginalPositionY = keepOriginalPositionY; info.keepOriginalPositionXZ = keepOriginalPositionXZ; info.heightFromFeet = heightFromFeet; info.mirror = mirror; info.hasAdditiveReferencePose = hasAdditiveReferencePose; info.additiveReferencePoseTime = additiveReferencePoseFrame / clip.frameRate; AnimationUtility.SetAnimationClipSettingsNoDirty(clip, info); } private float FixPrecisionErrors(float f) { float rounded = Mathf.Round(f); if (Mathf.Abs(f - rounded) < 0.0001f) return rounded; return f; } public void ExtractFromPreviewClip(AnimationClip clip) { AnimationClipSettings info = AnimationUtility.GetAnimationClipSettings(clip); // Ensure that we don't accidentally dirty settings due to floating point precision in the multiply / divide if (firstFrame / clip.frameRate != info.startTime) firstFrame = FixPrecisionErrors(info.startTime * clip.frameRate); if (lastFrame / clip.frameRate != info.stopTime) lastFrame = FixPrecisionErrors(info.stopTime * clip.frameRate); orientationOffsetY = info.orientationOffsetY; level = info.level; cycleOffset = info.cycleOffset; loopTime = info.loopTime; loopBlend = info.loopBlend; loopBlendOrientation = info.loopBlendOrientation; loopBlendPositionY = info.loopBlendPositionY; loopBlendPositionXZ = info.loopBlendPositionXZ; keepOriginalOrientation = info.keepOriginalOrientation; keepOriginalPositionY = info.keepOriginalPositionY; keepOriginalPositionXZ = info.keepOriginalPositionXZ; heightFromFeet = info.heightFromFeet; mirror = info.mirror; hasAdditiveReferencePose = info.hasAdditiveReferencePose; if (additiveReferencePoseFrame / clip.frameRate != info.additiveReferencePoseTime) additiveReferencePoseFrame = FixPrecisionErrors(info.additiveReferencePoseTime * clip.frameRate); } } }
UnityCsReference/Editor/Mono/ImportSettings/AnimationClipInfoProperties.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ImportSettings/AnimationClipInfoProperties.cs", "repo_id": "UnityCsReference", "token_count": 9293 }
320
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections; using System.Collections.Generic; using UnityEditorInternal; using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(Animation))] [CanEditMultipleObjects] internal class AnimationEditor : Editor { private int m_PrePreviewAnimationArraySize = -1; public void OnEnable() { m_PrePreviewAnimationArraySize = -1; } public override void OnInspectorGUI() { serializedObject.Update(); SerializedProperty clipProperty = serializedObject.FindProperty("m_Animation"); EditorGUILayout.PropertyField(clipProperty, true); int newAnimID = clipProperty.objectReferenceInstanceIDValue; SerializedProperty arrProperty = serializedObject.FindProperty("m_Animations"); int arrSize = arrProperty.arraySize; // Remember the array size when ObjectSelector becomes visible if (ObjectSelector.isVisible && m_PrePreviewAnimationArraySize == -1) m_PrePreviewAnimationArraySize = arrSize; // Make sure the array is the original array size + 1 at max (+1 for the ObjectSelector preview slot) if (m_PrePreviewAnimationArraySize != -1) { // Always resize if the last anim element is not the current animation int lastAnimID = arrSize > 0 ? arrProperty.GetArrayElementAtIndex(arrSize - 1).objectReferenceInstanceIDValue : -1; if (lastAnimID != newAnimID) arrProperty.arraySize = m_PrePreviewAnimationArraySize; if (!ObjectSelector.isVisible) m_PrePreviewAnimationArraySize = -1; } DrawPropertiesExcluding(serializedObject, "m_Animation", "m_UserAABB"); serializedObject.ApplyModifiedProperties(); } // A minimal list of settings to be shown in the Asset Store preview inspector internal override void OnAssetStoreInspectorGUI() { OnInspectorGUI(); } } }
UnityCsReference/Editor/Mono/Inspector/AnimationEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/AnimationEditor.cs", "repo_id": "UnityCsReference", "token_count": 887 }
321
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Audio; using UnityEngine.UIElements; namespace UnityEditor; [CustomEditor(typeof(AudioRandomContainer))] [CanEditMultipleObjects] sealed class AudioRandomContainerInspector : Editor { private StyleLength margin = 5; private Button button; public override VisualElement CreateInspectorGUI() { button = new Button(); button.text = "Edit Audio Random Container"; button.style.marginBottom = margin; button.style.marginTop = margin; button.style.marginLeft = 0; button.style.marginRight = 0; button.style.height = 24; button.clicked += () => { EditorWindow.GetWindow<AudioContainerWindow>(); }; return button; } }
UnityCsReference/Editor/Mono/Inspector/AudioRandomContainerInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/AudioRandomContainerInspector.cs", "repo_id": "UnityCsReference", "token_count": 315 }
322
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEditor; using UnityEditorInternal; using System.Reflection; using Object = UnityEngine.Object; namespace UnityEditor { internal class AvatarPreviewSelection : ScriptableSingleton<AvatarPreviewSelection> { [SerializeField] GameObject[] m_PreviewModels; void Awake() { int length = (int)ModelImporterAnimationType.Human + 1; if (m_PreviewModels == null || m_PreviewModels.Length != length) m_PreviewModels = new GameObject[length]; } static public void SetPreview(ModelImporterAnimationType type, GameObject go) { if (!System.Enum.IsDefined(typeof(ModelImporterAnimationType), type)) return; if (instance.m_PreviewModels[(int)type] != go) { instance.m_PreviewModels[(int)type] = go; instance.Save(false); } } static public GameObject GetPreview(ModelImporterAnimationType type) { if (!System.Enum.IsDefined(typeof(ModelImporterAnimationType), type)) return null; return instance.m_PreviewModels[(int)type]; } } // class AvatarPreviewSelection } // namespace UnityEditor
UnityCsReference/Editor/Mono/Inspector/AvatarPreviewSelection.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/AvatarPreviewSelection.cs", "repo_id": "UnityCsReference", "token_count": 601 }
323
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.CodeDom; using System.Collections.Generic; using System.Linq; using UnityEditor.IMGUI.Controls; namespace UnityEditor.AddComponent { internal class AddComponentDataSource : AdvancedDropdownDataSource { private static readonly string kSearchHeader = L10n.Tr("Search"); AdvancedDropdownState m_State; UnityEngine.GameObject[] m_Targets; internal static readonly string kScriptHeader = "Component/Scripts/"; public AddComponentDataSource(AdvancedDropdownState state, UnityEngine.GameObject[] targets) { m_State = state; m_Targets = targets; } protected override AdvancedDropdownItem FetchData() { return RebuildTree(); } struct MenuItemData { public string path; public string command; public bool isLegacy; } protected AdvancedDropdownItem RebuildTree() { m_SearchableElements = new List<AdvancedDropdownItem>(); AdvancedDropdownItem root = new ComponentDropdownItem("ROOT"); List<MenuItemData> menuItems = GetSortedMenuItems(m_Targets); Dictionary<string, int> pathHashCodeMap = new Dictionary<string, int>(); for (var i = 0; i < menuItems.Count; i++) { var menu = menuItems[i]; if (menu.command == "ADD") { continue; } var paths = menu.path.Split('/'); var parent = root; for (var j = 0; j < paths.Length; j++) { var path = paths[j]; if (j == paths.Length - 1) { var element = new ComponentDropdownItem(path, L10n.Tr(path), menu.path, menu.command, menu.isLegacy); parent.AddChild(element); m_SearchableElements.Add(element); continue; } if (!pathHashCodeMap.TryGetValue(path, out int pathHashCode)) { pathHashCode = path.GetHashCode(); pathHashCodeMap[path] = pathHashCode; } var group = (ComponentDropdownItem)parent.children.SingleOrDefault(c => c.id == pathHashCode); if (group == null) { group = new ComponentDropdownItem(path, L10n.Tr(path)); parent.AddChild(group); } parent = group; } } root = root.children.Single(); var newScript = new ComponentDropdownItem("New script", L10n.Tr("New script")); newScript.AddChild(new NewScriptDropdownItem()); root.AddChild(newScript); return root; } static List<MenuItemData> GetSortedMenuItems(UnityEngine.GameObject[] targets) { var menus = Unsupported.GetSubmenus("Component"); var commands = Unsupported.GetSubmenusCommands("Component"); var menuItems = new List<MenuItemData>(menus.Length); var legacyMenuItems = new List<MenuItemData>(menus.Length); const string kLegacyString = "legacy"; var hasFilterOverride = ModeService.HasExecuteHandler("inspector_filter_component"); for (var i = 0; i < menus.Length; i++) { var menuPath = menus[i]; bool isLegacy = menuPath.ToLower().Contains(kLegacyString); var item = new MenuItemData { path = menuPath, command = commands[i], isLegacy = isLegacy }; if (!hasFilterOverride || ModeService.Execute("inspector_filter_component", targets, menuPath)) { if (isLegacy) { legacyMenuItems.Add(item); } else { menuItems.Add(item); } } } int comparison(MenuItemData x, MenuItemData y) => string.CompareOrdinal(x.path, y.path); menuItems.Sort(comparison); legacyMenuItems.Sort(comparison); menuItems.AddRange(legacyMenuItems); return menuItems; } protected override AdvancedDropdownItem Search(string searchString) { if (string.IsNullOrEmpty(searchString) || m_SearchableElements == null) return null; // Support multiple search words separated by spaces. var searchWords = searchString.ToLower().Split(' '); // We keep two lists. Matches that matches the start of an item always get first priority. var matchesStart = new List<AdvancedDropdownItem>(); var matchesWithin = new List<AdvancedDropdownItem>(); bool found = false; foreach (var e in m_SearchableElements) { var addComponentItem = (ComponentDropdownItem)e; string name; if (addComponentItem.menuPath.StartsWith(kScriptHeader)) name = addComponentItem.menuPath.Remove(0, kScriptHeader.Length).ToLower().Replace(" ", ""); else name = addComponentItem.searchableName.ToLower().Replace(" ", ""); if (AddMatchItem(e, name, searchWords, matchesStart, matchesWithin)) found = true; } if (!found) { foreach (var e in m_SearchableElements) { var addComponentItem = (ComponentDropdownItem)e; var name = addComponentItem.searchableNameLocalized.Replace(" ", ""); AddMatchItem(e, name, searchWords, matchesStart, matchesWithin); } } var searchTree = new AdvancedDropdownItem(kSearchHeader); matchesStart.Sort(); foreach (var element in matchesStart) { searchTree.AddChild(element); } matchesWithin.Sort(); foreach (var element in matchesWithin) { searchTree.AddChild(element); } if (searchTree != null) { var addNewScriptGroup = new ComponentDropdownItem("New script", L10n.Tr("New script")); m_State.SetSelectedIndex(addNewScriptGroup, 0); var addNewScript = new NewScriptDropdownItem(); addNewScript.className = searchString; addNewScriptGroup.AddChild(addNewScript); searchTree.AddChild(addNewScriptGroup); } return searchTree; } } }
UnityCsReference/Editor/Mono/Inspector/Core/AddComponent/AddComponentDataSource.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/AddComponent/AddComponentDataSource.cs", "repo_id": "UnityCsReference", "token_count": 3613 }
324
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor { internal static partial class StatelessAdvancedDropdown { private static AdvancedDropdownWindow s_Instance; private static EditorWindow s_ParentWindow; private static bool m_WindowClosed; private static bool m_ShouldReturnValue; private static int m_Result; private static int s_CurrentControl; private static MultiselectDataSource s_DataSource; private static void ResetAndCreateWindow() { if (s_Instance != null) { s_Instance.Close(); s_Instance = null; } s_ParentWindow = EditorWindow.focusedWindow; s_Instance = ScriptableObject.CreateInstance<AdvancedDropdownWindow>(); m_WindowClosed = false; } private static void InitSearchableWindow(Rect rect, string label, int selectedIndex, string[] displayedOptions) { var dataSource = new MultiLevelDataSource(); dataSource.displayedOptions = displayedOptions; dataSource.selectedIndex = selectedIndex; dataSource.label = label; s_Instance.dataSource = dataSource; s_Instance.windowClosed += (w) => { if (s_ParentWindow != null) s_ParentWindow.Repaint(); }; s_Instance.Init(rect); } private static void InitPopupWindow(Rect rect, int selectedIndex, GUIContent[] displayedOptions) { var dataSource = new SimpleDataSource(); dataSource.displayedOptions = displayedOptions; dataSource.selectedIndex = selectedIndex; s_Instance.dataSource = dataSource; s_Instance.searchable = false; s_Instance.showHeader = false; s_Instance.selectionChanged += (w) => { if (s_ParentWindow != null) s_ParentWindow.Repaint(); }; s_Instance.Init(rect); } private static void InitMultiselectPopupWindow(Rect rect, MultiselectDataSource dataSource) { s_DataSource = dataSource; s_Instance.dataSource = dataSource; s_Instance.showHeader = false; s_Instance.searchable = false; s_Instance.closeOnSelection = false; s_Instance.selectionChanged += (w) => { if (s_ParentWindow != null) s_ParentWindow.Repaint(); }; s_Instance.Init(rect); } internal static int DoSearchablePopup(Rect rect, int selectedIndex, string[] displayedOptions, GUIStyle style) { string contentLabel = ""; if (selectedIndex >= 0) { contentLabel = displayedOptions[selectedIndex]; } var content = new GUIContent(contentLabel); int id = EditorGUIUtility.GetControlID("AdvancedDropdown".GetHashCode(), FocusType.Keyboard, rect); if (EditorGUI.DropdownButton(id, rect, content, style)) { s_CurrentControl = id; ResetAndCreateWindow(); InitSearchableWindow(rect, content.text, selectedIndex, displayedOptions); s_Instance.windowClosed += w => { m_Result = w.GetSelectedItem().elementIndex; m_WindowClosed = true; }; } if (m_WindowClosed && s_CurrentControl == id) { s_CurrentControl = 0; m_WindowClosed = false; return m_Result; } return selectedIndex; } internal static int DoLazySearchablePopup(Rect rect, string selectedOption, int selectedIndex, Func<Tuple<int, string[]>> displayedOptionsFunc, GUIStyle style) { var content = new GUIContent(selectedOption); int id = EditorGUIUtility.GetControlID("AdvancedDropdown".GetHashCode(), FocusType.Keyboard, rect); if (EditorGUI.DropdownButton(id, rect, content, style)) { s_CurrentControl = id; ResetAndCreateWindow(); var displayData = displayedOptionsFunc.Invoke(); InitSearchableWindow(rect, content.text, displayData.Item1, displayData.Item2); s_Instance.windowClosed += w => { m_Result = w.GetSelectedItem().elementIndex; m_WindowClosed = true; }; } if (m_WindowClosed && s_CurrentControl == id) { s_CurrentControl = 0; m_WindowClosed = false; return m_Result; } return selectedIndex; } public static int DoPopup(Rect rect, int selectedIndex, GUIContent[] displayedOptions) { GUIContent content = GUIContent.none; if (selectedIndex >= 0 && selectedIndex < displayedOptions.Length) content = displayedOptions[selectedIndex]; int id = EditorGUIUtility.GetControlID("AdvancedDropdown".GetHashCode(), FocusType.Keyboard, rect); if (EditorGUI.DropdownButton(id, rect, content, EditorStyles.popup)) { s_CurrentControl = id; ResetAndCreateWindow(); InitPopupWindow(rect, selectedIndex, displayedOptions); s_Instance.windowClosed += w => { m_Result = w.GetSelectedItem().elementIndex; m_WindowClosed = true; }; GUIUtility.ExitGUI(); } if (m_WindowClosed && s_CurrentControl == id) { s_CurrentControl = 0; m_WindowClosed = false; return m_Result; } return selectedIndex; } public static Enum DoEnumMaskPopup(Rect rect, Enum options, GUIStyle style) { var enumData = EnumDataUtility.GetCachedEnumData(options.GetType()); var optionValue = EnumDataUtility.EnumFlagsToInt(enumData, options); MaskFieldGUI.GetMenuOptions(optionValue, enumData.displayNames, enumData.flagValues, out var buttonText, out var buttonTextMixed, out _, out _, out _); var id = EditorGUIUtility.GetControlID("AdvancedDropdown".GetHashCode(), FocusType.Keyboard, rect); var buttonContent = MaskFieldGUI.DoMixedLabel(buttonText, buttonTextMixed, rect, EditorStyles.popup); if (EditorGUI.DropdownButton(id, rect, buttonContent, EditorStyles.popup)) { s_CurrentControl = id; ResetAndCreateWindow(); var dataSource = new MultiselectDataSource(options); InitMultiselectPopupWindow(rect, dataSource); s_Instance.selectionChanged += dataSource.UpdateSelectedId; s_Instance.selectionChanged += i => { m_ShouldReturnValue = true; }; s_Instance.windowClosed += w => { m_WindowClosed = true; }; } if (m_ShouldReturnValue && s_CurrentControl == id) { m_ShouldReturnValue = false; return s_DataSource.enumFlags; } if (m_WindowClosed && s_CurrentControl == id) { s_CurrentControl = 0; m_WindowClosed = false; var result = s_DataSource.enumFlags; s_DataSource = null; return result; } return options; } private static Enum DoEnumPopup(Rect rect, Enum selected, GUIStyle style, params GUILayoutOption[] options) { var enumType = selected.GetType(); var enumData = EnumDataUtility.GetCachedEnumData(enumType); var i = Array.IndexOf(enumData.values, selected); using (new LocalizationGroup(enumType)) { i = DoPopup(rect, i, EditorGUIUtility.TrTempContent(enumData.displayNames, enumData.tooltip)); } return (i < 0 || i >= enumData.flagValues.Length) ? selected : enumData.values[i]; } private static int DoIntPopup(Rect rect, int selectedValue, string[] displayedOptions, int[] optionValues) { var idx = Array.IndexOf(optionValues, selectedValue); var returnedValue = DoPopup(rect, idx, EditorGUIUtility.TempContent(displayedOptions)); return returnedValue >= 0 ? optionValues[returnedValue] : returnedValue; } static int DoMaskField(Rect rect, int mask, string[] displayedOptions, GUIStyle popup) { var flagValues = new int[displayedOptions.Length]; for (int i = 0; i < flagValues.Length; ++i) flagValues[i] = (1 << i); MaskFieldGUI.GetMenuOptions(mask, displayedOptions, flagValues, out var buttonText, out var buttonTextMixed, out _, out _, out _); var id = EditorGUIUtility.GetControlID("AdvancedDropdown".GetHashCode(), FocusType.Keyboard, rect); var buttonContent = MaskFieldGUI.DoMixedLabel(buttonText, buttonTextMixed, rect, EditorStyles.popup); if (EditorGUI.DropdownButton(id, rect, buttonContent, EditorStyles.popup)) { s_CurrentControl = id; ResetAndCreateWindow(); var dataSource = new MultiselectDataSource(mask, displayedOptions, flagValues); InitMultiselectPopupWindow(rect, dataSource); s_Instance.selectionChanged += dataSource.UpdateSelectedId; s_Instance.selectionChanged += i => { m_ShouldReturnValue = true; }; s_Instance.windowClosed += w => { m_WindowClosed = true; }; } if (m_ShouldReturnValue && s_CurrentControl == id) { m_ShouldReturnValue = false; return s_DataSource.mask; } if (m_WindowClosed && s_CurrentControl == id) { s_CurrentControl = 0; m_WindowClosed = false; var result = s_DataSource.mask; s_DataSource = null; return result; } return mask; } } }
UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/EditorGUI/StatelessAdvancedDropdown.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/AdvancedDropdown/EditorGUI/StatelessAdvancedDropdown.cs", "repo_id": "UnityCsReference", "token_count": 5243 }
325
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Reflection; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor { // Base class to derive custom property drawers from. Use this to create custom drawers // for your own [[Serializable]] classes or for script variables with custom [[PropertyAttribute]]s. public abstract class PropertyDrawer : GUIDrawer { internal PropertyAttribute m_Attribute; internal FieldInfo m_FieldInfo; internal string m_PreferredLabel; // The [[PropertyAttribute]] for the property. Not applicable for custom class drawers. (RO) public PropertyAttribute attribute { get { return m_Attribute; } } // The reflection FieldInfo for the member this property represents. (RO) public FieldInfo fieldInfo { get { return m_FieldInfo; } } // The preferred label for this property. public string preferredLabel => m_PreferredLabel; internal void OnGUISafe(Rect position, SerializedProperty property, GUIContent label) { ScriptAttributeUtility.s_DrawerStack.Push(this); OnGUI(position, property, label); ScriptAttributeUtility.s_DrawerStack.TryPop(out _); } // Override this method to make your own GUI for the property based on IMGUI. public virtual void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var labelCopy = new GUIContent(label); EditorGUI.LabelField(position, labelCopy, EditorGUIUtility.TempContent("No GUI Implemented")); } // Override this method to make your own GUI for the property based on UIElements. public virtual VisualElement CreatePropertyGUI(SerializedProperty property) { return null; } internal float GetPropertyHeightSafe(SerializedProperty property, GUIContent label) { ScriptAttributeUtility.s_DrawerStack.Push(this); float height = GetPropertyHeight(property, label); ScriptAttributeUtility.s_DrawerStack.TryPop(out _); return height; } // Override this method to specify how tall the GUI for this field is in pixels. public virtual float GetPropertyHeight(SerializedProperty property, GUIContent label) { return EditorGUI.kSingleLineHeight; } [Obsolete("CanCacheInspectorGUI has been deprecated and is no longer used.", false)] public virtual bool CanCacheInspectorGUI(SerializedProperty property) { return true; } } }
UnityCsReference/Editor/Mono/Inspector/Core/ScriptAttributeGUI/PropertyDrawer.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Core/ScriptAttributeGUI/PropertyDrawer.cs", "repo_id": "UnityCsReference", "token_count": 980 }
326
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using UnityEditor.AssetImporters; using UnityEngine; using UnityEngine.Internal; using UnityEngine.Rendering; using UnityEngine.Scripting; using UnityEngine.UIElements; using Component = UnityEngine.Component; using UnityObject = UnityEngine.Object; namespace UnityEditor { interface IPreviewable { void Initialize(UnityObject[] targets); void Cleanup(); UnityObject target { get; } bool MoveNextTarget(); void ResetTarget(); bool HasPreviewGUI(); GUIContent GetPreviewTitle(); void DrawPreview(Rect previewArea); VisualElement CreatePreview(VisualElement container); void OnPreviewGUI(Rect r, GUIStyle background); void OnInteractivePreviewGUI(Rect r, GUIStyle background); void OnPreviewSettings(); string GetInfoString(); void ReloadPreviewInstances(); } public class ObjectPreview : IPreviewable { static class Styles { public static readonly GUIStyle preBackground = "PreBackground"; public static readonly GUIStyle preBackgroundSolid = "PreBackgroundSolid"; public static readonly GUIStyle previewMiniLabel = "PreMiniLabel"; public static readonly GUIStyle dropShadowLabelStyle = "PreOverlayLabel"; } const int kPreviewLabelHeight = 12; const int kPreviewMinSize = 55; const int kGridTargetCount = 25; const int kGridSpacing = 10; const int kPreviewLabelPadding = 5; protected UnityObject[] m_Targets; protected int m_ReferenceTargetIndex; ~ObjectPreview() { // Watch out for Editor classes implementing OnDisableINTERNAL and not calling cleanup (GenericInspector). Debug.LogError($"{this} was not disposed properly. Make sure that base.Cleanup is called if overriding " + $"the Cleanup method. If you are implementing this in an Editor or EditorWindow, don't " + $"forget to call ObjectPreview.Cleanup in OnDisable."); } public virtual void Cleanup() { GC.SuppressFinalize(this); } public virtual void Initialize(UnityObject[] targets) { m_ReferenceTargetIndex = 0; m_Targets = targets; } public virtual bool MoveNextTarget() { m_ReferenceTargetIndex++; return (m_ReferenceTargetIndex < m_Targets.Length - 1); } public virtual void ResetTarget() { m_ReferenceTargetIndex = 0; } public virtual UnityObject target { get { return m_Targets[m_ReferenceTargetIndex]; } } public virtual bool HasPreviewGUI() { return false; } public virtual VisualElement CreatePreview(VisualElement inspectorPreviewWindow) { return null; } public virtual GUIContent GetPreviewTitle() { GUIContent guiContent = new GUIContent(); guiContent.text = GetPreviewTitleString(); return guiContent; } string GetPreviewTitleString() { string title = String.Empty; if (m_Targets.Length == 1) title = target.name; else { title = m_Targets.Length + " "; if (NativeClassExtensionUtilities.ExtendsANativeType(target)) title += MonoScript.FromScriptedObject(target).GetClass().Name; else title += ObjectNames.NicifyVariableName(ObjectNames.GetClassName(target)); title += "s"; } return title; } public virtual void OnPreviewGUI(Rect r, GUIStyle background) { if (Event.current.type == EventType.Repaint) background.Draw(r, false, false, false, false); } public virtual void OnInteractivePreviewGUI(Rect r, GUIStyle background) { OnPreviewGUI(r, background); } public virtual void OnPreviewSettings() { } public virtual string GetInfoString() { return ""; } public void DrawPreview(Rect previewArea) { DrawPreview(this, previewArea, m_Targets); } public virtual void ReloadPreviewInstances() { } internal static void DrawPreview(IPreviewable defaultPreview, Rect previewArea, UnityObject[] targets) { string text = string.Empty; Event evt = Event.current; // If multiple targets, draw a grid of previews if (targets.Length > 1) { // Draw the previews inside the region of the background that's solid colored Rect previewPositionInner = new RectOffset(16, 16, 20, 25).Remove(previewArea); // Number of previews to aim at int maxRows = Mathf.Max(1, Mathf.FloorToInt((previewPositionInner.height + kGridSpacing) / (kPreviewMinSize + kGridSpacing + kPreviewLabelHeight))); int maxCols = Mathf.Max(1, Mathf.FloorToInt((previewPositionInner.width + kGridSpacing) / (kPreviewMinSize + kGridSpacing))); int countWithMinimumSize = maxRows * maxCols; int neededCount = Mathf.Min(targets.Length, kGridTargetCount); // Get number of columns and rows bool fixedSize = true; int[] division = new int[2] { maxCols, maxRows }; if (neededCount < countWithMinimumSize) { division = GetGridDivision(previewPositionInner, neededCount, kPreviewLabelHeight); fixedSize = false; } // The available cells in the grid may be slightly higher than what was aimed at. // If the number of targets is also higher, we might as well fill in the remaining cells. int count = Mathf.Min(division[0] * division[1], targets.Length); // Calculations become simpler if we add one spacing to the width and height, // so there is the same number of spaces and previews. previewPositionInner.width += kGridSpacing; previewPositionInner.height += kGridSpacing; Vector2 cellSize = new Vector2( Mathf.FloorToInt(previewPositionInner.width / division[0] - kGridSpacing), Mathf.FloorToInt(previewPositionInner.height / division[1] - kGridSpacing) ); float previewSize = Mathf.Min(cellSize.x, cellSize.y - kPreviewLabelHeight); if (fixedSize) previewSize = Mathf.Min(previewSize, kPreviewMinSize); bool selectingOne = (evt.type == EventType.MouseDown && evt.button == 0 && evt.clickCount == 2 && previewArea.Contains(evt.mousePosition)); defaultPreview.ResetTarget(); for (int i = 0; i < count; i++) { Rect r = new Rect( previewPositionInner.x + (i % division[0]) * previewPositionInner.width / division[0], previewPositionInner.y + (i / division[0]) * previewPositionInner.height / division[1], cellSize.x, cellSize.y ); if (selectingOne && r.Contains(Event.current.mousePosition)) { if (defaultPreview.target is AssetImporter) // The new selection should be the asset itself, not the importer Selection.objects = new[] { AssetDatabase.LoadAssetAtPath<UnityObject>(((AssetImporter)defaultPreview.target).assetPath)}; else Selection.objects = new UnityObject[] {defaultPreview.target}; } // Make room for label underneath r.height -= kPreviewLabelHeight; // Make preview square Rect rSquare = new Rect(r.x + (r.width - previewSize) * 0.5f, r.y + (r.height - previewSize) * 0.5f, previewSize, previewSize); // Draw preview inside a group to prevent overdraw // @TODO: Make style with solid color that doesn't have overdraw GUI.BeginGroup(rSquare); Editor.m_AllowMultiObjectAccess = false; defaultPreview.OnInteractivePreviewGUI(new Rect(0, 0, previewSize, previewSize), Styles.preBackgroundSolid); Editor.m_AllowMultiObjectAccess = true; GUI.EndGroup(); // Draw the name of the object r.y = rSquare.yMax; r.height = 16; GUI.Label(r, targets[i].name, Styles.previewMiniLabel); defaultPreview.MoveNextTarget(); } defaultPreview.ResetTarget(); // Remember to reset referenceTargetIndex to prevent following calls to 'editor.target' will return a different target which breaks all sorts of places. Fix for case 600235 if (Event.current.type == EventType.Repaint) text = string.Format("Previewing {0} of {1} Objects", count, targets.Length); } // If only a single target, just draw that one else { defaultPreview.OnInteractivePreviewGUI(previewArea, Styles.preBackground); if (Event.current.type == EventType.Repaint) { // TODO: This should probably be calculated during import and stored together with the asset somehow. Or maybe not. Not sure, really... text = defaultPreview.GetInfoString(); if (text != string.Empty) { text = text.Replace("\n", " "); text = string.Format("{0}\n{1}", defaultPreview.target.name, text); } } } // Draw the asset info. if (Event.current.type == EventType.Repaint && text != string.Empty) { var textHeight = Styles.dropShadowLabelStyle.CalcHeight(GUIContent.Temp(text), previewArea.width); EditorGUI.DropShadowLabel(new Rect(previewArea.x, previewArea.yMax - textHeight - kPreviewLabelPadding, previewArea.width, textHeight), text); } } // Get the number or columns and rows for a grid with a certain minimum number of cells // such that the cells are as close to square as possible. private static int[] GetGridDivision(Rect rect, int minimumNr, int labelHeight) { // The edge size of a square calculated based on area float approxSize = Mathf.Sqrt(rect.width * rect.height / minimumNr); int xCount = Mathf.FloorToInt(rect.width / approxSize); int yCount = Mathf.FloorToInt(rect.height / (approxSize + labelHeight)); // This heuristic is not entirely optimal and could probably be improved while (xCount * yCount < minimumNr) { float ratioIfXInc = AbsRatioDiff((xCount + 1) / rect.width, yCount / (rect.height - yCount * labelHeight)); float ratioIfYInc = AbsRatioDiff(xCount / rect.width, (yCount + 1) / (rect.height - (yCount + 1) * labelHeight)); if (ratioIfXInc < ratioIfYInc) { xCount++; if (xCount * yCount > minimumNr) yCount = Mathf.CeilToInt((float)minimumNr / xCount); } else { yCount++; if (xCount * yCount > minimumNr) xCount = Mathf.CeilToInt((float)minimumNr / yCount); } } return new int[] { xCount, yCount }; } private static float AbsRatioDiff(float x, float y) { return Mathf.Max(x / y, y / x); } } internal interface IToolModeOwner { bool areToolModesAvailable { get; } int GetInstanceID(); Bounds GetWorldBoundsOfTargets(); bool ModeSurvivesSelectionChange(int toolMode); } [Obsolete(@"CustomEditorForRenderPipelineAttribute is deprecated. Use CustomEditor with SupportedOnCurrentPipeline instead. #from(2023.1)", false)] [AttributeUsage(AttributeTargets.Class)] public class CustomEditorForRenderPipelineAttribute : CustomEditor { internal Type renderPipelineType; public CustomEditorForRenderPipelineAttribute(Type inspectedType, Type renderPipeline) : base(inspectedType) { if (renderPipeline != null && !typeof(RenderPipelineAsset).IsAssignableFrom(renderPipeline)) Debug.LogError($"The CustomEditorForRenderPipeline Attribute targets an invalid RenderPipelineAsset. {renderPipeline} cannot be assigned from RenderPipelineAsset."); renderPipelineType = renderPipeline; } public CustomEditorForRenderPipelineAttribute(Type inspectedType, Type renderPipeline, bool editorForChildClasses) : base(inspectedType, editorForChildClasses) { if (renderPipeline != null && !typeof(RenderPipelineAsset).IsAssignableFrom(renderPipeline)) Debug.LogError($"The CustomEditorForRenderPipeline Attribute targets an invalid RenderPipelineAsset. {renderPipeline} cannot be assigned from RenderPipelineAsset."); renderPipelineType = renderPipeline; } } public sealed partial class CanEditMultipleObjects : System.Attribute {} [AttributeUsage(AttributeTargets.Field)] internal sealed class CachePropertyAttribute : System.Attribute { public string propertyPath { get; } public CachePropertyAttribute() { propertyPath = null; } public CachePropertyAttribute(string propertyPath) { this.propertyPath = propertyPath; } } internal interface ICoupledEditor { SerializedObject coupledComponent { get; } } // Base class to derive custom Editors from. Use this to create your own custom inspectors and editors for your objects. [ExcludeFromObjectFactory] public partial class Editor : ScriptableObject, IPreviewable, IToolModeOwner { //If you modify the members of the Editor class, please keep in mind //that you need to keep the c++ struct MonoInspectorData in sync. //Last time this struct could be found at: Editor\src\Utility\CreateEditor.cpp // The object currently inspected by this editor. UnityObject[] m_Targets; // The context object with which this Editor was created internal UnityObject m_Context; // Note that m_Dirty is not only set through 'isInspectorDirty' but also from C++ in 'SetCustomEditorIsDirty (MonoBehaviour* inspector, bool dirty)' int m_IsDirty; int m_ReferenceTargetIndex = 0; readonly PropertyHandlerCache m_PropertyHandlerCache = new PropertyHandlerCache(); internal IPreviewable m_DummyPreview; AudioFilterGUI m_AudioFilterGUI; internal SerializedObject m_SerializedObject = null; internal SerializedProperty m_EnabledProperty = null; private InspectorMode m_InspectorMode = InspectorMode.Normal; internal InspectorMode inspectorMode { get { return propertyViewer?.inspectorMode ?? m_InspectorMode; } set { if (m_InspectorMode != value) { m_InspectorMode = value; m_SerializedObject = null; m_EnabledProperty = null; } } } internal DataMode dataMode => propertyViewer is EditorWindow editorWindow ? editorWindow.dataModeController.dataMode : DataMode.Disabled; internal static float kLineHeight = EditorGUI.kSingleLineHeight; internal bool hideInspector = false; const float kImageSectionWidth = 44; internal const float k_WideModeMinWidth = 330f; internal const float k_HeaderHeight = 21f; internal delegate void OnEditorGUIDelegate(Editor editor, Rect drawRect); internal static OnEditorGUIDelegate OnPostIconGUI = null; internal static bool m_AllowMultiObjectAccess = true; bool m_HasUnsavedChanges = false; [UsedByNativeCode] private bool GetHasUnsavedChanges() { return hasUnsavedChanges; } public bool hasUnsavedChanges { get { return m_HasUnsavedChanges; } protected set { if (m_HasUnsavedChanges != value) { m_HasUnsavedChanges = value; if (propertyViewer != null) { propertyViewer.UnsavedChangesStateChanged(this, value); } } } } public string saveChangesMessage { get; protected set; } public virtual void SaveChanges() { hasUnsavedChanges = false; } public virtual void DiscardChanges() { hasUnsavedChanges = false; } // used internally to know if this the first editor in the inspector window internal bool firstInspectedEditor { get; set; } IPropertyView m_PropertyViewer; internal IPropertyView propertyViewer { get { return m_PropertyViewer; } set { if (m_PropertyViewer != value) { m_PropertyViewer = value; // We are being assigned a new property view with different inspector mode to what our serialized object was built with. if (null != m_PropertyViewer && m_PropertyViewer.inspectorMode != m_InspectorMode) { // Keep the local inspector mode in sync. m_InspectorMode = m_PropertyViewer.inspectorMode; // Trash the local serialized object and property cache to force a rebuild. m_SerializedObject = null; m_EnabledProperty = null; } } } } internal virtual bool HasLargeHeader() { return AssetDatabase.IsMainAsset(target) || AssetDatabase.IsSubAsset(target); } internal bool canEditMultipleObjects { get { return Attribute.IsDefined(GetType(), typeof(CanEditMultipleObjects), false); } } internal virtual IPreviewable preview { get { if (m_DummyPreview == null) { m_DummyPreview = new ObjectPreview(); m_DummyPreview.Initialize(targets); } return m_DummyPreview; } } internal PropertyHandlerCache propertyHandlerCache { get { return m_PropertyHandlerCache; } } static class BaseStyles { public static readonly GUIContent open = EditorGUIUtility.TrTextContent("Open"); public static readonly GUIStyle inspectorBig = new GUIStyle(EditorStyles.inspectorBig); public static readonly GUIStyle centerStyle = new GUIStyle(); public static readonly GUIStyle postLargeHeaderBackground = "IN BigTitle Post"; static BaseStyles() { centerStyle.alignment = TextAnchor.MiddleCenter; } } bool IToolModeOwner.areToolModesAvailable { get { // tool modes not available when the target is a prefab parent return !EditorUtility.IsPersistent(target); } } // The object being inspected. public UnityObject target { get { return m_Targets[referenceTargetIndex]; } set { throw new InvalidOperationException("You can't set the target on an editor."); } } // An array of all the object being inspected. public UnityObject[] targets { get { if (!m_AllowMultiObjectAccess) Debug.LogError("The targets array should not be used inside OnSceneGUI or OnPreviewGUI. Use the single target property instead."); return m_Targets; } } internal virtual int referenceTargetIndex { get { return Mathf.Clamp(m_ReferenceTargetIndex, 0, m_Targets.Length - 1); } // Modulus that works for negative numbers as well set { m_ReferenceTargetIndex = (Math.Abs(value * m_Targets.Length) + value) % m_Targets.Length; } } internal virtual string targetTitle { get { if (m_Targets.Length == 1 || !m_AllowMultiObjectAccess) return ObjectNames.GetInspectorTitle(target); else return m_Targets.Length + " " + ObjectNames.NicifyVariableName(ObjectNames.GetTypeName(target)) + "s"; } } // A [[SerializedObject]] representing the object or objects being inspected. public SerializedObject serializedObject { get { if (!m_AllowMultiObjectAccess) Debug.LogError("The serializedObject should not be used inside OnSceneGUI or OnPreviewGUI. Use the target property directly instead."); return GetSerializedObjectInternal(); } } internal SerializedProperty enabledProperty { get { GetSerializedObjectInternal(); return m_EnabledProperty; } } internal virtual void PostSerializedObjectCreation() {} internal bool isInspectorDirty { get { return m_IsDirty != 0; } set { m_IsDirty = value ? 1 : 0; } } public static Editor CreateEditorWithContext(UnityObject[] targetObjects, UnityObject context, [UnityEngine.Internal.DefaultValue("null")] Type editorType) { if (editorType != null && !editorType.IsSubclassOf(typeof(Editor))) throw new ArgumentException($"Editor type '{editorType}' does not derive from UnityEditor.Editor", "editorType"); return CreateEditorWithContextInternal(targetObjects, context, editorType); } [ExcludeFromDocs] public static Editor CreateEditorWithContext(UnityObject[] targetObjects, UnityObject context) { Type editorType = null; return CreateEditorWithContext(targetObjects, context, editorType); } public static void CreateCachedEditorWithContext(UnityObject targetObject, UnityObject context, Type editorType, ref Editor previousEditor) { CreateCachedEditorWithContext(new[] {targetObject}, context, editorType, ref previousEditor); } public static void CreateCachedEditorWithContext(UnityObject[] targetObjects, UnityObject context, Type editorType, ref Editor previousEditor) { if (previousEditor != null && ArrayUtility.ArrayEquals(previousEditor.m_Targets, targetObjects) && previousEditor.m_Context == context) return; if (previousEditor != null) DestroyImmediate(previousEditor); previousEditor = CreateEditorWithContext(targetObjects, context, editorType); } public static void CreateCachedEditor(UnityObject targetObject, Type editorType, ref Editor previousEditor) { CreateCachedEditorWithContext(new[] {targetObject}, null, editorType, ref previousEditor); } public static void CreateCachedEditor(UnityObject[] targetObjects, Type editorType, ref Editor previousEditor) { CreateCachedEditorWithContext(targetObjects, null, editorType, ref previousEditor); } [ExcludeFromDocs] public static Editor CreateEditor(UnityObject targetObject) { Type editorType = null; return CreateEditor(targetObject, editorType); } public static Editor CreateEditor(UnityObject targetObject, [UnityEngine.Internal.DefaultValue("null")] Type editorType) { return CreateEditorWithContext(new[] {targetObject}, null, editorType); } [ExcludeFromDocs] public static Editor CreateEditor(UnityObject[] targetObjects) { Type editorType = null; return CreateEditor(targetObjects, editorType); } public static Editor CreateEditor(UnityObject[] targetObjects, [UnityEngine.Internal.DefaultValue("null")] Type editorType) { return CreateEditorWithContext(targetObjects, null, editorType); } internal void CleanupPropertyEditor() { if (m_SerializedObject != null) { m_SerializedObject.Dispose(); m_SerializedObject = null; } } private void OnDisableINTERNAL() { CleanupPropertyEditor(); propertyHandlerCache.Dispose(); if (m_DummyPreview != null && m_DummyPreview is not Editor) m_DummyPreview.Cleanup(); } internal virtual SerializedObject GetSerializedObjectInternal() { if (m_SerializedObject == null) { CreateSerializedObject(); } return m_SerializedObject; } internal class SerializedObjectNotCreatableException : Exception { public SerializedObjectNotCreatableException(string msg) : base(msg) {} } private void CreateSerializedObject() { try { m_SerializedObject = new SerializedObject(targets, m_Context); m_SerializedObject.inspectorMode = inspectorMode; if (m_SerializedObject.inspectorDataMode != dataMode) m_SerializedObject.inspectorDataMode = dataMode; AssignCachedProperties(this, m_SerializedObject.GetIterator()); m_EnabledProperty = m_SerializedObject.FindProperty("m_Enabled"); PostSerializedObjectCreation(); } catch (ArgumentException e) { m_SerializedObject = null; m_EnabledProperty = null; throw new SerializedObjectNotCreatableException(e.Message); } } internal static void AssignCachedProperties<T>(T self, SerializedProperty root) where T : class { var fields = ScriptAttributeUtility.GetAutoLoadProperties(typeof(T)); if (fields.Count == 0) return; var properties = new Dictionary<string, FieldInfo>(fields.Count); var allParents = new HashSet<string>(); foreach (var fieldInfo in fields) { var attribute = (CachePropertyAttribute)fieldInfo.GetCustomAttributes(typeof(CachePropertyAttribute), false).First(); var propertyName = string.IsNullOrEmpty(attribute.propertyPath) ? fieldInfo.Name : attribute.propertyPath; properties.Add(propertyName, fieldInfo); int dot = propertyName.LastIndexOf('.'); while (dot != -1) { propertyName = propertyName.Substring(0, dot); if (!allParents.Add(propertyName)) break; dot = propertyName.LastIndexOf('.'); } } var parentPath = root.propertyPath; var parentPathLength = parentPath.Length > 0 ? parentPath.Length + 1 : 0; var exitCount = properties.Count; var iterator = root.Copy(); bool enterChildren = true; while (iterator.Next(enterChildren) && exitCount > 0) { FieldInfo fieldInfo; var propertyPath = iterator.propertyPath.Substring(parentPathLength); if (properties.TryGetValue(propertyPath, out fieldInfo)) { fieldInfo.SetValue(self, iterator.Copy()); properties.Remove(propertyPath); exitCount--; } enterChildren = allParents.Contains(propertyPath); } iterator.Dispose(); if (exitCount > 0) { Debug.LogWarning("The following properties registered with CacheProperty where not found during the inspector creation: " + string.Join(", ", properties.Keys.ToArray())); } } internal void InternalSetTargets(UnityObject[] t) { m_Targets = t; } internal void InternalSetHidden(bool hidden) { hideInspector = hidden; } internal void InternalSetContextObject(UnityObject context) { m_Context = context; } Bounds IToolModeOwner.GetWorldBoundsOfTargets() { var result = new Bounds(); bool initialized = false; foreach (var t in targets) { if (t == null) continue; Bounds targetBounds = GetWorldBoundsOfTarget(t); if (!initialized) result = targetBounds; result.Encapsulate(targetBounds); initialized = true; } return result; } internal virtual Bounds GetWorldBoundsOfTarget(UnityObject targetObject) { return targetObject is Component ? ((Component)targetObject).gameObject.CalculateBounds() : new Bounds(); } bool IToolModeOwner.ModeSurvivesSelectionChange(int toolMode) { return false; } // Reload SerializedObject because flags etc might have changed. internal virtual void OnForceReloadInspector() { if (m_SerializedObject != null) { m_SerializedObject.SetIsDifferentCacheDirty(); // Need to make sure internal target list PPtr have been updated from a native memory // When assets are reloaded they are destroyed and recreated and the managed list does not get updated // The m_SerializedObject is a native object thus its targetObjects is a native memory PPtr list which have the new PPtr ids. InternalSetTargets(m_SerializedObject.targetObjects); } } internal virtual bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out float height) { height = -1; return false; } internal virtual bool OnOptimizedInspectorGUI(Rect contentRect) { Debug.LogError("Not supported"); return false; } protected internal static void DrawPropertiesExcluding(SerializedObject obj, params string[] propertyToExclude) { // Loop through properties and create one field (including children) for each top level property. SerializedProperty property = obj.GetIterator(); bool expanded = true; while (property.NextVisible(expanded)) { expanded = false; if (propertyToExclude.Contains(property.name)) continue; EditorGUILayout.PropertyField(property, true); } } // Draw the built-in inspector. public bool DrawDefaultInspector() { return DoDrawDefaultInspector(); } internal static bool DoDrawDefaultInspector(SerializedObject obj) { EditorGUI.BeginChangeCheck(); obj.UpdateIfRequiredOrScript(); // Loop through properties and create one field (including children) for each top level property. SerializedProperty property = obj.GetIterator(); bool expanded = true; while (property.NextVisible(expanded)) { using (new EditorGUI.DisabledScope("m_Script" == property.propertyPath)) { EditorGUILayout.PropertyField(property, true); } expanded = false; } obj.ApplyModifiedProperties(); return EditorGUI.EndChangeCheck(); } internal bool DoDrawDefaultInspector() { bool res; using (new LocalizationGroup(target)) { res = DoDrawDefaultInspector(serializedObject); var behaviour = target as MonoBehaviour; if (behaviour == null || !AudioUtil.HasAudioCallback(behaviour) || AudioUtil.GetCustomFilterChannelCount(behaviour) <= 0) return res; // If we have an OnAudioFilterRead callback, draw vu meter if (m_AudioFilterGUI == null) m_AudioFilterGUI = new AudioFilterGUI(); m_AudioFilterGUI.DrawAudioFilterGUI(behaviour); } return res; } // Repaint any inspectors that shows this editor. public void Repaint() { if (propertyViewer != null) propertyViewer.Repaint(); else InspectorWindow.RepaintAllInspectors(); } // Implement this function to make a custom IMGUI inspector. public virtual void OnInspectorGUI() { DrawDefaultInspector(); } // Implement this function to make a custom UIElements inspector. public virtual VisualElement CreateInspectorGUI() { return null; } // Implement this function if you want your editor constantly repaint (every 33ms) public virtual bool RequiresConstantRepaint() { return false; } public static event Action<Editor> finishedDefaultHeaderGUI = null; // This is the method that should be called from externally e.g. myEditor.DrawHeader (); // Do not make this method virtual - override OnHeaderGUI instead. public void DrawHeader() { // If we call DrawHeader from inside an an editor's OnInspectorGUI call, we have to do special handling. // (See DrawHeaderFromInsideHierarchy for details.) // We know we're inside the OnInspectorGUI block (or a similar vertical block) if hierarchyMode is set to true. var hierarchyMode = EditorGUIUtility.hierarchyMode; if (hierarchyMode) DrawHeaderFromInsideHierarchy(); else OnHeaderGUI(); if (finishedDefaultHeaderGUI != null) { // see DrawHeaderFromInsideHierarchy() if (hierarchyMode) { EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(GUILayoutUtility.topLevel.style); } // reset label and field widths to defaults EditorGUIUtility.labelWidth = 0f; EditorGUIUtility.fieldWidth = 0f; GUILayout.Space( -1f // move up to cover up bottom pixel of header box - BaseStyles.inspectorBig.margin.bottom - BaseStyles.inspectorBig.padding.bottom - BaseStyles.inspectorBig.overflow.bottom // move up to bottom of content area in header ); // align with controls in the Inspector // see InspectorWindow.DrawEditor() before calls to OnOptimizedInspectorGUI()/OnInspectorGUI() EditorGUIUtility.hierarchyMode = true; EditorGUIUtility.wideMode = EditorGUIUtility.contextWidth > k_WideModeMinWidth; EditorGUILayout.BeginVertical(BaseStyles.postLargeHeaderBackground, GUILayout.ExpandWidth(true)); finishedDefaultHeaderGUI(this); EditorGUILayout.EndVertical(); if (hierarchyMode) { EditorGUILayout.EndVertical(); // see InspectorWindow.DoOnInspectorGUI() EditorGUILayout.BeginVertical(UseDefaultMargins() ? EditorStyles.inspectorDefaultMargins : GUIStyle.none); } } // Restore previous hierarchy mode EditorGUIUtility.hierarchyMode = hierarchyMode; } // This is the method to override to create custom header GUI. // Do not make this method internal or public - call DrawHeader instead. protected virtual void OnHeaderGUI() { DrawHeaderGUI(this, targetTitle); } internal virtual void OnHeaderControlsGUI() { // Ensure we take up the same amount of height as regular controls GUILayoutUtility.GetRect(10, 10, 16, 16, EditorStyles.layerMaskField); GUILayout.FlexibleSpace(); bool showOpenButton = true; var importerEditor = this as AssetImporterEditor; // only show open button for the main object of an asset and for AssetImportInProgressProxy (asset not yet imported) if (importerEditor == null && !(targets[0] is AssetImportInProgressProxy)) { var assetPath = AssetDatabase.GetAssetPath(targets[0]); // Don't show open button if the target is not an asset if (!AssetDatabase.IsMainAsset(targets[0])) showOpenButton = false; // Don't show open button if the target has an importer // (but ignore AssetImporters since they're not shown) AssetImporter importer = AssetImporter.GetAtPath(assetPath); if (importer && importer.GetType() != typeof(AssetImporter)) showOpenButton = false; } if (showOpenButton && !ShouldHideOpenButton()) { var assets = importerEditor != null ? importerEditor.assetTargets : targets; var disabled = importerEditor != null && importerEditor.assetTarget == null; ShowOpenButton(assets, !disabled); } } internal void ShowOpenButton(UnityObject[] assets, bool enableCondition = true) { int assetCount = assets != null? assets.Length : 0; enableCondition &= (CanOpenMultipleObjects() || assetCount == 1); bool previousGUIState = GUI.enabled; GUI.enabled = enableCondition; if (GUILayout.Button(BaseStyles.open, EditorStyles.miniButton)) { bool openAssets = false; // 'Check Out and Open' dialog openAssets = AssetDatabase.MakeEditable(assets.Select(AssetDatabase.GetAssetPath).ToArray(), "Do you want to check out " + (assetCount > 1 ? String.Format("these {0} files?", assetCount) : "this file?")); // 'Open multiple assets' dialog if (openAssets && assetCount > 1) { openAssets = (EditorUtility.DisplayDialog("Open Selected Assets?", String.Format("Are you sure you want to open {0} selected assets?", assetCount), "Open", "Cancel")); } if (openAssets) { AssetDatabase.OpenAsset(assets); GUIUtility.ExitGUI(); } } GUI.enabled = previousGUIState; } protected virtual bool ShouldHideOpenButton() { return false; } internal virtual bool CanOpenMultipleObjects() { return true; } internal virtual bool ShouldTryToMakeEditableOnOpen() { return true; } internal virtual void OnHeaderIconGUI(Rect iconRect) { Texture2D icon = null; // Fetch isLoadingAssetPreview to ensure that there is no situation where a preview needs a repaint because it hasn't finished loading yet. bool isLoadingAssetPreview = AssetPreview.IsLoadingAssetPreview(target.GetInstanceID()); icon = AssetPreview.GetAssetPreview(target); if (!icon) { // We have a static preview it just hasn't been loaded yet. Repaint until we have it loaded. if (isLoadingAssetPreview) Repaint(); icon = AssetPreview.GetMiniThumbnail(target); } GUI.Label(iconRect, icon, BaseStyles.centerStyle); } internal virtual void OnHeaderTitleGUI(Rect titleRect, string header) { titleRect.yMin -= 2; titleRect.yMax += 2; GUI.Label(titleRect, header, EditorStyles.largeLabel); } // Draws the help and settings part of the header. // Returns a Rect to know where to draw the rest of the header. internal virtual Rect DrawHeaderHelpAndSettingsGUI(Rect r) { // Help var settingsSize = EditorStyles.iconButton.CalcSize(EditorGUI.GUIContents.titleSettingsIcon); float currentOffset = settingsSize.x; const int kTopMargin = 5; // Settings; process event even for disabled UI Rect settingsRect = new Rect(r.xMax - currentOffset, r.y + kTopMargin, settingsSize.x, settingsSize.y); var wasEnabled = GUI.enabled; GUI.enabled = true; var showMenu = EditorGUI.DropdownButton(settingsRect, GUIContent.none, FocusType.Passive, EditorStyles.optionsButtonStyle); GUI.enabled = wasEnabled; if (showMenu) { EditorUtility.DisplayObjectContextMenu(settingsRect, targets, 0); } currentOffset += settingsSize.x; // Show Editor Header Items. return EditorGUIUtility.DrawEditorHeaderItems(new Rect(r.xMax - currentOffset, r.y + kTopMargin, settingsSize.x, settingsSize.y), targets); } // If we call DrawHeaderGUI from inside an an editor's OnInspectorGUI call, we have to do special handling. // Since OnInspectorGUI is wrapped inside a BeginVertical/EndVertical block that adds padding, // and we don't want this padding for headers, we have to stop the vertical block, // draw the header, and then start a new vertical block with the same style. private void DrawHeaderFromInsideHierarchy() { var style = GUILayoutUtility.topLevel.style; EditorGUILayout.EndVertical(); OnHeaderGUI(); EditorGUILayout.BeginVertical(style); } internal static Rect DrawHeaderGUI(Editor editor, string header) { return DrawHeaderGUI(editor, header, 0f); } internal static Rect DrawHeaderGUI(Editor editor, string header, float leftMargin) { GUILayout.BeginHorizontal(BaseStyles.inspectorBig); GUILayout.Space(kImageSectionWidth - 6); GUILayout.BeginVertical(); GUILayout.Space(k_HeaderHeight); GUILayout.BeginHorizontal(); if (leftMargin > 0f) GUILayout.Space(leftMargin); if (editor) editor.OnHeaderControlsGUI(); else EditorGUILayout.GetControlRect(); GUILayout.EndHorizontal(); GUILayout.EndVertical(); GUILayout.EndHorizontal(); Rect fullRect = GUILayoutUtility.GetLastRect(); // Content rect Rect r = new Rect(fullRect.x + leftMargin, fullRect.y, fullRect.width - leftMargin, fullRect.height); // Icon Rect iconRect = new Rect(r.x + 6, r.y + 6, 32, 32); if (editor) editor.OnHeaderIconGUI(iconRect); else GUI.Label(iconRect, AssetPreview.GetMiniTypeThumbnail(typeof(UnityObject)), BaseStyles.centerStyle); if (editor) editor.DrawPostIconContent(iconRect); // Help and Settings Rect titleRect; var titleHeight = EditorGUI.lineHeight; if (editor) { Rect helpAndSettingsRect = editor.DrawHeaderHelpAndSettingsGUI(r); float rectX = r.x + kImageSectionWidth; titleRect = new Rect(rectX, r.y + 6, (helpAndSettingsRect.x - rectX) - 4, titleHeight); } else titleRect = new Rect(r.x + kImageSectionWidth, r.y + 6, r.width - kImageSectionWidth, titleHeight); if (editor && editor.hasUnsavedChanges && !string.IsNullOrEmpty(header)) { header += " *"; } // Title if (editor) editor.OnHeaderTitleGUI(titleRect, header); else GUI.Label(titleRect, header, EditorStyles.largeLabel); CheckForMainObjectNameMismatch(editor); // Context Menu; process event even for disabled UI var wasEnabled = GUI.enabled; GUI.enabled = true; Event evt = Event.current; var showMenu = editor != null && evt.type == EventType.MouseDown && evt.button == 1 && r.Contains(evt.mousePosition); GUI.enabled = wasEnabled; if (showMenu) { EditorUtility.DisplayObjectContextMenu(new Rect(evt.mousePosition.x, evt.mousePosition.y, 0, 0), editor.targets, 0); evt.Use(); } return fullRect; } internal static void CheckForMainObjectNameMismatch(Editor editor) { if (editor && editor.target && AssetDatabase.IsNativeAsset(editor.target) && AssetDatabase.IsMainAsset(editor.target) && !Unsupported.GetSerializedAssetInterfaceSingleton(editor.target.name)) { var mainObjectName = editor.target.name; var fileName = FileUtil.GetLastPathNameComponent(AssetDatabase.GetAssetPath(editor.target)); var expectedMainObjectName = FileUtil.GetPathWithoutExtension(fileName); if (mainObjectName != expectedMainObjectName) { DrawMismatchedNameNotification(editor, expectedMainObjectName, mainObjectName); } } } static void DrawMismatchedNameNotification(Editor editor, string expectedMainObjectName, string mainObjectName) { var warningText = $"The main object name '{mainObjectName}' should match the asset filename '{expectedMainObjectName}'.\nPlease fix to avoid errors."; var image = EditorGUIUtility.GetHelpIcon(MessageType.Warning); var btnText = "Fix object name"; Action onBtnClick = () => { editor.target.name = expectedMainObjectName; AssetDatabase.SaveAssetIfDirty(editor.target); var message = String.Format("Main Object Name '{0}' does not match filename '{1}'", mainObjectName, expectedMainObjectName); var hash = Hash128.Compute(message); UInt32 correspondingLogID = (UInt32)hash.GetHashCode(); Debug.RemoveLogEntriesByIdentifier((int)correspondingLogID); }; DrawNotification(image, warningText, btnText, onBtnClick); } internal static void DrawNotification(Texture image, string text, string btnText, Action onBtnClick) { using (new GUILayout.VerticalScope(EditorStyles.helpBox)) { using (new GUILayout.HorizontalScope()) { GUILayout.Label(image, GUILayout.ExpandWidth(false)); using (new GUILayout.VerticalScope()) { GUILayout.FlexibleSpace(); GUILayout.Label(text, EditorStyles.wordWrappedLabel); GUILayout.FlexibleSpace(); } GUILayout.FlexibleSpace(); if (onBtnClick != null) { using (new GUILayout.VerticalScope()) { GUILayout.FlexibleSpace(); if (GUILayout.Button(btnText, EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false))) onBtnClick.Invoke(); GUILayout.FlexibleSpace(); } } } } } internal void DrawPostIconContent(Rect iconRect) { if (OnPostIconGUI != null && Event.current.type == EventType.Repaint) { // Post icon draws 16 x 16 at bottom right corner const float k_Size = 16; Rect drawRect = iconRect; drawRect.x = (drawRect.xMax - k_Size) + 4; // Move slightly outside bounds for overlap effect. drawRect.y = (drawRect.yMax - k_Size) + 1; drawRect.width = k_Size; drawRect.height = k_Size; OnPostIconGUI(this, drawRect); } } public static void DrawFoldoutInspector(UnityObject target, ref Editor editor) { if (editor != null && (editor.target != target || target == null)) { UnityObject.DestroyImmediate(editor); editor = null; } if (editor == null && target != null) editor = Editor.CreateEditor(target); if (editor == null) return; const float kSpaceForFoldoutArrow = 10f; Rect titleRect = Editor.DrawHeaderGUI(editor, editor.targetTitle, kSpaceForFoldoutArrow); int id = GUIUtility.GetControlID(45678, FocusType.Passive); Rect renderRect = EditorGUI.GetInspectorTitleBarObjectFoldoutRenderRect(titleRect); renderRect.y = titleRect.yMax - 17f; // align with bottom bool oldVisible = UnityEditorInternal.InternalEditorUtility.GetIsInspectorExpanded(target); bool newVisible = EditorGUI.DoObjectFoldout(oldVisible, titleRect, renderRect, editor.targets, id); if (newVisible != oldVisible) UnityEditorInternal.InternalEditorUtility.SetIsInspectorExpanded(target, newVisible); if (newVisible) editor.OnInspectorGUI(); } // Override this method in subclasses if you implement OnPreviewGUI. public virtual bool HasPreviewGUI() { return preview.HasPreviewGUI(); } public virtual VisualElement CreatePreview(VisualElement inspectorPreviewWindow) { return preview.CreatePreview(inspectorPreviewWindow); } // Override this method if you want to change the label of the Preview area. public virtual GUIContent GetPreviewTitle() { return preview.GetPreviewTitle(); } // Override this method if you want to render a static preview that shows. public virtual Texture2D RenderStaticPreview(string assetPath, UnityObject[] subAssets, int width, int height) { return null; } // Implement to create your own custom preview. Custom previews are used in the preview area of the inspector, primary editor headers, and the object selector. public virtual void OnPreviewGUI(Rect r, GUIStyle background) { preview.OnPreviewGUI(r, background); } // Implement to create your own interactive custom preview. Interactive custom previews are used in the preview area of the inspector and the object selector. public virtual void OnInteractivePreviewGUI(Rect r, GUIStyle background) { OnPreviewGUI(r, background); } // Override this method if you want to show custom controls in the preview header. public virtual void OnPreviewSettings() { preview.OnPreviewSettings(); } // Implement this method to show asset information on top of the asset preview. public virtual string GetInfoString() { return preview.GetInfoString(); } public virtual void DrawPreview(Rect previewArea) { ObjectPreview.DrawPreview(this, previewArea, targets); } public virtual void ReloadPreviewInstances() { preview.ReloadPreviewInstances(); } // Some custom editors manually display SerializedObjects with only private properties // Setting this to true allows them to properly toggling the visibility via the standard header foldout internal bool alwaysAllowExpansion {get; set;} // Auxiliary method that determines whether this editor has a set of public properties and, as thus, // can be expanded via a foldout. This is used in order to determine whether a foldout needs to be // rendered on top of the inspector title bar or not. Some examples of editors that don't require // a foldout are GUI Layer and Audio Listener. internal bool CanBeExpandedViaAFoldout() { if (alwaysAllowExpansion) return true; if (m_SerializedObject == null) { CreateSerializedObject(); } else m_SerializedObject.Update(); m_SerializedObject.inspectorMode = inspectorMode; if (m_SerializedObject.inspectorDataMode != dataMode) m_SerializedObject.inspectorDataMode = dataMode; return CanBeExpandedViaAFoldoutWithoutUpdate(); } internal bool CanBeExpandedViaAFoldoutWithoutUpdate() { if (alwaysAllowExpansion) return true; if (m_SerializedObject == null) { CreateSerializedObject(); } SerializedProperty property = m_SerializedObject.GetIterator(); bool analyzePropertyChildren = true; while (property.NextVisible(analyzePropertyChildren)) { if (EditorGUI.GetPropertyHeight(property, null, true) > 0) { return true; } analyzePropertyChildren = false; } return false; } static internal bool IsAppropriateFileOpenForEdit(UnityObject assetObject) { // The native object for a ScriptableObject with an invalid script will be considered not alive. // In order to allow editing of the m_Script property of a ScriptableObject with an invalid script // we use the instance ID instead of the UnityEngine.Object reference to check if the asset is open for edit. if ((object)assetObject == null) return false; var instanceID = assetObject.GetInstanceID(); if (instanceID == 0) return false; StatusQueryOptions opts = EditorUserSettings.allowAsyncStatusUpdate ? StatusQueryOptions.UseCachedAsync : StatusQueryOptions.UseCachedIfPossible; if (AssetDatabase.IsNativeAsset(instanceID)) { var assetPath = AssetDatabase.GetAssetPath(instanceID); if (!AssetDatabase.IsOpenForEdit(assetPath, opts)) return false; } else if (AssetDatabase.IsForeignAsset(instanceID)) { if (!AssetDatabase.IsMetaFileOpenForEdit(assetObject, opts)) return false; } return true; } internal virtual bool IsEnabled() { // disable editor if any objects in the editor are not editable foreach (UnityObject target in targets) { if (target == null) return false; if ((target.hideFlags & HideFlags.NotEditable) != 0) return false; if (EditorUtility.IsPersistent(target) && !IsAppropriateFileOpenForEdit(target)) return false; } return true; } internal bool IsOpenForEdit() { foreach (UnityObject target in targets) { if (EditorUtility.IsPersistent(target) && !IsAppropriateFileOpenForEdit(target)) return false; } return true; } public virtual bool UseDefaultMargins() { return true; } [EditorBrowsable(EditorBrowsableState.Never)] public void Initialize(UnityObject[] targets) { throw new InvalidOperationException("You shouldn't call Initialize for Editors"); } [EditorBrowsable(EditorBrowsableState.Never)] public void Cleanup() { throw new InvalidOperationException("You shouldn't call Cleanup for Editors. Dispose resources in " + "Editor.OnDisable"); } public bool MoveNextTarget() { referenceTargetIndex++; return referenceTargetIndex < targets.Length; } public void ResetTarget() { referenceTargetIndex = 0; } // Implement this method to show a limited inspector for showing tweakable parameters in an Asset Store preview. internal virtual void OnAssetStoreInspectorGUI() { } } }
UnityCsReference/Editor/Mono/Inspector/Editor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/Editor.cs", "repo_id": "UnityCsReference", "token_count": 26914 }
327
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine.UIElements; namespace UnityEditor { internal interface IEditorElement { Editor editor { get; } IEnumerable<Editor> Editors { get; } void Reinit(int editorIndex, Editor[] editors); void ReinitCulled(int editorIndex, Editor[] editors); void CreateInspectorElement(); void AddPrefabComponent(VisualElement comp); // From VisualElement void RemoveFromHierarchy(); string name { get; set; } } internal static class EditorElementHelper { internal static Func<int, IPropertyView, string, IEditorElement> CreateFunctor; internal static IEditorElement CreateEditorElement(int editorIndex, IPropertyView iw, string title) { return CreateFunctor.Invoke(editorIndex, iw, title); } } }
UnityCsReference/Editor/Mono/Inspector/IEditorElement.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/IEditorElement.cs", "repo_id": "UnityCsReference", "token_count": 373 }
328
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Animations; namespace UnityEditor { [CustomEditor(typeof(LookAtConstraint))] [CanEditMultipleObjects] internal class LookAtConstraintEditor : ConstraintEditorBase { private SerializedProperty m_RotationAtRest; private SerializedProperty m_RotationOffset; private SerializedProperty m_WorldUpObject; private SerializedProperty m_Roll; private SerializedProperty m_UseUpObject; private SerializedProperty m_Weight; private SerializedProperty m_IsContraintActive; private SerializedProperty m_IsLocked; private SerializedProperty m_Sources; internal override SerializedProperty atRest { get { return m_RotationAtRest; } } internal override SerializedProperty offset { get { return m_RotationOffset; } } internal override SerializedProperty weight { get { return m_Weight; } } internal override SerializedProperty isContraintActive { get { return m_IsContraintActive; } } internal override SerializedProperty isLocked { get { return m_IsLocked; } } internal override SerializedProperty sources { get { return m_Sources; } } private class Styles : ConstraintStyleBase { GUIContent m_RotationAtRest = EditorGUIUtility.TrTextContent("Rotation At Rest", "The orientation of the constrained object when the weights of the sources add up to zero or when all the rotation axes are disabled."); GUIContent m_RotationOffset = EditorGUIUtility.TrTextContent("Rotation Offset", "The offset from the constrained orientation."); GUIContent m_WorldUpObject = EditorGUIUtility.TrTextContent("World Up Object", "The reference object when the World Up Type is either Object Up or Object Rotation Up."); GUIContent m_Roll = EditorGUIUtility.TrTextContent("Roll", "Specifies the roll angle in degrees."); GUIContent m_UseUpObject = EditorGUIUtility.TrTextContent("Use Up Object", "Specifies how the world up vector should be computed. Either use the World Up Object or the Roll value"); public override GUIContent AtRest { get { return m_RotationAtRest; } } public override GUIContent Offset { get { return m_RotationOffset; } } public GUIContent WorldUpObject { get { return m_WorldUpObject; } } public GUIContent Roll { get { return m_Roll; } } public GUIContent UseUpObject { get { return m_UseUpObject; } } } private static Styles s_Style = null; public void OnEnable() { if (s_Style == null) s_Style = new Styles(); m_RotationAtRest = serializedObject.FindProperty("m_RotationAtRest"); m_RotationOffset = serializedObject.FindProperty("m_RotationOffset"); m_UseUpObject = serializedObject.FindProperty("m_UseUpObject"); m_WorldUpObject = serializedObject.FindProperty("m_WorldUpObject"); m_Roll = serializedObject.FindProperty("m_Roll"); m_Weight = serializedObject.FindProperty("m_Weight"); m_IsContraintActive = serializedObject.FindProperty("m_Active"); m_IsLocked = serializedObject.FindProperty("m_IsLocked"); m_Sources = serializedObject.FindProperty("m_Sources"); OnEnable(s_Style); } internal override void OnValueAtRestChanged() { foreach (var t in targets) { (t as LookAtConstraint).transform.SetLocalEulerAngles(atRest.vector3Value, RotationOrder.OrderZXY); EditorUtility.SetDirty(target); } } internal override void ShowCustomProperties() { EditorGUILayout.PropertyField(m_UseUpObject, s_Style.UseUpObject); using (new EditorGUI.DisabledGroupScope(m_UseUpObject.boolValue)) { EditorGUILayout.PropertyField(m_Roll, s_Style.Roll); } using (new EditorGUI.DisabledGroupScope(!m_UseUpObject.boolValue)) { EditorGUILayout.PropertyField(m_WorldUpObject, s_Style.WorldUpObject); } } internal override void ShowFreezeAxesControl() { } public override void OnInspectorGUI() { if (s_Style == null) s_Style = new Styles(); serializedObject.Update(); ShowConstraintEditor<LookAtConstraint>(s_Style); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Editor/Mono/Inspector/LookAtConstraintEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/LookAtConstraintEditor.cs", "repo_id": "UnityCsReference", "token_count": 1868 }
329
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEditorInternal; using UnityEngine; namespace UnityEditor { [CustomEditor(typeof(OcclusionPortal)), CanEditMultipleObjects] internal class OcclusionPortalEditor : Editor { private const string k_CenterPath = "m_Center"; private const string k_SizePath = "m_Size"; private readonly BoxBoundsHandle m_BoundsHandle = new BoxBoundsHandle(); protected virtual void OnEnable() { m_BoundsHandle.SetColor(Handles.s_ColliderHandleColor); } public override void OnInspectorGUI() { EditMode.DoEditModeInspectorModeButton( EditMode.SceneViewEditMode.Collider, "Edit Bounds", PrimitiveBoundsHandle.editModeButton, this ); base.OnInspectorGUI(); } public static bool IsSceneGUIEnabled() { return (EditMode.editMode == EditMode.SceneViewEditMode.Collider); } protected virtual void OnSceneGUI() { if (!EditMode.IsOwner(this) || !target) return; OcclusionPortal portal = target as OcclusionPortal; // this.serializedObject will not work within OnSceneGUI if multiple targets are selected using (var so = new SerializedObject(portal)) { so.Update(); using (new Handles.DrawingScope(portal.transform.localToWorldMatrix)) { SerializedProperty centerProperty = so.FindProperty(k_CenterPath); SerializedProperty sizeProperty = so.FindProperty(k_SizePath); m_BoundsHandle.center = centerProperty.vector3Value; m_BoundsHandle.size = sizeProperty.vector3Value; EditorGUI.BeginChangeCheck(); m_BoundsHandle.DrawHandle(); if (EditorGUI.EndChangeCheck()) { centerProperty.vector3Value = m_BoundsHandle.center; sizeProperty.vector3Value = m_BoundsHandle.size; so.ApplyModifiedProperties(); } } } } internal override Bounds GetWorldBoundsOfTarget(Object targetObject) { using (var so = new SerializedObject(targetObject)) { Vector3 center = so.FindProperty(k_CenterPath).vector3Value; Vector3 size = so.FindProperty(k_SizePath).vector3Value; var localBounds = new Bounds(center, size); Vector3 max = localBounds.max; Vector3 min = localBounds.min; Matrix4x4 portalTransformMatrix = ((OcclusionPortal)targetObject).transform.localToWorldMatrix; var worldBounds = new Bounds(portalTransformMatrix.MultiplyPoint3x4(new Vector3(max.x, max.y, max.z)), Vector3.zero); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(max.x, max.y, max.z))); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(max.x, max.y, min.z))); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(max.x, min.y, max.z))); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(min.x, max.y, max.z))); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(max.x, min.y, min.z))); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(min.x, max.y, min.z))); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(min.x, min.y, max.z))); worldBounds.Encapsulate(portalTransformMatrix.MultiplyPoint3x4(new Vector3(min.x, min.y, min.z))); return worldBounds; } } } }
UnityCsReference/Editor/Mono/Inspector/OcclusionPortalEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/OcclusionPortalEditor.cs", "repo_id": "UnityCsReference", "token_count": 1957 }
330
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { internal class RectHandles { static Styles s_Styles; class Styles { public readonly GUIStyle dragdot = "U2D.dragDot"; public readonly GUIStyle pivotdot = "U2D.pivotDot"; public readonly GUIStyle dragdotactive = "U2D.dragDotActive"; public readonly GUIStyle pivotdotactive = "U2D.pivotDotActive"; } private static int s_LastCursorId; internal static bool RaycastGUIPointToWorldHit(Vector2 guiPoint, Plane plane, out Vector3 hit) { Ray ray = HandleUtility.GUIPointToWorldRay(guiPoint); float dist = 0f; bool isHit = plane.Raycast(ray, out dist); hit = isHit ? ray.GetPoint(dist) : Vector3.zero; return isHit; } internal static void DetectCursorChange(int id) { if (HandleUtility.nearestControl == id) { // Don't optimize this to only use event if s_LastCursorId wasn't already id. // Cursor can sometimes change for the same handle. s_LastCursorId = id; Event.current.Use(); } else if (s_LastCursorId == id) { s_LastCursorId = 0; Event.current.Use(); } } internal static Vector3 SideSlider(int id, Vector3 position, Vector3 sideVector, Vector3 direction, float size, Handles.CapFunction capFunction, Vector2 snap) { return SideSlider(id, position, sideVector, direction, size, capFunction, snap, 0); } internal static Vector3 SideSlider(int id, Vector3 position, Vector3 sideVector, Vector3 direction, float size, Handles.CapFunction capFunction, Vector2 snap, float bias) { Event evt = Event.current; Vector3 handleDir = Vector3.Cross(sideVector, direction).normalized; Vector3 pos = Handles.Slider2D(id, position, handleDir, direction, sideVector, 0, capFunction, snap); pos = position + Vector3.Project(pos - position, direction); switch (evt.type) { case EventType.Layout: case EventType.MouseMove: Vector3 sideDir = sideVector.normalized; HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position + sideVector * 0.5f - sideDir * size * 2, position - sideVector * 0.5f + sideDir * size * 2) - bias); if (evt.type == EventType.MouseMove) DetectCursorChange(id); break; case EventType.Repaint: if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) HandleDirectionalCursor(position, handleDir, direction); break; } return pos; } internal static Vector3 CornerSlider(int id, Vector3 cornerPos, Vector3 handleDir, Vector3 outwardsDir1, Vector3 outwardsDir2, float handleSize, Handles.CapFunction drawFunc, Vector2 snap) { Event evt = Event.current; Vector3 pos = Handles.Slider2D(id, cornerPos, handleDir, outwardsDir1, outwardsDir2, handleSize, drawFunc, snap); switch (evt.type) { case EventType.MouseMove: DetectCursorChange(id); break; case EventType.Repaint: if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) HandleDirectionalCursor(cornerPos, handleDir, outwardsDir1 + outwardsDir2); break; } return pos; } private static void HandleDirectionalCursor(Vector3 handlePosition, Vector3 handlePlaneNormal, Vector3 direction) { Vector2 mousePosition = Event.current.mousePosition; // Find cursor direction (supports perspective camera) Plane guiPlane = new Plane(handlePlaneNormal, handlePosition); Vector3 mousePosWorld; if (RaycastGUIPointToWorldHit(mousePosition, guiPlane, out mousePosWorld)) { Vector2 cursorDir = WorldToScreenSpaceDir(mousePosWorld, direction); // 200px x 200px rect around mousepos to switch cursor via fake cursorRect. Rect mouseScreenRect = new Rect(mousePosition.x - 100f, mousePosition.y - 100f, 200f, 200f); EditorGUIUtility.AddCursorRect(mouseScreenRect, GetScaleCursor(cursorDir)); } } public static float AngleAroundAxis(Vector3 dirA, Vector3 dirB, Vector3 axis) { // Project A and B onto the plane orthogonal target axis dirA = Vector3.ProjectOnPlane(dirA, axis); dirB = Vector3.ProjectOnPlane(dirB, axis); // Find (positive) angle between A and B float angle = Vector3.Angle(dirA, dirB); // Return angle multiplied with 1 or -1 return angle * (Vector3.Dot(axis, Vector3.Cross(dirA, dirB)) < 0 ? -1 : 1); } public static float RotationSlider(int id, Vector3 cornerPos, float rotation, Vector3 pivot, Vector3 handleDir, Vector3 outwardsDir1, Vector3 outwardsDir2, float handleSize, Handles.CapFunction drawFunc, Vector2 snap) { Vector3 diagonal = (outwardsDir1 + outwardsDir2); Vector2 screenCorner = HandleUtility.WorldToGUIPoint(cornerPos); Vector2 screenOffset = HandleUtility.WorldToGUIPoint(cornerPos + diagonal) - screenCorner; screenOffset = screenOffset.normalized * 15; RaycastGUIPointToWorldHit(screenCorner + screenOffset, new Plane(handleDir, cornerPos), out cornerPos); Event evt = Event.current; Vector3 pos = Handles.Slider2D(id, cornerPos, handleDir, outwardsDir1, outwardsDir2, handleSize, drawFunc, Vector2.zero); if (evt.type == EventType.MouseMove) DetectCursorChange(id); if (evt.type == EventType.Repaint) { if ((HandleUtility.nearestControl == id && GUIUtility.hotControl == 0) || GUIUtility.hotControl == id) { Rect mouseScreenRect = new Rect(evt.mousePosition.x - 100f, evt.mousePosition.y - 100f, 200f, 200f); EditorGUIUtility.AddCursorRect(mouseScreenRect, MouseCursor.RotateArrow); } } return rotation - AngleAroundAxis(pos - pivot, cornerPos - pivot, handleDir); } static Vector2 WorldToScreenSpaceDir(Vector3 worldPos, Vector3 worldDir) { Vector3 screenPos = HandleUtility.WorldToGUIPoint(worldPos); Vector3 screenPosPlusDirection = HandleUtility.WorldToGUIPoint(worldPos + worldDir); Vector2 screenSpaceDir = screenPosPlusDirection - screenPos; screenSpaceDir.y *= -1; return screenSpaceDir; } private static MouseCursor GetScaleCursor(Vector2 direction) { float angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg; if (angle < 0f) angle = 360f + angle; if (angle < 0f + 27.5f) return MouseCursor.ResizeVertical; if (angle < 45f + 27.5f) return MouseCursor.ResizeUpRight; if (angle < 90f + 27.5f) return MouseCursor.ResizeHorizontal; if (angle < 135f + 27.5f) return MouseCursor.ResizeUpLeft; if (angle < 180f + 27.5f) return MouseCursor.ResizeVertical; if (angle < 225f + 27.5f) return MouseCursor.ResizeUpRight; if (angle < 270f + 27.5f) return MouseCursor.ResizeHorizontal; if (angle < 315f + 27.5f) return MouseCursor.ResizeUpLeft; else return MouseCursor.ResizeVertical; } public static void RectScalingHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { if (s_Styles == null) s_Styles = new Styles(); switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(position, size * .5f)); break; case EventType.Repaint: DrawImageBasedCap(controlID, position, rotation, size, s_Styles.dragdot, s_Styles.dragdotactive); break; } } public static void PivotHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { if (s_Styles == null) s_Styles = new Styles(); switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToCircle(position, size * .5f)); break; case EventType.Repaint: DrawImageBasedCap(controlID, position, rotation, size, s_Styles.pivotdot, s_Styles.pivotdotactive); break; } } static void DrawImageBasedCap(int controlID, Vector3 position, Quaternion rotation, float size, GUIStyle normal, GUIStyle active) { // Don't draw positions behind the camera if (Camera.current && Vector3.Dot(position - Camera.current.transform.position, Camera.current.transform.forward) < 0) return; Vector3 screenPos = HandleUtility.WorldToGUIPoint(position); Handles.BeginGUI(); float w = normal.fixedWidth; float h = normal.fixedHeight; Rect r = new Rect(screenPos.x - w / 2f, screenPos.y - h / 2f, w, h); if (GUIUtility.hotControl == controlID) active.Draw(r, GUIContent.none, controlID); else normal.Draw(r, GUIContent.none, controlID); Handles.EndGUI(); } public static void RenderRectWithShadow(bool active, params Vector3[] corners) { Vector3[] verts = new Vector3[] { corners[0], corners[1], corners[2], corners[3], corners[0] }; Color oldColor = Handles.color; Handles.color = new Color(1f, 1f, 1f, active ? 1f : 0.5f); DrawPolyLineWithShadow(new Color(0f, 0f, 0f, active ? 1f : 0.5f), new Vector2(1f, -1f), verts); Handles.color = oldColor; } static Vector3[] s_TempVectors = new Vector3[0]; public static void DrawPolyLineWithShadow(Color shadowColor, Vector2 screenOffset, params Vector3[] points) { Camera cam = Camera.current; if (!cam || Event.current.type != EventType.Repaint) return; if (s_TempVectors.Length != points.Length) s_TempVectors = new Vector3[points.Length]; for (int i = 0; i < points.Length; i++) s_TempVectors[i] = cam.ScreenToWorldPoint(cam.WorldToScreenPoint(points[i]) + (Vector3)screenOffset); Color oldColor = Handles.color; // shadow shadowColor.a = shadowColor.a * oldColor.a; Handles.color = shadowColor; Handles.DrawPolyLine(s_TempVectors); // line itself Handles.color = oldColor; Handles.DrawPolyLine(points); } public static void DrawDottedLineWithShadow(Color shadowColor, Vector2 screenOffset, Vector3 p1, Vector3 p2, float screenSpaceSize) { Camera cam = Camera.current; if (!cam || Event.current.type != EventType.Repaint) return; Color oldColor = Handles.color; // shadow shadowColor.a = shadowColor.a * oldColor.a; Handles.color = shadowColor; Handles.DrawDottedLine( cam.ScreenToWorldPoint(cam.WorldToScreenPoint(p1) + (Vector3)screenOffset), cam.ScreenToWorldPoint(cam.WorldToScreenPoint(p2) + (Vector3)screenOffset), screenSpaceSize); // line itself Handles.color = oldColor; Handles.DrawDottedLine(p1, p2, screenSpaceSize); } } }
UnityCsReference/Editor/Mono/Inspector/RectHandles.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/RectHandles.cs", "repo_id": "UnityCsReference", "token_count": 5988 }
331
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Scripting; namespace UnityEditor { public abstract class ShaderGUI { virtual public void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) { materialEditor.PropertiesDefaultGUI(properties); } virtual public void OnMaterialPreviewGUI(MaterialEditor materialEditor, Rect r, GUIStyle background) { materialEditor.DefaultPreviewGUI(r, background); } virtual public void OnMaterialInteractivePreviewGUI(MaterialEditor materialEditor, Rect r, GUIStyle background) { materialEditor.DefaultPreviewGUI(r, background); } virtual public void OnMaterialPreviewSettingsGUI(MaterialEditor materialEditor) { materialEditor.DefaultPreviewSettingsGUI(); } virtual public void OnClosed(Material material) { } virtual public void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) { material.shader = newShader; } virtual public void ValidateMaterial(Material material) { } // Utility methods protected static MaterialProperty FindProperty(string propertyName, MaterialProperty[] properties) { return FindProperty(propertyName, properties, true); } protected static MaterialProperty FindProperty(string propertyName, MaterialProperty[] properties, bool propertyIsMandatory) { for (var i = 0; i < properties.Length; i++) if (properties[i] != null && properties[i].name == propertyName) return properties[i]; // We assume all required properties can be found, otherwise something is broken if (propertyIsMandatory) throw new ArgumentException("Could not find MaterialProperty: '" + propertyName + "', Num properties: " + properties.Length); return null; } } internal static class ShaderGUIUtility { private static Type ExtractCustomEditorType(string customEditorName) { if (string.IsNullOrEmpty(customEditorName)) return null; // To allow users to implement their own ShaderGUI for the Standard shader we iterate in reverse order // because the UnityEditor assembly is assumed first in the assembly list. // Users can now place a copy of the StandardShaderGUI script in the project and start modifying that copy to make their own version. var unityEditorFullName = $"UnityEditor.{customEditorName}"; // for convenience: adding UnityEditor namespace is not needed in the shader foreach (var type in TypeCache.GetTypesDerivedFrom<ShaderGUI>()) { if (type.FullName.Equals(customEditorName, StringComparison.Ordinal) || type.FullName.Equals(unityEditorFullName, StringComparison.Ordinal)) return typeof(ShaderGUI).IsAssignableFrom(type) ? type : null; } return null; } internal static ShaderGUI CreateShaderGUI(string customEditorName) { Type customEditorType = ExtractCustomEditorType(customEditorName); return customEditorType != null ? (Activator.CreateInstance(customEditorType) as ShaderGUI) : null; } [RequiredByNativeCode] internal static void ValidateMaterial(Material material) { string customEditor = ShaderUtil.GetCurrentCustomEditor(material.shader); CreateShaderGUI(customEditor)?.ValidateMaterial(material); } } } // namespace UnityEditor
UnityCsReference/Editor/Mono/Inspector/ShaderGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/ShaderGUI.cs", "repo_id": "UnityCsReference", "token_count": 1475 }
332
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace UnityEditor { internal class StandardParticlesShaderGUI : ShaderGUI { public enum BlendMode { Opaque, Cutout, Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency Transparent, // Physically plausible transparency mode, implemented as alpha pre-multiply Additive, Subtractive, Modulate } public enum FlipbookMode { Simple, Blended } public enum ColorMode { Multiply, Additive, Subtractive, Overlay, Color, Difference } private static class Styles { public static GUIContent albedoText = EditorGUIUtility.TrTextContent("Albedo", "Albedo (RGB) and Transparency (A)."); public static GUIContent alphaCutoffText = EditorGUIUtility.TrTextContent("Alpha Cutoff", "Threshold for alpha cutoff."); public static GUIContent metallicMapText = EditorGUIUtility.TrTextContent("Metallic", "Metallic (R) and Smoothness (A)."); public static GUIContent smoothnessText = EditorGUIUtility.TrTextContent("Smoothness", "Smoothness value."); public static GUIContent smoothnessScaleText = EditorGUIUtility.TrTextContent("Smoothness", "Smoothness scale factor."); public static GUIContent normalMapText = EditorGUIUtility.TrTextContent("Normal Map", "Normal Map."); public static GUIContent emissionText = EditorGUIUtility.TrTextContent("Color", "Emission (RGB)."); public static GUIContent renderingMode = EditorGUIUtility.TrTextContent("Rendering Mode", "Determines the transparency and blending method for drawing the object to the screen."); public static GUIContent[] blendNames = Array.ConvertAll(Enum.GetNames(typeof(BlendMode)), item => new GUIContent(item)); public static GUIContent colorMode = EditorGUIUtility.TrTextContent("Color Mode", "Determines the blending mode between the particle color and the texture albedo."); public static GUIContent[] colorNames = Array.ConvertAll(Enum.GetNames(typeof(ColorMode)), item => new GUIContent(item)); public static GUIContent flipbookBlending = EditorGUIUtility.TrTextContent("Flip-Book Frame Blending", "Enables blending between the frames of animated texture sheets."); public static GUIContent twoSidedEnabled = EditorGUIUtility.TrTextContent("Two Sided", "Render both front and back faces of the particle geometry."); public static GUIContent distortionEnabled = EditorGUIUtility.TrTextContent("Distortion", "Use a grab pass and normal map to simulate refraction."); public static GUIContent distortionStrengthText = EditorGUIUtility.TrTextContent("Strength", "Distortion Strength."); public static GUIContent distortionBlendText = EditorGUIUtility.TrTextContent("Blend", "Weighting between albedo and grab pass."); public static GUIContent softParticlesEnabled = EditorGUIUtility.TrTextContent("Soft Particles", "Fade out particle geometry when it gets close to the surface of objects written into the depth buffer."); public static GUIContent softParticlesNearFadeDistanceText = EditorGUIUtility.TrTextContent("Near fade", "Soft Particles near fade distance."); public static GUIContent softParticlesFarFadeDistanceText = EditorGUIUtility.TrTextContent("Far fade", "Soft Particles far fade distance."); public static GUIContent cameraFadingEnabled = EditorGUIUtility.TrTextContent("Camera Fading", "Fade out particle geometry when it gets close to the camera."); public static GUIContent cameraNearFadeDistanceText = EditorGUIUtility.TrTextContent("Near fade", "Camera near fade distance."); public static GUIContent cameraFarFadeDistanceText = EditorGUIUtility.TrTextContent("Far fade", "Camera far fade distance."); public static GUIContent emissionEnabled = EditorGUIUtility.TrTextContent("Emission"); public static GUIContent blendingOptionsText = EditorGUIUtility.TrTextContent("Blending Options"); public static GUIContent mainOptionsText = EditorGUIUtility.TrTextContent("Main Options"); public static GUIContent mapsOptionsText = EditorGUIUtility.TrTextContent("Maps"); public static GUIContent advancedText = EditorGUIUtility.TrTextContent("Advanced Options"); public static GUIContent requiredVertexStreamsText = EditorGUIUtility.TrTextContent("Required Vertex Streams"); public static GUIContent streamPositionText = EditorGUIUtility.TrTextContent("Position (POSITION.xyz)"); public static GUIContent streamNormalText = EditorGUIUtility.TrTextContent("Normal (NORMAL.xyz)"); public static GUIContent streamColorText = EditorGUIUtility.TrTextContent("Color (COLOR.xyzw)"); public static GUIContent streamColorInstancedText = EditorGUIUtility.TrTextContent("Color (INSTANCED0.xyzw)"); public static GUIContent streamUVText = EditorGUIUtility.TrTextContent("UV (TEXCOORD0.xy)"); public static GUIContent streamUV2Text = EditorGUIUtility.TrTextContent("UV2 (TEXCOORD0.zw)"); public static GUIContent streamAnimBlendText = EditorGUIUtility.TrTextContent("AnimBlend (TEXCOORD1.x)"); public static GUIContent streamAnimFrameText = EditorGUIUtility.TrTextContent("AnimFrame (INSTANCED1.x)"); public static GUIContent streamTangentText = EditorGUIUtility.TrTextContent("Tangent (TANGENT.xyzw)"); public static GUIContent streamApplyToAllSystemsText = EditorGUIUtility.TrTextContent("Apply to Systems", "Apply the vertex stream layout to all Particle Systems using this material"); public static string undoApplyCustomVertexStreams = L10n.Tr("Apply custom vertex streams from material"); } MaterialProperty blendMode = null; MaterialProperty colorMode = null; MaterialProperty flipbookMode = null; MaterialProperty cullMode = null; MaterialProperty distortionEnabled = null; MaterialProperty distortionStrength = null; MaterialProperty distortionBlend = null; MaterialProperty albedoMap = null; MaterialProperty albedoColor = null; MaterialProperty alphaCutoff = null; MaterialProperty metallicMap = null; MaterialProperty metallic = null; MaterialProperty smoothness = null; MaterialProperty bumpScale = null; MaterialProperty bumpMap = null; MaterialProperty emissionEnabled = null; MaterialProperty emissionColorForRendering = null; MaterialProperty emissionMap = null; MaterialProperty softParticlesEnabled = null; MaterialProperty cameraFadingEnabled = null; MaterialProperty softParticlesNearFadeDistance = null; MaterialProperty softParticlesFarFadeDistance = null; MaterialProperty cameraNearFadeDistance = null; MaterialProperty cameraFarFadeDistance = null; MaterialEditor m_MaterialEditor; List<ParticleSystemRenderer> m_RenderersUsingThisMaterial = new List<ParticleSystemRenderer>(); bool m_FirstTimeApply = true; public void FindProperties(MaterialProperty[] props) { blendMode = FindProperty("_Mode", props); colorMode = FindProperty("_ColorMode", props, false); flipbookMode = FindProperty("_FlipbookMode", props); cullMode = FindProperty("_Cull", props); distortionEnabled = FindProperty("_DistortionEnabled", props); distortionStrength = FindProperty("_DistortionStrength", props); distortionBlend = FindProperty("_DistortionBlend", props); albedoMap = FindProperty("_MainTex", props); albedoColor = FindProperty("_Color", props); alphaCutoff = FindProperty("_Cutoff", props); metallicMap = FindProperty("_MetallicGlossMap", props, false); metallic = FindProperty("_Metallic", props, false); smoothness = FindProperty("_Glossiness", props, false); bumpScale = FindProperty("_BumpScale", props); bumpMap = FindProperty("_BumpMap", props); emissionEnabled = FindProperty("_EmissionEnabled", props); emissionColorForRendering = FindProperty("_EmissionColor", props); emissionMap = FindProperty("_EmissionMap", props); softParticlesEnabled = FindProperty("_SoftParticlesEnabled", props); cameraFadingEnabled = FindProperty("_CameraFadingEnabled", props); softParticlesNearFadeDistance = FindProperty("_SoftParticlesNearFadeDistance", props); softParticlesFarFadeDistance = FindProperty("_SoftParticlesFarFadeDistance", props); cameraNearFadeDistance = FindProperty("_CameraNearFadeDistance", props); cameraFarFadeDistance = FindProperty("_CameraFarFadeDistance", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) { FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly m_MaterialEditor = materialEditor; Material material = materialEditor.target as Material; if (m_FirstTimeApply) { CacheRenderersUsingThisMaterial(material); m_FirstTimeApply = false; } ShaderPropertiesGUI(material); } public void ShaderPropertiesGUI(Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; { GUILayout.Label(Styles.blendingOptionsText, EditorStyles.boldLabel); bool blendModeChanged = BlendModePopup(); ColorModePopup(); EditorGUILayout.Space(); GUILayout.Label(Styles.mainOptionsText, EditorStyles.boldLabel); FlipbookBlendingPopup(); TwoSidedPopup(material); FadingPopup(material); DistortionPopup(material); EditorGUILayout.Space(); GUILayout.Label(Styles.mapsOptionsText, EditorStyles.boldLabel); DoAlbedoArea(material); DoSpecularMetallicArea(material); DoNormalMapArea(material); DoEmissionArea(material); if (!flipbookMode.hasMixedValue && (FlipbookMode)flipbookMode.floatValue != FlipbookMode.Blended) { EditorGUI.BeginChangeCheck(); m_MaterialEditor.TextureScaleOffsetProperty(albedoMap); if (EditorGUI.EndChangeCheck()) emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake } EditorGUILayout.Space(); GUILayout.Label(Styles.advancedText, EditorStyles.boldLabel); m_MaterialEditor.RenderQueueField(); if (blendModeChanged) { foreach (var obj in blendMode.targets) SetupMaterialWithBlendMode((Material)obj, (BlendMode)((Material)obj).GetFloat("_Mode"), true); } } EditorGUILayout.Space(); GUILayout.Label(Styles.requiredVertexStreamsText, EditorStyles.boldLabel); DoVertexStreamsArea(material); } public override void OnClosed(Material material) { material.SetShaderPassEnabled("Always", true); // because grabpass used to use the always pass, we need to force it on, to correct old materials (case 1402353) material.SetShaderPassEnabled("GrabPass", true); } public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader) { // Sync the lighting flag for the unlit shader if (newShader.name.Contains("Unlit")) material.SetFloat("_LightingEnabled", 0.0f); else material.SetFloat("_LightingEnabled", 1.0f); // _Emission property is lost after assigning Standard shader to the material // thus transfer it before assigning the new shader if (material.HasProperty("_Emission")) { material.SetColor("_EmissionColor", material.GetColor("_Emission")); } base.AssignNewShaderToMaterial(material, oldShader, newShader); if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/")) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"), true); return; } BlendMode blendMode = BlendMode.Opaque; if (oldShader.name.Contains("/Transparent/Cutout/")) { blendMode = BlendMode.Cutout; } else if (oldShader.name.Contains("/Transparent/")) { // NOTE: legacy shaders did not provide physically based transparency // therefore Fade mode blendMode = BlendMode.Fade; } material.SetFloat("_Mode", (float)blendMode); SetupMaterialWithBlendMode(material, blendMode, true); } bool BlendModePopup() { EditorGUI.showMixedValue = blendMode.hasMixedValue; var mode = (BlendMode)blendMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (BlendMode)EditorGUILayout.Popup(Styles.renderingMode, (int)mode, Styles.blendNames); bool result = EditorGUI.EndChangeCheck(); if (result) { m_MaterialEditor.RegisterPropertyChangeUndo("Rendering Mode"); blendMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; return result; } void ColorModePopup() { if (colorMode != null) { EditorGUI.showMixedValue = colorMode.hasMixedValue; var mode = (ColorMode)colorMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (ColorMode)EditorGUILayout.Popup(Styles.colorMode, (int)mode, Styles.colorNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Color Mode"); colorMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } } void FlipbookBlendingPopup() { EditorGUI.showMixedValue = flipbookMode.hasMixedValue; var enabled = (flipbookMode.floatValue == (float)FlipbookMode.Blended); EditorGUI.BeginChangeCheck(); enabled = EditorGUILayout.Toggle(Styles.flipbookBlending, enabled); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Flip-Book Mode"); flipbookMode.floatValue = enabled ? (float)FlipbookMode.Blended : (float)FlipbookMode.Simple; } EditorGUI.showMixedValue = false; } void TwoSidedPopup(Material material) { EditorGUI.showMixedValue = cullMode.hasMixedValue; var enabled = (cullMode.floatValue == (float)UnityEngine.Rendering.CullMode.Off); EditorGUI.BeginChangeCheck(); enabled = EditorGUILayout.Toggle(Styles.twoSidedEnabled, enabled); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Two Sided Enabled"); cullMode.floatValue = enabled ? (float)UnityEngine.Rendering.CullMode.Off : (float)UnityEngine.Rendering.CullMode.Back; } EditorGUI.showMixedValue = false; } void FadingPopup(Material material) { // Z write doesn't work with fading bool hasZWrite = (material.GetFloat("_ZWrite") > 0.0f); if (!hasZWrite) { // Soft Particles { EditorGUI.showMixedValue = softParticlesEnabled.hasMixedValue; var enabled = softParticlesEnabled.floatValue; EditorGUI.BeginChangeCheck(); enabled = EditorGUILayout.Toggle(Styles.softParticlesEnabled, enabled != 0.0f) ? 1.0f : 0.0f; if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Soft Particles Enabled"); softParticlesEnabled.floatValue = enabled; } if (enabled != 0.0f) { int indentation = 2; m_MaterialEditor.ShaderProperty(softParticlesNearFadeDistance, Styles.softParticlesNearFadeDistanceText, indentation); m_MaterialEditor.ShaderProperty(softParticlesFarFadeDistance, Styles.softParticlesFarFadeDistanceText, indentation); } } // Camera Fading { EditorGUI.showMixedValue = cameraFadingEnabled.hasMixedValue; var enabled = cameraFadingEnabled.floatValue; EditorGUI.BeginChangeCheck(); enabled = EditorGUILayout.Toggle(Styles.cameraFadingEnabled, enabled != 0.0f) ? 1.0f : 0.0f; if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Camera Fading Enabled"); cameraFadingEnabled.floatValue = enabled; } if (enabled != 0.0f) { int indentation = 2; m_MaterialEditor.ShaderProperty(cameraNearFadeDistance, Styles.cameraNearFadeDistanceText, indentation); m_MaterialEditor.ShaderProperty(cameraFarFadeDistance, Styles.cameraFarFadeDistanceText, indentation); } } EditorGUI.showMixedValue = false; } } void DistortionPopup(Material material) { // Z write doesn't work with distortion bool hasZWrite = (material.GetFloat("_ZWrite") > 0.0f); if (!hasZWrite) { EditorGUI.showMixedValue = distortionEnabled.hasMixedValue; var enabled = (distortionEnabled.floatValue != 0.0f); EditorGUI.BeginChangeCheck(); enabled = EditorGUILayout.Toggle(Styles.distortionEnabled, enabled); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Distortion Enabled"); distortionEnabled.floatValue = enabled ? 1.0f : 0.0f; } if (enabled) { int indentation = 2; m_MaterialEditor.ShaderProperty(distortionStrength, Styles.distortionStrengthText, indentation); m_MaterialEditor.ShaderProperty(distortionBlend, Styles.distortionBlendText, indentation); } EditorGUI.showMixedValue = false; } } void DoAlbedoArea(Material material) { m_MaterialEditor.TexturePropertyWithHDRColor(Styles.albedoText, albedoMap, albedoColor, true); if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout)) { m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText, MaterialEditor.kMiniTextureFieldLabelIndentLevel); } } void DoEmissionArea(Material material) { // Emission EditorGUI.showMixedValue = emissionEnabled.hasMixedValue; var enabled = (emissionEnabled.floatValue != 0.0f); EditorGUI.BeginChangeCheck(); enabled = EditorGUILayout.Toggle(Styles.emissionEnabled, enabled); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Emission Enabled"); emissionEnabled.floatValue = enabled ? 1.0f : 0.0f; } if (enabled) { bool hadEmissionTexture = emissionMap.textureValue != null; // Texture and HDR color controls m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionText, emissionMap, emissionColorForRendering, false); // If texture was assigned and color was black set color to white float brightness = emissionColorForRendering.colorValue.maxColorComponent; if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f) emissionColorForRendering.colorValue = Color.white; } } void DoSpecularMetallicArea(Material material) { if (metallicMap == null) return; bool useLighting = (material.GetFloat("_LightingEnabled") > 0.0f); if (useLighting) { bool hasGlossMap = metallicMap.textureValue != null; m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicMap, hasGlossMap ? null : metallic); int indentation = 2; // align with labels of texture properties bool showSmoothnessScale = hasGlossMap; m_MaterialEditor.ShaderProperty(smoothness, showSmoothnessScale ? Styles.smoothnessScaleText : Styles.smoothnessText, indentation); } } void DoNormalMapArea(Material material) { bool hasZWrite = (material.GetFloat("_ZWrite") > 0.0f); bool useLighting = (material.GetFloat("_LightingEnabled") > 0.0f); bool useDistortion = (material.GetFloat("_DistortionEnabled") > 0.0f) && !hasZWrite; if (useLighting || useDistortion) { m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap, bumpMap.textureValue != null ? bumpScale : null); } } void DoVertexStreamsArea(Material material) { // Display list of streams required to make this shader work bool useLighting = (material.GetFloat("_LightingEnabled") > 0.0f); bool useFlipbookBlending = (material.GetFloat("_FlipbookMode") > 0.0f); bool useTangents = useLighting && material.GetTexture("_BumpMap"); bool useGPUInstancing = ShaderUtil.HasProceduralInstancing(material.shader); if (useGPUInstancing && m_RenderersUsingThisMaterial.Count > 0) { if (!m_RenderersUsingThisMaterial[0].enableGPUInstancing || m_RenderersUsingThisMaterial[0].renderMode != ParticleSystemRenderMode.Mesh) useGPUInstancing = false; } GUILayout.Label(Styles.streamPositionText, EditorStyles.label); if (useLighting) GUILayout.Label(Styles.streamNormalText, EditorStyles.label); GUILayout.Label(useGPUInstancing ? Styles.streamColorInstancedText : Styles.streamColorText, EditorStyles.label); GUILayout.Label(Styles.streamUVText, EditorStyles.label); if (useTangents) GUILayout.Label(Styles.streamTangentText, EditorStyles.label); if (useGPUInstancing) { GUILayout.Label(Styles.streamAnimFrameText, EditorStyles.label); } else if (useFlipbookBlending && !useGPUInstancing) { GUILayout.Label(Styles.streamUV2Text, EditorStyles.label); GUILayout.Label(Styles.streamAnimBlendText, EditorStyles.label); } // Build the list of expected vertex streams List<ParticleSystemVertexStream> streams = new List<ParticleSystemVertexStream>(); streams.Add(ParticleSystemVertexStream.Position); if (useLighting) streams.Add(ParticleSystemVertexStream.Normal); streams.Add(ParticleSystemVertexStream.Color); streams.Add(ParticleSystemVertexStream.UV); if (useTangents) streams.Add(ParticleSystemVertexStream.Tangent); List<ParticleSystemVertexStream> instancedStreams = new List<ParticleSystemVertexStream>(streams); if (useGPUInstancing) { instancedStreams.Add(ParticleSystemVertexStream.AnimFrame); } if (useFlipbookBlending) { streams.Add(ParticleSystemVertexStream.UV2); streams.Add(ParticleSystemVertexStream.AnimBlend); } // Set the streams on all systems using this material if (GUILayout.Button(Styles.streamApplyToAllSystemsText, EditorStyles.miniButton, GUILayout.ExpandWidth(false))) { Undo.RecordObjects(m_RenderersUsingThisMaterial.Where(r => r != null).ToArray(), Styles.undoApplyCustomVertexStreams); foreach (ParticleSystemRenderer renderer in m_RenderersUsingThisMaterial) { if (renderer != null) { if (useGPUInstancing && renderer.renderMode == ParticleSystemRenderMode.Mesh && renderer.supportsMeshInstancing) renderer.SetActiveVertexStreams(instancedStreams); else renderer.SetActiveVertexStreams(streams); } } } // Display a warning if any renderers have incorrect vertex streams string Warnings = ""; List<ParticleSystemVertexStream> rendererStreams = new List<ParticleSystemVertexStream>(); foreach (ParticleSystemRenderer renderer in m_RenderersUsingThisMaterial) { if (renderer != null) { renderer.GetActiveVertexStreams(rendererStreams); bool streamsValid; if (useGPUInstancing && renderer.renderMode == ParticleSystemRenderMode.Mesh && renderer.supportsMeshInstancing) streamsValid = CompareVertexStreams(rendererStreams, instancedStreams); else streamsValid = CompareVertexStreams(rendererStreams, streams); if (!streamsValid) Warnings += " " + renderer.name + "\n"; } } if (Warnings != "") { EditorGUILayout.HelpBox("The following Particle System Renderers are using this material with incorrect Vertex Streams:\n" + Warnings + "Use the Apply to Systems button to fix this", MessageType.Warning, true); } EditorGUILayout.Space(); } private static bool CompareVertexStreams(IEnumerable<ParticleSystemVertexStream> a, IEnumerable<ParticleSystemVertexStream> b) { var differenceA = a.Except(b); var differenceB = b.Except(a); var difference = differenceA.Union(differenceB).Distinct(); if (!difference.Any()) return true; // If normals are the only difference, ignore them, because the default particle streams include normals, to make it easy for users to switch between lit and unlit if (difference.Count() == 1) { if (difference.First() == ParticleSystemVertexStream.Normal) return true; } return false; } public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode, bool overrideRenderQueue) { int minRenderQueue = -1; int maxRenderQueue = 5000; int defaultRenderQueue = -1; switch (blendMode) { case BlendMode.Opaque: material.SetOverrideTag("RenderType", ""); material.SetFloat("_BlendOp", (float)UnityEngine.Rendering.BlendOp.Add); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.One); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.Zero); material.SetFloat("_ZWrite", 1.0f); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.DisableKeyword("_ALPHAMODULATE_ON"); minRenderQueue = -1; maxRenderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest - 1; defaultRenderQueue = -1; break; case BlendMode.Cutout: material.SetOverrideTag("RenderType", "TransparentCutout"); material.SetFloat("_BlendOp", (float)UnityEngine.Rendering.BlendOp.Add); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.One); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.Zero); material.SetFloat("_ZWrite", 1.0f); material.EnableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.DisableKeyword("_ALPHAMODULATE_ON"); minRenderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; maxRenderQueue = (int)UnityEngine.Rendering.RenderQueue.GeometryLast; defaultRenderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest; break; case BlendMode.Fade: material.SetOverrideTag("RenderType", "Transparent"); material.SetFloat("_BlendOp", (float)UnityEngine.Rendering.BlendOp.Add); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetFloat("_ZWrite", 0.0f); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.DisableKeyword("_ALPHAMODULATE_ON"); minRenderQueue = (int)UnityEngine.Rendering.RenderQueue.GeometryLast + 1; maxRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Overlay - 1; defaultRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; case BlendMode.Transparent: material.SetOverrideTag("RenderType", "Transparent"); material.SetFloat("_BlendOp", (float)UnityEngine.Rendering.BlendOp.Add); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.One); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetFloat("_ZWrite", 0.0f); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); material.DisableKeyword("_ALPHAMODULATE_ON"); minRenderQueue = (int)UnityEngine.Rendering.RenderQueue.GeometryLast + 1; maxRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Overlay - 1; defaultRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; case BlendMode.Additive: material.SetOverrideTag("RenderType", "Transparent"); material.SetFloat("_BlendOp", (float)UnityEngine.Rendering.BlendOp.Add); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.One); material.SetFloat("_ZWrite", 0.0f); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.DisableKeyword("_ALPHAMODULATE_ON"); minRenderQueue = (int)UnityEngine.Rendering.RenderQueue.GeometryLast + 1; maxRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Overlay - 1; defaultRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; case BlendMode.Subtractive: material.SetOverrideTag("RenderType", "Transparent"); material.SetFloat("_BlendOp", (float)UnityEngine.Rendering.BlendOp.ReverseSubtract); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.SrcAlpha); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.One); material.SetFloat("_ZWrite", 0.0f); material.DisableKeyword("_ALPHATEST_ON"); material.EnableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.DisableKeyword("_ALPHAMODULATE_ON"); minRenderQueue = (int)UnityEngine.Rendering.RenderQueue.GeometryLast + 1; maxRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Overlay - 1; defaultRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; case BlendMode.Modulate: material.SetOverrideTag("RenderType", "Transparent"); material.SetFloat("_BlendOp", (float)UnityEngine.Rendering.BlendOp.Add); material.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.DstColor); material.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); material.SetFloat("_ZWrite", 0.0f); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHABLEND_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.EnableKeyword("_ALPHAMODULATE_ON"); minRenderQueue = (int)UnityEngine.Rendering.RenderQueue.GeometryLast + 1; maxRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Overlay - 1; defaultRenderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent; break; } if (overrideRenderQueue || material.renderQueue < minRenderQueue || material.renderQueue > maxRenderQueue) { if (!overrideRenderQueue) Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Render queue value outside of the allowed range ({0} - {1}) for selected Blend mode, resetting render queue to default", minRenderQueue, maxRenderQueue); material.renderQueue = defaultRenderQueue; } } public static void SetupMaterialWithColorMode(Material material, ColorMode colorMode) { switch (colorMode) { case ColorMode.Multiply: material.DisableKeyword("_COLOROVERLAY_ON"); material.DisableKeyword("_COLORCOLOR_ON"); material.DisableKeyword("_COLORADDSUBDIFF_ON"); break; case ColorMode.Overlay: material.DisableKeyword("_COLORCOLOR_ON"); material.DisableKeyword("_COLORADDSUBDIFF_ON"); material.EnableKeyword("_COLOROVERLAY_ON"); break; case ColorMode.Color: material.DisableKeyword("_COLOROVERLAY_ON"); material.DisableKeyword("_COLORADDSUBDIFF_ON"); material.EnableKeyword("_COLORCOLOR_ON"); break; case ColorMode.Difference: material.DisableKeyword("_COLOROVERLAY_ON"); material.DisableKeyword("_COLORCOLOR_ON"); material.EnableKeyword("_COLORADDSUBDIFF_ON"); material.SetVector("_ColorAddSubDiff", new Vector4(-1.0f, 1.0f, 0.0f, 0.0f)); break; case ColorMode.Additive: material.DisableKeyword("_COLOROVERLAY_ON"); material.DisableKeyword("_COLORCOLOR_ON"); material.EnableKeyword("_COLORADDSUBDIFF_ON"); material.SetVector("_ColorAddSubDiff", new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); break; case ColorMode.Subtractive: material.DisableKeyword("_COLOROVERLAY_ON"); material.DisableKeyword("_COLORCOLOR_ON"); material.EnableKeyword("_COLORADDSUBDIFF_ON"); material.SetVector("_ColorAddSubDiff", new Vector4(-1.0f, 0.0f, 0.0f, 0.0f)); break; } } void SetMaterialKeywords(Material material) { // Z write doesn't work with distortion/fading bool hasZWrite = (material.GetFloat("_ZWrite") > 0.0f); // Lit shader? bool useLighting = (material.GetFloat("_LightingEnabled") > 0.0f); // Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation // (MaterialProperty value might come from renderer material property block) bool useDistortion = !hasZWrite && (material.GetFloat("_DistortionEnabled") > 0.0f); SetKeyword(material, "_NORMALMAP", (useLighting || useDistortion) && material.GetTexture("_BumpMap")); SetKeyword(material, "_METALLICGLOSSMAP", useLighting && material.GetTexture("_MetallicGlossMap")); material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.None; SetKeyword(material, "_EMISSION", material.GetFloat("_EmissionEnabled") > 0.0f); // Set the define for flipbook blending bool useFlipbookBlending = (material.GetFloat("_FlipbookMode") > 0.0f); SetKeyword(material, "_REQUIRE_UV2", useFlipbookBlending); // Clamp fade distances bool useSoftParticles = (material.GetFloat("_SoftParticlesEnabled") > 0.0f); bool useCameraFading = (material.GetFloat("_CameraFadingEnabled") > 0.0f); float softParticlesNearFadeDistance = material.GetFloat("_SoftParticlesNearFadeDistance"); float softParticlesFarFadeDistance = material.GetFloat("_SoftParticlesFarFadeDistance"); float cameraNearFadeDistance = material.GetFloat("_CameraNearFadeDistance"); float cameraFarFadeDistance = material.GetFloat("_CameraFarFadeDistance"); if (softParticlesNearFadeDistance < 0.0f) { softParticlesNearFadeDistance = 0.0f; material.SetFloat("_SoftParticlesNearFadeDistance", 0.0f); } if (softParticlesFarFadeDistance < 0.0f) { softParticlesFarFadeDistance = 0.0f; material.SetFloat("_SoftParticlesFarFadeDistance", 0.0f); } if (cameraNearFadeDistance < 0.0f) { cameraNearFadeDistance = 0.0f; material.SetFloat("_CameraNearFadeDistance", 0.0f); } if (cameraFarFadeDistance < 0.0f) { cameraFarFadeDistance = 0.0f; material.SetFloat("_CameraFarFadeDistance", 0.0f); } // Set the define for fading bool useFading = (useSoftParticles || useCameraFading) && !hasZWrite; SetKeyword(material, "_FADING_ON", useFading); if (useSoftParticles) material.SetVector("_SoftParticleFadeParams", new Vector4(softParticlesNearFadeDistance, 1.0f / (softParticlesFarFadeDistance - softParticlesNearFadeDistance), 0.0f, 0.0f)); else material.SetVector("_SoftParticleFadeParams", new Vector4(0.0f, 0.0f, 0.0f, 0.0f)); if (useCameraFading) material.SetVector("_CameraFadeParams", new Vector4(cameraNearFadeDistance, 1.0f / (cameraFarFadeDistance - cameraNearFadeDistance), 0.0f, 0.0f)); else material.SetVector("_CameraFadeParams", new Vector4(0.0f, Mathf.Infinity, 0.0f, 0.0f)); // Set the define for distortion + grabpass SetKeyword(material, "EFFECT_BUMP", useDistortion); material.SetShaderPassEnabled("Always", true); // because grabpass used to use the always pass, we need to force it on, to correct old materials (case 1402353) material.SetShaderPassEnabled("GrabPass", useDistortion); if (useDistortion) material.SetFloat("_DistortionStrengthScaled", material.GetFloat("_DistortionStrength") * 0.1f); // more friendly number scale than 1 unit per size of the screen } override public void ValidateMaterial(Material material) { SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"), false); if (material.HasProperty("_ColorMode")) SetupMaterialWithColorMode(material, (ColorMode)material.GetFloat("_ColorMode")); SetMaterialKeywords(material); } void CacheRenderersUsingThisMaterial(Material material) { m_RenderersUsingThisMaterial.Clear(); ParticleSystemRenderer[] renderers = Resources.FindObjectsOfTypeAll(typeof(ParticleSystemRenderer)) as ParticleSystemRenderer[]; foreach (ParticleSystemRenderer renderer in renderers) { var go = renderer.gameObject; if (go.hideFlags == HideFlags.NotEditable || go.hideFlags == HideFlags.HideAndDontSave) continue; if (renderer.sharedMaterial == material) m_RenderersUsingThisMaterial.Add(renderer); } } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } } // namespace UnityEditor
UnityCsReference/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/StandardParticlesShaderGUI.cs", "repo_id": "UnityCsReference", "token_count": 19963 }
333
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { [System.Serializable] internal class TransformRotationGUI { private GUIContent rotationContent = EditorGUIUtility.TrTextContent("Rotation", "The local rotation of this Game Object relative to the parent."); private const float kQuaternionFloatPrecision = 1e-6f; EditorGUI.NumberFieldValue[] m_EulerFloats = { new EditorGUI.NumberFieldValue(0.0f), new EditorGUI.NumberFieldValue(0.0f), new EditorGUI.NumberFieldValue(0.0f) }; SerializedProperty m_Rotation; Object[] targets; private static int s_FoldoutHash = "Foldout".GetHashCode(); private static readonly GUIContent[] s_XYZLabels = {EditorGUIUtility.TextContent("X"), EditorGUIUtility.TextContent("Y"), EditorGUIUtility.TextContent("Z")}; public void OnEnable(SerializedProperty m_Rotation, GUIContent label) { this.m_Rotation = m_Rotation; this.targets = m_Rotation.serializedObject.targetObjects; rotationContent = label; } public void RotationField() { RotationField(false); } public void RotationField(bool disabled) { Transform transform0 = targets[0] as Transform; Vector3 eulerAngles0 = transform0.GetLocalEulerAngles(transform0.rotationOrder); int differentRotationMask = 0b000; bool differentRotationOrder = false; for (int i = 1; i < targets.Length; i++) { Transform otherTransform = (targets[i] as Transform); if (differentRotationMask != 0b111) { Vector3 otherLocalEuler = otherTransform.GetLocalEulerAngles(otherTransform.rotationOrder); for (int j = 0; j < 3; j++) { if (otherLocalEuler[j] != eulerAngles0[j]) differentRotationMask |= 1 << j; } } differentRotationOrder |= otherTransform.rotationOrder != transform0.rotationOrder; } Rect r = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * (EditorGUIUtility.wideMode ? 1 : 2)); GUIContent label = EditorGUI.BeginProperty(r, rotationContent, m_Rotation); if (m_Rotation.isLiveModified) { Vector3 eulerValue = m_Rotation.quaternionValue.eulerAngles; m_EulerFloats[0].doubleVal = Mathf.Floor(eulerValue.x / kQuaternionFloatPrecision) * kQuaternionFloatPrecision; m_EulerFloats[1].doubleVal = Mathf.Floor(eulerValue.y / kQuaternionFloatPrecision) * kQuaternionFloatPrecision; m_EulerFloats[2].doubleVal = Mathf.Floor(eulerValue.z / kQuaternionFloatPrecision) * kQuaternionFloatPrecision; } else { m_EulerFloats[0].doubleVal = eulerAngles0.x; m_EulerFloats[1].doubleVal = eulerAngles0.y; m_EulerFloats[2].doubleVal = eulerAngles0.z; } int id = GUIUtility.GetControlID(s_FoldoutHash, FocusType.Keyboard, r); if (AnimationMode.InAnimationMode() && transform0.rotationOrder != RotationOrder.OrderZXY) { string rotationLabel = differentRotationOrder ? "Mixed" : transform0.rotationOrder.ToString().Substring(RotationOrder.OrderXYZ.ToString().Length - 3); label.text = label.text + " (" + rotationLabel + ")"; } // Using manual 3 float fields here instead of MultiFloatField or Vector3Field // since we want to query expression validity of each individually, and // so that the label and the fields can be disabled separately, similar to // regular property fields. Also want to avoid superfluous label, which // creates a focus target even when there's no content (Case 953241). r = EditorGUI.MultiFieldPrefixLabel(r, id, label, 3); r.height = EditorGUIUtility.singleLineHeight; int eulerChangedMask = 0; using (new EditorGUI.DisabledScope(disabled)) { var eCount = m_EulerFloats.Length; float w = (r.width - (eCount - 1) * EditorGUI.kSpacingSubLabel) / eCount; Rect nr = new Rect(r) {width = w}; var prevWidth = EditorGUIUtility.labelWidth; var prevIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; SerializedProperty rotation = m_Rotation.Copy(); for (int i = 0; i < m_EulerFloats.Length; i++) { rotation.Next(true); EditorGUI.BeginProperty(nr, s_XYZLabels[i], rotation); EditorGUIUtility.labelWidth = EditorGUI.GetLabelWidth(s_XYZLabels[i]); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = (differentRotationMask & (1 << i)) != 0; EditorGUI.FloatField(nr, s_XYZLabels[i], ref m_EulerFloats[i]); if (EditorGUI.EndChangeCheck() && m_EulerFloats[i].hasResult) eulerChangedMask |= 1 << i; if (Event.current.type == EventType.ContextClick && nr.Contains(Event.current.mousePosition)) { var childProperty = m_Rotation.Copy(); childProperty.Next(true); int childPropertyIndex = i; while (childPropertyIndex > 0) { childProperty.Next(false); childPropertyIndex--; } EditorGUI.DoPropertyContextMenu(childProperty); Event.current.Use(); } nr.x += w + EditorGUI.kSpacingSubLabel; EditorGUI.EndProperty(); } EditorGUIUtility.labelWidth = prevWidth; EditorGUI.indentLevel = prevIndent; } if (eulerChangedMask != 0) { eulerAngles0 = new Vector3( MathUtils.ClampToFloat(m_EulerFloats[0].doubleVal), MathUtils.ClampToFloat(m_EulerFloats[1].doubleVal), MathUtils.ClampToFloat(m_EulerFloats[2].doubleVal)); Undo.RecordObjects(targets, "Inspector"); // Generic undo title as remove duplicates will discard the name. Undo.SetCurrentGroupName(string.Format("Set Rotation")); for (var idx = 0; idx < targets.Length; ++idx) { var tr = targets[idx] as Transform; if (tr == null) continue; var trEuler = tr.GetLocalEulerAngles(tr.rotationOrder); // if we have any per-object expressions just entered, we need to evaluate // it for each object with their own individual input value for (int c = 0; c < 3; ++c) { if ((eulerChangedMask & (1 << c)) != 0) { if (m_EulerFloats[c].expression != null) { double trEulerComp = eulerAngles0[c]; if (m_EulerFloats[c].expression.Evaluate(ref trEulerComp, idx, targets.Length)) trEuler[c] = MathUtils.ClampToFloat(trEulerComp); } else { trEuler[c] = MathUtils.ClampToFloat(eulerAngles0[c]); } } } if (m_Rotation.isLiveModified) { m_Rotation.quaternionValue = Quaternion.Euler(trEuler.x, trEuler.y, trEuler.z); } else { tr.SetLocalEulerAngles(trEuler, tr.rotationOrder); if (tr.parent != null) tr.SendTransformChangedScale(); // force scale update, needed if tr has non-uniformly scaled parent. } } m_Rotation.serializedObject.SetIsDifferentCacheDirty(); } EditorGUI.showMixedValue = false; if (differentRotationOrder) { EditorGUILayout.HelpBox("Transforms have different rotation orders, keyframes saved will have the same value but not the same local rotation", MessageType.Warning); } EditorGUI.EndProperty(); } } }
UnityCsReference/Editor/Mono/Inspector/TransformRotationGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/TransformRotationGUI.cs", "repo_id": "UnityCsReference", "token_count": 4703 }
334
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEditor; using System.Globalization; namespace UnityEditor { [CustomEditor(typeof(WebCamTexture))] internal class WebCamTextureInspector : Editor { static GUIContent[] s_PlayIcons = {null, null}; Vector2 m_Pos; public override void OnInspectorGUI() { WebCamTexture t = target as WebCamTexture; EditorGUILayout.LabelField("Requested FPS", t.requestedFPS.ToString(CultureInfo.InvariantCulture.NumberFormat)); EditorGUILayout.LabelField("Requested Width", t.requestedWidth.ToString(CultureInfo.InvariantCulture.NumberFormat)); EditorGUILayout.LabelField("Requested Height", t.requestedHeight.ToString(CultureInfo.InvariantCulture.NumberFormat)); EditorGUILayout.LabelField("Device Name", t.deviceName); } static void Init() { s_PlayIcons[0] = EditorGUIUtility.IconContent("preAudioPlayOff"); s_PlayIcons[1] = EditorGUIUtility.IconContent("preAudioPlayOn"); } public override bool HasPreviewGUI() { return (target != null); } public override void OnPreviewSettings() { Init(); // Disallow playing movie previews in play mode. Better not to interfere // with any playback the game does. GUI.enabled = !Application.isPlaying; WebCamTexture t = target as WebCamTexture; bool isPlaying = PreviewGUI.CycleButton(t.isPlaying ? 1 : 0, s_PlayIcons) != 0; if (isPlaying != t.isPlaying) { if (isPlaying) { t.Stop(); t.Play(); } else { t.Pause(); } } GUI.enabled = true; } public override void OnPreviewGUI(Rect r, GUIStyle background) { if (Event.current.type == EventType.Repaint) background.Draw(r, false, false, false, false); // show texture WebCamTexture t = target as WebCamTexture; float zoomLevel = Mathf.Min(Mathf.Min(r.width / t.width, r.height / t.height), 1); Rect wantedRect = new Rect(r.x, r.y, t.width * zoomLevel, t.height * zoomLevel); PreviewGUI.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb"); GUI.DrawTexture(wantedRect, t, ScaleMode.StretchToFill, false); m_Pos = PreviewGUI.EndScrollView(); // force update GUI if (t.isPlaying) GUIView.current.Repaint(); if (Application.isPlaying) { if (t.isPlaying) EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10, r.width, 20), "Can't pause preview when in play mode"); else EditorGUI.DropShadowLabel(new Rect(r.x, r.y + 10, r.width, 20), "Can't start preview when in play mode"); } } public void OnDisable() { WebCamTexture t = target as WebCamTexture; //stop the camera if we started it if (!Application.isPlaying && t != null) { t.Stop(); } } public override string GetInfoString() { Texture t = target as Texture; string info = t.width + "x" + t.height; GraphicsFormat format = GraphicsFormatUtility.GetFormat(t); info += " " + GraphicsFormatUtility.GetFormatString(format); return info; } } }
UnityCsReference/Editor/Mono/Inspector/WebCamTextureInspector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Inspector/WebCamTextureInspector.cs", "repo_id": "UnityCsReference", "token_count": 1832 }
335
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using Object = UnityEngine.Object; using UnityEngine.Bindings; using UnityEditor; namespace UnityEditorInternal { [NativeHeader("Editor/Mono/MemorySettings.bindings.h")] [StaticAccessor("MemorySettingsBindings", StaticAccessorType.DoubleColon)] internal sealed partial class MemorySettingsUtils { extern internal static void SetPlatformDefaultValues(int platform); extern internal static void WriteEditorMemorySettings(); extern internal static void InitializeDefaultsForPlatform(int platform); } }
UnityCsReference/Editor/Mono/MemorySettings.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/MemorySettings.bindings.cs", "repo_id": "UnityCsReference", "token_count": 207 }
336
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor { internal class FileOpenInfo : IFileOpenInfo { public string FilePath { get; set; } public int LineNumber { get; set; } public FileOpenInfo() { LineNumber = 1; FilePath = string.Empty; } } }
UnityCsReference/Editor/Mono/MonoCecil/FileOpenInfo.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/MonoCecil/FileOpenInfo.cs", "repo_id": "UnityCsReference", "token_count": 181 }
337
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using JetBrains.Annotations; using UnityEditor.AnimatedValues; using UnityEditor.IMGUI.Controls; using UnityEditor.SceneManagement; using UnityEditor.SearchService; using UnityEditorInternal; using UnityEngine; using UnityEngine.Audio; using UnityObject = UnityEngine.Object; using Scene = UnityEngine.SceneManagement.Scene; namespace UnityEditor { internal abstract class ObjectSelectorReceiver : ScriptableObject { public abstract void OnSelectionChanged(UnityObject selection); public abstract void OnSelectionClosed(UnityObject selection); } internal class ObjectSelector : EditorWindow { // Styles used in the object selector static class Styles { public static GUIStyle smallStatus = "ObjectPickerSmallStatus"; public static GUIStyle largeStatus = "ObjectPickerLargeStatus"; public static GUIStyle tab = "ObjectPickerTab"; public static GUIStyle bottomResize = "WindowBottomResize"; public static GUIStyle previewBackground = "PopupCurveSwatchBackground"; // TODO: Make dedicated style public static GUIStyle previewTextureBackground = "ObjectPickerPreviewBackground"; // TODO: Make dedicated style public static GUIContent assetsTabLabel = EditorGUIUtility.TrTextContent("Assets"); public static GUIContent sceneTabLabel = EditorGUIUtility.TrTextContent("Scene"); public static readonly GUIContent packagesVisibilityContent = EditorGUIUtility.TrIconContent("SceneViewVisibility", "Number of hidden packages, click to toggle packages visibility"); } public const string ObjectSelectorClosedCommand = "ObjectSelectorClosed"; public const string ObjectSelectorUpdatedCommand = "ObjectSelectorUpdated"; public const string ObjectSelectorCanceledCommand = "ObjectSelectorCanceled"; public const string ObjectSelectorSelectionDoneCommand = "ObjectSelectorSelectionDone"; // Filters string[] m_RequiredTypes; string m_SearchFilter; // Display state bool m_FocusSearchFilter; bool m_AllowSceneObjects; bool m_IsShowingAssets; bool m_SkipHiddenPackages; SavedInt m_StartGridSize = new SavedInt("ObjectSelector.GridSize", 64); // Misc internal int objectSelectorID = 0; ObjectSelectorReceiver m_ObjectSelectorReceiver; int m_ModalUndoGroup = -1; UnityObject m_OriginalSelection; EditorCache m_EditorCache; GUIView m_DelegateView; PreviewResizer m_PreviewResizer = new PreviewResizer(); List<int> m_AllowedIDs; // Callbacks Action<UnityObject> m_OnObjectSelectorClosed; Action<UnityObject> m_OnObjectSelectorUpdated; ObjectListAreaState m_ListAreaState; ObjectListArea m_ListArea; ObjectTreeForSelector m_ObjectTreeWithSearch = new ObjectTreeForSelector(); UnityObject m_ObjectBeingEdited; SerializedProperty m_EditedProperty; bool m_ShowNoneItem; bool m_SelectionCancelled; int m_LastSelectedInstanceId = 0; readonly SearchService.ObjectSelectorSearchSessionHandler m_SearchSessionHandler = new SearchService.ObjectSelectorSearchSessionHandler(); readonly SearchSessionOptions m_LegacySearchSessionOptions = new SearchSessionOptions { legacyOnly = true }; // Layout const float kMinTopSize = 250; const float kMinWidth = 200; const float kPreviewMargin = 5; const float kPreviewExpandedAreaHeight = 75; static float kToolbarHeight => EditorGUI.kWindowToolbarHeight; static float kTopAreaHeight => kToolbarHeight * 2; const float kResizerHeight = 20f; float m_PreviewSize = 0; float m_TopSize = 0; AnimBool m_ShowWidePreview = new AnimBool(); AnimBool m_ShowOverlapPreview = new AnimBool(); static HashSet<Event> s_GridAreaPriorityKeyboardEvents; // Delayer for debouncing search inputs private Delayer m_Debounce; Rect listPosition { get { return new Rect(0, kTopAreaHeight, position.width, Mathf.Max(0f, m_TopSize - kTopAreaHeight)); } } public List<int> allowedInstanceIDs { get { return m_AllowedIDs; } } public UnityObject objectBeingEdited { get { return m_ObjectBeingEdited; } } // get an existing ObjectSelector or create one static ObjectSelector s_SharedObjectSelector = null; public static ObjectSelector get { get { if (s_SharedObjectSelector == null) { UnityObject[] objs = Resources.FindObjectsOfTypeAll(typeof(ObjectSelector)); if (objs != null && objs.Length > 0) s_SharedObjectSelector = (ObjectSelector)objs[0]; if (s_SharedObjectSelector == null) s_SharedObjectSelector = ScriptableObject.CreateInstance<ObjectSelector>(); } return s_SharedObjectSelector; } } public static bool isVisible { get { return s_SharedObjectSelector != null; } } bool IsUsingTreeView() { return m_ObjectTreeWithSearch.IsInitialized(); } // Internal for test purposes only internal int GetInternalSelectedInstanceID() { if (m_ListArea == null) InitIfNeeded(); int[] selection = IsUsingTreeView() ? m_ObjectTreeWithSearch.GetSelection() : m_ListArea.GetSelection(); if (selection.Length >= 1) return selection[0]; return 0; } int GetSelectedInstanceID() { return m_LastSelectedInstanceId; } [UsedImplicitly] void OnEnable() { hideFlags = HideFlags.DontSave; m_ShowOverlapPreview.valueChanged.AddListener(Repaint); m_ShowOverlapPreview.speed = 1.5f; m_ShowWidePreview.valueChanged.AddListener(Repaint); m_ShowWidePreview.speed = 1.5f; m_PreviewResizer.Init("ObjectPickerPreview"); m_PreviewSize = m_PreviewResizer.GetPreviewSize(); // Init size if (s_GridAreaPriorityKeyboardEvents == null) { s_GridAreaPriorityKeyboardEvents = new HashSet<Event> { Event.KeyboardEvent("up"), Event.KeyboardEvent("down"), }; } AssetPreview.ClearTemporaryAssetPreviews(); SetupPreview(); m_Debounce = Delayer.Debounce(_ => { FilterSettingsChanged(); Repaint(); }); } [UsedImplicitly] void OnDisable() { NotifySelectorClosed(false); if (m_ListArea != null) m_StartGridSize.value = m_ListArea.gridSize; if (s_SharedObjectSelector == this) s_SharedObjectSelector = null; if (m_EditorCache != null) m_EditorCache.Dispose(); AssetPreview.ClearTemporaryAssetPreviews(); HierarchyProperty.ClearSceneObjectsFilter(); m_Debounce?.Dispose(); m_Debounce = null; } public void SetupPreview() { bool open = PreviewIsOpen(); bool wide = PreviewIsWide(); m_ShowOverlapPreview.target = m_ShowOverlapPreview.value = (open && !wide); m_ShowWidePreview.target = m_ShowWidePreview.value = (open && wide); } void ListAreaItemSelectedCallback(bool doubleClicked) { m_LastSelectedInstanceId = GetInternalSelectedInstanceID(); if (doubleClicked) { ItemWasDoubleClicked(); } else { m_FocusSearchFilter = false; NotifySelectionChanged(true); } } internal string searchFilter { get { return m_SearchFilter; } set { if (ObjectSelectorSearch.HasEngineOverride()) { m_SearchSessionHandler.SetSearchFilter(value); return; } m_SearchFilter = value; m_Debounce?.Execute(); } } public ObjectSelectorReceiver objectSelectorReceiver { get { return m_ObjectSelectorReceiver; } set { m_ObjectSelectorReceiver = value; } } Scene GetSceneFromObject(UnityObject obj) { var go = obj as GameObject; if (go != null) return go.scene; var component = obj as Component; if (component != null) return component.gameObject.scene; return new Scene(); } // Used by tests internal void Internal_TriggerFilterSettingsChanged() { FilterSettingsChanged(); } void FilterSettingsChanged() { var filter = GetSearchFilter(); var hierarchyType = m_IsShowingAssets ? HierarchyType.Assets : HierarchyType.GameObjects; bool hasObject = false; var requiredTypes = new List<Type>(); var objectTypes = TypeCache.GetTypesDerivedFrom<UnityEngine.Object>(); foreach (var type in m_RequiredTypes) { foreach (var objectType in objectTypes) { if (objectType.Name == type) requiredTypes.Add(objectType); else if (!hasObject) { requiredTypes.Add(typeof(UnityObject)); hasObject = true; } } } m_ListArea.InitForSearch(listPosition, hierarchyType, filter, true, s => { foreach (var type in requiredTypes) { var asset = AssetDatabase.LoadAssetAtPath(s, type); if (asset != null && asset.GetInstanceID() != 0) return asset.GetInstanceID(); } return 0; }, m_LegacySearchSessionOptions); } SearchFilter GetSearchFilter() { var filter = new SearchFilter(); if (m_IsShowingAssets) filter.searchArea = SearchFilter.SearchArea.AllAssets; filter.SearchFieldStringToFilter(m_SearchFilter); if (filter.classNames.Length == 0 && m_RequiredTypes.All(type => !string.IsNullOrEmpty(type))) filter.classNames = m_RequiredTypes; var hierarchyType = m_IsShowingAssets ? HierarchyType.Assets : HierarchyType.GameObjects; if (hierarchyType == HierarchyType.GameObjects) { if (m_ObjectBeingEdited != null) { var scene = GetSceneFromObject(m_ObjectBeingEdited); if (scene.IsValid()) { // We do not support cross scene references so ensure we only show game objects // from the same scene as the object being edited is part of. // Also don't allow references to other scenes if object being edited // is in a preview scene. if (EditorSceneManager.IsPreviewScene(scene) || EditorSceneManager.preventCrossSceneReferences) filter.sceneHandles = new[] { scene.handle }; } } else { // If we don't know which object is being edited, assume it's one in current stage. PreviewSceneStage previewSceneStage = StageUtility.GetCurrentStage() as PreviewSceneStage; if (previewSceneStage != null) { filter.sceneHandles = new[] { previewSceneStage.scene.handle }; } } } if (hierarchyType == HierarchyType.Assets) { // When AssemblyDefinitionAsset is the required type, don't skip hidden packages foreach (var type in m_RequiredTypes) { if (!string.IsNullOrEmpty(type) && type == typeof(AssemblyDefinitionAsset).Name) { m_SkipHiddenPackages = false; break; } } filter.skipHidden = m_SkipHiddenPackages; } return filter; } static bool ShouldTreeViewBeUsed(String typeStr) { return (String.Equals(typeof(AudioMixerGroup).Name, typeStr)); } private readonly Regex s_MatchPPtrTypeName = new Regex(@"PPtr\<(\w+)\>"); internal void Show(Type requiredType, SerializedProperty property, bool allowSceneObjects, List<int> allowedInstanceIDs = null, Action<UnityObject> onObjectSelectorClosed = null, Action<UnityObject> onObjectSelectedUpdated = null) { if (property == null) throw new ArgumentNullException(nameof(property)); if (requiredType == null) { ScriptAttributeUtility.GetFieldInfoFromProperty(property, out requiredType); // case 951876: built-in types do not actually have reflectable fields, so their object types must be extracted from the type string // this works because built-in types will only ever have serialized references to other built-in types, which this window's filter expects as unqualified names if (requiredType == null) m_RequiredTypes = new string[] { s_MatchPPtrTypeName.Match(property.type).Groups[1].Value }; } // Don't select anything on multi selection UnityObject obj = property.hasMultipleDifferentValues ? null : property.objectReferenceValue; UnityObject objectBeingEdited = property.serializedObject.targetObject; m_EditedProperty = property; Show(obj, new Type[] { requiredType }, objectBeingEdited, allowSceneObjects, allowedInstanceIDs, onObjectSelectorClosed, onObjectSelectedUpdated); } internal void Show(Type[] requiredTypes, SerializedProperty property, bool allowSceneObjects, List<int> allowedInstanceIDs = null, Action<UnityObject> onObjectSelectorClosed = null, Action<UnityObject> onObjectSelectedUpdated = null) { if (requiredTypes == null) { Show((Type)null, property, allowSceneObjects, allowedInstanceIDs, onObjectSelectorClosed, onObjectSelectedUpdated); return; } if (property == null) throw new ArgumentNullException(nameof(property)); m_RequiredTypes = new string[requiredTypes.Length]; for (int i = 0; i < requiredTypes.Length; i++) { var requiredType = requiredTypes[i]; if (requiredType == null) { ScriptAttributeUtility.GetFieldInfoFromProperty(property, out requiredType); // case 951876: built-in types do not actually have reflectable fields, so their object types must be extracted from the type string // this works because built-in types will only ever have serialized references to other built-in types, which this window's filter expects as unqualified names if (requiredType == null) m_RequiredTypes[i] = s_MatchPPtrTypeName.Match(property.type).Groups[1].Value; else requiredTypes[i] = requiredType; } } // Don't select anything on multi selection UnityObject obj = property.hasMultipleDifferentValues ? null : property.objectReferenceValue; UnityObject objectBeingEdited = property.serializedObject.targetObject; m_EditedProperty = property; Show(obj, requiredTypes, objectBeingEdited, allowSceneObjects, allowedInstanceIDs, onObjectSelectorClosed, onObjectSelectedUpdated); } internal void Show(UnityObject obj, Type requiredType, UnityObject objectBeingEdited, bool allowSceneObjects, List<int> allowedInstanceIDs = null, Action<UnityObject> onObjectSelectorClosed = null, Action<UnityObject> onObjectSelectedUpdated = null, bool showNoneItem = true) { Show(obj, new Type[] { requiredType }, objectBeingEdited, allowSceneObjects, allowedInstanceIDs, onObjectSelectorClosed, onObjectSelectedUpdated, showNoneItem); } internal void Show(UnityObject obj, Type[] requiredTypes, UnityObject objectBeingEdited, bool allowSceneObjects, List<int> allowedInstanceIDs = null, Action<UnityObject> onObjectSelectorClosed = null, Action<UnityObject> onObjectSelectedUpdated = null, bool showNoneItem = true) { m_ObjectSelectorReceiver = null; m_AllowSceneObjects = allowSceneObjects; m_IsShowingAssets = true; m_SkipHiddenPackages = true; m_AllowedIDs = allowedInstanceIDs; m_ObjectBeingEdited = objectBeingEdited; m_LastSelectedInstanceId = obj?.GetInstanceID() ?? 0; m_SelectionCancelled = false; m_ShowNoneItem = showNoneItem; m_OnObjectSelectorClosed = onObjectSelectorClosed; m_OnObjectSelectorUpdated = onObjectSelectedUpdated; // Do not allow to show scene objects if the object being edited is persistent if (m_ObjectBeingEdited != null && EditorUtility.IsPersistent(m_ObjectBeingEdited)) m_AllowSceneObjects = false; // Set which tab should be visible at startup if (m_AllowSceneObjects) { if (obj != null) { if (typeof(Component).IsAssignableFrom(obj.GetType())) { obj = ((Component)obj).gameObject; } // Set the right tab visible (so we can see our selection) m_IsShowingAssets = EditorUtility.IsPersistent(obj); } else { foreach (var requiredType in requiredTypes) m_IsShowingAssets &= (requiredType != typeof(GameObject) && !typeof(Component).IsAssignableFrom(requiredType)); } } else { m_IsShowingAssets = true; } // Set member variables m_DelegateView = GUIView.current; // type filter requires unqualified names for built-in types, but will prioritize them over user types, so ensure user types are namespace-qualified if (m_RequiredTypes == null || m_RequiredTypes.Length != requiredTypes.Length) m_RequiredTypes = new string[requiredTypes.Length]; for (int i = 0; i < requiredTypes.Length; i++) { if (requiredTypes[i] != null) m_RequiredTypes[i] = typeof(ScriptableObject).IsAssignableFrom(requiredTypes[i]) || typeof(MonoBehaviour).IsAssignableFrom(requiredTypes[i]) ? requiredTypes[i].FullName : requiredTypes[i].Name; } m_SearchFilter = ""; m_OriginalSelection = obj; m_ModalUndoGroup = Undo.GetCurrentGroup(); // Show custom selector if available if (ObjectSelectorSearch.HasEngineOverride()) { m_SearchSessionHandler.BeginSession(() => { return new SearchService.ObjectSelectorSearchContext { currentObject = obj, editedObjects = m_EditedProperty != null ? m_EditedProperty.serializedObject.targetObjects : new[] { objectBeingEdited }, requiredTypes = requiredTypes, requiredTypeNames = m_RequiredTypes, allowedInstanceIds = allowedInstanceIDs, visibleObjects = allowSceneObjects ? SearchService.VisibleObjects.All : SearchService.VisibleObjects.Assets, searchFilter = GetSearchFilter() }; }); Action<UnityObject> onSelectionChanged = selectedObj => { m_LastSelectedInstanceId = selectedObj == null ? 0 : selectedObj.GetInstanceID(); NotifySelectionChanged(false); }; Action<UnityObject, bool> onSelectorClosed = (selectedObj, canceled) => { m_SearchSessionHandler.EndSession(); if (canceled) { // Undo changes we have done in the ObjectSelector Undo.RevertAllDownToGroup(m_ModalUndoGroup); m_LastSelectedInstanceId = 0; m_SelectionCancelled = true; } else { m_LastSelectedInstanceId = selectedObj == null ? 0 : selectedObj.GetInstanceID(); NotifySelectionChanged(false); } m_EditedProperty = null; NotifySelectorClosed(false); }; if (m_SearchSessionHandler.SelectObject(onSelectorClosed, onSelectionChanged)) return; else m_SearchSessionHandler.EndSession(); } // Freeze to prevent flicker on OSX. // Screen will be updated again when calling // SetFreezeDisplay(false) further down. ContainerWindow.SetFreezeDisplay(true); var shouldRepositionWindow = m_Parent != null; ShowWithMode(ShowMode.AuxWindow); titleContent = EditorGUIUtility.TrTextContent(GenerateTitleContent(requiredTypes, m_RequiredTypes)); // Deal with window size if (shouldRepositionWindow) { m_Parent.window.LoadInCurrentMousePosition(); m_Parent.window.FitWindowToScreen(true); } Rect p = m_Parent == null ? new Rect(0, 0, 1, 1) : m_Parent.window.position; p.width = EditorPrefs.GetFloat("ObjectSelectorWidth", 200); p.height = EditorPrefs.GetFloat("ObjectSelectorHeight", 390); position = p; minSize = new Vector2(kMinWidth, kMinTopSize + kPreviewExpandedAreaHeight + 2 * kPreviewMargin); maxSize = new Vector2(10000, 10000); SetupPreview(); // Focus Focus(); ContainerWindow.SetFreezeDisplay(false); m_FocusSearchFilter = true; // Add after unfreezing display because AuxWindowManager.cpp assumes that aux windows are added after we get 'got/lost'- focus calls. if (m_Parent != null) m_Parent.AddToAuxWindowList(); // Initial selection int initialSelection = obj != null ? obj.GetInstanceID() : 0; if (initialSelection != 0) { var assetPath = AssetDatabase.GetAssetPath(initialSelection); if (m_SkipHiddenPackages && !PackageManagerUtilityInternal.IsPathInVisiblePackage(assetPath)) m_SkipHiddenPackages = false; } if (m_RequiredTypes.All(t => ShouldTreeViewBeUsed(t))) { m_ObjectTreeWithSearch.Init(position, this, CreateAndSetTreeView, TreeViewSelection, ItemWasDoubleClicked, initialSelection, 0); } else { // To frame the selected item we need to wait to initialize the search until our window has been setup InitIfNeeded(); m_ListArea.InitSelection(new[] { initialSelection }); if (initialSelection != 0) m_ListArea.Frame(initialSelection, true, false); } } internal static string GenerateTitleContent(Type[] requiredTypes, string[] requiredTypeStrings) { var typeName = requiredTypes[0] == null ? requiredTypeStrings[0] : requiredTypes[0].Name; var text = "Select " + ObjectNames.NicifyVariableName(typeName); for (int i = 1; i < requiredTypes.Length; i++) { typeName = requiredTypes[i] == null ? requiredTypeStrings[i] : requiredTypes[i].Name; text += (i == requiredTypes.Length - 1 ? " or " : ", ") + ObjectNames.NicifyVariableName(typeName); } return text; } void ItemWasDoubleClicked() { SendEvent(ObjectSelectorSelectionDoneCommand, false); Close(); GUIUtility.ExitGUI(); } // TreeView Section void CreateAndSetTreeView(ObjectTreeForSelector.TreeSelectorData data) { TreeViewForAudioMixerGroup.CreateAndSetTreeView(data); } void TreeViewSelection(TreeViewItem item) { m_LastSelectedInstanceId = GetInternalSelectedInstanceID(); NotifySelectionChanged(true); } // Grid Section void InitIfNeeded() { if (m_ListAreaState == null) m_ListAreaState = new ObjectListAreaState(); // is serialized if (m_ListArea == null) { m_ListArea = new ObjectListArea(m_ListAreaState, this, m_ShowNoneItem); m_ListArea.allowDeselection = false; m_ListArea.allowDragging = false; m_ListArea.allowFocusRendering = false; m_ListArea.allowMultiSelect = false; m_ListArea.allowRenaming = false; m_ListArea.allowBuiltinResources = true; m_ListArea.repaintCallback += Repaint; m_ListArea.itemSelectedCallback += ListAreaItemSelectedCallback; m_ListArea.gridSize = m_StartGridSize.value; FilterSettingsChanged(); } } public static bool SelectionCanceled() { return ObjectSelector.get.m_SelectionCancelled; } public static UnityObject GetCurrentObject() { return EditorUtility.InstanceIDToObject(ObjectSelector.get.GetSelectedInstanceID()); } // This is the public Object that the inspector might revert to public static UnityObject GetInitialObject() { return ObjectSelector.get.m_OriginalSelection; } // This is our search field void SearchArea() { GUI.Label(new Rect(0, 0, position.width, kToolbarHeight), GUIContent.none, EditorStyles.toolbar); // ESC clears search field and removes it's focus. But if we get an esc event we only want to clear search field. // So we need special handling afterwards. bool wasEscape = Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape; GUI.SetNextControlName("SearchFilter"); string searchFilter = EditorGUI.ToolbarSearchField(new Rect(2, 2, position.width - 2, 16), m_SearchFilter, false); if (wasEscape && Event.current.type == EventType.Used) { // If we hit esc and the string WAS empty, it's an actual cancel event. if (m_SearchFilter == "") Cancel(); // Otherwise the string has been cleared and focus has been lost. We don't have anything else to recieve focus, so we want to refocus the search field. m_FocusSearchFilter = true; } if (searchFilter != m_SearchFilter || m_FocusSearchFilter) { m_SearchFilter = searchFilter; m_Debounce.Execute(); } if (m_FocusSearchFilter) { EditorGUI.FocusTextInControl("SearchFilter"); m_FocusSearchFilter = false; } GUI.changed = false; GUI.Label(new Rect(0, kToolbarHeight, position.width, kToolbarHeight), GUIContent.none, EditorStyles.toolbar); // TAB BAR GUILayout.BeginArea(new Rect(4, kToolbarHeight, position.width - 4, kToolbarHeight)); GUILayout.BeginHorizontal(); // Asset Tab bool showAssets = GUILayout.Toggle(m_IsShowingAssets, Styles.assetsTabLabel, Styles.tab); if (!m_IsShowingAssets && showAssets) m_IsShowingAssets = true; // The Scene Tab if (!m_AllowSceneObjects) { GUI.enabled = false; GUI.color = new Color(1, 1, 1, 0); } bool showingSceneTab = !m_IsShowingAssets; showingSceneTab = GUILayout.Toggle(showingSceneTab, Styles.sceneTabLabel, Styles.tab); if (m_IsShowingAssets && showingSceneTab) m_IsShowingAssets = false; if (!m_AllowSceneObjects) { GUI.color = new Color(1, 1, 1, 1); GUI.enabled = true; } GUILayout.EndHorizontal(); GUILayout.EndArea(); if (GUI.changed) m_Debounce.Execute(); var size = new Vector2(0, 0); if (m_IsShowingAssets) { Styles.packagesVisibilityContent.text = PackageManagerUtilityInternal.HiddenPackagesCount.ToString(); size = EditorStyles.toolbarButton.CalcSize(Styles.packagesVisibilityContent); } if (m_ListArea.CanShowThumbnails()) { EditorGUI.BeginChangeCheck(); var newGridSize = (int)GUI.HorizontalSlider(new Rect(position.width - (60 + size.x), kToolbarHeight + GUI.skin.horizontalSlider.margin.top, 55, EditorGUI.kSingleLineHeight), m_ListArea.gridSize, m_ListArea.minGridSize, m_ListArea.maxGridSize); if (EditorGUI.EndChangeCheck()) { m_ListArea.gridSize = newGridSize; } } if (m_IsShowingAssets) { EditorGUI.BeginChangeCheck(); var skipHiddenPackages = GUI.Toggle(new Rect(position.width - size.x, kToolbarHeight, size.x, EditorStyles.toolbarButton.fixedHeight), m_SkipHiddenPackages, Styles.packagesVisibilityContent, EditorStyles.toolbarButtonRight); if (EditorGUI.EndChangeCheck()) { m_SkipHiddenPackages = skipHiddenPackages; FilterSettingsChanged(); } } } [UsedImplicitly] void OnInspectorUpdate() { if (m_ListArea != null && AssetPreview.HasAnyNewPreviewTexturesAvailable(m_ListArea.GetAssetPreviewManagerID())) Repaint(); } // This is the preview area at the bottom of the screen void PreviewArea() { GUI.Box(new Rect(0, m_TopSize, position.width, m_PreviewSize), "", Styles.previewBackground); if (m_ListArea.GetSelection().Length == 0) return; EditorWrapper p = null; UnityObject selectedObject = GetCurrentObject(); if (m_PreviewSize < kPreviewExpandedAreaHeight) { // Get info string string s; if (selectedObject != null) { p = m_EditorCache[selectedObject]; string typeName = ObjectNames.NicifyVariableName(selectedObject.GetType().Name); if (p != null) s = p.name + " (" + typeName + ")"; else s = selectedObject.name + " (" + typeName + ")"; s += " " + AssetDatabase.GetAssetPath(selectedObject); } else s = "None"; LinePreview(s, selectedObject, p); } else { if (m_EditorCache == null) m_EditorCache = new EditorCache(EditorFeatures.PreviewGUI); // Get info string string s; if (selectedObject != null) { p = m_EditorCache[selectedObject]; string typeName = ObjectNames.NicifyVariableName(selectedObject.GetType().Name); if (p != null) { s = p.GetInfoString(); if (s != "") s = p.name + "\n" + typeName + "\n" + s; else s = p.name + "\n" + typeName; } else { s = selectedObject.name + "\n" + typeName; } s += "\n" + AssetDatabase.GetAssetPath(selectedObject); } else s = "None"; // Make previews if (m_ShowWidePreview.faded != 0.0f) { GUI.color = new Color(1, 1, 1, m_ShowWidePreview.faded); WidePreview(m_PreviewSize, s, selectedObject, p); } if (m_ShowOverlapPreview.faded != 0.0f) { GUI.color = new Color(1, 1, 1, m_ShowOverlapPreview.faded); OverlapPreview(m_PreviewSize, s, selectedObject, p); } GUI.color = Color.white; m_EditorCache.CleanupUntouchedEditors(); } } void WidePreview(float actualSize, string s, UnityObject o, EditorWrapper p) { float margin = kPreviewMargin; Rect previewRect = new Rect(margin, m_TopSize + margin, actualSize - margin * 2, actualSize - margin * 2); Rect labelRect = new Rect(m_PreviewSize + 3, m_TopSize + (m_PreviewSize - kPreviewExpandedAreaHeight) * 0.5f, m_Parent.window.position.width - m_PreviewSize - 3 - margin, kPreviewExpandedAreaHeight); if (p != null && p.HasPreviewGUI()) p.OnPreviewGUI(previewRect, Styles.previewTextureBackground); else if (o != null) DrawObjectIcon(previewRect, m_ListArea.m_SelectedObjectIcon); var prevClipping = Styles.smallStatus.clipping; Styles.smallStatus.clipping = TextClipping.Overflow; if (EditorGUIUtility.isProSkin) EditorGUI.DropShadowLabel(labelRect, s, Styles.smallStatus); else GUI.Label(labelRect, s, Styles.smallStatus); Styles.smallStatus.clipping = prevClipping; } void OverlapPreview(float actualSize, string s, UnityObject o, EditorWrapper p) { float margin = kPreviewMargin; Rect previewRect = new Rect(margin, m_TopSize + margin, position.width - margin * 2, actualSize - margin * 2); if (p != null && p.HasPreviewGUI()) p.OnPreviewGUI(previewRect, Styles.previewTextureBackground); else if (o != null) DrawObjectIcon(previewRect, m_ListArea.m_SelectedObjectIcon); if (EditorGUIUtility.isProSkin) EditorGUI.DropShadowLabel(previewRect, s, Styles.largeStatus); else EditorGUI.DoDropShadowLabel(previewRect, EditorGUIUtility.TempContent(s), Styles.largeStatus, .3f); } void LinePreview(string s, UnityObject o, EditorWrapper p) { if (m_ListArea.m_SelectedObjectIcon != null) GUI.DrawTexture(new Rect(2, (int)(m_TopSize + 2), 16, 16), m_ListArea.m_SelectedObjectIcon, ScaleMode.StretchToFill); Rect labelRect = new Rect(20, m_TopSize + 1, position.width - 22, 18); if (EditorGUIUtility.isProSkin) EditorGUI.DropShadowLabel(labelRect, s, Styles.smallStatus); else GUI.Label(labelRect, s, Styles.smallStatus); } void DrawObjectIcon(Rect position, Texture icon) { if (icon == null) return; int size = Mathf.Min((int)position.width, (int)position.height); if (size >= icon.width * 2) size = icon.width * 2; FilterMode temp = icon.filterMode; icon.filterMode = FilterMode.Point; GUI.DrawTexture(new Rect(position.x + ((int)position.width - size) / 2, position.y + ((int)position.height - size) / 2, size, size), icon, ScaleMode.ScaleToFit); icon.filterMode = temp; } // Resize the preview area void ResizeBottomPartOfWindow() { GUI.changed = false; // Handle preview size m_PreviewSize = m_PreviewResizer.ResizeHandle(position, kPreviewExpandedAreaHeight + kPreviewMargin * 2 - kResizerHeight, kMinTopSize + kResizerHeight, kResizerHeight) + kResizerHeight; m_TopSize = position.height - m_PreviewSize; bool open = PreviewIsOpen(); bool wide = PreviewIsWide(); m_ShowOverlapPreview.target = open && !wide; m_ShowWidePreview.target = open && wide; } bool PreviewIsOpen() { return m_PreviewSize >= 32 + kPreviewMargin; } bool PreviewIsWide() { return position.width - m_PreviewSize - kPreviewMargin > Mathf.Min(m_PreviewSize * 2 - 20, 256); } // send an event to the delegate view (the view that called us) void SendEvent(string eventName, bool exitGUI) { if (m_DelegateView) { Event e = EditorGUIUtility.CommandEvent(eventName); try { m_DelegateView.SendEvent(e); } finally { } if (exitGUI) GUIUtility.ExitGUI(); } } void HandleKeyboard() { // Handle events on the object selector window if (Event.current.type != EventType.KeyDown) return; switch (Event.current.keyCode) { case KeyCode.Return: case KeyCode.KeypadEnter: Close(); GUI.changed = true; GUIUtility.ExitGUI(); break; default: //Debug.Log ("Unhandled " + Event.current.keyCode); return; } Event.current.Use(); GUI.changed = true; } internal void Cancel() { // Undo changes we have done in the ObjectSelector Undo.RevertAllDownToGroup(m_ModalUndoGroup); // Clear selection so that object field doesn't grab it m_ListArea?.InitSelection(new int[0]); m_ObjectTreeWithSearch.Clear(); m_LastSelectedInstanceId = 0; m_SelectionCancelled = true; m_EditedProperty = null; SendEvent(ObjectSelectorCanceledCommand, false); Close(); GUI.changed = true; GUIUtility.ExitGUI(); } [UsedImplicitly] void OnDestroy() { if (m_ListArea != null) m_ListArea.OnDestroy(); m_ObjectTreeWithSearch.Clear(); } [UsedImplicitly] void OnGUI() { HandleKeyboard(); if (m_ObjectTreeWithSearch.IsInitialized()) OnObjectTreeGUI(); else OnObjectGridGUI(); // Must be after gui so search field can use the Escape event if it has focus if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape) Cancel(); else if (Event.current.commandName == EventCommandNames.UndoRedoPerformed && Selection.activeObject == null) { Close(); GUI.changed = true; GUIUtility.ExitGUI(); } } void OnObjectTreeGUI() { m_ObjectTreeWithSearch.OnGUI(new Rect(0, 0, position.width, position.height)); } void OnObjectGridGUI() { InitIfNeeded(); if (m_EditorCache == null) m_EditorCache = new EditorCache(EditorFeatures.PreviewGUI); // Handle window/preview stuff ResizeBottomPartOfWindow(); Rect p = position; EditorPrefs.SetFloat("ObjectSelectorWidth", p.width); EditorPrefs.SetFloat("ObjectSelectorHeight", p.height); GUI.BeginGroup(new Rect(0, 0, position.width, position.height), GUIContent.none); // Let grid/list area take priority over search area on up/down arrow keys if (s_GridAreaPriorityKeyboardEvents.Contains(Event.current)) m_ListArea.HandleKeyboard(false); SearchArea(); // Let grid/list area handle any keyboard events not used by search area m_ListArea.HandleKeyboard(false); GridListArea(); PreviewArea(); GUI.EndGroup(); // overlay preview resize widget GUI.Label(new Rect(position.width * .5f - 16, position.height - m_PreviewSize + 2, 32, Styles.bottomResize.fixedHeight), GUIContent.none, Styles.bottomResize); } void GridListArea() { int listKeyboardControlID = GUIUtility.GetControlID(FocusType.Keyboard); m_ListArea.OnGUI(listPosition, listKeyboardControlID); } void NotifySelectionChanged(bool exitGUI) { var currentObject = GetCurrentObject(); Internal_NotifySelectionChanged(currentObject, exitGUI); } // Used by tests internal void Internal_NotifySelectionChanged(UnityObject selectedObject, bool exitGUI) { if (m_ObjectSelectorReceiver != null) { m_ObjectSelectorReceiver.OnSelectionChanged(selectedObject); } m_OnObjectSelectorUpdated?.Invoke(selectedObject); SendEvent(ObjectSelectorUpdatedCommand, exitGUI); } void NotifySelectorClosed(bool exitGUI) { var currentObject = GetCurrentObject(); Internal_NotifySelectorClosed(currentObject, exitGUI); } // Used by tests internal void Internal_NotifySelectorClosed(UnityObject selectedObject, bool exitGUI) { if (m_ObjectSelectorReceiver != null) { m_ObjectSelectorReceiver.OnSelectionClosed(selectedObject); } m_OnObjectSelectorClosed?.Invoke(selectedObject); SendEvent(ObjectSelectorClosedCommand, exitGUI); Undo.CollapseUndoOperations(m_ModalUndoGroup); } } }
UnityCsReference/Editor/Mono/ObjectSelector.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ObjectSelector.cs", "repo_id": "UnityCsReference", "token_count": 21171 }
338
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace UnityEditor.Overlays { class OverlayInsertIndicator : VisualElement { const string k_ClassName = "unity-overlay-insert-indicator"; const string k_VerticalState = k_ClassName + "--vertical"; const string k_Horizontal = k_ClassName + "--horizontal"; const string k_VisualClass = k_ClassName + "__visual"; const string k_FirstVisibleClass = k_ClassName + "--first-visible"; public OverlayInsertIndicator() { pickingMode = PickingMode.Ignore; AddToClassList(k_ClassName); var visual = new VisualElement(); visual.AddToClassList(k_VisualClass); Add(visual); } public void Setup(bool horizontalContainer, bool firstVisible) { var verticalIndicator = horizontalContainer; // Horizontal container has vertical seperators EnableInClassList(k_VerticalState, verticalIndicator); EnableInClassList(k_Horizontal, !verticalIndicator); style.width = new StyleLength(StyleKeyword.Auto); style.height = new StyleLength(StyleKeyword.Auto); EnableInClassList(k_FirstVisibleClass, firstVisible); } } }
UnityCsReference/Editor/Mono/Overlays/OverlayInsertIndicator.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayInsertIndicator.cs", "repo_id": "UnityCsReference", "token_count": 560 }
339
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; using System.Runtime.InteropServices; namespace UnityEditorInternal.FrameDebuggerInternal { [NativeHeader("Editor/Mono/PerformanceTools/FrameDebugger.bindings.h")] [StaticAccessor("FrameDebugger", StaticAccessorType.DoubleColon)] internal sealed class FrameDebuggerUtility { public extern static void SetEnabled(bool enabled, int remotePlayerGUID); public extern static int GetRemotePlayerGUID(); public extern static bool receivingRemoteFrameEventData { [NativeName("IsReceivingRemoteFrameEventData")] get; } public extern static bool locallySupported { [NativeName("IsSupported")] get; } [NativeName("FinalDrawCallCount")] public extern static int count { get; } [NativeName("DrawCallLimit")] public extern static int limit { get; set; } [NativeName("FrameEventsHash")] public extern static int eventsHash { get; } [NativeName("FrameEventDataHash")] public extern static uint eventDataHash { get; } public extern static void SetRenderTargetDisplayOptions(int rtIndex, Vector4 channels, float blackLevel, float whiteLevel); [NativeName("GetProfilerEventName")] public extern static string GetFrameEventInfoName(int index); public extern static Object GetFrameEventObject(int index); [FreeFunction("FrameDebuggerBindings::GetBatchBreakCauseStrings")] public extern static string[] GetBatchBreakCauseStrings(); public static FrameDebuggerEvent[] GetFrameEvents() { return (FrameDebuggerEvent[])GetFrameEventsImpl(); } [NativeName("GetFrameEvents")] extern private static System.Array GetFrameEventsImpl(); // Returns false, if frameEventData holds data from previous selected frame public static bool GetFrameEventData(int index, FrameDebuggerEventData frameDebuggerEventData) { // native code will poke and modify the FrameDebuggerEventData object fields // directly via a pointer to it var handle = GCHandle.Alloc(frameDebuggerEventData, GCHandleType.Pinned); GetFrameEventDataImpl(handle.AddrOfPinnedObject()); handle.Free(); return frameDebuggerEventData.m_FrameEventIndex == index; } [FreeFunction("FrameDebuggerBindings::GetFrameEventDataImpl")] extern private static void GetFrameEventDataImpl(System.IntPtr frameDebuggerEventData); } }
UnityCsReference/Editor/Mono/PerformanceTools/FrameDebugger.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PerformanceTools/FrameDebugger.bindings.cs", "repo_id": "UnityCsReference", "token_count": 848 }
340
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Analytics; namespace UnityEditor { internal class PlayModeAnalytics { internal class BaseData : IAnalytic.IData { [SerializeField] public string PlayModeEvent; } internal class SimulatorEnableData : BaseData { [SerializeField] public string[] SimulatorPlugins; } internal class SimulatorDeviceData : BaseData { [SerializeField] public string DeviceName; } [AnalyticInfo(eventName: "playModeUsage", vendorKey: "unity.playModeUsage")] internal class Analytic : IAnalytic { public Analytic(BaseData data) { m_data = data; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } private BaseData m_data = null; } public static void GameViewEnableEvent() { SendPlayModeEvent(new BaseData() { PlayModeEvent = "Game OnEnable" }); } public static void GameViewDisableEvent() { SendPlayModeEvent(new BaseData() { PlayModeEvent = "Game OnDisable" }); } public static void SimulatorEnableEvent(string[] pluginNames) { SendPlayModeEvent(new SimulatorEnableData() { PlayModeEvent = "Simulator OnEnable", SimulatorPlugins = pluginNames }); } public static void SimulatorDisableEvent() { SendPlayModeEvent(new BaseData() { PlayModeEvent = "Simulator OnDisable" }); } public static void SimulatorSelectDeviceEvent(string deviceName) { SendPlayModeEvent(new SimulatorDeviceData() { PlayModeEvent = "Simulator Device", DeviceName = deviceName }); } private static void SendPlayModeEvent(BaseData data) { EditorAnalytics.SendAnalytic(new PlayModeAnalytics.Analytic(data)); } } }
UnityCsReference/Editor/Mono/PlayModeView/PlayModeAnalytics.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlayModeView/PlayModeAnalytics.cs", "repo_id": "UnityCsReference", "token_count": 972 }
341
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; using System; using System.Runtime.CompilerServices; namespace UnityEditor { public sealed partial class PlayerSettings { [NativeHeader("Runtime/Misc/PlayerSettings.h")] [StaticAccessor("GetPlayerSettings().GetEditorOnlyForUpdate()", StaticAccessorType.Dot)] public sealed partial class PS4 { public enum PS4AppCategory { Application = 0, // Application package. Patch = 1, // Patch Remaster = 2, // Remaster package } public enum PS4RemotePlayKeyAssignment { None = -1, PatternA = 0, PatternB = 1, PatternC = 2, PatternD = 3, PatternE = 4, PatternF = 5, PatternG = 6, PatternH = 7, } public enum PS4EnterButtonAssignment { CircleButton = 0, CrossButton = 1, SystemDefined = 2, } public enum PlayStationVREyeToEyeDistanceSettings { PerUser = 0, ForceDefault = 1, DynamicModeAtRuntime = 2, } [NativeProperty("ps4NPTrophyPackPath")] extern public static string npTrophyPackPath { get; set; } [NativeProperty("ps4NPAgeRating", false, TargetType.Field)] extern public static int npAgeRating { get; set; } [NativeProperty("ps4NPTitleSecret", false, TargetType.Function)] extern public static string npTitleSecret { get; set; } [NativeProperty("ps4ParentalLevel", false, TargetType.Field)] extern public static int parentalLevel { get; set; } [NativeProperty("ps4ApplicationParam1", false, TargetType.Field)] extern public static int applicationParameter1 { get; set; } [NativeProperty("ps4ApplicationParam2", false, TargetType.Field)] extern public static int applicationParameter2 { get; set; } [NativeProperty("ps4ApplicationParam3", false, TargetType.Field)] extern public static int applicationParameter3 { get; set; } [NativeProperty("ps4ApplicationParam4", false, TargetType.Field)] extern public static int applicationParameter4 { get; set; } [NativeProperty("ps4Passcode", false, TargetType.Function)] extern public static string passcode { get; set; } [NativeProperty("monoEnv", false, TargetType.Function)] extern public static string monoEnv { get; set; } [NativeProperty(TargetType = TargetType.Field)] extern public static bool playerPrefsSupport { get; set; } [NativeProperty(TargetType = TargetType.Field)] extern public static bool restrictedAudioUsageRights { get; set; } [NativeProperty("ps4UseResolutionFallback", false, TargetType.Field)] extern public static bool useResolutionFallback { get; set; } [NativeProperty("ps4ContentID", false, TargetType.Function)] extern public static string contentID { get; set; } [NativeProperty("ps4Category", false, TargetType.Field)] extern public static PS4AppCategory category { get; set; } [NativeProperty("ps4AppType", false, TargetType.Field)] extern public static int appType { get; set; } [NativeProperty("ps4MasterVersion", false, TargetType.Function)] extern public static string masterVersion { get; set; } [NativeProperty("ps4AppVersion", false, TargetType.Function)] extern public static string appVersion { get; set; } [NativeProperty("ps4RemotePlayKeyAssignment", false, TargetType.Field)] extern public static PS4RemotePlayKeyAssignment remotePlayKeyAssignment { get; set; } [NativeProperty("ps4RemotePlayKeyMappingDir", false, TargetType.Function)] extern public static string remotePlayKeyMappingDir { get; set; } [NativeProperty("ps4PlayTogetherPlayerCount", false, TargetType.Field)] extern public static int playTogetherPlayerCount { get; set; } [NativeProperty("ps4EnterButtonAssignment", false, TargetType.Field)] extern public static PS4EnterButtonAssignment enterButtonAssignment { get; set; } [NativeProperty("ps4ParamSfxPath", false, TargetType.Function)] extern public static string paramSfxPath { get; set; } [NativeProperty("ps4VideoOutPixelFormat", false, TargetType.Field)] extern public static int videoOutPixelFormat { get; set; } [NativeProperty("ps4VideoOutInitialWidth", false, TargetType.Field)] extern public static int videoOutInitialWidth { get; set; } [Obsolete("videoOutResolution is deprecated. Use PlayerSettings.PS4.videoOutInitialWidth and PlayerSettings.PS4.videoOutReprojectionRate to control initial display resolution and reprojection rate.")] public static int videoOutResolution { get { int reprojectionRate = videoOutReprojectionRate; int initialWidth = videoOutInitialWidth; switch (reprojectionRate) { // if we have any projection rates then assume we have 1920x1080 res case 60: return 5; // 1920By1080_VR60 case 90: return 6; // 1920By1080_VR90 case 120: return 7; // 1920By1080_VR120 default: switch (initialWidth) { case 1280: return 0; // 1280By720 case 1440: return 1; // 1440By810 case 1600: return 2; // 1660By900 case 1760: return 3; // 1760By990 default: case 1920: return 4; // 1920By1080 } } } set { int reprojectionRate = 0; int initialWidth = 1920; switch (value) { case 0: initialWidth = 1280; break; case 1: initialWidth = 1440; break; case 2: initialWidth = 1600; break; case 3: initialWidth = 1760; break; case 4: initialWidth = 1920; break; case 5: reprojectionRate = 60; break; case 6: reprojectionRate = 90; break; case 7: reprojectionRate = 120; break; } videoOutInitialWidth = initialWidth; videoOutReprojectionRate = reprojectionRate; } } public static string SdkOverride { get { return SdkOverrideInternal; } set { SdkOverrideInternal = value; string newSDK = value; if (String.IsNullOrEmpty(newSDK)) { // newSDK is an empty path which is perfectly valid for the player settings and the UI where an empty path means "use the SDK set in the // system environment". We need the underlying environment to always have a valid SDK path so use the SDK that was set in SCE_ORBIS_SDK_DIR // when the editor was launched, which we recorded in the SCE_ORBIS_SDK_DIR_ORIGINAL env var. newSDK = Environment.GetEnvironmentVariable("SCE_ORBIS_SDK_DIR_ORIGINAL"); } Environment.SetEnvironmentVariable("SCE_ORBIS_SDK_DIR", newSDK); UnityEditor.PlayerSettings.ReinitialiseShaderCompiler("SCE_ORBIS_SDK_DIR", newSDK); } } [NativeProperty("ps4VideoOutBaseModeInitialWidth", false, TargetType.Field)] extern public static int videoOutBaseModeInitialWidth { get; set; } [NativeProperty("ps4VideoOutReprojectionRate", false, TargetType.Field)] extern public static int videoOutReprojectionRate { get; set; } [NativeProperty("ps4PronunciationXMLPath", false, TargetType.Function)] extern public static string PronunciationXMLPath { get; set; } [NativeProperty("ps4PronunciationSIGPath", false, TargetType.Function)] extern public static string PronunciationSIGPath { get; set; } [NativeProperty("ps4BackgroundImagePath", false, TargetType.Function)] extern public static string BackgroundImagePath { get; set; } [NativeProperty("ps4StartupImagePath", false, TargetType.Function)] extern public static string StartupImagePath { get; set; } [NativeProperty("ps4StartupImagesFolder", false, TargetType.Function)] extern public static string startupImagesFolder { get; set; } [NativeProperty("ps4IconImagesFolder", false, TargetType.Function)] extern public static string iconImagesFolder { get; set; } [NativeProperty("ps4SaveDataImagePath", false, TargetType.Function)] extern public static string SaveDataImagePath { get; set; } [NativeProperty("ps4SdkOverride", false, TargetType.Function)] extern private static string SdkOverrideInternal { get; set; } [NativeProperty("ps4BGMPath", false, TargetType.Function)] extern public static string BGMPath { get; set; } [NativeProperty("ps4ShareFilePath", false, TargetType.Function)] extern public static string ShareFilePath { get; set; } [NativeProperty("ps4ShareOverlayImagePath", false, TargetType.Function)] extern public static string ShareOverlayImagePath { get; set; } [NativeProperty("ps4PrivacyGuardImagePath", false, TargetType.Function)] extern public static string PrivacyGuardImagePath { get; set; } [NativeProperty("ps4ExtraSceSysFile", false, TargetType.Function)] extern public static string ExtraSceSysFile { get; set; } [NativeProperty("ps4PatchDayOne", false, TargetType.Field)] extern public static bool patchDayOne { get; set; } [NativeProperty("ps4PatchPkgPath", false, TargetType.Function)] extern public static string PatchPkgPath { get; set; } [NativeProperty("ps4PatchLatestPkgPath", false, TargetType.Function)] extern public static string PatchLatestPkgPath { get; set; } [NativeProperty("ps4PatchChangeinfoPath", false, TargetType.Function)] extern public static string PatchChangeinfoPath { get; set; } [NativeProperty("ps4NPtitleDatPath", false, TargetType.Function)] extern public static string NPtitleDatPath { get; set; } [NativeProperty("ps4pnSessions", false, TargetType.Field)] extern public static bool pnSessions { get; set; } [NativeProperty("ps4pnPresence", false, TargetType.Field)] extern public static bool pnPresence { get; set; } [NativeProperty("ps4pnFriends", false, TargetType.Field)] extern public static bool pnFriends { get; set; } [NativeProperty("ps4pnGameCustomData", false, TargetType.Field)] extern public static bool pnGameCustomData { get; set; } [NativeProperty("ps4DownloadDataSize", false, TargetType.Field)] extern public static int downloadDataSize { get; set; } [NativeProperty("ps4GarlicHeapSize", false, TargetType.Field)] extern public static int garlicHeapSize { get; set; } [NativeProperty("ps4ProGarlicHeapSize", false, TargetType.Field)] extern public static int proGarlicHeapSize { get; set; } [NativeProperty("ps4ReprojectionSupport", false, TargetType.Field)] extern public static bool reprojectionSupport { get; set; } [NativeProperty("ps4UseAudio3dBackend", false, TargetType.Field)] extern public static bool useAudio3dBackend { get; set; } [NativeProperty("ps4Audio3dVirtualSpeakerCount", false, TargetType.Field)] extern public static int audio3dVirtualSpeakerCount { get; set; } [Obsolete("Use PlayerSettings.SetIl2CppCompilerConfiguration() instead.")] public static int scriptOptimizationLevel { get; set; } [NativeProperty("ps4UseLowGarlicFragmentationMode", true, TargetType.Field)] extern public static bool useLowGarlicFragmentationMode { get; set; } [NativeProperty("ps4SocialScreenEnabled", false, TargetType.Field)] extern public static int socialScreenEnabled { get; set; } [NativeProperty("ps4attribUserManagement", false, TargetType.Field)] extern public static bool attribUserManagement { get; set; } [NativeProperty("ps4attribMoveSupport", false, TargetType.Field)] extern public static bool attribMoveSupport { get; set; } [NativeProperty("ps4attrib3DSupport", false, TargetType.Field)] extern public static bool attrib3DSupport { get; set; } [NativeProperty("ps4attribShareSupport", false, TargetType.Field)] extern public static bool attribShareSupport { get; set; } [NativeProperty("ps4attribExclusiveVR", false, TargetType.Field)] extern public static bool attribExclusiveVR { get; set; } [NativeProperty("ps4disableAutoHideSplash", false, TargetType.Field)] extern public static bool disableAutoHideSplash { get; set; } [NativeProperty("ps4attribCpuUsage", false, TargetType.Field)] extern public static int attribCpuUsage { get; set; } [NativeProperty("ps4videoRecordingFeaturesUsed", false, TargetType.Field)] extern public static bool videoRecordingFeaturesUsed { get; set; } [NativeProperty("ps4contentSearchFeaturesUsed", false, TargetType.Field)] extern public static bool contentSearchFeaturesUsed { get; set; } [NativeProperty("ps4attribEyeToEyeDistanceSettingVR", false, TargetType.Field)] extern public static PlayStationVREyeToEyeDistanceSettings attribEyeToEyeDistanceSettingVR { get; set; } [NativeProperty("ps4IncludedModules", false, TargetType.Function)] extern public static string[] includedModules { get; set; } [NativeProperty(TargetType = TargetType.Field)] extern public static bool enableApplicationExit { get; set; } [NativeProperty(TargetType = TargetType.Field)] extern public static bool resetTempFolder { get; set; } [NativeProperty(TargetType = TargetType.Field)] extern public static int playerPrefsMaxSize { get; set; } [NativeProperty("ps4attribVROutputEnabled", false, TargetType.Field)] extern public static bool attribVROutputEnabled { get; set; } [NativeProperty("ps4CompatibilityPS5", false, TargetType.Field)] extern public static bool compatibilityPS5 { get; set; } [NativeProperty("ps4AllowPS5Detection", false, TargetType.Field)] extern public static bool allowPS5Detection { get; set; } [NativeProperty("ps4GPU800MHz", false, TargetType.Field)] extern public static bool gpu800MHz { get; set; } } } }
UnityCsReference/Editor/Mono/PlayerSettingsPS4.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PlayerSettingsPS4.bindings.cs", "repo_id": "UnityCsReference", "token_count": 6802 }
342
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnityEditor { [NativeHeader("Editor/Src/PolygonEditor.h")] internal partial class PolygonEditor { [NativeThrows] extern public static void StartEditing([NotNull] Collider2D collider); [NativeThrows] extern public static void ApplyEditing([NotNull] Collider2D collider); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static void StopEditing(); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static bool GetNearestPoint(Vector2 point, out int pathIndex, out int pointIndex, out float distance); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static bool GetNearestEdge(Vector2 point, out int pathIndex, out int pointIndex0, out int pointIndex1, out float distance, bool loop); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static int GetPathCount(); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static int GetPointCount(int pathIndex); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static bool GetPoint(int pathIndex, int pointIndex, out Vector2 point); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static void SetPoint(int pathIndex, int pointIndex, Vector2 value); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static void InsertPoint(int pathIndex, int pointIndex, Vector2 value); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static void RemovePoint(int pathIndex, int pointIndex); [StaticAccessor("PolygonEditor::Get()", StaticAccessorType.Dot)] extern public static void TestPointMove(int pathIndex, int pointIndex, Vector2 movePosition, out bool leftIntersect, out bool rightIntersect, bool loop); } }
UnityCsReference/Editor/Mono/PolygonEditor.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PolygonEditor.bindings.cs", "repo_id": "UnityCsReference", "token_count": 781 }
343
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs.LowLevel.Unsafe; using UnityEngine; using UnityEngine.Analytics; class JobsMenu { private static int savedJobWorkerCount = JobsUtility.JobWorkerCount; [SettingsProvider] private static SettingsProvider JobsPreferencesItem() { var provider = new SettingsProvider("Preferences/Jobs", SettingsScope.User) { label = "Jobs", keywords = new[] { "Jobs" }, guiHandler = (searchContext) => { var originalWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 200f; EditorGUILayout.BeginVertical(); GUILayout.BeginVertical(); EditorGUILayout.LabelField("For safety, these values are reset on editor restart."); bool madeChange = false; bool oldWorkerCount = (JobsUtility.JobWorkerCount > 0); bool newWorkerCount = EditorGUILayout.Toggle(new GUIContent("Use Job Threads:"), oldWorkerCount); if (newWorkerCount != oldWorkerCount) { madeChange = true; SwitchUseJobThreads(); } bool oldUseJobsDebugger = JobsUtility.JobDebuggerEnabled; var newUseJobsDebugger = EditorGUILayout.Toggle(new GUIContent("Enable Jobs Debugger"), JobsUtility.JobDebuggerEnabled); if (newUseJobsDebugger != oldUseJobsDebugger) { madeChange = true; SetUseJobsDebugger(newUseJobsDebugger); } var oldLeakDetectionMode = NativeLeakDetection.Mode; var newLeakDetectionMode = (NativeLeakDetectionMode)EditorGUILayout.EnumPopup(new GUIContent("Leak Detection Level"), oldLeakDetectionMode); if (newLeakDetectionMode != oldLeakDetectionMode) { madeChange = true; SetLeakDetection(newLeakDetectionMode); } if (madeChange) Telemetry.LogMenuPreferences(new Telemetry(new Telemetry.MenuPreferencesEvent { useJobsThreads = newUseJobsDebugger, enableJobsDebugger = newUseJobsDebugger, nativeLeakDetectionMode = newLeakDetectionMode })); GUILayout.EndVertical(); EditorGUILayout.EndVertical(); EditorGUIUtility.labelWidth = originalWidth; } }; return provider; } static void SwitchUseJobThreads() { if (JobsUtility.JobWorkerCount > 0) { savedJobWorkerCount = JobsUtility.JobWorkerCount; JobsUtility.JobWorkerCount = 0; } else { JobsUtility.JobWorkerCount = savedJobWorkerCount; if (savedJobWorkerCount == 0) { JobsUtility.ResetJobWorkerCount(); } } } static void SetUseJobsDebugger(bool value) { JobsUtility.JobDebuggerEnabled = value; } static void SetLeakDetection(NativeLeakDetectionMode value) { switch (value) { case NativeLeakDetectionMode.Disabled: { Debug.LogWarning("Leak detection has been disabled. Leak warnings will not be generated, and all leaks up to now are forgotten."); break; } case NativeLeakDetectionMode.Enabled: { Debug.Log("Leak detection has been enabled. Leak warnings will be generated upon domain reload."); break; } case NativeLeakDetectionMode.EnabledWithStackTrace: { Debug.Log("Leak detection with stack traces has been enabled. Leak warnings will be generated upon domain reload."); break; } default: { throw new Exception($"Unhandled {nameof(NativeLeakDetectionMode)}"); } } NativeLeakDetection.Mode = value; } [AnalyticInfo(eventName: "collectionsMenuPreferences", vendorKey: "unity.collections")] internal struct Telemetry : IAnalytic { public Telemetry(MenuPreferencesEvent data) { m_data = data; } [Serializable] internal struct MenuPreferencesEvent : IAnalytic.IData { public bool enableJobsDebugger; public bool useJobsThreads; public NativeLeakDetectionMode nativeLeakDetectionMode; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_data; return data != null; } public static void LogMenuPreferences(Telemetry analytics) { EditorAnalytics.SendAnalytic(analytics); } MenuPreferencesEvent m_data; } }
UnityCsReference/Editor/Mono/PreferencesWindow/CollectionsPreferences.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/PreferencesWindow/CollectionsPreferences.cs", "repo_id": "UnityCsReference", "token_count": 2589 }
344
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; namespace UnityEditor { public static partial class Progress { [DebuggerDisplay("name={name}")] public class Item { struct CachedValue<T> { readonly Func<int, T> m_UpdateCallback; T m_LocalValue; bool m_Updated; public T GetValue(int id) { if (!m_Updated) { m_LocalValue = m_UpdateCallback(id); m_Updated = true; } return m_LocalValue; } public CachedValue(Func<int, T> updateCallback) { m_UpdateCallback = updateCallback; m_Updated = false; m_LocalValue = default(T); } public void Dirty() { m_Updated = false; } public bool IsDirty() { return !m_Updated; } } CachedValue<string> m_Name = new CachedValue<string>(GetName); CachedValue<string> m_Description = new CachedValue<string>(GetDescription); CachedValue<float> m_Progress = new CachedValue<float>(GetProgress); CachedValue<int> m_CurrentStep = new CachedValue<int>(GetCurrentStep); CachedValue<int> m_TotalSteps = new CachedValue<int>(GetTotalSteps); CachedValue<string> m_StepsLabel = new CachedValue<string>(GetStepLabel); CachedValue<int> m_ParentId = new CachedValue<int>(GetParentId); CachedValue<DateTime> m_StartTime = new CachedValue<DateTime>(id => MSecToDateTime(GetStartDateTime(id))); CachedValue<DateTime> m_EndTime = new CachedValue<DateTime>(id => MSecToDateTime(GetEndDateTime(id))); CachedValue<DateTime> m_UpdateTime = new CachedValue<DateTime>(id => MSecToDateTime(GetUpdateDateTime(id))); CachedValue<Status> m_Status = new CachedValue<Status>(GetStatus); CachedValue<Options> m_Options = new CachedValue<Options>(GetOptions); CachedValue<TimeDisplayMode> m_TimeDisplayMode = new CachedValue<TimeDisplayMode>(GetTimeDisplayMode); CachedValue<TimeSpan> m_RemainingTime = new CachedValue<TimeSpan>(id => SecToTimeSpan(GetRemainingTime(id))); CachedValue<int> m_Priority = new CachedValue<int>(GetPriority); CachedValue<DateTime> m_LastResumeTime = new CachedValue<DateTime>(id => MSecToDateTime(GetLastResumeDateTime(id))); CachedValue<TimeSpan> m_ElapsedTimeUntilLastPause = new CachedValue<TimeSpan>(id => MSecToTimeSpan(GetElapsedTimeUntilLastPause(id))); DateTime m_LastRemainingTime; public string name => m_Name.GetValue(id); public string description => m_Description.GetValue(id); public int id { get; internal set; } public float progress => m_Progress.GetValue(id); public int currentStep => m_CurrentStep.GetValue(id); public int totalSteps => m_TotalSteps.GetValue(id); public string stepLabel => m_StepsLabel.GetValue(id); public int parentId => m_ParentId.GetValue(id); public DateTime startTime => m_StartTime.GetValue(id); public DateTime endTime => m_EndTime.GetValue(id); public DateTime updateTime => m_UpdateTime.GetValue(id); public Status status => m_Status.GetValue(id); public Options options => m_Options.GetValue(id); public TimeDisplayMode timeDisplayMode => m_TimeDisplayMode.GetValue(id); public int priority => m_Priority.GetValue(id); public TimeSpan remainingTime { get { if (m_RemainingTime.IsDirty()) { m_LastRemainingTime = DateTime.Now; } var duration = (DateTime.Now - m_LastRemainingTime).Duration(); return m_RemainingTime.GetValue(id) - new TimeSpan(duration.Days, duration.Hours, duration.Minutes, duration.Seconds); } } public bool finished => status != Status.Running && status != Status.Paused; public bool running => status == Status.Running; public bool paused => status == Status.Paused; public bool responding => !running || (DateTime.Now.ToUniversalTime() - updateTime) <= TimeSpan.FromSeconds(5f) || (priority >= (int)Priority.Idle && priority < (int)Priority.Normal); public bool cancellable => IsCancellable(id); public bool pausable => IsPausable(id); public bool indefinite => running && (progress == -1f || (options & Options.Indefinite) == Options.Indefinite); public float elapsedTime { get { if (finished) { var executionTime = endTime - startTime; return (float)executionTime.TotalSeconds; } else return paused ? (float)elapsedTimeUntilLastPause.TotalSeconds : (float)(elapsedTimeUntilLastPause + (DateTime.UtcNow - lastResumeTime)).TotalSeconds; } } public bool exists => Exists(id); internal DateTime lastResumeTime => m_LastResumeTime.GetValue(id); internal TimeSpan elapsedTimeUntilLastPause => m_ElapsedTimeUntilLastPause.GetValue(id); internal Updates lastUpdates { get; private set; } internal Item(int id) { this.id = id; } public void Report(float newProgress) { Progress.Report(id, newProgress); } public void Report(int newCurrentStep, int newTotalSteps) { Progress.Report(id, newCurrentStep, newTotalSteps); } public void Report(float newProgress, string newDescription) { Progress.Report(id, newProgress, newDescription); } public void Report(int newCurrentStep, int newTotalSteps, string newDescription) { Progress.Report(id, newCurrentStep, newTotalSteps, newDescription); } public bool Cancel() { return Progress.Cancel(id); } public bool Pause() { return Progress.Pause(id); } public bool Resume() { return Progress.Resume(id); } public void Finish(Status finishedStatus = Status.Succeeded) { Progress.Finish(id, finishedStatus); } public int Remove() { return Progress.Remove(id); } public void RegisterCancelCallback(Func<bool> callback) { Progress.RegisterCancelCallback(id, callback); } public void UnregisterCancelCallback() { Progress.UnregisterCancelCallback(id); } public void RegisterPauseCallback(Func<bool, bool> callback) { Progress.RegisterPauseCallback(id, callback); } public void UnregisterPauseCallback() { Progress.UnregisterPauseCallback(id); } public void SetDescription(string newDescription) { Progress.SetDescription(id, newDescription); } public void SetTimeDisplayMode(TimeDisplayMode mode) { Progress.SetTimeDisplayMode(id, mode); } public void SetRemainingTime(long seconds) { Progress.SetRemainingTime(id, seconds); } public void SetPriority(int priority) { Progress.SetPriority(id, priority); } public void SetPriority(Priority priority) { Progress.SetPriority(id, priority); } public void ClearRemainingTime() { Progress.ClearRemainingTime(id); } public void SetStepLabel(string label) { Progress.SetStepLabel(id, label); } internal void Dirty(Updates updates) { lastUpdates = updates; // If the item was updated, update time is always updated m_UpdateTime.Dirty(); if (updates.HasAny(Updates.DescriptionChanged)) m_Description.Dirty(); if (updates.HasAny(Updates.PriorityChanged)) m_Priority.Dirty(); if (updates.HasAny(Updates.ProgressChanged)) m_Progress.Dirty(); if (updates.HasAny(Updates.CurrentStepChanged)) m_CurrentStep.Dirty(); if (updates.HasAny(Updates.TotalStepsChanged)) m_TotalSteps.Dirty(); if (updates.HasAny(Updates.StepLabelChanged)) m_StepsLabel.Dirty(); if (updates.HasAny(Updates.StatusChanged)) m_Status.Dirty(); if (updates.HasAny(Updates.RemainingTimeChanged)) m_RemainingTime.Dirty(); if (updates.HasAny(Updates.TimeDisplayModeChanged)) m_TimeDisplayMode.Dirty(); if (updates.HasAny(Updates.LastResumeTimeChanged)) m_LastResumeTime.Dirty(); if (updates.HasAny(Updates.ElapsedTimeSinceLastPauseChanged)) m_ElapsedTimeUntilLastPause.Dirty(); if (updates.HasAny(Updates.EndTimeChanged)) m_EndTime.Dirty(); } internal void ClearUpdates() { lastUpdates = Updates.NothingChanged; } internal static DateTime MSecToDateTime(long msec) { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(msec); } internal static TimeSpan SecToTimeSpan(long sec) { return new TimeSpan(0, 0, 0, (int)sec); } internal static TimeSpan MSecToTimeSpan(long msec) { return new TimeSpan(0, 0, 0, 0, (int)msec); } } } }
UnityCsReference/Editor/Mono/Progress/Progress.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Progress/Progress.cs", "repo_id": "UnityCsReference", "token_count": 5587 }
345
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor; using UnityEditor.SceneManagement; using UnityEditor.ShortcutManagement; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditorInternal { [NativeHeader("Editor/Src/RenderDoc/RenderDoc.h")] [StaticAccessor("RenderDoc", StaticAccessorType.DoubleColon)] public static partial class RenderDoc { [WindowAction] static WindowAction RenderDocGlobalAction() { // Developer-mode render doc button to enable capturing any HostView content/panels var action = WindowAction.CreateWindowActionButton("RenderDoc", CaptureRenderDoc, null, ContainerWindow.kButtonWidth + 1, RenderDocCaptureButton); action.validateHandler = ShowRenderDocButton; return action; } public static extern bool IsInstalled(); public static extern bool IsLoaded(); public static extern bool IsSupported(); public static extern void Load(); public static void BeginCaptureRenderDoc(EditorWindow window) => window.m_Parent.BeginCaptureRenderDoc(); public static void EndCaptureRenderDoc(EditorWindow window) => window.m_Parent.EndCaptureRenderDoc(); static EditorWindow s_EditorWindowScheduledForCapture = null; static GUIContent s_RenderDocContent; internal static bool RenderDocCaptureButton(EditorWindow view, WindowAction self, Rect r) { if (s_RenderDocContent == null) s_RenderDocContent = EditorGUIUtility.TrIconContent("FrameCapture", RenderDocUtil.openInRenderDocTooltip); Rect r2 = new Rect(r.xMax - r.width, r.y, r.width, r.height); return GUI.Button(r2, s_RenderDocContent, EditorStyles.iconButton); } private static void CaptureRenderDoc(EditorWindow view, WindowAction self) { if (view is GameView) view.m_Parent.CaptureRenderDocScene(); else view.m_Parent.CaptureRenderDocFullContent(); } private static bool ShowRenderDocButton(EditorWindow view, WindowAction self) { return Unsupported.IsDeveloperMode() && IsLoaded() && IsSupported(); } internal static void LoadRenderDoc() { if (IsInstalled() && !IsLoaded() && EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) { ShaderUtil.RequestLoadRenderDoc(); } } [Shortcut(RenderDocUtil.captureRenderDocShortcutID, KeyCode.C, ShortcutModifiers.Alt)] internal static void CaptureRenderDoc() { if (IsInstalled() && !IsLoaded()) { s_EditorWindowScheduledForCapture = EditorWindow.focusedWindow; LoadRenderDoc(); } else if (EditorWindow.focusedWindow != null) { CaptureRenderDoc(EditorWindow.focusedWindow, null); } } [RequiredByNativeCode] static void RenderDocLoaded() { if (s_EditorWindowScheduledForCapture != null) { s_EditorWindowScheduledForCapture.Focus(); CaptureRenderDoc(); s_EditorWindowScheduledForCapture = null; } } } }
UnityCsReference/Editor/Mono/RenderDoc/RenderDoc.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/RenderDoc/RenderDoc.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1450 }
346
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine; // The setup information for a scene in the SceneManager. namespace UnityEditor.SceneManagement { [StructLayout(LayoutKind.Sequential)] [Serializable] public class SceneSetup { [SerializeField] private string m_Path = null; [SerializeField] private bool m_IsLoaded = false; [SerializeField] private bool m_IsActive = false; [SerializeField] private bool m_IsSubScene = false; public string path { get { return m_Path; } set { m_Path = value; } } public bool isLoaded { get { return m_IsLoaded; } set { m_IsLoaded = value; } } public bool isActive { get { return m_IsActive; } set { m_IsActive = value; } } public bool isSubScene { get { return m_IsSubScene; } set { m_IsSubScene = value; } } } }
UnityCsReference/Editor/Mono/SceneManagement/SceneSetup.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneManagement/SceneSetup.cs", "repo_id": "UnityCsReference", "token_count": 547 }
347
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.ShortcutManagement; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.Scripting; namespace UnityEditor.SceneManagement { public static partial class StageUtility { internal enum ContextRenderMode { Normal, GreyedOut, Hidden } [Shortcut("Stage/Go Back")] static void GoBackShortcut() { StageUtility.GoBackToPreviousStage(); } public static bool IsGameObjectRenderedByCamera(GameObject gameObject, Camera camera) { return IsGameObjectRenderedByCameraInternal(gameObject, camera); } public static bool IsGameObjectRenderedByCameraAndPartOfEditableScene(GameObject gameObject, Camera camera) { if (!IsGameObjectRenderedByCamera(gameObject, camera)) return false; var scene = GetFocusedScene(); if (scene.handle == 0) return true; return gameObject.scene == scene; } internal static void SetSceneToRenderInStage(Scene scene, StageHandle stageHandle) { if (!stageHandle.IsValid()) throw new System.ArgumentException("Stage is not valid.", nameof(stageHandle)); if (stageHandle.isMainStage) SetSceneToRenderInMainStageInternal(scene.handle); else SetSceneToRenderInSameStageAsOtherSceneInternal(scene.handle, stageHandle.customScene.handle); } public static Stage GetCurrentStage() { return StageNavigationManager.instance.currentStage; } public static MainStage GetMainStage() { return StageNavigationManager.instance.mainStage; } public static Stage GetStage(GameObject gameObject) { return GetStage(gameObject.scene); } public static Stage GetStage(Scene scene) { return StageNavigationManager.instance.GetStage(scene); } public static StageHandle GetCurrentStageHandle() { return StageHandle.GetCurrentStageHandle(); } public static StageHandle GetMainStageHandle() { return StageHandle.GetMainStageHandle(); } public static StageHandle GetStageHandle(GameObject gameObject) { return StageHandle.GetStageHandle(gameObject.scene); } public static StageHandle GetStageHandle(Scene scene) { return StageHandle.GetStageHandle(scene); } [RequiredByNativeCode] public static void GoToMainStage() { StageNavigationManager.instance.GoToMainStage(StageNavigationManager.Analytics.ChangeType.GoToMainViaUnknown); } public static void GoBackToPreviousStage() { StageNavigationManager.instance.NavigateBack(StageNavigationManager.Analytics.ChangeType.NavigateBackViaUnknown); } public static void GoToStage(Stage stage, bool setAsFirstItemAfterMainStage) { StageNavigationManager.instance.SwitchToStage(stage, setAsFirstItemAfterMainStage, StageNavigationManager.Analytics.ChangeType.Unknown); } public static void PlaceGameObjectInCurrentStage(GameObject gameObject) { StageNavigationManager.instance.PlaceGameObjectInCurrentStage(gameObject); } internal static Hash128 CreateWindowAndStageIdentifier(string windowGUID, Stage stage) { Hash128 hash = stage.GetHashForStateStorage(); hash.Append(windowGUID); hash.Append(stage.GetType().FullName); return hash; } internal static void SetPrefabInstanceHiddenForInContextEditing(GameObject gameObject, bool hide) { SetPrefabInstanceHiddenForInContextEditingInternal(gameObject, hide); } internal static bool IsPrefabInstanceHiddenForInContextEditing(GameObject gameObject) { return IsPrefabInstanceHiddenForInContextEditingInternal(gameObject); } internal static void EnableHidingForInContextEditingInSceneView(bool enable) { EnableHidingForInContextEditingInSceneViewInternal(enable); } internal static void SetFocusedScene(Scene scene) { SetFocusedSceneInternal(scene.IsValid() ? scene.handle : 0); } internal static Scene GetFocusedScene() { return GetFocusedSceneInternal(); } internal static void SetFocusedSceneContextRenderMode(ContextRenderMode contextRenderMode) { SetFocusedSceneContextRenderModeInternal(contextRenderMode); } internal static void CallAwakeFromLoadOnSubHierarchy(GameObject prefabInstanceRoot) { CallAwakeFromLoadOnSubHierarchyInternal(prefabInstanceRoot); } } }
UnityCsReference/Editor/Mono/SceneManagement/StageManager/StageUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneManagement/StageManager/StageUtility.cs", "repo_id": "UnityCsReference", "token_count": 2113 }
348
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor { class SceneViewPickingShortcutContext : SceneViewMotion.SceneViewContext { public override bool active => ViewHasFocusAndViewportUnderMouse && Tools.current != Tool.View; } }
UnityCsReference/Editor/Mono/SceneView/PickingShortcutContext.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneView/PickingShortcutContext.cs", "repo_id": "UnityCsReference", "token_count": 115 }
349
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine; namespace UnityEditor { class ViewpointProxyTypeCache { static ViewpointProxyTypeCache[] s_Cache; Type m_ViewpointType; Type m_TranslatorType; internal Type viewpointType { get => m_ViewpointType; } internal Type translatorType { get => m_TranslatorType; } internal static ViewpointProxyTypeCache[] caches { get { if (s_Cache == null) s_Cache = GetProxiesForViewpoints(); return s_Cache; } } ViewpointProxyTypeCache(Type targetType, Type translatorType) { m_ViewpointType = targetType; m_TranslatorType = translatorType; } internal static IEnumerable<ViewpointProxyTypeCache> GetSupportedCameraComponents() { foreach (var entry in s_Cache) { bool found = false; foreach (Type interfaceType in entry.translatorType.GetInterfaces()) { if (interfaceType == typeof(ICameraLensData)) found = true; } if (!found) continue; yield return entry; } } internal static Type GetTranslatorTypeForType(Type type) { foreach (var entry in caches) { if (entry.viewpointType == type) return entry.translatorType; } return null; } internal static Texture2D GetIcon(IViewpoint viewpoint) { Texture2D icon = EditorGUIUtility.GetIconForObject(viewpoint.TargetObject); // This way works better to get the icon for the Camera component. if (icon == null) icon = EditorGUIUtility.FindTexture(viewpoint.TargetObject.GetType()); return icon; } static ViewpointProxyTypeCache[] GetProxiesForViewpoints() { (Type, Type) k_NullData = (null, null); var types = TypeCache.GetTypesDerivedFrom<IViewpoint>(); List<Type> filteredTypes = new List<Type>(); foreach (var type in types) { if (!type.IsAbstract && !type.IsSubclassOf(typeof(MonoBehaviour))) filteredTypes.Add(type); } List<ViewpointProxyTypeCache> viewpoints = new List<ViewpointProxyTypeCache>(); foreach (Type type in filteredTypes) { (Type, Type) targetAndTranslatorTypes = GetGenericViewpointType(type); if (targetAndTranslatorTypes == k_NullData) continue; viewpoints.Add(new ViewpointProxyTypeCache(targetAndTranslatorTypes.Item2, type)); } return viewpoints.ToArray(); } static (Type, Type) GetGenericViewpointType(Type type) { Type baseT = type.BaseType; while (baseT != null) { if (baseT.IsGenericType) { if (baseT.GetGenericTypeDefinition() == typeof(Viewpoint<>)) return (baseT, baseT.GetGenericArguments()[0]); } baseT = baseT.BaseType; } return (null, null); } } }
UnityCsReference/Editor/Mono/SceneView/Viewpoint/ViewpointProxyTypeCache.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SceneView/Viewpoint/ViewpointProxyTypeCache.cs", "repo_id": "UnityCsReference", "token_count": 1784 }
350
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace UnityEditor.Scripting.Compilers { internal abstract class CompilerOutputParserBase { protected static CompilerMessage CreateInternalCompilerErrorMessage(string[] compileroutput) { return new CompilerMessage { file = "", message = String.Join(Environment.NewLine, compileroutput), type = CompilerMessageType.Error, line = 0, column = 0, }; } protected internal static CompilerMessage CreateCompilerMessageFromMatchedRegex(string line, Match m, string errorId, string informationId = null) { CompilerMessage message = new CompilerMessage(); if (m.Groups["filename"].Success) { message.file = m.Groups["filename"].Value; } if (m.Groups["line"].Success) { message.line = Int32.Parse(m.Groups["line"].Value); } if (m.Groups["column"].Success) { message.column = Int32.Parse(m.Groups["column"].Value); } message.message = line; string messageType = m.Groups["type"].Value; if (messageType == errorId) { message.type = CompilerMessageType.Error; } else if (!string.IsNullOrEmpty(informationId) && messageType == informationId) { message.type = CompilerMessageType.Information; } else { message.type = CompilerMessageType.Warning; } return message; } public virtual IEnumerable<CompilerMessage> Parse(string[] errorOutput, bool compilationHadFailure) { return Parse(errorOutput, new string[0], compilationHadFailure); } /* we want to remove the assemblyName_unused argument, but today burst uses internalsvisibleto and inherits from this class :( so we cannot change this signature*/ public virtual IEnumerable<CompilerMessage> Parse(string[] errorOutput, string[] standardOutput, bool compilationHadFailure, string assemblyName_unused = null) { var hasErrors = false; var msgs = new List<CompilerMessage>(); var regex = GetOutputRegex(); var internalErrorRegex = GetInternalErrorOutputRegex(); foreach (var line in errorOutput) { if (!ShouldParseLine(line)) continue; //Jamplus can fail with enormous lines in the stdout, parsing of which can take 30! seconds. var line2 = line.Length > 1000 ? line.Substring(0, 100) : line; Match m = regex.Match(line2); if (!m.Success) { if (internalErrorRegex != null) m = internalErrorRegex.Match(line2); if (!m.Success) continue; } CompilerMessage message = CreateCompilerMessageFromMatchedRegex(line, m, GetErrorIdentifier(), GetInformationIdentifier()); if (message.type == CompilerMessageType.Error) hasErrors = true; msgs.Add(message); } if (compilationHadFailure && !hasErrors) { msgs.Add(CreateInternalCompilerErrorMessage(errorOutput)); } return msgs; } protected virtual bool ShouldParseLine(string line) { return true; } protected abstract string GetErrorIdentifier(); protected virtual string GetInformationIdentifier() { return "info"; } protected abstract Regex GetOutputRegex(); protected virtual Regex GetInternalErrorOutputRegex() { return null; } } }
UnityCsReference/Editor/Mono/Scripting/Compilers/CompilerOutputParserBase.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/Compilers/CompilerOutputParserBase.cs", "repo_id": "UnityCsReference", "token_count": 1942 }
351
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.Utils; using File = System.IO.File; using SystemPath = System.IO.Path; namespace UnityEditor.Scripting.ScriptCompilation { static class AssetPath { public static readonly char Separator = '/'; /// <summary> /// Compares two paths /// type of slashes is ignored, so different path separators is allowed /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool ComparePaths(string left, string right) { var lengthDiff = left.Length - right.Length; if (lengthDiff > 1 || lengthDiff < -1) return false; for (int i = 0; i < left.Length || i < right.Length; i++) { char leftCharLower = ' '; char rightCharLower= ' '; if (i < left.Length) { leftCharLower = Utility.FastToLower(left[i]); leftCharLower = Utility.IsPathSeparator(leftCharLower) ? ' ' : leftCharLower; } if (i < right.Length) { rightCharLower = Utility.FastToLower(right[i]); rightCharLower = Utility.IsPathSeparator(rightCharLower) ? ' ' : rightCharLower; } if (leftCharLower != rightCharLower) return false; } return true; } public static string GetFullPath(string path) { return ReplaceSeparators(SystemPath.GetFullPath(path.NormalizePath())); } public static string Combine(params string[] paths) { return ReplaceSeparators(Paths.Combine(paths)); } public static string Combine(string path1, string path2) { return ReplaceSeparators(SystemPath.Combine(path1, path2)); } public static bool IsPathRooted(string path) { return SystemPath.IsPathRooted(path.NormalizePath()); } public static string GetFileName(string path) { return SystemPath.GetFileName(path.NormalizePath()); } public static string GetExtension(string path) { return SystemPath.GetExtension(path.NormalizePath()); } public static string GetDirectoryName(string path) { return ReplaceSeparators(SystemPath.GetDirectoryName(path.NormalizePath())); } public static string ReplaceSeparators(string path) { int length = path.Length; var chars = new char[length]; for (int i = 0; i < length; ++i) { if (path[i] == '\\') chars[i] = Separator; else chars[i] = path[i]; } return new string(chars); } public static bool Exists(string path) { return File.Exists(path); } public static string GetAssemblyNameWithoutExtension(string assemblyName) { if (AssetPath.GetExtension(assemblyName) == ".dll") return SystemPath.GetFileNameWithoutExtension(assemblyName.NormalizePath()); return SystemPath.GetFileName(assemblyName.NormalizePath()); } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/AssetPath.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/AssetPath.cs", "repo_id": "UnityCsReference", "token_count": 1680 }
352
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.Scripting.ScriptCompilation { [Serializable] class CustomScriptAssemblyReferenceData { // Disable the `x is never assigned to, and will always have its default value' warning (CS0649) #pragma warning disable 649 public string reference; public static CustomScriptAssemblyReferenceData FromJson(string json) { CustomScriptAssemblyReferenceData assemblyRefData = new CustomScriptAssemblyReferenceData(); UnityEngine.JsonUtility.FromJsonOverwrite(json, assemblyRefData); if (assemblyRefData == null) throw new Exception("Json file does not contain an assembly reference definition"); return assemblyRefData; } public static string ToJson(CustomScriptAssemblyReferenceData data) { return UnityEngine.JsonUtility.ToJson(data, true); } } class CustomScriptAssemblyReference { public bool Equals(CustomScriptAssemblyReference other) { return string.Equals(FilePath, other.FilePath, StringComparison.Ordinal) && string.Equals(PathPrefix, other.PathPrefix, StringComparison.Ordinal) && string.Equals(Reference, other.Reference, StringComparison.Ordinal); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((CustomScriptAssemblyReference) obj); } public override int GetHashCode() { return HashCode.Combine(FilePath, PathPrefix, Reference); } public string FilePath { get; set; } public string PathPrefix { get; set; } public string Reference { get; set; } // Name or GUID public static CustomScriptAssemblyReference FromCustomScriptAssemblyReferenceData(string path, CustomScriptAssemblyReferenceData customScriptAssemblyReferenceData) { if (customScriptAssemblyReferenceData == null) return null; var pathPrefix = path.Substring(0, path.Length - AssetPath.GetFileName(path).Length); var customScriptAssemblyReference = new CustomScriptAssemblyReference(); customScriptAssemblyReference.FilePath = path; customScriptAssemblyReference.PathPrefix = pathPrefix; customScriptAssemblyReference.Reference = customScriptAssemblyReferenceData.reference; return customScriptAssemblyReference; } public static CustomScriptAssemblyReference FromPathAndReference(string path, string reference) { var pathPrefix = path.Substring(0, path.Length - AssetPath.GetFileName(path).Length); var customScriptAssemblyReference = new CustomScriptAssemblyReference(); customScriptAssemblyReference.FilePath = path; customScriptAssemblyReference.PathPrefix = pathPrefix; customScriptAssemblyReference.Reference = reference; return customScriptAssemblyReference; } public CustomScriptAssemblyReferenceData CreateData() { return new CustomScriptAssemblyReferenceData() { reference = Reference }; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/CustomScriptAssemblyReference.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/CustomScriptAssemblyReference.cs", "repo_id": "UnityCsReference", "token_count": 1317 }
353
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEditor.Modules; namespace UnityEditor.Scripting.ScriptCompilation { static class PlatformSupportModuleHelpers { public static void AddAdditionalPlatformSupportData(ICompilationExtension compilationExtension, ref ScriptAssembly scriptAssembly) { if (compilationExtension == null) { return; } scriptAssembly.Defines = AddAdditionalToArray(scriptAssembly.Defines, compilationExtension.GetAdditionalDefines().ToArray()); scriptAssembly.References = AddAdditionalToArray(scriptAssembly.References, compilationExtension.GetAdditionalAssemblyReferences() .Concat(compilationExtension.GetWindowsMetadataReferences()).ToArray()); scriptAssembly.Files = AddAdditionalToArray(scriptAssembly.Files, compilationExtension.GetAdditionalSourceFiles().ToArray()); } private static string[] AddAdditionalToArray(string[] source, string[] extras) { if (extras == null) { return source; } var destinationArray = new string[source.Length + extras.Length]; Array.Copy(source, destinationArray, source.Length); Array.Copy(extras, 0, destinationArray, source.Length, extras.Length); return destinationArray; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/PlatformSupportModuleHelpers.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/PlatformSupportModuleHelpers.cs", "repo_id": "UnityCsReference", "token_count": 575 }
354
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.Scripting.ScriptCompilation { internal static class VersionRangesEvaluators<TVersion> where TVersion : struct, IVersion<TVersion> { public static bool MinimumVersionInclusive(TVersion left, TVersion right, TVersion version) { return version.Equals(left) || version.CompareTo(left) > 0; // version >= left; } public static bool MinimumVersionExclusive(TVersion left, TVersion right, TVersion version) { return version.CompareTo(left) > 0; // version > left; } public static bool ExactVersionMatch(TVersion left, TVersion right, TVersion version) { return version.Equals(left); // left == version; } public static bool MaximumVersionInclusive(TVersion left, TVersion right, TVersion version) { return version.Equals(right) || version.CompareTo(right) < 0; // version <= right; } public static bool MaximumVersionExclusive(TVersion left, TVersion right, TVersion version) { return version.CompareTo(right) < 0; // version < right; } public static bool ExactRangeInclusive(TVersion left, TVersion right, TVersion version) { return MinimumVersionInclusive(left, right, version) // left <= version && MaximumVersionInclusive(left, right, version); // && version <= right; } public static bool ExactRangeExclusive(TVersion left, TVersion right, TVersion version) { return MinimumVersionExclusive(left, right, version) // left < version && MaximumVersionExclusive(left, right, version); // && version < right; } public static bool MixedInclusiveMinimumAndExclusiveMaximumVersion(TVersion left, TVersion right, TVersion version) { return MinimumVersionInclusive(left, right, version) // left <= version && MaximumVersionExclusive(left, right, version); // && version < right; } public static bool MixedExclusiveMinimumAndInclusiveMaximumVersion(TVersion left, TVersion right, TVersion version) { return MinimumVersionExclusive(left, right, version) // left < version && MaximumVersionInclusive(left, right, version); // && version <= right; } public static bool Invalid(string expression) { throw new ExpressionNotValidException($"Unknown expression: {expression}"); } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/VersionRangesEvaluators.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/VersionRangesEvaluators.cs", "repo_id": "UnityCsReference", "token_count": 998 }
355
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Bindings; using Object = UnityEngine.Object; namespace UnityEditor { // SelectionMode can be used to tweak the selection returned by Selection.GetTransforms. [Flags] public enum SelectionMode { // Return the whole selection. Unfiltered = 0, // Only return the topmost selected transform. A selected child of another selected transform will be filtered out. TopLevel = 1, // Return the selection and all child transforms of the selection. Deep = 2, // Excludes any prefabs from the selection. ExcludePrefab = 4, // Excludes any objects which shall not be modified. Editable = 8, // Only return objects that are assets in the Asset directory. Assets = 16, // If the selection contains folders, also include all assets and subfolders within that folder in the file hierarchy. DeepAssets = 32, // Return a selection that only contains top level selection of all visible assets //TopLevelAssets = 64, // Renamed to Editable [Obsolete("'OnlyUserModifiable' is obsolete. Use 'Editable' instead. (UnityUpgradeable) -> Editable", true)] OnlyUserModifiable = 8 } [NativeHeader("Editor/Src/Gizmos/GizmoUtil.h")] [NativeHeader("Editor/Src/Selection/Selection.bindings.h")] [NativeHeader("Editor/Src/Selection/Selection.h")] [NativeHeader("Editor/Src/Selection/SceneInspector.h")] public sealed partial class Selection { // Returns the top level selection, excluding prefabs. public extern static Transform[] transforms { [NativeMethod("GetTransformSelection", true)] get; } // Returns the actual game object selection. Includes prefabs, non-modifyable objects. public extern static Transform activeTransform { [NativeMethod("GetActiveTransform", true)] get; [NativeMethod("SetActiveObject", true)] set; } // Returns the actual game object selection. Includes prefabs, non-modifyable objects. public extern static GameObject[] gameObjects { [NativeMethod("GetGameObjectSelection", true)] get; } // Returns the active game object. (The one shown in the inspector) public extern static GameObject activeGameObject { [NativeMethod("GetActiveGO", true)] get; [NativeMethod("SetActiveObject", true)] set; } // Returns the actual object selection. Includes prefabs, non-modifyable objects. extern public static Object activeObject { [NativeMethod("GetActiveObject", true)] get; [NativeMethod("SetActiveObject", true)] set; } [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern internal static void SetSelectionWithActiveObject([Unmarshalled] Object[] newSelection, Object activeObject); [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern internal static void SetSelectionWithActiveInstanceID([NotNull] int[] newSelection, int activeObject); [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] internal static extern void SetFullSelection([Unmarshalled] Object[] newSelection, Object activeObject, Object context, DataMode dataModeHint); [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] internal static extern void SetFullSelectionByID([NotNull]int[] newSelection, int activeObjectInstanceID, int contextInstanceID, DataMode dataModeHint); [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] internal static extern void UpdateSelectionMetaData(Object context, DataMode dataModeHint); // Returns the active context object extern public static Object activeContext { [NativeMethod("GetActiveContext", true)] get; } internal extern static DataMode dataModeHint { [NativeMethod("GetDataModeHint", true)] get; } // Returns the instanceID of the actual object selection. Includes prefabs, non-modifiable objects. [StaticAccessor("Selection", StaticAccessorType.DoubleColon)] [NativeName("ActiveID")] extern public static int activeInstanceID { get; set; } // Returns the active context object's instance ID [StaticAccessor("Selection", StaticAccessorType.DoubleColon)] [NativeName("ActiveContextID")] extern internal static int activeContextInstanceID { get; } // The actual unfiltered selection from the Scene. [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern public static Object[] objects { [return: Unmarshalled] get; [param:Unmarshalled] set; } // The actual unfiltered selection from the Scene returned as instance ids instead of ::ref::objects. [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] public static int[] instanceIDs { get => GetInstanceIDs(); set => SetInstanceIDs(value); } [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern static int[] GetInstanceIDs(); [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern static void SetInstanceIDs([NotNull] int[] instanceIDs); [StaticAccessor("GetSceneTracker()", StaticAccessorType.Dot)] [NativeMethod("IsSelected")] extern public static bool Contains(int instanceID); [NativeMethod("SetActiveObjectWithContextInternal", true)] extern public static void SetActiveObjectWithContext(Object obj, Object context); // Allows for fine grained control of the selection type using the [[SelectionMode]] bitmask. [NativeMethod("GetTransformSelection", true)] extern public static Transform[] GetTransforms(SelectionMode mode); //* undocumented - utility function [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern internal static Object[] GetObjectsMode(SelectionMode mode); [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern internal static string[] assetGUIDsDeepSelection { [NativeMethod("GetSelectedAssetGUIDStringsDeep")] get; } [StaticAccessor("SelectionBindings", StaticAccessorType.DoubleColon)] extern public static string[] assetGUIDs { [NativeMethod("GetSelectedAssetGUIDStrings")] get; } [StaticAccessor("Selection", StaticAccessorType.DoubleColon)] [NativeName("SelectionCount")] public extern static int count { get; } [NativeMethod("DoAllGOsHaveConstrainProportionsEnabled", true)] internal static extern bool DoAllGOsHaveConstrainProportionsEnabled([NotNull] Object[] targetObjects); } }
UnityCsReference/Editor/Mono/Selection/Selection.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Selection/Selection.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2670 }
356
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using System.Collections.Generic; using UnityEditor.Experimental; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEditor.StyleSheets; namespace UnityEditor { internal class SettingsTreeView : TreeView { private struct SettingsNode { public string path; public Dictionary<string, SettingsNode> children; } private static class Styles { public static StyleBlock tree => EditorResources.GetStyle("sb-settings-tree"); public static GUIStyle listItem = "SettingsListItem"; public static GUIStyle treeItem = "SettingsTreeItem"; } private bool m_ListViewMode; public SettingsProvider[] providers { get; } public SettingsProvider currentProvider { get; private set; } public string searchContext { get; set; } public delegate void ProviderChangedHandler(SettingsProvider lastSelectedProvider, SettingsProvider newlySelectedProvider); public event ProviderChangedHandler currentProviderChanged; public SettingsTreeView(TreeViewState state, SettingsProvider[] providers) : base(state) { this.providers = providers; Reload(); ExpandAll(); } public void FocusSelection(int selectedId) { List<int> selectedIDs = new List<int> { selectedId }; SetSelection(selectedIDs); SelectionChanged(selectedIDs); } public List<SettingsProvider> GetChildrenAtPath(string path) { List<SettingsProvider> children = null; var pathItem = FindItem(path.GetHashCode(), rootItem); if (pathItem != null) children = pathItem.children.Select(item => FindProviderById(item.id)).Where(p => p != null).ToList(); return children ?? new List<SettingsProvider>(); } protected override bool CanMultiSelect(TreeViewItem item) { return false; } protected override void SelectionChanged(IList<int> selectedIds) { SettingsProvider selectedProvider = GetFirstValidProvider(selectedIds.Count > 0 ? selectedIds.First() : -1); currentProviderChanged?.Invoke(currentProvider, selectedProvider); currentProvider = selectedProvider; } protected SettingsProvider GetFirstValidProvider(int id) { if (id == -1) return null; var treeViewItem = FindItem(id, rootItem); var provider = FindProviderById(id); while (provider == null && treeViewItem != null) { if (treeViewItem.children.Count <= 0) break; treeViewItem = treeViewItem.children.First(); provider = FindProviderById(treeViewItem.id); } return provider; } private SettingsProvider FindProviderById(int id) { return providers.FirstOrDefault(p => p.settingsPath.GetHashCode() == id); } protected override void RowGUI(RowGUIArgs args) { var labelRect = args.rowRect; var contentIndent = GetContentIndent(args.item); if (!m_ListViewMode) { labelRect.xMin += contentIndent; } if (Styles.tree.GetBool("-unity-show-icon") && args.item.icon != null) { const float k_IconSize = 16.0f; var iconRect = labelRect; iconRect.xMin -= k_IconSize; iconRect.xMax = iconRect.xMin + k_IconSize; GUI.DrawTexture(iconRect, args.item.icon); } if (Event.current.type == EventType.Repaint) { var elementStyle = m_ListViewMode ? Styles.listItem : Styles.treeItem; elementStyle.Draw(labelRect, args.item.displayName, args.rowRect.Contains(Event.current.mousePosition), HasFocus(), args.selected, false); } } protected override bool DoesItemMatchSearch(TreeViewItem item, string search) { if (base.DoesItemMatchSearch(item, search)) return true; var provider = FindProviderById(item.id); return provider != null && provider.HasSearchInterest(search); } protected override void SearchChanged(string newSearch) { base.SearchChanged(newSearch); var rows = GetRows(); if (rows.Count == 0) return; if (!GetSelection().Any(selectedId => rows.Any(r => r.id == selectedId))) SetSelection(new[] { rows[0].id }, TreeViewSelectionOptions.FireSelectionChanged); } protected override TreeViewItem BuildRoot() { SettingsNode rootNode = new SettingsNode() { children = new Dictionary<string, SettingsNode>() }; BuildSettingsNodeTree(rootNode); var allItems = new List<TreeViewItem>(); AppendSettingsNode(rootNode, "", 0, allItems); var root = new TreeViewItem { id = 0, depth = -1, displayName = "Root" }; SetupParentsAndChildrenFromDepths(root, allItems); return root; } private void BuildSettingsNodeTree(SettingsNode rootNode) { // If all provider have same root, hide the root name: var allChildrenUnderSameRoot = true; m_ListViewMode = true; string rootName = null; foreach (var provider in providers) { if (rootName == null) rootName = provider.pathTokens[0]; if (rootName != provider.pathTokens[0]) { allChildrenUnderSameRoot = false; m_ListViewMode = false; } else if (provider.pathTokens.Length > 2) { m_ListViewMode = false; } } foreach (var provider in providers) { SettingsNode current = rootNode; var nodePath = allChildrenUnderSameRoot ? rootName : ""; for (var tokenIndex = allChildrenUnderSameRoot ? 1 : 0; tokenIndex < provider.pathTokens.Length; ++tokenIndex) { var token = provider.pathTokens[tokenIndex]; if (nodePath.Length > 0) nodePath += "/"; nodePath += token; if (!current.children.ContainsKey(token)) { current.children[token] = new SettingsNode() { path = nodePath, children = new Dictionary<string, SettingsNode>() }; } current = current.children[token]; } } } private void AppendSettingsNode(SettingsNode node, string rootPath, int depth, ICollection<TreeViewItem> items) { var sortedChildNames = node.children.Keys.ToList(); sortedChildNames.Sort(); foreach (var nodeName in sortedChildNames) { var childNode = node.children[nodeName]; var childNodePath = rootPath.Length == 0 ? nodeName : rootPath + "/" + nodeName; var id = childNode.path.GetHashCode(); var provider = FindProviderById(id); items.Add(new TreeViewItem { id = id, depth = depth, displayName = provider != null ? provider.label : nodeName, icon = provider?.icon }); AppendSettingsNode(childNode, childNodePath, depth + 1, items); } } } }
UnityCsReference/Editor/Mono/Settings/SettingsTreeView.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Settings/SettingsTreeView.cs", "repo_id": "UnityCsReference", "token_count": 3623 }
357
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.IO; using System.Linq; using UnityEditorInternal; using UnityEngine; using UnityEngine.Experimental.Rendering; using System.Collections.Generic; using UnityEngine.SceneManagement; using UnityEngine.U2D.Interface; using Object = UnityEngine.Object; using UnityTexture2D = UnityEngine.Texture2D; using UnityEditor.SceneManagement; using UnityEngine.Scripting; namespace UnityEditor { internal static class SpriteUtility { static class SpriteUtilityStrings { public static readonly GUIContent saveAnimDialogMessage = EditorGUIUtility.TrTextContent("Create a new animation for the game object '{0}':"); public static readonly GUIContent saveAnimDialogTitle = EditorGUIUtility.TrTextContent("Create New Animation"); public static readonly GUIContent saveAnimDialogName = EditorGUIUtility.TrTextContent("New Animation"); public static readonly GUIContent unableToFindSpriteRendererWarning = EditorGUIUtility.TrTextContent("There should be a SpriteRenderer in dragged object"); public static readonly GUIContent unableToAddSpriteRendererWarning = EditorGUIUtility.TrTextContent("Unable to add SpriteRenderer into Gameobject."); public static readonly GUIContent failedToCreateAnimationError = EditorGUIUtility.TrTextContent("Failed to create animation for dragged object"); } private static Material s_PreviewSpriteDefaultMaterial; internal static Material previewSpriteDefaultMaterial { get { if (s_PreviewSpriteDefaultMaterial == null) { Shader shader = Shader.Find("Sprites/Default"); s_PreviewSpriteDefaultMaterial = new Material(shader); } return s_PreviewSpriteDefaultMaterial; } } static List<Object> s_SceneDragObjects; static DragType s_DragType; enum DragType { NotInitialized, SpriteAnimation, CreateMultiple } public delegate string ShowFileDialogDelegate(string title, string defaultName, string extension, string message, string defaultPath); public static void OnSceneDrag(SceneView sceneView) { HandleSpriteSceneDrag(sceneView, new UnityEngine.U2D.Interface.Event(), DragAndDrop.objectReferences, DragAndDrop.paths, EditorUtility.SaveFilePanelInProject); } public static void HandleSpriteSceneDrag(SceneView sceneView, IEvent evt, Object[] objectReferences, string[] paths, ShowFileDialogDelegate saveFileDialog) { if (evt.type != EventType.DragUpdated && evt.type != EventType.DragPerform && evt.type != EventType.DragExited) return; // Return if any of the dragged objects are null, e.g. a MonoBehaviour without a managed instance if (objectReferences.Any(obj => obj == null)) return; // Regardless of EditorBehaviorMode or SceneView mode we don't handle if texture is dragged over a GO with renderer if (objectReferences.Length == 1 && objectReferences[0] as UnityTexture2D != null) { GameObject go = HandleUtility.PickGameObject(evt.mousePosition, true); if (go != null) { var renderer = go.GetComponent<Renderer>(); if (renderer != null && !(renderer is SpriteRenderer)) { // There is an object where the cursor is // and we are dragging a texture. Most likely user wants to // assign texture to the GO // Case 730444: Proceed only if the go has a renderer CleanUp(true); return; } } } switch (evt.type) { case (EventType.DragUpdated): DragType newDragType = evt.alt ? DragType.CreateMultiple : DragType.SpriteAnimation; if (s_DragType != newDragType || s_SceneDragObjects == null) // Either this is first time we are here OR evt.alt changed during drag { if (!ExistingAssets(objectReferences) && PathsAreValidTextures(paths)) // External drag with images that are not in the project { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; s_SceneDragObjects = new List<Object>(); s_DragType = newDragType; } else // Internal drag with assets from project { List<Sprite> assets = GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type); if (assets.Count == 0) return; if (s_DragType != DragType.NotInitialized) // evt.alt changed during drag, so we need to cleanup and start over CleanUp(true); s_DragType = newDragType; CreateSceneDragObjects(assets, sceneView); IgnoreForRaycasts(s_SceneDragObjects); } } PositionSceneDragObjects(s_SceneDragObjects, sceneView, evt.mousePosition); DragAndDrop.visualMode = DragAndDropVisualMode.Copy; evt.Use(); break; case (EventType.DragPerform): List<Sprite> sprites = GetSpriteFromPathsOrObjects(objectReferences, paths, evt.type); if (sprites.Count > 0 && s_SceneDragObjects != null) { // Store current undoIndex to undo all operations done if any part of sprite creation fails int undoIndex = Undo.GetCurrentGroup(); // For external drags, we have delayed all creation to DragPerform because only now we have the imported sprite assets if (s_SceneDragObjects.Count == 0) { CreateSceneDragObjects(sprites, sceneView); PositionSceneDragObjects(s_SceneDragObjects, sceneView, evt.mousePosition); } foreach (GameObject dragGO in s_SceneDragObjects) { dragGO.hideFlags = HideFlags.None; // When in e.g Prefab Mode ensure to reparent dragged objects under the prefab root Transform defaultObjectTransform = SceneView.GetDefaultParentObjectIfSet(); if (defaultObjectTransform != null) dragGO.transform.SetParent(defaultObjectTransform, true); else if (sceneView.customParentForDraggedObjects != null) dragGO.transform.SetParent(sceneView.customParentForDraggedObjects, true); Undo.RegisterCreatedObjectUndo(dragGO, "Create Sprite"); EditorUtility.SetDirty(dragGO); } bool createGameObject = true; if (s_DragType == DragType.SpriteAnimation && sprites.Count > 1) { createGameObject = AddAnimationToGO((GameObject)s_SceneDragObjects[0], sprites.ToArray(), saveFileDialog); } if (createGameObject) { Selection.objects = s_SceneDragObjects.ToArray(); } else { // Revert all Create Sprite actions if animation failed to be created or was cancelled Undo.RevertAllDownToGroup(undoIndex); } CleanUp(!createGameObject); evt.Use(); } break; case EventType.DragExited: if (s_SceneDragObjects != null) { CleanUp(true); evt.Use(); } break; } } private static void IgnoreForRaycasts(List<Object> objects) { List<Transform> ignoredTransforms = new List<Transform>(); foreach (GameObject gameObject in objects) ignoredTransforms.AddRange(gameObject.GetComponentsInChildren<Transform>()); HandleUtility.ignoreRaySnapObjects = ignoredTransforms.ToArray(); } private static void PositionSceneDragObjects(List<Object> objects, SceneView sceneView, Vector2 mousePosition) { Vector3 position = Vector3.zero; position = HandleUtility.GUIPointToWorldRay(mousePosition).GetPoint(10); if (sceneView.in2DMode) { position.z = 0f; } else { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; object hit = HandleUtility.RaySnap(HandleUtility.GUIPointToWorldRay(mousePosition)); if (hit != null) { RaycastHit rh = (RaycastHit)hit; position = rh.point; } } if (Selection.activeGameObject != null) { Grid grid = Selection.activeGameObject.GetComponentInParent<Grid>(); if (grid != null) { Vector3Int cell = grid.WorldToCell(position); position = grid.GetCellCenterWorld(cell); } } foreach (GameObject gameObject in objects) { gameObject.transform.position = position; } } private static void CreateSceneDragObjects(List<Sprite> sprites, SceneView sceneView) { if (s_SceneDragObjects == null) s_SceneDragObjects = new List<Object>(); if (s_DragType == DragType.CreateMultiple) { foreach (Sprite sprite in sprites) s_SceneDragObjects.Add(CreateDragGO(sprite, Vector3.zero, sceneView)); } else { s_SceneDragObjects.Add(CreateDragGO(sprites[0], Vector3.zero, sceneView)); } } private static void CleanUp(bool deleteTempSceneObject) { if (s_SceneDragObjects != null) { if (deleteTempSceneObject) { foreach (GameObject gameObject in s_SceneDragObjects) Object.DestroyImmediate(gameObject, false); } s_SceneDragObjects.Clear(); s_SceneDragObjects = null; } HandleUtility.ignoreRaySnapObjects = null; s_DragType = DragType.NotInitialized; } [RequiredByNativeCode] static bool CreateAnimation(GameObject gameObject, Object[] frames, ShowFileDialogDelegate saveFileDialog) { saveFileDialog = saveFileDialog ?? EditorUtility.SaveFilePanelInProject; // Use same name compare as when we sort in the backend: See AssetDatabase.cpp: SortChildren System.Array.Sort(frames, (a, b) => EditorUtility.NaturalCompare(a.name, b.name)); Animator animator = AnimationWindowUtility.EnsureActiveAnimationPlayer(gameObject) ? AnimationWindowUtility.GetClosestAnimatorInParents(gameObject.transform) : null; bool createSuccess = animator != null; if (animator != null) { // Go forward with presenting user a save clip dialog string message = string.Format(SpriteUtilityStrings.saveAnimDialogMessage.text, gameObject.name); string newClipDirectory = ProjectWindowUtil.GetActiveFolderPath(); string newClipPath = saveFileDialog(SpriteUtilityStrings.saveAnimDialogTitle.text, SpriteUtilityStrings.saveAnimDialogName.text, "anim", message, newClipDirectory); if (string.IsNullOrEmpty(newClipPath)) { Undo.ClearUndo(animator); Object.DestroyImmediate(animator); return false; } else { AnimationClip newClip = AnimationWindowUtility.CreateNewClipAtPath(newClipPath); if (newClip != null) { AddSpriteAnimationToClip(newClip, frames); createSuccess = AnimationWindowUtility.AddClipToAnimatorComponent(animator, newClip); } } } if (createSuccess == false) Debug.LogError(SpriteUtilityStrings.failedToCreateAnimationError.text); return createSuccess; } [RequiredByNativeCode] static void AddSpriteAnimationToClip(AnimationClip newClip, Object[] frames) { // TODO Default framerate be exposed to user? newClip.frameRate = 12; // Add keyframes ObjectReferenceKeyframe[] keyframes = new ObjectReferenceKeyframe[frames.Length]; for (int i = 0; i < keyframes.Length; i++) { keyframes[i] = new ObjectReferenceKeyframe(); keyframes[i].value = RemapObjectToSprite(frames[i]); keyframes[i].time = i / newClip.frameRate; } // Create binding EditorCurveBinding curveBinding = EditorCurveBinding.PPtrCurve("", typeof(SpriteRenderer), "m_Sprite"); // Save curve to clip AnimationUtility.SetObjectReferenceCurve(newClip, (EditorCurveBinding)curveBinding, keyframes); } public static List<Sprite> GetSpriteFromPathsOrObjects(Object[] objects, string[] paths, EventType currentEventType) { List<Sprite> result = new List<Sprite>(); foreach (Object obj in objects) { if (AssetDatabase.Contains(obj)) { if (obj is Sprite) result.Add(obj as Sprite); else if (obj is UnityTexture2D) result.AddRange(TextureToSprites(obj as UnityTexture2D)); } } // Fix case 742896. If any of the drag objects is already in the AssetDatabase, means we don't have to handle external drags. // Fix case 857231. We only handle external drag if default behaviour mode is 2D if (!ExistingAssets(objects) && currentEventType == EventType.DragPerform && EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D) { HandleExternalDrag(paths, true, ref result); } return result; } public static bool ExistingAssets(Object[] objects) { foreach (Object obj in objects) { if (AssetDatabase.Contains(obj)) return true; } return false; } private static void HandleExternalDrag(string[] paths, bool perform, ref List<Sprite> result) { foreach (var path in paths) { if (!ValidPathForTextureAsset(path)) continue; DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (!perform) continue; var newPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine("Assets", FileUtil.GetLastPathNameComponent(path))); if (newPath.Length <= 0) continue; FileUtil.CopyFileOrDirectory(path, newPath); ForcedImportFor(newPath); Sprite defaultSprite = GenerateDefaultSprite(AssetDatabase.LoadMainAssetAtPath(newPath) as UnityTexture2D); if (defaultSprite != null) result.Add(defaultSprite); } } private static bool PathsAreValidTextures(string[] paths) { if (paths == null || paths.Length == 0) return false; foreach (var path in paths) { if (!ValidPathForTextureAsset(path)) return false; } return true; } private static void ForcedImportFor(string newPath) { try { AssetDatabase.StartAssetEditing(); AssetDatabase.ImportAsset(newPath); } finally { AssetDatabase.StopAssetEditing(); } } private static Sprite GenerateDefaultSprite(UnityTexture2D texture) { string assetPath = AssetDatabase.GetAssetPath(texture); TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (textureImporter == null) // could be DDS importer or other non-TextureImporter type return null; if (textureImporter.textureType != TextureImporterType.Sprite) return null; if (textureImporter.spriteImportMode == SpriteImportMode.None) { textureImporter.spriteImportMode = SpriteImportMode.Single; AssetDatabase.WriteImportSettingsIfDirty(assetPath); ForcedImportFor(assetPath); } Object firstSprite = null; firstSprite = AssetDatabase.LoadAllAssetsAtPath(assetPath).FirstOrDefault(t => t is Sprite); return firstSprite as Sprite; } public static GameObject CreateDragGO(Sprite frame, Vector3 position, SceneView sceneView) { string name = string.IsNullOrEmpty(frame.name) ? "Sprite" : frame.name; name = GameObjectUtility.GetUniqueNameForSibling(null, name); // ObjectFactory registers an Undo for the GameObject created, which we do not // want for the drag preview. We register an Undo only when the user does a // DragPerform to confirm the creation of the Sprite GameObject. // The GameObject is cloned and returned while the original is destroyed to // remove the Undo operation. GameObject go = ObjectFactory.CreateGameObject(name, typeof(SpriteRenderer)); GameObject cloneGO = GameObject.Instantiate(go); Object.DestroyImmediate(go); go = cloneGO; go.name = name; SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>(); spriteRenderer.sprite = frame; go.transform.position = position; go.hideFlags = HideFlags.HideInHierarchy; Scene destinationScene = GetDestinationSceneForNewGameObjectsForSceneView(sceneView); // According to how GameOjectInspector.cs moves the object into scene if (EditorApplication.isPlaying && !EditorSceneManager.IsPreviewScene(destinationScene)) { SceneManager.MoveGameObjectToScene(go, destinationScene); } return go; } static Scene GetDestinationSceneForNewGameObjectsForSceneView(SceneView sceneView) { if (sceneView.customParentForNewGameObjects != null) return sceneView.customParentForNewGameObjects.gameObject.scene; if (sceneView.customScene.IsValid()) return sceneView.customScene; return SceneManager.GetActiveScene(); } public static bool AddAnimationToGO(GameObject go, Sprite[] frames, ShowFileDialogDelegate saveFileDialog) { SpriteRenderer spriteRenderer = go.GetComponent<SpriteRenderer>(); if (spriteRenderer == null) { Debug.LogWarning(SpriteUtilityStrings.unableToFindSpriteRendererWarning.text); spriteRenderer = (SpriteRenderer)ObjectFactory.AddComponent(go, typeof(SpriteRenderer)); if (spriteRenderer == null) { Debug.LogWarning(SpriteUtilityStrings.unableToAddSpriteRendererWarning.text); return false; } } spriteRenderer.sprite = frames[0]; return CreateAnimation(go, frames, saveFileDialog); } public static GameObject DropSpriteToSceneToCreateGO(Sprite sprite, Vector3 position) { GameObject go = new GameObject(string.IsNullOrEmpty(sprite.name) ? "Sprite" : sprite.name); SpriteRenderer spriteRenderer = (SpriteRenderer)ObjectFactory.AddComponent(go, typeof(SpriteRenderer)); spriteRenderer.sprite = sprite; go.transform.position = position; Selection.activeObject = go; return go; } public static Sprite RemapObjectToSprite(Object obj) { if (obj is Sprite) return (Sprite)obj; if (obj is UnityTexture2D) { Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(obj)); for (int i = 0; i < assets.Length; i++) { if (assets[i].GetType() == typeof(Sprite)) return assets[i] as Sprite; } } return null; } public static List<Sprite> TextureToSprites(UnityTexture2D tex) { Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(tex)); List<Sprite> result = new List<Sprite>(); for (int i = 0; i < assets.Length; i++) { if (assets[i].GetType() == typeof(Sprite)) result.Add(assets[i] as Sprite); } if (result.Count > 0) return result; Sprite defaultSprite = GenerateDefaultSprite(tex); if (defaultSprite != null) result.Add(defaultSprite); return result; } public static Sprite TextureToSprite(UnityTexture2D tex) { List<Sprite> sprites = TextureToSprites(tex); if (sprites.Count > 0) return sprites[0]; return null; } private static bool ValidPathForTextureAsset(string path) { string ext = FileUtil.GetPathExtension(path).ToLower(); return ext == "jpg" || ext == "jpeg" || ext == "tif" || ext == "tiff" || ext == "tga" || ext == "gif" || ext == "png" || ext == "psd" || ext == "bmp" || ext == "iff" || ext == "pict" || ext == "pic" || ext == "pct" || ext == "exr" || ext == "hdr"; } public static UnityTexture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height) { return RenderStaticPreview(sprite, color, width, height, Matrix4x4.identity); } public static UnityTexture2D RenderStaticPreview(Sprite sprite, Color color, int width, int height, Matrix4x4 transform) { return SpriteInspector.BuildPreviewTexture(sprite, previewSpriteDefaultMaterial, false, width, height, color, transform); } public static UnityTexture2D CreateTemporaryDuplicate(UnityTexture2D original, int width, int height) { if (!ShaderUtil.hardwareSupportsRectRenderTexture || !original) return null; RenderTexture save = RenderTexture.active; var savedViewport = ShaderUtil.rawViewportRect; RenderTexture tmp = RenderTexture.GetTemporary( width, height, 0, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR)); Graphics.Blit(original, tmp); RenderTexture.active = tmp; // If the user system doesn't support this texture size, force it to use mipmap bool forceUseMipMap = width >= SystemInfo.maxTextureSize || height >= SystemInfo.maxTextureSize; UnityTexture2D copy = new UnityTexture2D(width, height, TextureFormat.RGBA32, original.mipmapCount > 1 || forceUseMipMap); copy.ReadPixels(new Rect(0, 0, width, height), 0, 0); copy.Apply(); RenderTexture.ReleaseTemporary(tmp); EditorGUIUtility.SetRenderTextureNoViewport(save); ShaderUtil.rawViewportRect = savedViewport; copy.alphaIsTransparency = original.alphaIsTransparency; return copy; } } }
UnityCsReference/Editor/Mono/Sprites/SpriteUtility.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Sprites/SpriteUtility.cs", "repo_id": "UnityCsReference", "token_count": 12338 }
358
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using UnityEngine; using UObject = UnityEngine.Object; using UnityEditor.EditorTools; using UnityEditor.StyleSheets; using UnityEditor.Experimental; namespace UnityEditor { public sealed partial class EditorGUILayout { static readonly EditorToolGUI.ReusableArrayPool<GUIContent> s_ButtonArrays = new EditorToolGUI.ReusableArrayPool<GUIContent>(); static readonly EditorToolGUI.ReusableArrayPool<bool> s_BoolArrays = new EditorToolGUI.ReusableArrayPool<bool>(); static readonly List<EditorTool> s_CustomEditorTools = new List<EditorTool>(); static readonly List<EditorToolContext> s_CustomEditorContexts = new List<EditorToolContext>(); static class Styles { public static GUIStyle command = "AppCommand"; public static GUIStyle commandLeft; public static GUIStyle commandMid; public static GUIStyle commandRight; static Styles() { GUI.FindStyles(ref command, out commandLeft, out commandMid, out commandRight, "left", "mid", "right"); var normalColor = command.normal.textColor; command.imagePosition = ImagePosition.ImageAbove; command.active.textColor = normalColor; command.onActive.textColor = normalColor; command.onNormal.textColor = normalColor; command.fontStyle = FontStyle.Bold; commandLeft.imagePosition = ImagePosition.ImageAbove; commandLeft.active.textColor = normalColor; commandLeft.onActive.textColor = normalColor; commandLeft.onNormal.textColor = normalColor; commandLeft.fontStyle = FontStyle.Bold; commandMid.imagePosition = ImagePosition.ImageAbove; commandMid.active.textColor = normalColor; commandMid.onActive.textColor = normalColor; commandMid.onNormal.textColor = normalColor; commandMid.fontStyle = FontStyle.Bold; commandRight.imagePosition = ImagePosition.ImageAbove; commandRight.active.textColor = normalColor; commandRight.onActive.textColor = normalColor; commandRight.onNormal.textColor = normalColor; commandRight.fontStyle = FontStyle.Bold; } } public static void EditorToolbarForTarget(UObject target) { if (target == null) throw new ArgumentNullException("target"); EditorToolbarForTarget(null, target); } public static void EditorToolbarForTarget(GUIContent content, UObject target) { if (target == null) throw new ArgumentNullException("target"); if (target is Editor editor) target = editor.target; EditorToolManager.GetComponentTools(x => x.target == target, s_CustomEditorTools, true); using (new PrefixScope(content)) EditorToolbar<EditorTool>(s_CustomEditorTools); s_CustomEditorTools.Clear(); } public static void ToolContextToolbarForTarget(GUIContent content, UObject target) { if (target == null) throw new ArgumentNullException("target"); if (target is Editor editor) EditorToolManager.GetComponentContexts(x => x.inspector == editor, s_CustomEditorContexts); else EditorToolManager.GetComponentContexts(x => x.target == target, s_CustomEditorContexts); ToolContextToolbar(content, s_CustomEditorContexts); s_CustomEditorTools.Clear(); } public static void EditorToolbar(params EditorTool[] tools) { EditorToolbar<EditorTool>(tools); } public static void EditorToolbar<T>(IList<T> tools) where T : EditorTool { T selected; if (EditorToolbar(null, EditorToolManager.activeTool as T, tools, out selected)) { if (ToolManager.IsActiveTool(selected)) ToolManager.RestorePreviousTool(); else EditorToolManager.activeTool = selected; } } public static void ToolContextToolbar<T>(GUIContent content, IList<T> contexts) where T : EditorToolContext { T selected; if (EditorToolbar(content, EditorToolManager.activeToolContext as T, contexts, out selected)) { if (EditorToolManager.activeToolContext == selected) ToolManager.SetActiveContext<GameObjectToolContext>(); else EditorToolManager.activeToolContext = selected; } } struct PrefixScope : IDisposable { public PrefixScope(GUIContent label) { GUILayout.BeginHorizontal(); if (label != null && label != GUIContent.none) PrefixLabel(label); } public void Dispose() { GUILayout.EndHorizontal(); } } internal static bool EditorToolbar<T>(GUIContent content, T selected, IList<T> tools, out T clicked) where T : IEditor { using (new PrefixScope(content)) { int toolsLength = tools.Count; int index = -1; var buttons = s_ButtonArrays.Get(toolsLength); var enabled = s_BoolArrays.Get(toolsLength); clicked = selected; for (int i = 0; i < toolsLength; i++) { // can happen if the user deletes a tool through scripting if (tools[i] == null) { buttons[i] = GUIContent.none; continue; } if (ReferenceEquals(tools[i], selected)) index = i; enabled[i] = tools[i] is EditorTool tool && !tool.IsAvailable() ? false : true; buttons[i] = EditorToolUtility.GetToolbarIcon(tools[i]); } EditorGUI.BeginChangeCheck(); index = GUILayout.Toolbar(index, buttons, enabled, Styles.command, Styles.commandLeft, Styles.commandMid, Styles.commandRight); if (EditorGUI.EndChangeCheck()) { clicked = tools[index]; return true; } return false; } } } static class EditorToolGUI { // Number of buttons present in the tools toolbar. internal const int k_ToolbarButtonCount = 7; static class Styles { public static readonly GUIContent selectionTools = EditorGUIUtility.TrTextContent("Selection"); public static readonly GUIContent globalTools = EditorGUIUtility.TrTextContent("Global"); public static readonly GUIContent noToolsAvailable = EditorGUIUtility.TrTextContent("No custom tools available"); } public static GUIContent[] s_ShownToolIcons = new GUIContent[k_ToolbarButtonCount]; public static bool[] s_ShownToolEnabled = new bool[k_ToolbarButtonCount]; [EditorBrowsable(EditorBrowsableState.Never)] internal class ReusableArrayPool<T> { Dictionary<int, T[]> m_Pool = new Dictionary<int, T[]>(); int m_MaxEntries = 8; public int maxEntries { get { return m_MaxEntries; } set { m_MaxEntries = value; } } public T[] Get(int count) { T[] res; if (m_Pool.TryGetValue(count, out res)) return res; if (m_Pool.Count > m_MaxEntries) m_Pool.Clear(); m_Pool.Add(count, res = new T[count]); return res; } } static readonly List<EditorTool> s_ToolList = new List<EditorTool>(); static readonly List<EditorTool> s_EditorToolModes = new List<EditorTool>(8); public static readonly StyleRect s_ButtonRect = EditorResources.GetStyle("AppToolbar-Button").GetRect(StyleCatalogKeyword.size, StyleRect.Size(22, 22)); internal static Rect GetToolbarEntryRect(Rect pos) { return new Rect(pos.x, 4, pos.width, s_ButtonRect.height); } internal static void DoContextualToolbarOverlay() { GUILayout.BeginHorizontal(GUIStyle.none, GUILayout.MinWidth(210), GUILayout.Height(30)); EditorToolManager.GetComponentToolsForSharedTracker(s_EditorToolModes); if (s_EditorToolModes.Count > 0) { EditorGUI.BeginChangeCheck(); EditorGUILayout.EditorToolbar(s_EditorToolModes); if (EditorGUI.EndChangeCheck()) { foreach (var inspector in InspectorWindow.GetInspectors()) { foreach (var editor in inspector.tracker.activeEditors) editor.Repaint(); } } } else { var fontStyle = EditorStyles.label.fontStyle; EditorStyles.label.fontStyle = FontStyle.Italic; GUILayout.Label(Styles.noToolsAvailable, EditorStyles.centeredGreyMiniLabel); EditorStyles.label.fontStyle = fontStyle; } GUILayout.EndHorizontal(); } internal static void ShowComponentToolsContextMenu() { BuildCustomGlobalToolsContextMenu().ShowAsContext(); } internal static void ShowCustomGlobalToolsContextMenu(Rect worldBound) { BuildCustomGlobalToolsContextMenu().DropDown(worldBound); } static GenericMenu BuildCustomGlobalToolsContextMenu() { var toolHistoryMenu = new GenericMenu() { allowDuplicateNames = true }; bool foundGlobalTools = false; var global = EditorToolUtility.GetCustomEditorToolsForType(null); foreach (var tool in global) { if (tool.targetContext != null && tool.targetContext != ToolManager.activeContextType) continue; foundGlobalTools = true; toolHistoryMenu.AddItem( new GUIContent(EditorToolUtility.GetToolMenuPath(tool.editor)), false, () => { ToolManager.SetActiveTool(tool.editor); }); } if (!foundGlobalTools) toolHistoryMenu.AddDisabledItem(Styles.noToolsAvailable); return toolHistoryMenu; } } }
UnityCsReference/Editor/Mono/Tools/EditorToolGUI.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Tools/EditorToolGUI.cs", "repo_id": "UnityCsReference", "token_count": 5248 }
359
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor { [NativeHeader("Editor/Src/Highlighter/HighlighterCore.bindings.h")] public sealed partial class Highlighter { // Internal API [NativeProperty("s_SearchMode", false, TargetType.Field)] internal static extern HighlightSearchMode searchMode { get; set; } [FreeFunction("Internal_Handle")] internal static extern void Handle(Rect position, string text); public static extern string activeText { [FreeFunction] get; [FreeFunction] private set; } [NativeProperty("s_ActiveRect", false, TargetType.Field)] public static extern Rect activeRect { get; private set; } [NativeProperty("s_ActiveVisible", false, TargetType.Field)] public static extern bool activeVisible { get; private set; } [NativeProperty("s_UseUIToolkitScrolling", false, TargetType.Field)] internal static extern bool useUIToolkitScrolling { get; private set; } [NativeProperty("k_Padding", false, TargetType.Field)] internal static extern float padding { get; } [NativeProperty("k_ScrollSpeed", false, TargetType.Field)] internal static extern float scrollSpeed { get; } } }
UnityCsReference/Editor/Mono/Tutorial/Highlighter.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Tutorial/Highlighter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 543 }
360
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Text; using Unity.Properties; using UnityEngine; using UnityEngine.Pool; using UnityEngine.UIElements; namespace UnityEditor.UIElements { /// <summary> /// Base class implementing the shared functionality for editing bit mask values. For more information, refer to [[wiki:UIE-uxml-element-MaskField|UXML element MaskField]]. /// </summary> public abstract class BaseMaskField<TChoice> : BasePopupField<TChoice, string> { internal static readonly BindingId choicesMasksProperty = nameof(choicesMasks); internal abstract TChoice MaskToValue(int newMask); internal abstract int ValueToMask(TChoice value); static readonly int s_NothingIndex = 0; static readonly int s_EverythingIndex = 1; static readonly int s_TotalIndex = 2; static readonly string s_MixedLabel = L10n.Tr("Mixed..."); static readonly string s_EverythingLabel = L10n.Tr("Everything"); static readonly string s_NothingLabel = L10n.Tr("Nothing"); // This is the list of string representing all the user choices List<string> m_UserChoices; // This is the list of masks for every specific choice... if null, the mask will be computed with the default values // More details about this : // In IMGUI, the MaskField is only allowing the creation of the field with an array of choices that will have a mask // based on power of 2 value starting from 1. // However, the LayerMaskField is created based on the Layers and do not necessarily has power of 2 consecutive masks. // Therefore, this specific internal field (in IMGUI...) is requiring a specific array to contain the mask value of the // actual list of choices. List<int> m_UserChoicesMasks; // This is containing a mask to cover all the choices from the list. Computed with the help of m_UserChoicesMasks // or based on the power of 2 mask values. int m_FullChoiceMask; internal int fullChoiceMask => m_FullChoiceMask; internal BaseMaskField(string label) : base(label) { textElement.RegisterCallback<GeometryChangedEvent>(OnTextElementGeometryChanged); m_AutoCloseMenu = false; } private void OnTextElementGeometryChanged(GeometryChangedEvent evt) { var mask = ValueToMask(value); switch (mask) { case 0: case ~0: // Don't do anything for Nothing or Everything break; default: // Mixed values if (!IsPowerOf2(mask)) { // If the current text is "Mixed..." and we now have more space, we might need to check if the // actual values would fit. // If the current label contains the actual values and we now have less space, we might need to // change it to "Mixed..." if (textElement.text == s_MixedLabel && evt.oldRect.width < evt.newRect.width || textElement.text != s_MixedLabel && evt.oldRect.width > evt.newRect.width) { textElement.text = GetMixedString(); } } break; } } /// <summary> /// The list of choices to display in the popup menu. /// </summary> public override List<string> choices { get { return m_UserChoices; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } // Keep the original list in a separate user list ... if (m_UserChoices == null) { m_UserChoices = new List<string>(); } else { m_UserChoices.Clear(); } m_UserChoices.AddRange(value); // Now, add the nothing and everything choices... if (m_Choices == null) { m_Choices = new List<string>(); } else { m_Choices.Clear(); } ComputeFullChoiceMask(); m_Choices.Add(GetNothingName()); m_Choices.Add(GetEverythingName()); m_Choices.AddRange(m_UserChoices); // Make sure to update the text displayed SetValueWithoutNotify(rawValue); NotifyPropertyChanged(choicesProperty); } } internal virtual string GetNothingName() { return s_NothingLabel; } internal virtual string GetEverythingName() { return s_EverythingLabel; } /// <summary> /// The list of list of masks for every specific choice to display in the popup menu. /// </summary> [CreateProperty] public virtual List<int> choicesMasks { get { return m_UserChoicesMasks; } set { if (value == null) { m_UserChoicesMasks = null; } else { // Keep the original list in a separate user list ... if (m_UserChoicesMasks == null) { m_UserChoicesMasks = new List<int>(); } else { m_UserChoicesMasks.Clear(); } m_UserChoicesMasks.AddRange(value); ComputeFullChoiceMask(); // Make sure to update the text displayed SetValueWithoutNotify(rawValue); } NotifyPropertyChanged(choicesMasksProperty); } } void ComputeFullChoiceMask() { // Compute the full mask for all the items... it is not necessarily ~0 (which is all bits set to 1) if (m_UserChoices.Count == 0) { m_FullChoiceMask = 0; } else { if ((m_UserChoicesMasks != null) && (m_UserChoicesMasks.Count == m_UserChoices.Count)) { if (m_UserChoices.Count >= (sizeof(int) * 8)) { m_FullChoiceMask = ~0; } else { m_FullChoiceMask = 0; foreach (int itemMask in m_UserChoicesMasks) { if (itemMask == ~0) { continue; } m_FullChoiceMask |= itemMask; } } } else { if (m_UserChoices.Count >= (sizeof(int) * 8)) { m_FullChoiceMask = ~0; } else { m_FullChoiceMask = (1 << m_UserChoices.Count) - 1; } } } } // Trick to get the number of selected values... // A power of 2 number means only 1 selected... internal bool IsPowerOf2(int itemIndex) { return ((itemIndex & (itemIndex - 1)) == 0); } internal override string GetValueToDisplay() { return GetDisplayedValue(ValueToMask(value)); } internal override string GetListItemToDisplay(TChoice item) { return GetDisplayedValue(ValueToMask(item)); } internal string GetDisplayedValue(int itemIndex) { if (showMixedValue) return mixedValueString; var newValueToShowUser = ""; switch (itemIndex) { case 0: newValueToShowUser = m_Choices[s_NothingIndex]; break; case ~0: newValueToShowUser = m_Choices[s_EverythingIndex]; break; default: // Show up the right selected value if (IsPowerOf2(itemIndex)) { var indexOfValue = 0; if (m_UserChoicesMasks != null) { // Find the actual index of the selected choice... foreach (int itemMask in m_UserChoicesMasks) { if (itemMask != ~0 && ((itemMask & itemIndex) == itemIndex)) { indexOfValue = m_UserChoicesMasks.IndexOf(itemMask); break; } } } else { while ((1 << indexOfValue) != itemIndex) { indexOfValue++; } } // To get past the Nothing + Everything choices... indexOfValue += s_TotalIndex; if (indexOfValue < m_Choices.Count) { newValueToShowUser = m_Choices[indexOfValue]; } } else { if (m_UserChoicesMasks != null) { // Check if there's a name defined for this value for (int i = 0; i < m_UserChoicesMasks.Count; i++) { var itemMask = m_UserChoicesMasks[i]; if (itemMask == itemIndex) { var index = i + s_TotalIndex; newValueToShowUser = m_Choices[index]; break; } } } if (string.IsNullOrEmpty(newValueToShowUser)) { newValueToShowUser = GetMixedString(); } } break; } return newValueToShowUser; } private string GetMixedString() { var sb = GenericPool<StringBuilder>.Get(); foreach (var item in m_Choices) { var maskOfItem = GetMaskValueOfItem(item); if (!IsItemSelected(maskOfItem)) { continue; } if (sb.Length > 0) { sb.Append(", "); } sb.Append(item); } var mixedString = sb.ToString(); var minSize = textElement.MeasureTextSize(mixedString, 0, MeasureMode.Undefined, 0, MeasureMode.Undefined); // If text doesn't fit, we use "Mixed..." if (float.IsNaN(textElement.resolvedStyle.width) || minSize.x > textElement.resolvedStyle.width) { mixedString = s_MixedLabel; } sb.Clear(); GenericPool<StringBuilder>.Release(sb); return mixedString; } public override TChoice value { get => base.value; set { // We need to convert the value to an accepted mask value so that the comparision with the old value works (UUM-56605) // For example, if the value is null, we need to convert it to the mask value of the Nothing choice or it will be considered as different. base.value = MaskToValue(UpdateMaskIfEverything(ValueToMask(value))); } } public override void SetValueWithoutNotify(TChoice newValue) { base.SetValueWithoutNotify(MaskToValue(UpdateMaskIfEverything(ValueToMask(newValue)))); } internal override void AddMenuItems(IGenericMenu menu) { if (menu == null) { throw new ArgumentNullException(nameof(menu)); } foreach (var item in m_Choices) { var maskOfItem = GetMaskValueOfItem(item); var isSelected = IsItemSelected(maskOfItem); menu.AddItem(GetListItemToDisplay(MaskToValue(maskOfItem)), isSelected, () => ChangeValueFromMenu(item)); } } private bool IsItemSelected(int maskOfItem) { int valueMask = ValueToMask(value); if(maskOfItem == 0) return valueMask == 0; return (maskOfItem & valueMask) == maskOfItem; } private void UpdateMenuItems() { var menu = m_GenericMenu as GenericDropdownMenu; if (menu == null) return; foreach (var item in m_Choices) { var maskOfItem = GetMaskValueOfItem(item); var isSelected = IsItemSelected(maskOfItem); menu.UpdateItem(GetListItemToDisplay(MaskToValue(maskOfItem)), isSelected); } } // Based on the current mask, this is updating the value of the actual mask to use vs the full mask. // This is returning ~0 if all the values are selected... int UpdateMaskIfEverything(int currentMask) { var newMask = currentMask; // If the mask is full, put back the Everything flag. if (m_FullChoiceMask != 0) { if ((currentMask & m_FullChoiceMask) == m_FullChoiceMask) { newMask = ~0; } else { newMask &= m_FullChoiceMask; } } return newMask; } private void ChangeValueFromMenu(string menuItem) { var newMask = ValueToMask(value); var maskFromItem = GetMaskValueOfItem(menuItem); switch (maskFromItem) { // Nothing case 0: newMask = 0; break; // Everything case ~0: newMask = ~0; break; default: // Make sure to have only the real selected one... //newMask &= m_FullChoiceMask; // Add or remove the newly selected... if ((newMask & maskFromItem) == maskFromItem) { newMask &= ~maskFromItem; } else { newMask |= maskFromItem; } // If the mask is full, put back the Everything flag. newMask = UpdateMaskIfEverything(newMask); break; } // Finally, make sure to update the value of the mask... value = MaskToValue(newMask); UpdateMenuItems(); } // Returns the mask to be used for the item... int GetMaskValueOfItem(string item) { int maskValue; var indexOfItem = m_Choices.IndexOf(item); switch (indexOfItem) { case 0: // Nothing maskValue = 0; break; case 1: // Everything maskValue = ~0; break; default: // All others if (indexOfItem > 0) { if ((m_UserChoicesMasks != null) && (m_UserChoicesMasks.Count == m_UserChoices.Count)) { maskValue = m_UserChoicesMasks[(indexOfItem - s_TotalIndex)]; } else { maskValue = 1 << (indexOfItem - s_TotalIndex); } } else { // If less than 0, it means the item was not found... maskValue = 0; } break; } return maskValue; } } /// <summary> /// Make a field for masks. /// </summary> public class MaskField : BaseMaskField<int> { internal override int MaskToValue(int newMask) => newMask; internal override int ValueToMask(int value) => value; [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : BaseMaskField<int>.UxmlSerializedData { #pragma warning disable 649 [SerializeField] List<string> choices; [SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags choices_UxmlAttributeFlags; #pragma warning restore 649 public override object CreateInstance() => new MaskField(); public override void Deserialize(object obj) { base.Deserialize(obj); // Assigning null value throws. if (ShouldWriteAttributeValue(choices_UxmlAttributeFlags) && choices != null) { var e = (MaskField)obj; e.choices = choices; } } } /// <summary> /// Instantiates a <see cref="MaskField"/> using the data read from a UXML file. /// </summary> [Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlFactory : UxmlFactory<MaskField, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="MaskField"/>. /// </summary> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : BasePopupField<int, UxmlIntAttributeDescription>.UxmlTraits { UxmlStringAttributeDescription m_MaskChoices = new UxmlStringAttributeDescription { name = "choices" }; UxmlIntAttributeDescription m_MaskValue = new UxmlIntAttributeDescription { name = "value" }; /// <summary> /// Initializes the <see cref="UxmlTraits"/> for <see cref="MaskField"/>. /// </summary> /// <param name="ve">The VisualElement that will be populated.</param> /// <param name="bag">The bag from where the attributes are taken.</param> /// <param name="cc">The creation context, unused.</param> public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { var f = (MaskField)ve; string choicesFromBag = m_MaskChoices.GetValueFromBag(bag, cc); var listOfChoices = UxmlUtility.ParseStringListAttribute(choicesFromBag); if (listOfChoices != null && listOfChoices.Count > 0) { f.choices = listOfChoices; } // The mask is simply an int f.SetValueWithoutNotify(m_MaskValue.GetValueFromBag(bag, cc)); base.Init(ve, bag, cc); } } /// <summary> /// Callback that provides a string representation used to display the selected value. /// </summary> public virtual Func<string, string> formatSelectedValueCallback { get { return m_FormatSelectedValueCallback; } set { m_FormatSelectedValueCallback = value; textElement.text = GetValueToDisplay(); } } /// <summary> /// Callback that provides a string representation used to populate the popup menu. /// </summary> public virtual Func<string, string> formatListItemCallback { get { return m_FormatListItemCallback; } set { m_FormatListItemCallback = value; } } internal override string GetListItemToDisplay(int itemIndex) { string displayedValue = GetDisplayedValue(itemIndex); if (ShouldFormatListItem(itemIndex)) displayedValue = m_FormatListItemCallback(displayedValue); return displayedValue; } internal override string GetValueToDisplay() { string displayedValue = GetDisplayedValue(rawValue); if (ShouldFormatSelectedValue()) displayedValue = m_FormatSelectedValueCallback(displayedValue); return displayedValue; } internal bool ShouldFormatListItem(int itemIndex) { return itemIndex != 0 && itemIndex != -1 && m_FormatListItemCallback != null; } internal bool ShouldFormatSelectedValue() { return rawValue != 0 && rawValue != -1 && m_FormatSelectedValueCallback != null && IsPowerOf2(rawValue); } /// <summary> /// USS class name of elements of this type. /// </summary> public new static readonly string ussClassName = "unity-mask-field"; /// <summary> /// USS class name of labels in elements of this type. /// </summary> public new static readonly string labelUssClassName = ussClassName + "__label"; /// <summary> /// USS class name of input elements in elements of this type. /// </summary> public new static readonly string inputUssClassName = ussClassName + "__input"; /// <summary> /// Initializes and returns an instance of MaskField. /// </summary> /// <param name="choices">A list of choices to populate the field.</param> /// <param name="defaultValue">The initial mask value for this field.</param> /// <param name="formatSelectedValueCallback">A callback to format the selected value. Unity calls this method automatically when a new value is selected in the field..</param> /// <param name="formatListItemCallback">The initial mask value this field should use. Unity calls this method automatically when displaying choices for the field.</param> public MaskField(List<string> choices, int defaultMask, Func<string, string> formatSelectedValueCallback = null, Func<string, string> formatListItemCallback = null) : this(null, choices, defaultMask, formatSelectedValueCallback, formatListItemCallback) { } /// <summary> /// Initializes and returns an instance of MaskField. /// </summary> /// <param name="label">The text to use as a label for the field.</param> /// <param name="choices">A list of choices to populate the field.</param> /// <param name="defaultValue">The initial mask value for this field.</param> /// <param name="formatSelectedValueCallback">A callback to format the selected value. Unity calls this method automatically when a new value is selected in the field..</param> /// <param name="formatListItemCallback">The initial mask value this field should use. Unity calls this method automatically when displaying choices for the field.</param> public MaskField(string label, List<string> choices, int defaultMask, Func<string, string> formatSelectedValueCallback = null, Func<string, string> formatListItemCallback = null) : this(label) { this.choices = choices; m_FormatListItemCallback = formatListItemCallback; m_FormatSelectedValueCallback = formatSelectedValueCallback; SetValueWithoutNotify(defaultMask); this.formatListItemCallback = formatListItemCallback; this.formatSelectedValueCallback = formatSelectedValueCallback; } /// <summary> /// Initializes and returns an instance of MaskField. /// </summary> public MaskField() : this(null) {} /// <summary> /// Initializes and returns an instance of MaskField. /// </summary> /// <param name="label">The text to use as a label for the field.</param> public MaskField(string label) : base(label) { AddToClassList(ussClassName); labelElement.AddToClassList(labelUssClassName); visualInput.AddToClassList(inputUssClassName); } } }
UnityCsReference/Editor/Mono/UIElements/Controls/MaskField.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/MaskField.cs", "repo_id": "UnityCsReference", "token_count": 13093 }
361
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; using UnityEngine; using System; namespace UnityEditor.UIElements { internal class DropdownOptionListItem : BindableElement { [Serializable] internal new class UxmlSerializedData : BindableElement.UxmlSerializedData { public override object CreateInstance() => new DropdownOptionListItem(); } ObjectField imageProperty { get; set; } TextField textProperty { get; set; } public DropdownOptionListItem(string textPath, string imagePath) { SetItem(textPath, imagePath); } public DropdownOptionListItem() { SetItem("", ""); } void SetItem(string textPath, string imagePath) { textProperty = new TextField() { label = "", bindingPath = textPath }; Add(textProperty); imageProperty = new ObjectField() { label = "", bindingPath = imagePath, objectType = typeof(Sprite) }; Add(imageProperty); } } }
UnityCsReference/Editor/Mono/UIElements/Drawers/Internal/DropdownOptionListItem.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/Drawers/Internal/DropdownOptionListItem.cs", "repo_id": "UnityCsReference", "token_count": 603 }
362
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.UIElements.StyleSheets { class ThemeAssetDefinitionState : ScriptableObject { public List<StyleSheet> StyleSheets; public List<ThemeStyleSheet> InheritedThemes; } }
UnityCsReference/Editor/Mono/UIElements/StyleSheets/ThemeAssetDefinitionState.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/StyleSheets/ThemeAssetDefinitionState.cs", "repo_id": "UnityCsReference", "token_count": 149 }
363
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEditor.Web; using UnityEditorInternal; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditor.Connect { //*undocumented* internal enum CloudConfigUrl { CloudCore = 0, CloudCollab = 1, CloudWebauth = 2, CloudLogin = 3, CloudLicense = 4, CloudActivation = 5, CloudIdentity = 6, CloudPortal = 7, CloudPerfEvents = 8, CloudAdsDashboard = 9, CloudServicesDashboard = 10, CloudPackagesApi = 11, CloudPackagesKey = 12, CloudAssetStoreUrl = 13 } internal enum COPPACompliance { COPPAUndefined = 0, COPPACompliant = 1, COPPANotCompliant = 2 } static class COPPAComplianceExtensions { internal static CoppaCompliance ToCoppaCompliance(this COPPACompliance coppaCompliance) { return (CoppaCompliance)coppaCompliance; } } #pragma warning disable 649 //*undocumented* [NativeType(CodegenOptions.Custom, "MonoUnityProjectInfo")] internal struct ProjectInfo { public bool valid { get { return m_Valid != 0; } } public bool buildAllowed { get { return m_BuildAllowed != 0; } } public bool projectBound { get { return m_ProjectBound != 0; } } public string projectId { get { return m_ProjectId; } } public string projectGUID { get { return m_ProjectGUID; } } public string projectName { get { return m_ProjectName; } } public string organizationId { get { return m_OrganizationID; } } public string organizationName { get { return m_OrganizationName; } } public string organizationForeignKey { get { return m_OrganizationForeignKey; } } public CoppaCompliance COPPA { get { if (m_COPPA == 1) return COPPACompliance.COPPACompliant.ToCoppaCompliance(); if (m_COPPA == 2) return COPPACompliance.COPPANotCompliant.ToCoppaCompliance(); return COPPACompliance.COPPAUndefined.ToCoppaCompliance(); } } public bool coppaLock { get { return m_COPPALock != 0; } } public bool moveLock { get { return m_MoveLock != 0; } } int m_Valid; int m_BuildAllowed; int m_ProjectBound; string m_ProjectId; string m_ProjectGUID; string m_ProjectName; string m_OrganizationID; string m_OrganizationName; string m_OrganizationForeignKey; int m_COPPA; int m_COPPALock; int m_MoveLock; } [Serializable] [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeAsStruct] [NativeType(IntermediateScriptingStructName = "Connect_UserInfo")] internal partial class UserInfo { public bool valid { get { return m_Valid; } } public string userId { get { return m_UserId; } } public string userName { get { return m_UserName; } } public string displayName { get { return m_DisplayName; } } public string primaryOrg { get { return m_PrimaryOrg; } } public bool whitelisted { get { return m_Whitelisted != 0; } } public string organizationForeignKeys { get { return m_OrganizationForeignKeys; } } public string accessToken { get { return m_AccessToken; } } public string[] organizationNames { get { return m_OrganizationNames; } } [NativeName("valid")] bool m_Valid; [NativeName("id")] string m_UserId; [NativeName("name")] string m_UserName; [NativeName("displayName")] string m_DisplayName; [NativeName("primaryOrg")] string m_PrimaryOrg; [NativeName("organizationForeignKeys")] string m_OrganizationForeignKeys; [NativeName("organizationNames")] string[] m_OrganizationNames; [NativeName("accessToken")] string m_AccessToken; [Ignore] int m_Whitelisted = 1; } //*undocumented* [NativeType(CodegenOptions.Custom, "MonoUnityConnectInfo")] internal struct ConnectInfo { public bool initialized { get { return m_Initialized != 0; } } public bool ready { get { return m_Ready != 0; } } public bool online { get { return m_Online != 0; } } public bool loggedIn { get { return m_LoggedIn != 0; } } public bool workOffline { get { return m_WorkOffline != 0; } } public bool showLoginWindow { get { return m_ShowLoginWindow != 0; } } public bool error { get { return m_Error != 0; } } public string lastErrorMsg { get { return m_LastErrorMsg; } } public bool maintenance { get { return m_Maintenance != 0; } } int m_Initialized; int m_Ready; int m_Online; int m_LoggedIn; int m_WorkOffline; int m_ShowLoginWindow; int m_Error; string m_LastErrorMsg; int m_Maintenance; } #pragma warning disable 1635 #pragma warning restore 649 #pragma warning restore 1635 internal delegate void StateChangedDelegate(ConnectInfo state); internal delegate void ProjectStateChangedDelegate(ProjectInfo state); internal delegate void ProjectRefreshedDelegate(ProjectInfo state); internal delegate void UserStateChangedDelegate(UserInfo state); public static class UnityOAuth { public static event Action UserLoggedIn; public static event Action UserLoggedOut; public struct AuthCodeResponse { public string AuthCode { get; set; } public Exception Exception { get; set; } } public static void GetAuthorizationCodeAsync(string clientId, Action<AuthCodeResponse> callback) { if (string.IsNullOrEmpty(clientId)) { throw new ArgumentException("clientId is null or empty.", "clientId"); } if (callback == null) { throw new ArgumentNullException("callback"); } if (string.IsNullOrEmpty(UnityConnect.instance.GetAccessToken())) { throw new InvalidOperationException("User is not logged in or user status invalid."); } string url = string.Format("{0}/v1/oauth2/authorize", UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudIdentity)); AsyncHTTPClient client = new AsyncHTTPClient(url); client.postData = string.Format("client_id={0}&response_type=code&format=json&access_token={1}&prompt=none", clientId, UnityConnect.instance.GetAccessToken()); client.doneCallback = delegate(IAsyncHTTPClient c) { AuthCodeResponse response = new AuthCodeResponse(); if (!c.IsSuccess()) { response.Exception = new InvalidOperationException("Failed to call Unity ID to get auth code."); } else { try { var json = new JSONParser(c.text).Parse(); if (json.ContainsKey("code") && !json["code"].IsNull()) { response.AuthCode = json["code"].AsString(); } else if (json.ContainsKey("message")) { response.Exception = new InvalidOperationException(string.Format("Error from server: {0}", json["message"].AsString())); } else { response.Exception = new InvalidOperationException("Unexpected response from server."); } } catch (JSONParseException) { response.Exception = new InvalidOperationException("Unexpected response from server: Failed to parse JSON."); } } callback(response); }; client.Begin(); } [RequiredByNativeCode] private static void OnUserLoggedIn() { if (UserLoggedIn != null) UserLoggedIn(); } [RequiredByNativeCode] private static void OnUserLoggedOut() { if (UserLoggedOut != null) UserLoggedOut(); } } [NativeHeader("Editor/Src/UnityConnect/UnityErrors.h")] [StructLayout(LayoutKind.Sequential)] internal struct UnityErrorInfo { public int code; public int priority; public int behaviour; public string msg; public string shortMsg; public string codeStr; } // Keep internal and undocumented until we expose more functionality //*undocumented [NativeHeader("Editor/Src/UnityConnect/UnityConnect.h")] [NativeHeader("Editor/Src/UnityConnect/UnityConnectMarshalling.h")] [StaticAccessor("UnityConnect::Get()", StaticAccessorType.Dot)] [InitializeOnLoad] internal partial class UnityConnect { public event StateChangedDelegate StateChanged; public event ProjectRefreshedDelegate ProjectRefreshed; public event ProjectStateChangedDelegate ProjectStateChanged; public event UserStateChangedDelegate UserStateChanged; Action<bool> m_AccessTokenRefreshed; private static readonly UnityConnect s_Instance; [Flags] internal enum UnityErrorPriority { Critical = 0, Error, Warning, Info, None } [Flags] internal enum UnityErrorBehaviour { Alert = 0, Automatic, Hidden, ConsoleOnly, Reconnect } [Flags] internal enum UnityErrorFilter { ByContext = 1, ByParent = 2, ByChild = 4, All = 7 } private UnityConnect() { } [Obsolete] public void GoToHub(string page) { // Old CEF approach to go to the hub was removed. Keeping method for legacy. } public void UnbindProject() { UnbindCloudProject(); } // For Javascript Only public ProjectInfo GetProjectInfo() { return projectInfo; } public UserInfo GetUserInfo() { return userInfo; } public ConnectInfo GetConnectInfo() { return connectInfo; } public string GetConfigurationUrlByIndex(int index) { if (index == 0) return GetConfigurationURL(CloudConfigUrl.CloudCore); if (index == 1) return GetConfigurationURL(CloudConfigUrl.CloudCollab); if (index == 2) return GetConfigurationURL(CloudConfigUrl.CloudWebauth); if (index == 3) return GetConfigurationURL(CloudConfigUrl.CloudLogin); // unityeditor-cloud only called this API with index as {0,1,2,3}. // We add the new URLs in case some module might need them in the future if (index == 6) return GetConfigurationURL(CloudConfigUrl.CloudIdentity); if (index == 7) return GetConfigurationURL(CloudConfigUrl.CloudPortal); return ""; } public string GetCoreConfigurationUrl() { return GetConfigurationURL(CloudConfigUrl.CloudCore); } public bool DisplayDialog(string title, string message, string okBtn, string cancelBtn) { return EditorUtility.DisplayDialog(title, message, okBtn, cancelBtn); } public bool SetCOPPACompliance(int compliance) { return SetCOPPACompliance((COPPACompliance)compliance); } // End for Javascript Only [MenuItem("Window/Unity Connect/Clear Access Token", false, 1000, true, secondaryPriority = 1)] public static void InvokeClearAccessTokenForTesting() { instance.ClearAccessToken(); } [MenuItem("Window/Unity Connect/Computer GoesToSleep", false, 1000, true, secondaryPriority = 2)] public static void TestComputerGoesToSleep() { instance.ComputerGoesToSleep(); } [MenuItem("Window/Unity Connect/Computer DidWakeUp", false, 1000, true, secondaryPriority = 3)] public static void TestComputerDidWakeUp() { instance.ComputerDidWakeUp(); } public static UnityConnect instance { get { return s_Instance; } } static UnityConnect() { s_Instance = new UnityConnect(); } [RequiredByNativeCode] private static void OnStateChanged() { var handler = instance.StateChanged; if (handler != null) handler(instance.connectInfo); } [RequiredByNativeCode] private static void OnProjectStateChanged() { var handler = instance.ProjectStateChanged; if (handler != null) handler(instance.projectInfo); } [RequiredByNativeCode] private static void OnProjectRefreshed() { var handler = instance.ProjectRefreshed; if (handler != null) handler(instance.projectInfo); } [RequiredByNativeCode] private static void OnUserStateChanged() { var handler = instance.UserStateChanged; if (handler != null) handler(instance.userInfo); } public static extern bool preferencesEnabled { get; } public static extern bool skipMissingUPID { get; } private static extern bool Online(); public bool online { get { return Online(); } } private static extern bool LoggedIn(); public bool loggedIn { get { return LoggedIn(); } } private static extern bool ProjectValid(); public bool projectValid { get { return ProjectValid(); } } private static extern bool WorkingOffline(); public bool workingOffline { get { return WorkingOffline(); } } private static extern string GetConfigEnvironment(); public string configuration { get { return GetConfigEnvironment(); } } private static extern string GetConfigUrl(CloudConfigUrl config); public string GetConfigurationURL(CloudConfigUrl config) { return GetConfigUrl(config); } [NativeMethod("isDisableServicesWindow")] private static extern bool isDisableServicesWindow_Internal(); public bool isDisableServicesWindow { get { return isDisableServicesWindow_Internal(); } } [NativeMethod("isDisableUserLogin")] private static extern bool isDisableUserLogin_Internal(); public bool isDisableUserLogin { get { return isDisableUserLogin_Internal(); } } [NativeMethod("isDisableCollabWindow")] private static extern bool isDisableCollabWindow_Internal(); public bool isDisableCollabWindow { get { return isDisableCollabWindow_Internal(); } } public string GetEnvironment() { return GetConfigEnvironment(); } private static extern string GetConfigAPIVersion(); public string GetAPIVersion() { return GetConfigAPIVersion(); } [NativeMethod("GetUserId")] private static extern string GetUserId_Internal(); public string GetUserId() { return GetUserId_Internal(); } [NativeMethod("GetUserName")] private static extern string GetUserName_Internal(); public string GetUserName() { return GetUserName_Internal(); } [NativeMethod("GetUserDisplayName")] private static extern string GetUserDisplayName_Internal(); public string GetUserDisplayName() { return GetUserDisplayName_Internal(); } [NativeMethod("GetAccessToken")] private static extern string GetAccessToken_Internal(); public string GetAccessToken() { return GetAccessToken_Internal(); } [NativeMethod("ClearAccessToken")] private static extern void ClearAccessToken_Internal(); public void ClearAccessToken() { ClearAccessToken_Internal(); } private static extern void RefreshAccessToken(); public void RefreshAccessToken(Action<bool> refresh) { m_AccessTokenRefreshed += refresh; RefreshAccessToken(); } [RequiredByNativeCode] internal static void AccessTokenRefreshed(bool success) { if (instance.m_AccessTokenRefreshed != null) { instance.m_AccessTokenRefreshed(success); instance.m_AccessTokenRefreshed = null; } } [NativeMethod("GetProjectGUID")] private static extern string GetProjectGUID_Internal(); public string GetProjectGUID() { return GetProjectGUID_Internal(); } [NativeMethod("GetProjectName")] private static extern string GetProjectName_Internal(); public string GetProjectName() { return GetProjectName_Internal(); } [NativeMethod("GetOrganizationId")] private static extern string GetOrganizationId_Internal(); public string GetOrganizationId() { return GetOrganizationId_Internal(); } [NativeMethod("GetOrganizationName")] private static extern string GetOrganizationName_Internal(); public string GetOrganizationName() { return GetOrganizationName_Internal(); } [NativeMethod("GetOrganizationForeignKey")] private static extern string GetOrganizationForeignKey_Internal(); public string GetOrganizationForeignKey() { return GetOrganizationForeignKey_Internal(); } [NativeMethod("RefreshProject")] private static extern void RefreshProject_Internal(); public void RefreshProject() { RefreshProject_Internal(); } [NativeMethod("ClearCache")] private static extern void ClearCache_Internal(); public void ClearCache() { ClearCache_Internal(); } private static extern void Logout(bool clearUserInfo); public void Logout() { Logout(true); } [NativeMethod("WorkOffline")] private static extern void WorkOffline_Internal(bool rememberDecision); public void WorkOffline(bool rememberDecision) { WorkOffline_Internal(rememberDecision); } [NativeMethod("ShowLogin")] private static extern void ShowLogin_Internal(); public void ShowLogin() { ShowLogin_Internal(); } [NativeMethod("OpenAuthorizedURLInWebBrowser")] private static extern void OpenAuthorizedURLInWebBrowser_Internal(string url); public void OpenAuthorizedURLInWebBrowser(string url) { OpenAuthorizedURLInWebBrowser_Internal(url); } [NativeMethod("BindProject")] private static extern void BindProject_Internal(string projectGUID, string projectName, string organizationId); public void BindProject(string projectGUID, string projectName, string organizationId) { BindProject_Internal(projectGUID, projectName, organizationId); } [NativeMethod("UnbindProject")] private static extern void UnbindProject_Internal(); private void UnbindCloudProject() { UnbindProject_Internal(); } [NativeMethod("SetCOPPACompliance")] private static extern void SetCOPPACompliance_Internal(COPPACompliance compliance); public bool SetCOPPACompliance(COPPACompliance compliance) { if (compliance == COPPACompliance.COPPAUndefined) { return false; } SetCOPPACompliance_Internal(compliance); return true; } private static extern string GetLastErrorMessage(); public string lastErrorMessage { get { return GetLastErrorMessage(); } } private static extern int GetLastErrorCode(); public int lastErrorCode { get { return GetLastErrorCode(); } } [NativeMethod("SetError")] private static extern void SetError_Internal(int errorCode); public void SetError(int errorCode) { SetError_Internal(errorCode); } [NativeMethod("ClearError")] private static extern void ClearError_Internal(int errorCode); public void ClearError(int errorCode) { ClearError_Internal(errorCode); } [NativeMethod("ClearErrors")] private static extern void ClearErrors_Internal(); public void ClearErrors() { ClearErrors_Internal(); } [NativeMethod("UnhandledError")] private static extern void UnhandledError_Internal(string request, int responseCode, string response); public void UnhandledError(string request, int responseCode, string response) { UnhandledError_Internal(request, responseCode, response); } private static extern void InvokeComputerGoesToSleep(); public void ComputerGoesToSleep() { InvokeComputerGoesToSleep(); } private static extern void InvokeComputerDidWakeUp(); public void ComputerDidWakeUp() { InvokeComputerDidWakeUp(); } [NativeMethod("GetUserInfo")] private static extern UserInfo GetUserInfo_Internal(); public UserInfo userInfo { get { return GetUserInfo_Internal(); } } [NativeMethod("GetIsUserInfoReady")] private static extern bool GetIsUserInfoReady_Internal(); public bool isUserInfoReady { get { return GetIsUserInfoReady_Internal(); } } [NativeMethod("GetProjectInfo")] private static extern ProjectInfo GetProjectInfo_Internal(); public ProjectInfo projectInfo { get { return GetProjectInfo_Internal(); } } [NativeMethod("GetConnectInfo")] private static extern ConnectInfo GetConnectInfo_Internal(); public ConnectInfo connectInfo { get { return GetConnectInfo_Internal(); } } private static extern bool CanBuildWithUPID(); public bool canBuildWithUPID { get { return CanBuildWithUPID(); } } [NativeMethod("IsCollabAcceleratorInUse")] private static extern bool IsCollabAcceleratorInUse_Internal(); public bool isCollabAcceleratorInUse { get { return IsCollabAcceleratorInUse_Internal(); } } [NativeMethod("GetCollabAcceleratorId")] private static extern string GetCollabAcceleratorId_Internal(); public string collabAcceleratorId { get { return GetCollabAcceleratorId_Internal(); } } [NativeMethod("GetCollabAcceleratorName")] private static extern string GetCollabAcceleratorName_Internal(); public string collabAcceleratorName { get { return GetCollabAcceleratorName_Internal(); } } } }
UnityCsReference/Editor/Mono/UnityConnect/UnityConnect.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UnityConnect/UnityConnect.bindings.cs", "repo_id": "UnityCsReference", "token_count": 10841 }
364
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.IO; using UnityEngine; namespace UnityEditor.Utils { class MonoInstallationFinder { public const string MonoInstallation = "Mono"; public const string MonoBleedingEdgeInstallation = "MonoBleedingEdge"; public static string GetFrameWorksFolder() { var editorAppPath = FileUtil.NiceWinPath(EditorApplication.applicationPath); if (Application.platform == RuntimePlatform.WindowsEditor) return Path.Combine(Path.GetDirectoryName(editorAppPath), "Data"); else if (Application.platform == RuntimePlatform.OSXEditor) return Path.Combine(editorAppPath, "Contents"); else // Linux...? return Path.Combine(Path.GetDirectoryName(editorAppPath), "Data"); } public static string GetProfileDirectory(string profile) { var monoprefix = GetMonoInstallation(); return Path.Combine(monoprefix, Path.Combine("lib", Path.Combine("mono", profile))); } public static string GetProfileDirectory(string profile, string monoInstallation) { var monoprefix = GetMonoInstallation(monoInstallation); return Path.Combine(monoprefix, Path.Combine("lib", Path.Combine("mono", profile))); } public static string GetProfilesDirectory(string monoInstallation) { var monoprefix = GetMonoInstallation(monoInstallation); return Path.Combine(monoprefix, Path.Combine("lib", "mono")); } public static string GetEtcDirectory(string monoInstallation) { var monoprefix = GetMonoInstallation(monoInstallation); return Path.Combine(monoprefix, Path.Combine("etc", "mono")); } public static string GetMonoInstallation() { return GetMonoInstallation(MonoInstallation); } public static string GetMonoBleedingEdgeInstallation() { return GetMonoInstallation(MonoBleedingEdgeInstallation); } public static string GetMonoInstallation(string monoName) { return Path.Combine(GetFrameWorksFolder(), monoName); } } }
UnityCsReference/Editor/Mono/Utils/MonoInstallationFinder.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/MonoInstallationFinder.cs", "repo_id": "UnityCsReference", "token_count": 946 }
365
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Events; using Object = UnityEngine.Object; namespace UnityEditor.Events { public static class UnityEventTools { public static void AddPersistentListener(UnityEventBase unityEvent) { unityEvent.AddPersistentListener(); } public static void RemovePersistentListener(UnityEventBase unityEvent, int index) { unityEvent.RemovePersistentListener(index); } // Add functions public static void AddPersistentListener(UnityEvent unityEvent, UnityAction call) { unityEvent.AddPersistentListener(call); } public static void AddPersistentListener<T0>(UnityEvent<T0> unityEvent, UnityAction<T0> call) { unityEvent.AddPersistentListener(call); } public static void AddPersistentListener<T0, T1>(UnityEvent<T0, T1> unityEvent, UnityAction<T0, T1> call) { unityEvent.AddPersistentListener(call); } public static void AddPersistentListener<T0, T1, T2>(UnityEvent<T0, T1, T2> unityEvent, UnityAction<T0, T1, T2> call) { unityEvent.AddPersistentListener(call); } public static void AddPersistentListener<T0, T1, T2, T3>(UnityEvent<T0, T1, T2, T3> unityEvent, UnityAction<T0, T1, T2, T3> call) { unityEvent.AddPersistentListener(call); } // register functions public static void RegisterPersistentListener(UnityEvent unityEvent, int index, UnityAction call) { unityEvent.RegisterPersistentListener(index, call); } public static void RegisterPersistentListener<T0>(UnityEvent<T0> unityEvent, int index, UnityAction<T0> call) { unityEvent.RegisterPersistentListener(index, call); } public static void RegisterPersistentListener<T0, T1>(UnityEvent<T0, T1> unityEvent, int index, UnityAction<T0, T1> call) { unityEvent.RegisterPersistentListener(index, call); } public static void RegisterPersistentListener<T0, T1, T2>(UnityEvent<T0, T1, T2> unityEvent, int index, UnityAction<T0, T1, T2> call) { unityEvent.RegisterPersistentListener(index, call); } public static void RegisterPersistentListener<T0, T1, T2, T3>(UnityEvent<T0, T1, T2, T3> unityEvent, int index, UnityAction<T0, T1, T2, T3> call) { unityEvent.RegisterPersistentListener(index, call); } // Removal functions public static void RemovePersistentListener(UnityEventBase unityEvent, UnityAction call) { unityEvent.RemovePersistentListener(call.Target as Object, call.Method); } public static void RemovePersistentListener<T0>(UnityEventBase unityEvent, UnityAction<T0> call) { unityEvent.RemovePersistentListener(call.Target as Object, call.Method); } public static void RemovePersistentListener<T0, T1>(UnityEventBase unityEvent, UnityAction<T0, T1> call) { unityEvent.RemovePersistentListener(call.Target as Object, call.Method); } public static void RemovePersistentListener<T0, T1, T2>(UnityEventBase unityEvent, UnityAction<T0, T1, T2> call) { unityEvent.RemovePersistentListener(call.Target as Object, call.Method); } public static void RemovePersistentListener<T0, T1, T2, T3>(UnityEventBase unityEvent, UnityAction<T0, T1, T2, T3> call) { unityEvent.RemovePersistentListener(call.Target as Object, call.Method); } public static void UnregisterPersistentListener(UnityEventBase unityEvent, int index) { unityEvent.UnregisterPersistentListener(index); } // void public static void AddVoidPersistentListener(UnityEventBase unityEvent, UnityAction call) { unityEvent.AddVoidPersistentListener(call); } public static void RegisterVoidPersistentListener(UnityEventBase unityEvent, int index, UnityAction call) { unityEvent.RegisterVoidPersistentListener(index, call); } // int public static void AddIntPersistentListener(UnityEventBase unityEvent, UnityAction<int> call, int argument) { unityEvent.AddIntPersistentListener(call, argument); } public static void RegisterIntPersistentListener(UnityEventBase unityEvent, int index, UnityAction<int> call, int argument) { unityEvent.RegisterIntPersistentListener(index, call, argument); } // float public static void AddFloatPersistentListener(UnityEventBase unityEvent, UnityAction<float> call, float argument) { unityEvent.AddFloatPersistentListener(call, argument); } public static void RegisterFloatPersistentListener(UnityEventBase unityEvent, int index, UnityAction<float> call, float argument) { unityEvent.RegisterFloatPersistentListener(index, call, argument); } // bool public static void AddBoolPersistentListener(UnityEventBase unityEvent, UnityAction<bool> call, bool argument) { unityEvent.AddBoolPersistentListener(call, argument); } public static void RegisterBoolPersistentListener(UnityEventBase unityEvent, int index, UnityAction<bool> call, bool argument) { unityEvent.RegisterBoolPersistentListener(index, call, argument); } // string public static void AddStringPersistentListener(UnityEventBase unityEvent, UnityAction<string> call, string argument) { unityEvent.AddStringPersistentListener(call, argument); } public static void RegisterStringPersistentListener(UnityEventBase unityEvent, int index, UnityAction<string> call, string argument) { unityEvent.RegisterStringPersistentListener(index, call, argument); } // object public static void AddObjectPersistentListener<T>(UnityEventBase unityEvent, UnityAction<T> call, T argument) where T : Object { unityEvent.AddObjectPersistentListener(call, argument); } public static void RegisterObjectPersistentListener<T>(UnityEventBase unityEvent, int index, UnityAction<T> call, T argument) where T : Object { unityEvent.RegisterObjectPersistentListener(index, call, argument); } } }
UnityCsReference/Editor/Mono/Utils/UnityEventTools.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/UnityEventTools.cs", "repo_id": "UnityCsReference", "token_count": 2629 }
366
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.VersionControl { public class VersionControlDescriptor { public string name { get; } public string displayName { get; } internal Type type { get; } internal VersionControlDescriptor(string name, string displayName, Type type) { this.name = name; this.displayName = displayName; this.type = type; } } }
UnityCsReference/Editor/Mono/VersionControl/Common/VersionControlDescriptor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/Common/VersionControlDescriptor.cs", "repo_id": "UnityCsReference", "token_count": 228 }
367
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; using UnityEngine.Scripting; using System.Runtime.InteropServices; namespace UnityEditor.VersionControl { //*undocumented* [NativeHeader("Editor/Src/VersionControl/VCChangeSet.h")] [NativeHeader("Editor/Src/VersionControl/VC_bindings.h")] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] partial class ChangeSet { // The bindings generator will set the instance pointer in this field IntPtr m_Self; [FreeFunction("VersionControlBindings::ChangeSet::Create", IsThreadSafe = true)] static extern IntPtr Create(); [FreeFunction("VersionControlBindings::ChangeSet::CreateFromCopy", IsThreadSafe = true)] static extern IntPtr CreateFromCopy(ChangeSet other); [FreeFunction("VersionControlBindings::ChangeSet::CreateFromString", IsThreadSafe = true)] static extern IntPtr CreateFromString(string description); [FreeFunction("VersionControlBindings::ChangeSet::CreateFromStringString", IsThreadSafe = true)] static extern IntPtr CreateFromStringString(string description, string changeSetID); [FreeFunction("VersionControlBindings::ChangeSet::Destroy", IsThreadSafe = true)] static extern void Destroy(IntPtr changeSet); void InternalCreate() { m_Self = Create(); } void InternalCopyConstruct(ChangeSet other) { m_Self = CreateFromCopy(other); } void InternalCreateFromString(string description) { m_Self = CreateFromString(description); } void InternalCreateFromStringString(string description, string changeSetID) { m_Self = CreateFromStringString(description, changeSetID); } //*undocumented public void Dispose() { Destroy(m_Self); m_Self = IntPtr.Zero; } [NativeMethod(IsThreadSafe = true)] public extern string description { get; } [NativeMethod(IsThreadSafe = true)] public extern string id { [NativeName("GetID")] get; } internal static class BindingsMarshaller { public static IntPtr ConvertToNative(ChangeSet changeSet) => changeSet.m_Self; } } }
UnityCsReference/Editor/Mono/VersionControl/VCChangeSet.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/VCChangeSet.bindings.cs", "repo_id": "UnityCsReference", "token_count": 965 }
368
// // File autogenerated from Include/C/Baselib_SystemFutex.h // using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using size_t = System.UIntPtr; namespace Unity.Baselib.LowLevel { [NativeHeader("baselib/CSharp/BindingsUnity/Baselib_SystemFutex.gen.binding.h")] internal static unsafe partial class Binding { /// <summary>Determines if the platform has access to a kernel level futex api</summary> /// <remarks> /// If native support is not present the futex will fallback to an emulated futex setup. /// /// Notes on the emulation: /// * It uses a single synchronization primitive to multiplex all potential addresses. This means there will be /// additional contention as well as spurious wakeups compared to a native implementation. /// * While the fallback implementation is not something that should be used in production it can still provide value /// when bringing up new platforms or to test features built on top of the futex api. /// </remarks> [FreeFunction(IsThreadSafe = true)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool Baselib_SystemFutex_NativeSupport(); /// <summary>Wait for notification.</summary> /// <remarks> /// Address will be checked atomically against expected before entering wait. This can be used to guarantee there are no lost wakeups. /// Note: When notified the thread always wake up regardless if the expectation match the value at address or not. /// /// | Problem this solves /// | Thread 1: checks condition and determine we should enter wait /// | Thread 2: change condition and notify waiting threads /// | Thread 1: enters waiting state /// | /// | With a futex the two Thread 1 operations become a single op. /// /// Spurious Wakeup - This function is subject to spurious wakeups. /// </remarks> /// <param name="address">Any address that can be read from both user and kernel space.</param> /// <param name="expected">What address points to will be checked against this value. If the values don't match thread will not enter a waiting state.</param> /// <param name="timeoutInMilliseconds">A timeout indicating to the kernel when to wake the thread. Regardless of being notified or not.</param> [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_SystemFutex_Wait(IntPtr address, Int32 expected, UInt32 timeoutInMilliseconds); /// <summary>Notify threads waiting on a specific address.</summary> /// <param name="address">Any address that can be read from both user and kernel space</param> /// <param name="count">Number of waiting threads to wakeup.</param> /// <param name="wakeupFallbackStrategy">Platforms that don't support waking up a specific number of threads will use this strategy.</param> [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_SystemFutex_Notify(IntPtr address, UInt32 count, Baselib_WakeupFallbackStrategy wakeupFallbackStrategy); } }
UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_SystemFutex.gen.binding.cs/0
{ "file_path": "UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_SystemFutex.gen.binding.cs", "repo_id": "UnityCsReference", "token_count": 1022 }
369
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.AI { // Keep this enum in sync with the one defined in "NavMeshBindingTypes.h" [MovedFrom("UnityEngine")] public enum NavMeshObstacleShape { // Capsule shaped obstacle. Capsule = 0, // Box shaped obstacle. Box = 1, } // Navigation mesh obstacle. [MovedFrom("UnityEngine")] [NativeHeader("Modules/AI/Components/NavMeshObstacle.bindings.h")] [HelpURL("https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/NavMeshObstacle.html")] public sealed class NavMeshObstacle : Behaviour { // Obstacle height. public extern float height { get; set; } // Obstacle radius. public extern float radius { get; set; } // Obstacle velocity. public extern Vector3 velocity { get; set; } // Enable carving public extern bool carving { get; set; } // When carving enabled, carve only when obstacle is stationary, moving obstacles are avoided dynamically. public extern bool carveOnlyStationary { get; set; } // Update carving if moved at least this distance, or if carveWhenStationary if moved at least this distance, the obstacle is considered moving. [NativeProperty("MoveThreshold")] public extern float carvingMoveThreshold { get; set; } // If carveWhenStationary is set, the obstacle is considered stationary if it has not moved during this long period. [NativeProperty("TimeToStationary")] public extern float carvingTimeToStationary { get; set; } // Shape of the obstacle, NavMeshObstacleShape.Box or NavMeshObstacleShape.Capsule. public extern NavMeshObstacleShape shape { get; set; } public extern Vector3 center { get; set; } public extern Vector3 size { [FreeFunction("NavMeshObstacleScriptBindings::GetSize", HasExplicitThis = true)] get; [FreeFunction("NavMeshObstacleScriptBindings::SetSize", HasExplicitThis = true)] set; } [FreeFunction("NavMeshObstacleScriptBindings::FitExtents", HasExplicitThis = true)] internal extern void FitExtents(); } }
UnityCsReference/Modules/AI/Components/NavMeshObstacle.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AI/Components/NavMeshObstacle.bindings.cs", "repo_id": "UnityCsReference", "token_count": 889 }
370
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using UnityEngine.Bindings; using UnityEngine.Pool; using UnityEngine.Scripting; namespace UnityEngine.Accessibility { /// <summary> /// Requests and makes updates to the accessibility settings for each /// platform. /// </summary> [NativeHeader("Modules/Accessibility/Native/AccessibilityManager.h")] [VisibleToOtherModules("UnityEditor.AccessibilityModule")] internal static class AccessibilityManager { public struct NotificationContext { public AccessibilityNotification notification { get; set; } public bool isScreenReaderEnabled { get; set; } public string announcement { get; set; } public bool wasAnnouncementSuccessful { get; set; } public AccessibilityNode currentNode { get; set; } public AccessibilityNode nextNode { get; set; } public float fontScale { get; set; } public bool isBoldTextEnabled { get; set; } public bool isClosedCaptioningEnabled { get; set; } public AccessibilityNotificationContext nativeContext { get; set; } public NotificationContext(ref AccessibilityNotificationContext nativeNotification) { nativeContext = nativeNotification; notification = nativeNotification.notification; isScreenReaderEnabled = nativeNotification.isScreenReaderEnabled; announcement = nativeNotification.announcement; wasAnnouncementSuccessful = nativeNotification.wasAnnouncementSuccessful; AccessibilityNode node = null; AssistiveSupport.activeHierarchy?.TryGetNode(nativeNotification.currentNodeId, out node); currentNode = node; AssistiveSupport.activeHierarchy?.TryGetNode(nativeNotification.nextNodeId, out node); nextNode = node; fontScale = 1; isBoldTextEnabled = false; isClosedCaptioningEnabled = false; } } static Queue<NotificationContext> s_AsyncNotificationContexts = new(); /// <summary> /// Indicates whether our Accessibility support is implemented for the current platform. /// </summary> public static bool isSupportedPlatform => Application.platform is RuntimePlatform.Android or RuntimePlatform.IPhonePlayer; /// <summary> /// Event that is invoked on the main thread when the screen reader is /// enabled or disabled. /// </summary> public static event Action<bool> screenReaderStatusChanged; /// <summary> /// Event that is invoked on the main thread when the screen reader /// focus changes. /// </summary> public static event Action<AccessibilityNode> nodeFocusChanged; /// <summary> /// Indicates whether a screen reader is enabled. /// </summary> internal static extern bool IsScreenReaderEnabled(); /// <summary> /// Handles the request for sending an accessibility notification to the /// assistive technology. /// </summary> internal static extern void SendAccessibilityNotification(in AccessibilityNotificationContext context); /// <summary> /// Retrieves the current accessibility language that assistive technologies /// use for the application. /// </summary> internal static extern SystemLanguage GetApplicationAccessibilityLanguage(); /// <summary> /// Sets the accessibility language that assistive technologies use for /// the application. /// </summary> internal static extern void SetApplicationAccessibilityLanguage(SystemLanguage languageCode); [RequiredByNativeCode] [VisibleToOtherModules("UnityEditor.AccessibilityModule")] internal static void Internal_Initialize() { AssistiveSupport.Initialize(); } [RequiredByNativeCode] static void Internal_Update() { // Prevent lock if empty. if (s_AsyncNotificationContexts.Count == 0) return; NotificationContext[] contexts; lock (s_AsyncNotificationContexts) { if (s_AsyncNotificationContexts.Count == 0) return; contexts = s_AsyncNotificationContexts.ToArray(); s_AsyncNotificationContexts.Clear(); } using var amLock = GetExclusiveLock(); foreach (var context in contexts) { switch (context.notification) { case AccessibilityNotification.ScreenReaderStatusChanged: { screenReaderStatusChanged?.Invoke(context.isScreenReaderEnabled); break; } case AccessibilityNotification.ElementFocused: { context.currentNode.InvokeFocusChanged(true); nodeFocusChanged?.Invoke(context.currentNode); break; } case AccessibilityNotification.ElementUnfocused: { context.currentNode.InvokeFocusChanged(false); break; } case AccessibilityNotification.FontScaleChanged: { AccessibilitySettings.InvokeFontScaleChanged(context.fontScale); break; } case AccessibilityNotification.BoldTextStatusChanged: { AccessibilitySettings.InvokeBoldTextStatusChanged(context.isBoldTextEnabled); break; } case AccessibilityNotification.ClosedCaptioningStatusChanged: { AccessibilitySettings.InvokeClosedCaptionStatusChanged(context.isClosedCaptioningEnabled); break; } } } } [RequiredByNativeCode] static int[] Internal_GetRootNodeIds() { var service = AssistiveSupport.GetService<AccessibilityHierarchyService>(); var rootNodes = service?.GetRootNodes(); if (rootNodes == null || rootNodes.Count == 0) return null; using (ListPool<int>.Get(out var rootNodeIds)) { for (var i = 0; i < rootNodes.Count; i++) rootNodeIds.Add(rootNodes[i].id); if (rootNodeIds.Count == 0) return null; return rootNodeIds.ToArray(); } } // Returns a struct with information from the managed AccessibilityNode. [RequiredByNativeCode] internal static void Internal_GetNode(int id, ref AccessibilityNodeData nodeData) { var service = AssistiveSupport.GetService<AccessibilityHierarchyService>(); if (service == null) { nodeData.id = AccessibilityNodeManager.k_InvalidNodeId; return; } if (service.TryGetNode(id, out var node)) { node.GetNodeData(ref nodeData); } else { nodeData.id = AccessibilityNodeManager.k_InvalidNodeId; } } [RequiredByNativeCode] static int Internal_GetNodeIdAt(float x, float y) { var service = AssistiveSupport.GetService<AccessibilityHierarchyService>(); if (service == null) return AccessibilityNodeManager.k_InvalidNodeId; var rootNodes = service.GetRootNodes(); if (rootNodes.Count == 0) return AccessibilityNodeManager.k_InvalidNodeId; if (service.TryGetNodeAt(x, y, out var node)) { return node.id; } return AccessibilityNodeManager.k_InvalidNodeId; } [RequiredByNativeCode] static void Internal_OnAccessibilityNotificationReceived(ref AccessibilityNotificationContext context) { // Ignore the global notification and only rely on the per-node notification. if (context.notification == AccessibilityNotification.ElementFocused) return; QueueNotification(new NotificationContext(ref context)); } internal static void QueueNotification(NotificationContext notification) { lock (s_AsyncNotificationContexts) { s_AsyncNotificationContexts.Enqueue(notification); } } internal static IDisposable GetExclusiveLock() { return new ExclusiveLock(); } sealed class ExclusiveLock : IDisposable { bool m_Disposed; public ExclusiveLock() { Lock(); } ~ExclusiveLock() { InternalDispose(); } void InternalDispose() { if (!m_Disposed) { Unlock(); m_Disposed = true; } } public void Dispose() { InternalDispose(); GC.SuppressFinalize(this); } } [ThreadSafe] static extern void Lock(); [ThreadSafe] static extern void Unlock(); } }
UnityCsReference/Modules/Accessibility/Bindings/AccessibilityManager.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Accessibility/Bindings/AccessibilityManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 4622 }
371
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using Unity.Properties; using UnityEngine; using UnityEngine.Accessibility; namespace UnityEditor.Accessibility { /// <summary> /// A view model of an accessibility hierarchy /// </summary> internal class AccessibilityHierarchyViewModel { private AccessibilityHierarchy m_Hierarchy; /// <summary> /// The underlying accessibility hierarchy. /// </summary> public AccessibilityHierarchy accessibilityHierarchy { get => m_Hierarchy; set { if (m_Hierarchy == value) return; if (m_Hierarchy != null) { m_Hierarchy.changed -= OnHierarchyChanged; } m_Hierarchy = value; if (m_Hierarchy != null) { m_Hierarchy.changed += OnHierarchyChanged; } Reset(); } } /// <summary> /// The root node. /// </summary> public AccessibilityViewModelNode root { get; } /// <summary> /// Sent when the model is reset, causing a rebuild of the attached views. /// </summary> public event Action modelReset; /// <summary> /// Constructor. /// </summary> public AccessibilityHierarchyViewModel() { root = CreateRootNode(); } private void OnHierarchyChanged(AccessibilityHierarchy hierarchy) { Reset(); } /// <summary> /// Resets the model. /// </summary> public void Reset() { modelReset?.Invoke(); } /// <summary> /// Creates a model node from an accessibility node /// </summary> /// <param name="node">The accessibility node</param> /// <returns>The created model node</returns> public AccessibilityViewModelNode CreateNode(AccessibilityNode node) { return new AccessibilityViewModelNode(node, this); } /// <summary> /// Tries to get the model node with the specified node id. /// </summary> /// <param name="nodeId">The node id</param> /// <param name="modelNode">The node found</param> /// <returns>Returns true if a node is found with the specified id and false otherwise.</returns> public bool TryGetNode(int nodeId, out AccessibilityViewModelNode modelNode) { modelNode = default; if (m_Hierarchy == null) return false; if (m_Hierarchy.TryGetNode(nodeId, out var node)) { modelNode = CreateNode(node); return true; } return false; } private AccessibilityViewModelNode CreateRootNode() { return new AccessibilityViewModelNode(null, this, true); } } /// <summary> /// A view model node of an accessibility node. /// </summary> internal struct AccessibilityViewModelNode : IEquatable<AccessibilityViewModelNode> { const int k_RootNodeId = int.MaxValue; private AccessibilityHierarchyViewModel m_Model; private AccessibilityNode m_Node; internal bool m_Root; /// <summary> /// Indicates whether the model node is the root node of the model. /// </summary> [CreateProperty] public bool isRoot => m_Root; /// <summary> /// Indicates whether the model node is null. /// </summary> public bool isNull => m_Node == null && !isRoot; /// <summary> /// The id of the node. /// </summary> [CreateProperty] public int id => isRoot ? k_RootNodeId : (m_Node?.id ?? 0); /// <summary> /// The label of the node. /// </summary> [CreateProperty] public string label { get { if (isRoot) { if (m_Model.accessibilityHierarchy != null) return m_Model.accessibilityHierarchy == AssistiveSupport.activeHierarchy ? L10n.Tr("Active Hierarchy") : L10n.Tr("Inactive Hierarchy"); return L10n.Tr("No Active Hierarchy"); } return m_Node?.label; } } /// <summary> /// The value of the node. /// </summary> [CreateProperty] public string value => m_Node?.value; /// <summary> /// The hint of the node. /// </summary> [CreateProperty] public string hint => m_Node?.hint; /// <summary> /// Indicates whether the node is active. /// </summary> [CreateProperty] public bool isActive => m_Node?.isActive ?? false; /// <summary> /// The frame of the node. /// </summary> [CreateProperty] public Rect frame => m_Node?.frame ?? Rect.zero; /// <summary> /// The role of the node. /// </summary> [CreateProperty] public AccessibilityRole role => m_Node?.role ?? default; // Indicates whether the node allows direct interaction. [CreateProperty] public bool allowsDirectInteraction => m_Node?.allowsDirectInteraction ?? default; /// <summary> /// The state of the node. /// </summary> [CreateProperty] public AccessibilityState state => m_Node?.state ?? default; /// <summary> /// The number of child model nodes. /// </summary> [CreateProperty] public int childNodeCount => isRoot ? (m_Model.accessibilityHierarchy?.rootNodes.Count ?? 0) : m_Node?.children.Count ?? 0; /// <summary> /// The accessibility node. /// </summary> public AccessibilityNode accessibilityNode => m_Node; /// <summary> /// The child model node at the specified index. /// </summary> /// <param name="index">The index</param> /// <returns>The node at the index.</returns> public AccessibilityViewModelNode GetChildNode(int index) { return m_Model?.CreateNode(isRoot ? m_Model.accessibilityHierarchy.rootNodes[index] : m_Node.children[index]) ?? default; } /// <summary> /// Constructs a model node from an accessibility node, a view model and a value that indicates whether is the root node of the model. /// </summary> /// <param name="accessibilityNode">The accessibility node.</param> /// <param name="model">The parent view model.</param> /// <param name="isRootNode">Indicates whether the node is the root of the view model.</param> internal AccessibilityViewModelNode(AccessibilityNode accessibilityNode, AccessibilityHierarchyViewModel model, bool isRootNode = false) { m_Model = model; m_Node = accessibilityNode; m_Root = isRootNode; } public override string ToString() { return id.ToString(); } public bool Equals(AccessibilityViewModelNode other) { return Equals(m_Root, other.m_Root) && Equals(m_Model, other.m_Model) && Equals(m_Node, other.m_Node); } public override bool Equals(object obj) { return obj is AccessibilityViewModelNode other && Equals(other); } public override int GetHashCode() { return HashCode.Combine(m_Model, m_Node, m_Root); } public static bool operator ==(AccessibilityViewModelNode obj1, AccessibilityViewModelNode obj2) { return obj1.Equals(obj2); } public static bool operator !=(AccessibilityViewModelNode obj1, AccessibilityViewModelNode obj2) { return !(obj1 == obj2); } } }
UnityCsReference/Modules/AccessibilityEditor/Managed/AccessibilityHierarchyViewModel.cs/0
{ "file_path": "UnityCsReference/Modules/AccessibilityEditor/Managed/AccessibilityHierarchyViewModel.cs", "repo_id": "UnityCsReference", "token_count": 3642 }
372
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine.Android { public class PermissionCallbacks : AndroidJavaProxy { enum Result { Dismissed = 0, Granted = 1, Denied = 2, DeniedDontAskAgain = 3, } public event Action<string> PermissionGranted; public event Action<string> PermissionDenied; [Obsolete("Unreliable. Query ShouldShowRequestPermissionRationale and use PermissionDenied event.", false)] public event Action<string> PermissionDeniedAndDontAskAgain; public event Action<string> PermissionRequestDismissed; public PermissionCallbacks() : base("com.unity3d.player.IPermissionRequestCallbacks") {} // override Invoke so we don't pay for C# reflection public override IntPtr Invoke(string methodName, IntPtr javaArgs) { switch (methodName) { case nameof(onPermissionResult): onPermissionResult(javaArgs); return IntPtr.Zero; default: return base.Invoke(methodName, javaArgs); } } private void onPermissionResult(IntPtr javaArgs) { var names = AndroidJNISafe.GetObjectArrayElement(javaArgs, 0); var grantResults = AndroidJNISafe.FromIntArray(AndroidJNISafe.GetObjectArrayElement(javaArgs, 1)); for (int i = 0; i < grantResults.Length; ++i) { string permission = AndroidJNISafe.GetStringChars(AndroidJNISafe.GetObjectArrayElement(names, i)); switch ((Result)grantResults[i]) { case Result.Dismissed: if (PermissionRequestDismissed == null) goto case Result.Denied; PermissionRequestDismissed.Invoke(permission); break; case Result.Granted: PermissionGranted?.Invoke(permission); break; case Result.DeniedDontAskAgain: if (PermissionDeniedAndDontAskAgain == null) goto case Result.Denied; PermissionDeniedAndDontAskAgain.Invoke(permission); break; case Result.Denied: PermissionDenied?.Invoke(permission); break; } } } } public struct Permission { public const string Camera = "android.permission.CAMERA"; public const string Microphone = "android.permission.RECORD_AUDIO"; public const string FineLocation = "android.permission.ACCESS_FINE_LOCATION"; public const string CoarseLocation = "android.permission.ACCESS_COARSE_LOCATION"; public const string ExternalStorageRead = "android.permission.READ_EXTERNAL_STORAGE"; public const string ExternalStorageWrite = "android.permission.WRITE_EXTERNAL_STORAGE"; private static AndroidJavaObject m_UnityPermissions; private static AndroidJavaObject GetUnityPermissions() { if (m_UnityPermissions != null) return m_UnityPermissions; m_UnityPermissions = new AndroidJavaClass("com.unity3d.player.UnityPermissions"); return m_UnityPermissions; } public static bool ShouldShowRequestPermissionRationale(string permission) { if (string.IsNullOrWhiteSpace(permission)) return false; return true; } public static bool HasUserAuthorizedPermission(string permission) { if (permission == null) return false; return true; } public static void RequestUserPermission(string permission) { if (permission == null) return; RequestUserPermissions(new[] { permission }, null); } public static void RequestUserPermissions(string[] permissions) { if (permissions == null || permissions.Length == 0) return; RequestUserPermissions(permissions, null); } public static void RequestUserPermission(string permission, PermissionCallbacks callbacks) { if (permission == null) return; RequestUserPermissions(new[] { permission }, callbacks); } public static void RequestUserPermissions(string[] permissions, PermissionCallbacks callbacks) { if (permissions == null || permissions.Length == 0) return; } } }
UnityCsReference/Modules/AndroidJNI/AndroidPermissions.cs/0
{ "file_path": "UnityCsReference/Modules/AndroidJNI/AndroidPermissions.cs", "repo_id": "UnityCsReference", "token_count": 2301 }
373
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; using uei = UnityEngine.Internal; using Unity.Collections.LowLevel.Unsafe; namespace UnityEngine { // Used by Animation.Play function. public enum PlayMode { // Will stop all animations that were started in the same layer. This is the default when playing animations. StopSameLayer = 0, // Will stop all animations that were started with this component before playing StopAll = 4, } // Used by Animation.Play function. public enum QueueMode { // Will start playing after all other animations have stopped playing CompleteOthers = 0, // Starts playing immediately. This can be used if you just want to quickly create a duplicate animation. PlayNow = 2 } // Used by Animation.Play function. public enum AnimationBlendMode { // Animations will be blended Blend = 0, // Animations will be added Additive = 1 } // considered deprecated public enum AnimationPlayMode { Stop = 0, Queue = 1, Mix = 2 } // This enum controlls culling of Animation component. public enum AnimationCullingType { // Animation culling is disabled - object is animated even when offscreen. AlwaysAnimate = 0, // Animation is disabled when renderers are not visible. BasedOnRenderers = 1, // Animation is disabled when localBounds are not visible. [System.Obsolete("Enum member AnimatorCullingMode.BasedOnClipBounds has been deprecated. Use AnimationCullingType.AlwaysAnimate or AnimationCullingType.BasedOnRenderers instead")] BasedOnClipBounds = 2, // Animation is disabled when localBounds are not visible. [System.Obsolete("Enum member AnimatorCullingMode.BasedOnUserBounds has been deprecated. Use AnimationCullingType.AlwaysAnimate or AnimationCullingType.BasedOnRenderers instead")] BasedOnUserBounds = 3 } public enum AnimationUpdateMode { Normal = 0, Fixed = 1 } internal enum AnimationEventSource { NoSource = 0, Legacy = 1, Animator = 2, } // The animation component is used to play back animations. [NativeHeader("Modules/Animation/Animation.h")] public sealed class Animation : Behaviour, IEnumerable { public extern AnimationClip clip { get; set; } public extern bool playAutomatically { get; set; } public extern WrapMode wrapMode { get; set; } public extern void Stop(); public void Stop(string name) { StopNamed(name); } [NativeName("Stop")] private extern void StopNamed(string name); public extern void Rewind(); public void Rewind(string name) { RewindNamed(name); } [NativeName("Rewind")] private extern void RewindNamed(string name); public extern void Sample(); public extern bool isPlaying { [NativeName("IsPlaying")] get; } public extern bool IsPlaying(string name); public AnimationState this[string name] { get { return GetState(name); } } [uei.ExcludeFromDocs] public bool Play() { return Play(PlayMode.StopSameLayer); } public bool Play([uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode) { return PlayDefaultAnimation(mode); } [NativeName("Play")] extern private bool PlayDefaultAnimation(PlayMode mode); [uei.ExcludeFromDocs] public bool Play(string animation) { return Play(animation, PlayMode.StopSameLayer); } extern public bool Play(string animation, [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); [uei.ExcludeFromDocs] public void CrossFade(string animation) { CrossFade(animation, 0.3f); } [uei.ExcludeFromDocs] public void CrossFade(string animation, float fadeLength) { CrossFade(animation, fadeLength, PlayMode.StopSameLayer); } extern public void CrossFade(string animation, [uei.DefaultValue("0.3F")] float fadeLength, [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); [uei.ExcludeFromDocs] public void Blend(string animation) { Blend(animation, 1.0f); } [uei.ExcludeFromDocs] public void Blend(string animation, float targetWeight) { Blend(animation, targetWeight, 0.3f); } extern public void Blend(string animation, [uei.DefaultValue("1.0F")] float targetWeight, [uei.DefaultValue("0.3F")] float fadeLength); [uei.ExcludeFromDocs] public AnimationState CrossFadeQueued(string animation) { return CrossFadeQueued(animation, 0.3F); } [uei.ExcludeFromDocs] public AnimationState CrossFadeQueued(string animation, float fadeLength) { return CrossFadeQueued(animation, fadeLength, QueueMode.CompleteOthers); } [uei.ExcludeFromDocs] public AnimationState CrossFadeQueued(string animation, float fadeLength, QueueMode queue) { return CrossFadeQueued(animation, fadeLength, queue, PlayMode.StopSameLayer); } [FreeFunction("AnimationBindings::CrossFadeQueuedImpl", HasExplicitThis = true)] [return: Unmarshalled] extern public AnimationState CrossFadeQueued(string animation, [uei.DefaultValue("0.3F")] float fadeLength, [uei.DefaultValue("QueueMode.CompleteOthers")] QueueMode queue, [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); [uei.ExcludeFromDocs] public AnimationState PlayQueued(string animation) { return PlayQueued(animation, QueueMode.CompleteOthers); } [uei.ExcludeFromDocs] public AnimationState PlayQueued(string animation, QueueMode queue) { return PlayQueued(animation, queue, PlayMode.StopSameLayer); } [FreeFunction("AnimationBindings::PlayQueuedImpl", HasExplicitThis = true)] [return: Unmarshalled] extern public AnimationState PlayQueued(string animation, [uei.DefaultValue("QueueMode.CompleteOthers")] QueueMode queue, [uei.DefaultValue("PlayMode.StopSameLayer")] PlayMode mode); public void AddClip(AnimationClip clip, string newName) { AddClip(clip, newName, Int32.MinValue, Int32.MaxValue); } [uei.ExcludeFromDocs] public void AddClip(AnimationClip clip, string newName, int firstFrame, int lastFrame) { AddClip(clip, newName, firstFrame, lastFrame, false); } extern public void AddClip([NotNull] AnimationClip clip, string newName, int firstFrame, int lastFrame, [uei.DefaultValue("false")] bool addLoopFrame); extern public void RemoveClip([NotNull] AnimationClip clip); public void RemoveClip(string clipName) { RemoveClipNamed(clipName); } [NativeName("RemoveClip")] extern private void RemoveClipNamed(string clipName); extern public int GetClipCount(); [System.Obsolete("use PlayMode instead of AnimationPlayMode.")] public bool Play(AnimationPlayMode mode) { return PlayDefaultAnimation((PlayMode)mode); } [System.Obsolete("use PlayMode instead of AnimationPlayMode.")] public bool Play(string animation, AnimationPlayMode mode) { return Play(animation, (PlayMode)mode); } extern public void SyncLayer(int layer); public IEnumerator GetEnumerator() { return new Animation.Enumerator(this); } private sealed partial class Enumerator : IEnumerator { Animation m_Outer; int m_CurrentIndex = -1; internal Enumerator(Animation outer) { m_Outer = outer; } public object Current { get { return m_Outer.GetStateAtIndex(m_CurrentIndex); } } public bool MoveNext() { int childCount = m_Outer.GetStateCount(); m_CurrentIndex++; return m_CurrentIndex < childCount; } public void Reset() { m_CurrentIndex = -1; } } [FreeFunction("AnimationBindings::GetState", HasExplicitThis = true)] [return: Unmarshalled] extern internal AnimationState GetState(string name); [FreeFunction("AnimationBindings::GetStateAtIndex", HasExplicitThis = true, ThrowsException = true)] [return: Unmarshalled] extern internal AnimationState GetStateAtIndex(int index); [NativeName("GetAnimationStateCount")] extern internal int GetStateCount(); public AnimationClip GetClip(string name) { AnimationState state = GetState(name); if (state) return state.clip; else return null; } extern public bool animatePhysics { get; set; } extern public AnimationUpdateMode updateMode { get; set; } [System.Obsolete("Use cullingType instead")] public extern bool animateOnlyIfVisible { [FreeFunction("AnimationBindings::GetAnimateOnlyIfVisible", HasExplicitThis = true)] get; [FreeFunction("AnimationBindings::SetAnimateOnlyIfVisible", HasExplicitThis = true)] set; } extern public AnimationCullingType cullingType { get; set; } extern public Bounds localBounds { [NativeName("GetLocalAABB")] get; [NativeName("SetLocalAABB")] set; } } [NativeHeader("Modules/Animation/AnimationState.h")] [UsedByNativeCode] public sealed class AnimationState : TrackedReference { extern public bool enabled { get; set; } extern public float weight { get; set; } extern public WrapMode wrapMode { get; set; } extern public float time { get; set; } extern public float normalizedTime { get; set; } extern public float speed { get; set; } extern public float normalizedSpeed { get; set; } extern public float length { get; } extern public int layer { get; set; } extern public AnimationClip clip { get; } extern public string name { get; set; } extern public AnimationBlendMode blendMode { get; set; } [uei.ExcludeFromDocs] public void AddMixingTransform(Transform mix) { AddMixingTransform(mix, true); } extern public void AddMixingTransform([NotNull] Transform mix, [uei.DefaultValue("true")] bool recursive); extern public void RemoveMixingTransform([NotNull] Transform mix); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(AnimationState animationState) => animationState.m_Ptr; } } [System.Serializable] [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] internal struct AnimationEventBlittable : IDisposable { internal float m_Time; internal IntPtr m_FunctionName; internal IntPtr m_StringParameter; internal IntPtr m_ObjectReferenceParameter; internal float m_FloatParameter; internal int m_IntParameter; internal int m_MessageOptions; internal AnimationEventSource m_Source; internal IntPtr m_StateSender; internal AnimatorStateInfo m_AnimatorStateInfo; internal AnimatorClipInfo m_AnimatorClipInfo; internal static AnimationEventBlittable FromAnimationEvent(AnimationEvent animationEvent) { if (s_handlePool == null) s_handlePool = new GCHandlePool(); var handlePool = s_handlePool; var animationEventBlittable = new AnimationEventBlittable { m_Time = animationEvent.m_Time, m_FunctionName = handlePool.AllocHandleIfNotNull(animationEvent.m_FunctionName), m_StringParameter = handlePool.AllocHandleIfNotNull(animationEvent.m_StringParameter), m_ObjectReferenceParameter = handlePool.AllocHandleIfNotNull(animationEvent.m_ObjectReferenceParameter), m_FloatParameter = animationEvent.m_FloatParameter, m_IntParameter = animationEvent.m_IntParameter, m_MessageOptions = animationEvent.m_MessageOptions, m_Source = animationEvent.m_Source, m_StateSender = handlePool.AllocHandleIfNotNull(animationEvent.m_StateSender), m_AnimatorStateInfo = animationEvent.m_AnimatorStateInfo, m_AnimatorClipInfo = animationEvent.m_AnimatorClipInfo }; return animationEventBlittable; } internal unsafe static void FromAnimationEvents(AnimationEvent[] animationEvents, AnimationEventBlittable* animationEventBlittables) { if (s_handlePool == null) s_handlePool = new GCHandlePool(); var handlePool = s_handlePool; var animationEventBlittable = animationEventBlittables; for (var i = 0; i < animationEvents.Length; ++i) { var animationEvent = animationEvents[i]; animationEventBlittable->m_Time = animationEvent.m_Time; animationEventBlittable->m_FunctionName = handlePool.AllocHandleIfNotNull(animationEvent.m_FunctionName); animationEventBlittable->m_StringParameter = handlePool.AllocHandleIfNotNull(animationEvent.m_StringParameter); animationEventBlittable->m_ObjectReferenceParameter = handlePool.AllocHandleIfNotNull(animationEvent.m_ObjectReferenceParameter); animationEventBlittable->m_FloatParameter = animationEvent.m_FloatParameter; animationEventBlittable->m_IntParameter = animationEvent.m_IntParameter; animationEventBlittable->m_MessageOptions = animationEvent.m_MessageOptions; animationEventBlittable->m_Source = animationEvent.m_Source; animationEventBlittable->m_StateSender = handlePool.AllocHandleIfNotNull(animationEvent.m_StateSender); animationEventBlittable->m_AnimatorStateInfo = animationEvent.m_AnimatorStateInfo; animationEventBlittable->m_AnimatorClipInfo = animationEvent.m_AnimatorClipInfo; animationEventBlittable++; } } [RequiredByNativeCode] internal unsafe static AnimationEvent PointerToAnimationEvent(IntPtr animationEventBlittable) { return ToAnimationEvent(*(AnimationEventBlittable*)animationEventBlittable); } internal unsafe static AnimationEvent[] PointerToAnimationEvents(IntPtr animationEventBlittableArray, int size) { var animationEvents = new AnimationEvent[size]; var animationEventsBlittable = (AnimationEventBlittable*)animationEventBlittableArray; for (int i = 0; i < size; i++) { animationEvents[i] = PointerToAnimationEvent((IntPtr)(animationEventsBlittable + i)); } return animationEvents; } internal unsafe static void DisposeEvents(IntPtr animationEventBlittableArray, int size) { var animationEventsBlittable = (AnimationEventBlittable*)animationEventBlittableArray; for (int i = 0; i < size; i++) { animationEventsBlittable[i].Dispose(); } FreeEventsInternal(animationEventBlittableArray); } [FreeFunction(Name = "AnimationClipBindings::FreeEventsInternal")] extern static private void FreeEventsInternal(IntPtr value); [ThreadStatic] static GCHandlePool s_handlePool; internal static AnimationEvent ToAnimationEvent(AnimationEventBlittable animationEventBlittable) { var animationEvent = new AnimationEvent(); animationEvent.m_Time = animationEventBlittable.m_Time; if (animationEventBlittable.m_FunctionName != IntPtr.Zero) animationEvent.m_FunctionName = (string)UnsafeUtility.As<IntPtr, GCHandle>(ref animationEventBlittable.m_FunctionName).Target; if (animationEventBlittable.m_StringParameter != IntPtr.Zero) animationEvent.m_StringParameter = (string)UnsafeUtility.As<IntPtr, GCHandle>(ref animationEventBlittable.m_StringParameter).Target; if (animationEventBlittable.m_ObjectReferenceParameter != IntPtr.Zero) animationEvent.m_ObjectReferenceParameter = (Object)UnsafeUtility.As<IntPtr, GCHandle>(ref animationEventBlittable.m_ObjectReferenceParameter).Target; animationEvent.m_FloatParameter = animationEventBlittable.m_FloatParameter; animationEvent.m_IntParameter = animationEventBlittable.m_IntParameter; animationEvent.m_MessageOptions = animationEventBlittable.m_MessageOptions; animationEvent.m_Source = animationEventBlittable.m_Source; if (animationEventBlittable.m_StateSender != IntPtr.Zero) animationEvent.m_StateSender = (AnimationState)UnsafeUtility.As<IntPtr, GCHandle>(ref animationEventBlittable.m_StateSender).Target; animationEvent.m_AnimatorStateInfo = animationEventBlittable.m_AnimatorStateInfo; animationEvent.m_AnimatorClipInfo = animationEventBlittable.m_AnimatorClipInfo; return animationEvent; } public void Dispose() { if (s_handlePool == null) s_handlePool = new GCHandlePool(); var handlePool = s_handlePool; if (m_FunctionName != IntPtr.Zero) handlePool.Free(UnsafeUtility.As<IntPtr, GCHandle>(ref m_FunctionName)); if (m_StringParameter != IntPtr.Zero) handlePool.Free(UnsafeUtility.As<IntPtr, GCHandle>(ref m_StringParameter)); if (m_ObjectReferenceParameter != IntPtr.Zero) handlePool.Free(UnsafeUtility.As<IntPtr, GCHandle>(ref m_ObjectReferenceParameter)); if (m_StateSender != IntPtr.Zero) handlePool.Free(UnsafeUtility.As<IntPtr, GCHandle>(ref m_StateSender)); } } [System.Serializable] [RequiredByNativeCode] public sealed class AnimationEvent { internal float m_Time; internal string m_FunctionName; internal string m_StringParameter; internal Object m_ObjectReferenceParameter; internal float m_FloatParameter; internal int m_IntParameter; internal int m_MessageOptions; internal AnimationEventSource m_Source; internal AnimationState m_StateSender; internal AnimatorStateInfo m_AnimatorStateInfo; internal AnimatorClipInfo m_AnimatorClipInfo; public AnimationEvent() { m_Time = 0.0f; m_FunctionName = ""; m_StringParameter = ""; m_ObjectReferenceParameter = null; m_FloatParameter = 0.0f; m_IntParameter = 0; m_MessageOptions = 0; m_Source = AnimationEventSource.NoSource; m_StateSender = null; } [System.Obsolete("Use stringParameter instead")] public string data { get { return m_StringParameter; } set { m_StringParameter = value; } } public string stringParameter { get { return m_StringParameter; } set { m_StringParameter = value; } } public float floatParameter { get { return m_FloatParameter; } set { m_FloatParameter = value; } } public int intParameter { get { return m_IntParameter; } set { m_IntParameter = value; } } public Object objectReferenceParameter { get { return m_ObjectReferenceParameter; } set { m_ObjectReferenceParameter = value; } } public string functionName { get { return m_FunctionName; } set { m_FunctionName = value; } } public float time { get { return m_Time; } set { m_Time = value; } } public SendMessageOptions messageOptions { get { return (SendMessageOptions)m_MessageOptions; } set { m_MessageOptions = (int)value; } } public bool isFiredByLegacy { get { return m_Source == AnimationEventSource.Legacy; } } public bool isFiredByAnimator { get { return m_Source == AnimationEventSource.Animator; } } public AnimationState animationState { get { if (!isFiredByLegacy) Debug.LogError("AnimationEvent was not fired by Animation component, you shouldn't use AnimationEvent.animationState"); return m_StateSender; } } public AnimatorStateInfo animatorStateInfo { get { if (!isFiredByAnimator) Debug.LogError("AnimationEvent was not fired by Animator component, you shouldn't use AnimationEvent.animatorStateInfo"); return m_AnimatorStateInfo; } } public AnimatorClipInfo animatorClipInfo { get { if (!isFiredByAnimator) Debug.LogError("AnimationEvent was not fired by Animator component, you shouldn't use AnimationEvent.animatorClipInfo"); return m_AnimatorClipInfo; } } internal int GetHash() { unchecked { int hash = 0; hash = functionName.GetHashCode(); hash = 33 * hash + time.GetHashCode(); return hash; } } } }
UnityCsReference/Modules/Animation/ScriptBindings/Animation.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/Animation.bindings.cs", "repo_id": "UnityCsReference", "token_count": 8394 }
374
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.Animations { // This enum is mapped to UnityEngine::Animation::BindType internal enum BindType { Unbound = 0, // UnityEngine::Animation::kUnbound Float = 5, // UnityEngine::Animation::kBindFloat Bool = 6, // UnityEngine::Animation::kBindFloatToBool GameObjectActive = 7, // UnityEngine::Animation::kBindGameObjectActive ObjectReference = 9, // UnityEngine::Animation::kBindScriptObjectReference; Int = 10, // UnityEngine::Animation::kBindFloatToInt DiscreetInt = 11, // UnityEngine::Animation::kBindDiscreteInt } [MovedFrom("UnityEngine.Experimental.Animations")] [NativeHeader("Modules/Animation/ScriptBindings/AnimationStreamHandles.bindings.h")] [NativeHeader("Modules/Animation/Director/AnimationStreamHandles.h")] [StructLayout(LayoutKind.Sequential)] public struct TransformStreamHandle { private UInt32 m_AnimatorBindingsVersion; private int handleIndex; private int skeletonIndex; public bool IsValid(AnimationStream stream) { return IsValidInternal(ref stream); } private bool IsValidInternal(ref AnimationStream stream) { return stream.isValid && createdByNative && hasHandleIndex; } private bool createdByNative { get { return animatorBindingsVersion != (UInt32)AnimatorBindingsVersion.kInvalidNotNative; } } private bool IsSameVersionAsStream(ref AnimationStream stream) { return animatorBindingsVersion == stream.animatorBindingsVersion; } private bool hasHandleIndex { get { return handleIndex != AnimationStream.InvalidIndex; } } private bool hasSkeletonIndex { get { return skeletonIndex != AnimationStream.InvalidIndex; } } // internal for EditorTests internal UInt32 animatorBindingsVersion { private set { m_AnimatorBindingsVersion = value; } get { return m_AnimatorBindingsVersion; } } public void Resolve(AnimationStream stream) { CheckIsValidAndResolve(ref stream); } public bool IsResolved(AnimationStream stream) { return IsResolvedInternal(ref stream); } private bool IsResolvedInternal(ref AnimationStream stream) { return IsValidInternal(ref stream) && IsSameVersionAsStream(ref stream) && hasSkeletonIndex; } private void CheckIsValidAndResolve(ref AnimationStream stream) { // Verify stream. stream.CheckIsValid(); if (IsResolvedInternal(ref stream)) return; // Handle create directly by user are never valid if (!createdByNative || !hasHandleIndex) throw new InvalidOperationException("The TransformStreamHandle is invalid. Please use proper function to create the handle."); if (!IsSameVersionAsStream(ref stream) || (hasHandleIndex && !hasSkeletonIndex)) { ResolveInternal(ref stream); } if (hasHandleIndex && !hasSkeletonIndex) throw new InvalidOperationException("The TransformStreamHandle cannot be resolved."); } public Vector3 GetPosition(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetPositionInternal(ref stream); } public void SetPosition(AnimationStream stream, Vector3 position) { CheckIsValidAndResolve(ref stream); SetPositionInternal(ref stream, position); } public Quaternion GetRotation(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetRotationInternal(ref stream); } public void SetRotation(AnimationStream stream, Quaternion rotation) { CheckIsValidAndResolve(ref stream); SetRotationInternal(ref stream, rotation); } public Vector3 GetLocalPosition(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetLocalPositionInternal(ref stream); } public void SetLocalPosition(AnimationStream stream, Vector3 position) { CheckIsValidAndResolve(ref stream); SetLocalPositionInternal(ref stream, position); } public Quaternion GetLocalRotation(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetLocalRotationInternal(ref stream); } public void SetLocalRotation(AnimationStream stream, Quaternion rotation) { CheckIsValidAndResolve(ref stream); SetLocalRotationInternal(ref stream, rotation); } public Vector3 GetLocalScale(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetLocalScaleInternal(ref stream); } public void SetLocalScale(AnimationStream stream, Vector3 scale) { CheckIsValidAndResolve(ref stream); SetLocalScaleInternal(ref stream, scale); } public Matrix4x4 GetLocalToParentMatrix(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetLocalToParentMatrixInternal(ref stream); } public bool GetPositionReadMask(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetPositionReadMaskInternal(ref stream); } public bool GetRotationReadMask(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetRotationReadMaskInternal(ref stream); } public bool GetScaleReadMask(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetScaleReadMaskInternal(ref stream); } public void GetLocalTRS(AnimationStream stream, out Vector3 position, out Quaternion rotation, out Vector3 scale) { CheckIsValidAndResolve(ref stream); GetLocalTRSInternal(ref stream, out position, out rotation, out scale); } public void SetLocalTRS(AnimationStream stream, Vector3 position, Quaternion rotation, Vector3 scale, bool useMask) { CheckIsValidAndResolve(ref stream); SetLocalTRSInternal(ref stream, position, rotation, scale, useMask); } public void GetGlobalTR(AnimationStream stream, out Vector3 position, out Quaternion rotation) { CheckIsValidAndResolve(ref stream); GetGlobalTRInternal(ref stream, out position, out rotation); } public Matrix4x4 GetLocalToWorldMatrix(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetLocalToWorldMatrixInternal(ref stream); } public void SetGlobalTR(AnimationStream stream, Vector3 position, Quaternion rotation, bool useMask) { CheckIsValidAndResolve(ref stream); SetGlobalTRInternal(ref stream, position, rotation, useMask); } [NativeMethod(Name = "Resolve", IsThreadSafe = true)] private extern void ResolveInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::GetPositionInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Vector3 GetPositionInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::SetPositionInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void SetPositionInternal(ref AnimationStream stream, Vector3 position); [NativeMethod(Name = "TransformStreamHandleBindings::GetRotationInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Quaternion GetRotationInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::SetRotationInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void SetRotationInternal(ref AnimationStream stream, Quaternion rotation); [NativeMethod(Name = "TransformStreamHandleBindings::GetLocalPositionInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Vector3 GetLocalPositionInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::SetLocalPositionInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void SetLocalPositionInternal(ref AnimationStream stream, Vector3 position); [NativeMethod(Name = "TransformStreamHandleBindings::GetLocalRotationInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Quaternion GetLocalRotationInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::SetLocalRotationInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void SetLocalRotationInternal(ref AnimationStream stream, Quaternion rotation); [NativeMethod(Name = "TransformStreamHandleBindings::GetLocalScaleInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Vector3 GetLocalScaleInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::SetLocalScaleInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void SetLocalScaleInternal(ref AnimationStream stream, Vector3 scale); [NativeMethod(Name = "TransformStreamHandleBindings::GetLocalToParentMatrixInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Matrix4x4 GetLocalToParentMatrixInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::GetPositionReadMaskInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern bool GetPositionReadMaskInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::GetRotationReadMaskInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern bool GetRotationReadMaskInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::GetScaleReadMaskInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern bool GetScaleReadMaskInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::GetLocalTRSInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void GetLocalTRSInternal(ref AnimationStream stream, out Vector3 position, out Quaternion rotation, out Vector3 scale); [NativeMethod(Name = "TransformStreamHandleBindings::SetLocalTRSInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void SetLocalTRSInternal(ref AnimationStream stream, Vector3 position, Quaternion rotation, Vector3 scale, bool useMask); [NativeMethod(Name = "TransformStreamHandleBindings::GetGlobalTRInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void GetGlobalTRInternal(ref AnimationStream stream, out Vector3 position, out Quaternion rotation); [NativeMethod(Name = "TransformStreamHandleBindings::GetLocalToWorldMatrixInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Matrix4x4 GetLocalToWorldMatrixInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformStreamHandleBindings::SetGlobalTRInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern void SetGlobalTRInternal(ref AnimationStream stream, Vector3 position, Quaternion rotation, bool useMask); } [MovedFrom("UnityEngine.Experimental.Animations")] [NativeHeader("Modules/Animation/Director/AnimationStreamHandles.h")] [StructLayout(LayoutKind.Sequential)] public struct PropertyStreamHandle { private UInt32 m_AnimatorBindingsVersion; private int handleIndex; private int valueArrayIndex; private int bindType; public bool IsValid(AnimationStream stream) { return IsValidInternal(ref stream); } private bool IsValidInternal(ref AnimationStream stream) { return stream.isValid && createdByNative && hasHandleIndex && hasBindType; } private bool createdByNative { get { return animatorBindingsVersion != (UInt32)AnimatorBindingsVersion.kInvalidNotNative; } } private bool IsSameVersionAsStream(ref AnimationStream stream) { return animatorBindingsVersion == stream.animatorBindingsVersion; } private bool hasHandleIndex { get { return handleIndex != AnimationStream.InvalidIndex; } } private bool hasValueArrayIndex { get { return valueArrayIndex != AnimationStream.InvalidIndex; } } private bool hasBindType { get { return bindType != (int)BindType.Unbound; } } // internal for EditorTests internal UInt32 animatorBindingsVersion { private set { m_AnimatorBindingsVersion = value; } get { return m_AnimatorBindingsVersion; } } public void Resolve(AnimationStream stream) { CheckIsValidAndResolve(ref stream); } public bool IsResolved(AnimationStream stream) { return IsResolvedInternal(ref stream); } private bool IsResolvedInternal(ref AnimationStream stream) { return IsValidInternal(ref stream) && IsSameVersionAsStream(ref stream) && hasValueArrayIndex; } private void CheckIsValidAndResolve(ref AnimationStream stream) { // Verify stream. stream.CheckIsValid(); if (IsResolvedInternal(ref stream)) return; // Handle create directly by user are never valid if (!createdByNative || !hasHandleIndex || !hasBindType) throw new InvalidOperationException("The PropertyStreamHandle is invalid. Please use proper function to create the handle."); if (!IsSameVersionAsStream(ref stream) || (hasHandleIndex && !hasValueArrayIndex)) { ResolveInternal(ref stream); } if (hasHandleIndex && !hasValueArrayIndex) throw new InvalidOperationException("The PropertyStreamHandle cannot be resolved."); } public float GetFloat(AnimationStream stream) { CheckIsValidAndResolve(ref stream); if (bindType != (int)BindType.Float) throw new InvalidOperationException("GetValue type doesn't match PropertyStreamHandle bound type."); return GetFloatInternal(ref stream); } public void SetFloat(AnimationStream stream, float value) { CheckIsValidAndResolve(ref stream); if (bindType != (int)BindType.Float) throw new InvalidOperationException("SetValue type doesn't match PropertyStreamHandle bound type."); SetFloatInternal(ref stream, value); } public int GetInt(AnimationStream stream) { CheckIsValidAndResolve(ref stream); if (bindType != (int)BindType.Int && bindType != (int)BindType.DiscreetInt && bindType != (int)BindType.ObjectReference) throw new InvalidOperationException("GetValue type doesn't match PropertyStreamHandle bound type."); return GetIntInternal(ref stream); } public void SetInt(AnimationStream stream, int value) { CheckIsValidAndResolve(ref stream); if (bindType != (int)BindType.Int && bindType != (int)BindType.DiscreetInt && bindType != (int)BindType.ObjectReference) throw new InvalidOperationException("SetValue type doesn't match PropertyStreamHandle bound type."); SetIntInternal(ref stream, value); } public bool GetBool(AnimationStream stream) { CheckIsValidAndResolve(ref stream); if (bindType != (int)BindType.Bool && bindType != (int)BindType.GameObjectActive) throw new InvalidOperationException("GetValue type doesn't match PropertyStreamHandle bound type."); return GetBoolInternal(ref stream); } public void SetBool(AnimationStream stream, bool value) { CheckIsValidAndResolve(ref stream); if (bindType != (int)BindType.Bool && bindType != (int)BindType.GameObjectActive) throw new InvalidOperationException("SetValue type doesn't match PropertyStreamHandle bound type."); SetBoolInternal(ref stream, value); } public bool GetReadMask(AnimationStream stream) { CheckIsValidAndResolve(ref stream); return GetReadMaskInternal(ref stream); } [NativeMethod(Name = "Resolve", IsThreadSafe = true)] private extern void ResolveInternal(ref AnimationStream stream); [NativeMethod(Name = "GetFloat", IsThreadSafe = true)] private extern float GetFloatInternal(ref AnimationStream stream); [NativeMethod(Name = "SetFloat", IsThreadSafe = true)] private extern void SetFloatInternal(ref AnimationStream stream, float value); [NativeMethod(Name = "GetInt", IsThreadSafe = true)] private extern int GetIntInternal(ref AnimationStream stream); [NativeMethod(Name = "SetInt", IsThreadSafe = true)] private extern void SetIntInternal(ref AnimationStream stream, int value); [NativeMethod(Name = "GetBool", IsThreadSafe = true)] private extern bool GetBoolInternal(ref AnimationStream stream); [NativeMethod(Name = "SetBool", IsThreadSafe = true)] private extern void SetBoolInternal(ref AnimationStream stream, bool value); [NativeMethod(Name = "GetReadMask", IsThreadSafe = true)] private extern bool GetReadMaskInternal(ref AnimationStream stream); } [MovedFrom("UnityEngine.Experimental.Animations")] [NativeHeader("Modules/Animation/ScriptBindings/AnimationStreamHandles.bindings.h")] [NativeHeader("Modules/Animation/Director/AnimationSceneHandles.h")] [StructLayout(LayoutKind.Sequential)] public struct TransformSceneHandle { private UInt32 valid; private int transformSceneHandleDefinitionIndex; public bool IsValid(AnimationStream stream) { // [case 1032369] Cannot call native code before validating that handle was created in native and has a valid handle index return stream.isValid && createdByNative && hasTransformSceneHandleDefinitionIndex && HasValidTransform(ref stream); } private bool createdByNative { get { return valid != 0; } } private bool hasTransformSceneHandleDefinitionIndex { get { return transformSceneHandleDefinitionIndex != AnimationStream.InvalidIndex; } } private void CheckIsValid(ref AnimationStream stream) { // Verify stream. stream.CheckIsValid(); // Handle create directly by user are never valid if (!createdByNative || !hasTransformSceneHandleDefinitionIndex) throw new InvalidOperationException("The TransformSceneHandle is invalid. Please use proper function to create the handle."); // [case 1032369] Cannot call native code before validating that handle was created in native and has a valid handle index if (!HasValidTransform(ref stream)) throw new NullReferenceException("The transform is invalid."); } public Vector3 GetPosition(AnimationStream stream) { CheckIsValid(ref stream); return GetPositionInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetPosition(AnimationStream stream, Vector3 position) {} public Vector3 GetLocalPosition(AnimationStream stream) { CheckIsValid(ref stream); return GetLocalPositionInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetLocalPosition(AnimationStream stream, Vector3 position) {} public Quaternion GetRotation(AnimationStream stream) { CheckIsValid(ref stream); return GetRotationInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetRotation(AnimationStream stream, Quaternion rotation) {} public Quaternion GetLocalRotation(AnimationStream stream) { CheckIsValid(ref stream); return GetLocalRotationInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetLocalRotation(AnimationStream stream, Quaternion rotation) {} public Vector3 GetLocalScale(AnimationStream stream) { CheckIsValid(ref stream); return GetLocalScaleInternal(ref stream); } public void GetLocalTRS(AnimationStream stream, out Vector3 position, out Quaternion rotation, out Vector3 scale) { CheckIsValid(ref stream); GetLocalTRSInternal(ref stream, out position, out rotation, out scale); } public Matrix4x4 GetLocalToParentMatrix(AnimationStream stream) { CheckIsValid(ref stream); return GetLocalToParentMatrixInternal(ref stream); } public void GetGlobalTR(AnimationStream stream, out Vector3 position, out Quaternion rotation) { CheckIsValid(ref stream); GetGlobalTRInternal(ref stream, out position, out rotation); } public Matrix4x4 GetLocalToWorldMatrix(AnimationStream stream) { CheckIsValid(ref stream); return GetLocalToWorldMatrixInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetLocalScale(AnimationStream stream, Vector3 scale) {} [ThreadSafe] private extern bool HasValidTransform(ref AnimationStream stream); [NativeMethod(Name = "TransformSceneHandleBindings::GetPositionInternal", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)] private extern Vector3 GetPositionInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformSceneHandleBindings::GetLocalPositionInternal", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)] private extern Vector3 GetLocalPositionInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformSceneHandleBindings::GetRotationInternal", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)] private extern Quaternion GetRotationInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformSceneHandleBindings::GetLocalRotationInternal", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)] private extern Quaternion GetLocalRotationInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformSceneHandleBindings::GetLocalScaleInternal", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)] private extern Vector3 GetLocalScaleInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformSceneHandleBindings::GetLocalTRSInternal", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)] private extern void GetLocalTRSInternal(ref AnimationStream stream, out Vector3 position, out Quaternion rotation, out Vector3 scale); [NativeMethod(Name = "TransformSceneHandleBindings::GetLocalToParentMatrixInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Matrix4x4 GetLocalToParentMatrixInternal(ref AnimationStream stream); [NativeMethod(Name = "TransformSceneHandleBindings::GetGlobalTRInternal", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)] private extern void GetGlobalTRInternal(ref AnimationStream stream, out Vector3 position, out Quaternion rotation); [NativeMethod(Name = "TransformSceneHandleBindings::GetLocalToWorldMatrixInternal", IsFreeFunction = true, HasExplicitThis = true, IsThreadSafe = true)] private extern Matrix4x4 GetLocalToWorldMatrixInternal(ref AnimationStream stream); } [MovedFrom("UnityEngine.Experimental.Animations")] [NativeHeader("Modules/Animation/Director/AnimationSceneHandles.h")] [StructLayout(LayoutKind.Sequential)] public struct PropertySceneHandle { private UInt32 valid; private int handleIndex; public bool IsValid(AnimationStream stream) { return IsValidInternal(ref stream); } private bool IsValidInternal(ref AnimationStream stream) { // [case 1032369] Cannot call native code before validating that handle was created in native and has a valid handle index return stream.isValid && createdByNative && hasHandleIndex && HasValidTransform(ref stream); } private bool createdByNative { get { return valid != 0; } } private bool hasHandleIndex { get { return handleIndex != AnimationStream.InvalidIndex; } } public void Resolve(AnimationStream stream) { CheckIsValid(ref stream); ResolveInternal(ref stream); } public bool IsResolved(AnimationStream stream) { return IsValidInternal(ref stream) && IsBound(ref stream); } private void CheckIsValid(ref AnimationStream stream) { // Verify stream. stream.CheckIsValid(); // Handle create directly by user are never valid if (!createdByNative || !hasHandleIndex) throw new InvalidOperationException("The PropertySceneHandle is invalid. Please use proper function to create the handle."); // [case 1032369] Cannot call native code before validating that handle was created in native and has a valid handle index if (!HasValidTransform(ref stream)) throw new NullReferenceException("The transform is invalid."); } public float GetFloat(AnimationStream stream) { CheckIsValid(ref stream); return GetFloatInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetFloat(AnimationStream stream, float value) {} public int GetInt(AnimationStream stream) { CheckIsValid(ref stream); return GetIntInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetInt(AnimationStream stream, int value) {} public bool GetBool(AnimationStream stream) { CheckIsValid(ref stream); return GetBoolInternal(ref stream); } [Obsolete("SceneHandle is now read-only; it was problematic with the engine multithreading and determinism", true)] public void SetBool(AnimationStream stream, bool value) {} [ThreadSafe] private extern bool HasValidTransform(ref AnimationStream stream); [ThreadSafe] private extern bool IsBound(ref AnimationStream stream); [NativeMethod(Name = "Resolve", IsThreadSafe = true)] private extern void ResolveInternal(ref AnimationStream stream); [NativeMethod(Name = "GetFloat", IsThreadSafe = true)] private extern float GetFloatInternal(ref AnimationStream stream); [NativeMethod(Name = "GetInt", IsThreadSafe = true)] private extern int GetIntInternal(ref AnimationStream stream); [NativeMethod(Name = "GetBool", IsThreadSafe = true)] private extern bool GetBoolInternal(ref AnimationStream stream); } [MovedFrom("UnityEngine.Experimental.Animations")] [NativeHeader("Modules/Animation/ScriptBindings/AnimationStreamHandles.bindings.h")] unsafe public static class AnimationSceneHandleUtility { public static void ReadInts(AnimationStream stream, NativeArray<PropertySceneHandle> handles, NativeArray<int> buffer) { int count = ValidateAndGetArrayCount(ref stream, handles, buffer); if (count == 0) return; ReadSceneIntsInternal(ref stream, handles.GetUnsafePtr(), buffer.GetUnsafePtr(), count); } public static void ReadFloats(AnimationStream stream, NativeArray<PropertySceneHandle> handles, NativeArray<float> buffer) { int count = ValidateAndGetArrayCount(ref stream, handles, buffer); if (count == 0) return; ReadSceneFloatsInternal(ref stream, handles.GetUnsafePtr(), buffer.GetUnsafePtr(), count); } internal static int ValidateAndGetArrayCount<T0, T1>(ref AnimationStream stream, NativeArray<T0> handles, NativeArray<T1> buffer) where T0 : struct where T1 : struct { stream.CheckIsValid(); if (!handles.IsCreated) throw new NullReferenceException("Handle array is invalid."); if (!buffer.IsCreated) throw new NullReferenceException("Data buffer is invalid."); if (buffer.Length < handles.Length) throw new InvalidOperationException("Data buffer array is smaller than handles array."); return handles.Length; } // PropertySceneHandle [NativeMethod(Name = "AnimationHandleUtilityBindings::ReadSceneIntsInternal", IsFreeFunction = true, HasExplicitThis = false, IsThreadSafe = true)] static private extern void ReadSceneIntsInternal(ref AnimationStream stream, void* propertySceneHandles, void* intBuffer, int count); [NativeMethod(Name = "AnimationHandleUtilityBindings::ReadSceneFloatsInternal", IsFreeFunction = true, HasExplicitThis = false, IsThreadSafe = true)] static private extern void ReadSceneFloatsInternal(ref AnimationStream stream, void* propertySceneHandles, void* floatBuffer, int count); } [MovedFrom("UnityEngine.Experimental.Animations")] [NativeHeader("Modules/Animation/ScriptBindings/AnimationStreamHandles.bindings.h")] unsafe public static class AnimationStreamHandleUtility { public static void WriteInts(AnimationStream stream, NativeArray<PropertyStreamHandle> handles, NativeArray<int> buffer, bool useMask) { stream.CheckIsValid(); int count = AnimationSceneHandleUtility.ValidateAndGetArrayCount(ref stream, handles, buffer); if (count == 0) return; WriteStreamIntsInternal(ref stream, handles.GetUnsafePtr(), buffer.GetUnsafePtr(), count, useMask); } public static void WriteFloats(AnimationStream stream, NativeArray<PropertyStreamHandle> handles, NativeArray<float> buffer, bool useMask) { stream.CheckIsValid(); int count = AnimationSceneHandleUtility.ValidateAndGetArrayCount(ref stream, handles, buffer); if (count == 0) return; WriteStreamFloatsInternal(ref stream, handles.GetUnsafePtr(), buffer.GetUnsafePtr(), count, useMask); } public static void ReadInts(AnimationStream stream, NativeArray<PropertyStreamHandle> handles, NativeArray<int> buffer) { stream.CheckIsValid(); int count = AnimationSceneHandleUtility.ValidateAndGetArrayCount(ref stream, handles, buffer); if (count == 0) return; ReadStreamIntsInternal(ref stream, handles.GetUnsafePtr(), buffer.GetUnsafePtr(), count); } public static void ReadFloats(AnimationStream stream, NativeArray<PropertyStreamHandle> handles, NativeArray<float> buffer) { stream.CheckIsValid(); int count = AnimationSceneHandleUtility.ValidateAndGetArrayCount(ref stream, handles, buffer); if (count == 0) return; ReadStreamFloatsInternal(ref stream, handles.GetUnsafePtr(), buffer.GetUnsafePtr(), count); } // PropertyStreamHandle [NativeMethod(Name = "AnimationHandleUtilityBindings::ReadStreamIntsInternal", IsFreeFunction = true, HasExplicitThis = false, IsThreadSafe = true)] static private extern void ReadStreamIntsInternal(ref AnimationStream stream, void* propertyStreamHandles, void* intBuffer, int count); [NativeMethod(Name = "AnimationHandleUtilityBindings::ReadStreamFloatsInternal", IsFreeFunction = true, HasExplicitThis = false, IsThreadSafe = true)] static private extern void ReadStreamFloatsInternal(ref AnimationStream stream, void* propertyStreamHandles, void* floatBuffer, int count); [NativeMethod(Name = "AnimationHandleUtilityBindings::WriteStreamIntsInternal", IsFreeFunction = true, HasExplicitThis = false, IsThreadSafe = true)] static private extern void WriteStreamIntsInternal(ref AnimationStream stream, void* propertyStreamHandles, void* intBuffer, int count, bool useMask); [NativeMethod(Name = "AnimationHandleUtilityBindings::WriteStreamFloatsInternal", IsFreeFunction = true, HasExplicitThis = false, IsThreadSafe = true)] static private extern void WriteStreamFloatsInternal(ref AnimationStream stream, void* propertyStreamHandles, void* floatBuffer, int count, bool useMask); } }
UnityCsReference/Modules/Animation/ScriptBindings/AnimationStreamHandles.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimationStreamHandles.bindings.cs", "repo_id": "UnityCsReference", "token_count": 12605 }
375
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine { [NativeHeader("Modules/Animation/Motion.h")] public partial class Motion : Object { protected Motion() {} extern public float averageDuration { get; } extern public float averageAngularSpeed { get; } extern public Vector3 averageSpeed { get; } extern public float apparentSpeed { get; } extern public bool isLooping { [NativeMethod("IsLooping")] get; } extern public bool legacy { [NativeMethod("IsLegacy")] get; } extern public bool isHumanMotion { [NativeMethod("IsHumanMotion")] get; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("ValidateIfRetargetable is not supported anymore, please use isHumanMotion instead.", true)] public bool ValidateIfRetargetable(bool val) { return false; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("isAnimatorMotion is not supported anymore, please use !legacy instead.", true)] public bool isAnimatorMotion { get; } } }
UnityCsReference/Modules/Animation/ScriptBindings/Motion.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/Motion.bindings.cs", "repo_id": "UnityCsReference", "token_count": 571 }
376
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using UnityEditorInternal; using UnityEngine; using UnityEngine.Bindings; using UnityEngineInternal; using uei = UnityEngine.Internal; using Object = UnityEngine.Object; using UnityEngine.Scripting; using UnityEditor.Experimental; using UnityEngine.Internal; using UnityEditor.AssetImporters; namespace UnityEditor { public enum RemoveAssetOptions { MoveAssetToTrash = 0, DeleteAssets = 2 } // Subset of C++ UpdateAssetOptions in AssetDatabaseStructs.h [Flags] public enum ImportAssetOptions { Default = 0, // Default import options. ForceUpdate = 1 << 0, // User initiated asset import. ForceSynchronousImport = 1 << 3, // Import all assets synchronously. ImportRecursive = 1 << 8, // When a folder is imported, import all its contents as well. DontDownloadFromCacheServer = 1 << 13, // Force a full reimport but don't download the assets from the cache server. ForceUncompressedImport = 1 << 14, // Forces asset import as uncompressed for edition facilities. } public enum StatusQueryOptions { ForceUpdate = 0, // Always ask version control for the true status of the file and wait for the response. Recommended for operations that will open a file for edit, or revert, or update a file from version control where you need to know the status of the file accurately. UseCachedIfPossible = 1, // Use the cached status of the asset in version control. The version control system will be queried for the first request and then periodically for subsequent requests. Cached status can be queried very quickly, so is recommended for any UI operations where accuracy is not strictly necessary. UseCachedAsync = 2, // Use the cached status of the asset in version control. Similar to UseCachedIfPossible, except that it doesn't await a response and will submit a query and return immediately if no cached status is available. } public enum ForceReserializeAssetsOptions { ReserializeAssets = 1 << 0, ReserializeMetadata = 1 << 1, ReserializeAssetsAndMetadata = ReserializeAssets | ReserializeMetadata } public enum AssetPathToGUIDOptions { IncludeRecentlyDeletedAssets = 0, // Return a GUID if an asset has been recently deleted. OnlyExistingAssets = 1, // Return a GUID only if the asset exists on disk. } internal enum ImportPackageOptions { Default = 0, NoGUI = 1 << 0, ImportDelayed = 1 << 1 } // keep in sync with AssetDatabasePreventExecutionChecks in AssetDatabasePreventExecution.h internal enum AssetDatabasePreventExecution { kNoAssetDatabaseRestriction = 0, kImportingAsset = 1 << 0, kImportingInWorkerProcess = 1 << 1, kPreventCustomDependencyChanges = 1 << 2, kGatheringDependenciesFromSourceFile = 1 << 3, kPreventForceReserializeAssets = 1 << 4, kDomainBackup = 1 << 5, } public struct CacheServerConnectionChangedParameters { } [RequiredByNativeCode] internal class AssetDatabaseLoadOperationHelper { // When the load operation completes this is invoked to hold the result so that it doesn't // get garbage collected [RequiredByNativeCode] public static void SetAssetDatabaseLoadObjectResult(AssetDatabaseLoadOperation op, UnityEngine.Object result) { op.m_Result = result; } } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public class AssetDatabaseLoadOperation : AsyncOperation { internal Object m_Result; public UnityEngine.Object LoadedObject { get { return m_Result; } } public AssetDatabaseLoadOperation() { } private AssetDatabaseLoadOperation(IntPtr ptr) : base(ptr) { } new internal static class BindingsMarshaller { public static AssetDatabaseLoadOperation ConvertToManaged(IntPtr ptr) => new AssetDatabaseLoadOperation(ptr); } } [NativeHeader("Modules/AssetDatabase/Editor/Public/AssetDatabase.h")] [NativeHeader("Modules/AssetDatabase/Editor/Public/AssetDatabaseUtility.h")] [NativeHeader("Modules/AssetDatabase/Editor/ScriptBindings/AssetDatabase.bindings.h")] [NativeHeader("Runtime/Core/PreventExecutionInState.h")] [NativeHeader("Modules/AssetDatabase/Editor/Public/AssetDatabasePreventExecution.h")] [NativeHeader("Editor/Src/PackageUtility.h")] [NativeHeader("Editor/Src/VersionControl/VC_bindings.h")] [NativeHeader("Editor/Src/Application/ApplicationFunctions.h")] [StaticAccessor("AssetDatabaseBindings", StaticAccessorType.DoubleColon)] public partial class AssetDatabase { extern internal static bool CanGetAssetMetaInfo(string path); extern internal static void RegisterAssetFolder(string path, bool immutable, string guid); extern internal static void UnregisterAssetFolder(string path); // used by integration tests extern internal static void RegisterRedirectedAssetFolder(string mountPoint, string folder, string physicalPath, bool immutable, string guid); extern internal static void UnregisterRedirectedAssetFolder(string mountPoint, string folder); // This will return all registered roots, i.e. Assets/, Packages/** (all registered package roots), Workspaces/, etc. [FreeFunction("AssetDatabase::GetAssetRootFolders")] extern internal static string[] GetAssetRootFolders(); // returns true if the folder is known by the asset database // rootFolder is true if the path is a registered root folder // immutable is true when the root of the path was registered with the immutable flag (e.g. shared package) // asset folders marked immutable are not modified by the asset database extern public static bool TryGetAssetFolderInfo(string path, out bool rootFolder, out bool immutable); public static bool Contains(Object obj) { return Contains(obj.GetInstanceID()); } extern public static bool Contains(int instanceID); [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.CreateFolder() was called as part of running an import in a worker process.")] extern public static string CreateFolder(string parentFolder, string newFolderName); public static bool IsMainAsset(Object obj) { return IsMainAsset(obj.GetInstanceID()); } [FreeFunction("AssetDatabase::IsMainAsset")] extern public static bool IsMainAsset(int instanceID); public static bool IsSubAsset(Object obj) { return IsSubAsset(obj.GetInstanceID()); } [FreeFunction("AssetDatabase::IsSubAsset")] extern public static bool IsSubAsset(int instanceID); public static bool IsForeignAsset(Object obj) { if (obj == null) throw new ArgumentNullException("obj is null"); return IsForeignAsset(obj.GetInstanceID()); } extern public static bool IsForeignAsset(int instanceID); public static bool IsNativeAsset(Object obj) { if (obj == null) throw new ArgumentNullException("obj is null"); return IsNativeAsset(obj.GetInstanceID()); } extern public static bool IsNativeAsset(int instanceID); [NativeThrows] extern public static int GetScriptableObjectsWithMissingScriptCount(string assetPath); [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.RemoveScriptableObjectsWithMissingScript() was called as part of running an import in a worker process.")] [NativeThrows] extern public static int RemoveScriptableObjectsWithMissingScript(string assetPath); [FreeFunction()] extern public static string GetCurrentCacheServerIp(); extern public static string GenerateUniqueAssetPath(string path); [FreeFunction("AssetDatabase::StartAssetImporting")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException)] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_Error)] extern public static void StartAssetEditing(); [FreeFunction("AssetDatabase::StopAssetImporting")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException)] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_Error)] extern public static void StopAssetEditing(); // A class used for Starting/Stopping asset editing. Let's a user start/stop using RAII public class AssetEditingScope : IDisposable { private bool disposed = false; public AssetEditingScope() { AssetDatabase.StartAssetEditing(); } ~AssetEditingScope() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // We've already been disposed. if (this.disposed) return; // disposing is only false when the user forgot to Dispose() it properly // so we should warn them about not properly disposing it as it will freeze the editor. if (!disposing) { // It would be cool to inform the user about where new AssetEditingScope was called, // but I'm unsure how to do that correctly/efficiently, so we'll just warn the user. Debug.LogWarning( "AssetEditingScope.Dispose() was never called on an instance of AssetEditingScope. " + "This could freeze the editor for a short while. Check out the documentation for more info." ); } else { // StopAssetEditing isn't threadsafe, so we don't call it from the finalizer (as that is in a different thread) AssetDatabase.StopAssetEditing(); } } } [FreeFunction("AssetDatabase::UnloadAllFileStreams")] extern public static void ReleaseCachedFileHandles(); extern public static string ValidateMoveAsset(string oldPath, string newPath); [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.MoveAsset() was called as part of running an import in a worker process.")] extern public static string MoveAsset(string oldPath, string newPath); [NativeThrows] extern public static string ExtractAsset(Object asset, string newPath); [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.RenameAsset() was called as part of running an import in a worker process.")] extern public static string RenameAsset(string pathName, string newName); [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.MoveAssetToTrash() was called as part of running an import in a worker process.")] extern public static bool MoveAssetToTrash(string path); [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "Asset deletion method was called as part of running an import in a worker process.")] extern private static bool DeleteAssetsCommon(string[] paths, object outFailedPaths, bool moveAssetsToTrash); public static bool MoveAssetsToTrash(string[] paths, List<string> outFailedPaths) { if (paths == null) throw new ArgumentNullException(nameof(paths)); if (outFailedPaths == null) throw new ArgumentNullException(nameof(outFailedPaths)); return DeleteAssetsCommon(paths, outFailedPaths, true); } [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.DeleteAsset() was called as part of running an import in a worker process.")] extern public static bool DeleteAsset(string path); public static bool DeleteAssets(string[] paths, List<string> outFailedPaths) { if (paths == null) throw new ArgumentNullException(nameof(paths)); if (outFailedPaths == null) throw new ArgumentNullException(nameof(outFailedPaths)); return DeleteAssetsCommon(paths, outFailedPaths, false); } [uei.ExcludeFromDocs] public static void ImportAsset(string path) { ImportAsset(path, ImportAssetOptions.Default); } extern public static void ImportAsset(string path, [uei.DefaultValue("ImportAssetOptions.Default")] ImportAssetOptions options); [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.CopyAsset() was called as part of running an import in a worker process.")] extern public static bool CopyAsset(string path, string newPath); [NativeThrows] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be copied during AssetImporting as this leads to new asset creation in the middle of an import.")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be copied during AssetImporting as this leads to new asset creation in the middle of an import.")] extern public static bool CopyAssets(string[] paths, string[] newPaths); extern public static bool WriteImportSettingsIfDirty(string path); [NativeThrows] extern public static string[] GetSubFolders([NotNull] string path); [FreeFunction("AssetDatabase::IsFolderAsset")] extern public static bool IsValidFolder(string path); [NativeThrows] [PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be created during gathering of import dependencies")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_Warning, "AssetDatabase.CreateAsset() was called as part of running an import. Please make sure this function is not called from ScriptedImporters or PostProcessors, as it is a source of non-determinism and will be disallowed in a forthcoming release.")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.CreateAsset() was called as part of running an import in a worker process.")] extern public static void CreateAsset([NotNull] Object asset, string path); [NativeThrows] extern static internal void CreateAssetFromObjects(Object[] assets, string path); [NativeThrows] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.AddObjectToAsset() was called as part of running an import in a worker process.")] extern public static void AddObjectToAsset([NotNull] Object objectToAdd, string path); static public void AddObjectToAsset(Object objectToAdd, Object assetObject) { AddObjectToAsset_Obj(objectToAdd, assetObject); } [NativeThrows] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.AddObjectToAsset() was called as part of running an import in a worker process.")] extern private static void AddObjectToAsset_Obj([NotNull] Object newAsset, [NotNull] Object sameAssetFile); extern static internal void AddInstanceIDToAssetWithRandomFileId(int instanceIDToAdd, Object assetObject, bool hide); [NativeThrows] extern public static void SetMainObject([NotNull] Object mainObject, string assetPath); extern public static string GetAssetPath(Object assetObject); public static string GetAssetPath(int instanceID) { return GetAssetPathFromInstanceID(instanceID); } [FreeFunction("::GetAssetPathFromInstanceID")] extern private static string GetAssetPathFromInstanceID(int instanceID); extern internal static int GetMainAssetInstanceID(string assetPath); extern internal static int GetMainAssetOrInProgressProxyInstanceID(string assetPath); [FreeFunction("::GetAssetOrScenePath")] extern public static string GetAssetOrScenePath(Object assetObject); [FreeFunction("AssetDatabase::TextMetaFilePathFromAssetPath")] extern public static string GetTextMetaFilePathFromAssetPath(string path); [FreeFunction("AssetDatabase::AssetPathFromTextMetaFilePath")] extern public static string GetAssetPathFromTextMetaFilePath(string path); [NativeThrows] [TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] [PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be loaded while dependencies are being gathered, as these assets may not have been imported yet.")] [PreventExecutionInState(AssetDatabasePreventExecution.kDomainBackup, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be loaded while domain backup is running, as this will change the underlying state.")] extern public static Object LoadAssetAtPath(string assetPath, Type type); public static T LoadAssetAtPath<T>(string assetPath) where T : Object { return (T)LoadAssetAtPath(assetPath, typeof(T)); } [PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be loaded while dependencies are being gathered, as these assets may not have been imported yet.")] extern public static Object LoadMainAssetAtPath(string assetPath); [FreeFunction("AssetDatabase::GetMainAssetObject")] [PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be loaded while dependencies are being gathered, as these assets may not have been imported yet.")] extern internal static Object LoadMainAssetAtGUID(GUID assetGUID); [FreeFunction("AssetDatabase::InstanceIDsToGUIDs")] extern internal static void InstanceIDsToGUIDs(IntPtr instanceIDsPtr, IntPtr guidsPtr, int len); public unsafe static void InstanceIDsToGUIDs(NativeArray<int> instanceIDs, NativeArray<GUID> guidsOut) { if (!instanceIDs.IsCreated) throw new ArgumentException("NativeArray is uninitialized", nameof(instanceIDs)); if (!guidsOut.IsCreated) throw new ArgumentException("NativeArray is uninitialized", nameof(guidsOut)); if (instanceIDs.Length != guidsOut.Length) throw new ArgumentException("instanceIDs and guidsOut size mismatch!"); InstanceIDsToGUIDs((IntPtr)instanceIDs.GetUnsafeReadOnlyPtr(), (IntPtr)guidsOut.GetUnsafePtr(), instanceIDs.Length); } [FreeFunction("AssetDatabase::ReserveMonoScriptInstanceID")] extern internal static int ReserveMonoScriptInstanceID(GUID guid); extern public static System.Type GetMainAssetTypeAtPath(string assetPath); extern public static System.Type GetMainAssetTypeFromGUID(GUID guid); extern public static System.Type GetTypeFromPathAndFileID(string assetPath, long localIdentifierInFile); extern public static bool IsMainAssetAtPathLoaded(string assetPath); [PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be loaded while dependencies are being gathered, as these assets may not have been imported yet.")] extern public static Object[] LoadAllAssetRepresentationsAtPath(string assetPath); [PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Assets may not be loaded while dependencies are being gathered, as these assets may not have been imported yet.")] extern public static Object[] LoadAllAssetsAtPath(string assetPath); extern public static string[] GetAllAssetPaths(); [uei.ExcludeFromDocs] public static void Refresh() { Refresh(ImportAssetOptions.Default); } [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException)] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_Error)] extern public static void Refresh([uei.DefaultValue("ImportAssetOptions.Default")] ImportAssetOptions options); [FreeFunction("::CanOpenAssetInEditor")] extern public static bool CanOpenAssetInEditor(int instanceID); [uei.ExcludeFromDocs] public static bool OpenAsset(int instanceID) { return OpenAsset(instanceID, -1); } public static bool OpenAsset(int instanceID, [uei.DefaultValue("-1")] int lineNumber) { return OpenAsset(instanceID, lineNumber, -1); } [FreeFunction("::OpenAsset")] extern public static bool OpenAsset(int instanceID, int lineNumber, int columnNumber); [uei.ExcludeFromDocs] public static bool OpenAsset(Object target) { return OpenAsset(target, -1); } public static bool OpenAsset(Object target, [uei.DefaultValue("-1")] int lineNumber) { return OpenAsset(target, lineNumber, -1); } static public bool OpenAsset(Object target, int lineNumber, int columnNumber) { if (target) return OpenAsset(target.GetInstanceID(), lineNumber, columnNumber); else return false; } static public bool OpenAsset(Object[] objects) { bool allOpened = true; foreach (Object obj in objects) if (!OpenAsset(obj)) allOpened = false; return allOpened; } [FreeFunction("AssetDatabase::GetAssetOrigin")] extern private static AssetOrigin GetAssetOrigin_Internal(GUID guid); internal static AssetOrigin GetAssetOrigin(GUID guid) { return GetAssetOrigin_Internal(guid); } internal static AssetOrigin GetAssetOrigin(string guid) { return GetAssetOrigin_Internal(new GUID(guid)); } extern internal static string GUIDToAssetPath_Internal(GUID guid); extern internal static GUID AssetPathToGUID_Internal(string path); public static string GUIDToAssetPath(string guid) { return GUIDToAssetPath_Internal(new GUID(guid)); } public static string GUIDToAssetPath(GUID guid) { return GUIDToAssetPath_Internal(guid); } public static GUID GUIDFromAssetPath(string path) { return AssetPathToGUID_Internal(path); } public static string AssetPathToGUID(string path) { return AssetPathToGUID(path, AssetPathToGUIDOptions.IncludeRecentlyDeletedAssets); } public static string AssetPathToGUID(string path, [DefaultValue("AssetPathToGUIDOptions.IncludeRecentlyDeletedAssets")] AssetPathToGUIDOptions options) { GUID guid; switch (options) { case AssetPathToGUIDOptions.OnlyExistingAssets: guid = GUIDFromExistingAssetPath(path); break; default: guid = AssetPathToGUID_Internal(path); break; } return guid.Empty() ? "" : guid.ToString(); } extern public static bool AssetPathExists(string path); extern public static Hash128 GetAssetDependencyHash(GUID guid); public static Hash128 GetAssetDependencyHash(string path) { return GetAssetDependencyHash(GUIDFromAssetPath(path)); } extern internal static Hash128 GetSourceAssetFileHash(string guid); extern internal static Hash128 GetSourceAssetMetaFileHash(string guid); [FreeFunction("AssetDatabase::SaveAssets")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException)] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_Error)] extern public static void SaveAssets(); [FreeFunction("AssetDatabase::SaveAssetIfDirty")] extern public static void SaveAssetIfDirty(GUID guid); public static void SaveAssetIfDirty(Object obj) { string guidString; long localID; if (TryGetGUIDAndLocalFileIdentifier(obj.GetInstanceID(), out guidString, out localID)) SaveAssetIfDirty(new GUID(guidString)); } extern public static Texture GetCachedIcon(string path); extern public static void SetLabels(Object obj, string[] labels); extern private static void GetAllLabelsImpl(object labelsList, object scoresList); internal static Dictionary<string, float> GetAllLabels() { var labelsList = new List<string>(); var scoresList = new List<float>(); GetAllLabelsImpl(labelsList, scoresList); Dictionary<string, float> res = new Dictionary<string, float>(labelsList.Count); for (int i = 0; i < labelsList.Count; ++i) { res[labelsList[i]] = scoresList[i]; } return res; } [FreeFunction("AssetDatabase::GetLabels")] extern private static string[] GetLabelsInternal(GUID guid); public static string[] GetLabels(GUID guid) { return GetLabelsInternal(guid); } extern public static string[] GetLabels(Object obj); extern public static void ClearLabels(Object obj); extern public static string[] GetAllAssetBundleNames(); [System.Obsolete("Method GetAssetBundleNames has been deprecated. Use GetAllAssetBundleNames instead.",true)] public string[] GetAssetBundleNames() { return GetAllAssetBundleNames(); } // TODO DELETE IN 2024 extern internal static string[] GetAllAssetBundleNamesWithoutVariant(); extern internal static string[] GetAllAssetBundleVariants(); extern public static string[] GetUnusedAssetBundleNames(); [FreeFunction("AssetDatabase::RemoveAssetBundleByName")] extern public static bool RemoveAssetBundleName(string assetBundleName, bool forceRemove); [FreeFunction("AssetDatabase::RemoveUnusedAssetBundleNames")] extern public static void RemoveUnusedAssetBundleNames(); extern public static string[] GetAssetPathsFromAssetBundle(string assetBundleName); extern public static string[] GetAssetPathsFromAssetBundleAndAssetName(string assetBundleName, string assetName); [NativeThrows] extern public static string GetImplicitAssetBundleName(string assetPath); [NativeThrows] extern public static string GetImplicitAssetBundleVariantName(string assetPath); extern public static string[] GetAssetBundleDependencies(string assetBundleName, bool recursive); public static string[] GetDependencies(string pathName) { return GetDependencies(pathName, true); } public static string[] GetDependencies(string pathName, bool recursive) { string[] input = new string[1]; input[0] = pathName; return GetDependencies(input, recursive); } public static string[] GetDependencies(string[] pathNames) { return GetDependencies(pathNames, true); } extern public static string[] GetDependencies(string[] pathNames, bool recursive); public static void ExportPackage(string assetPathName, string fileName) { string[] input = new string[1]; input[0] = assetPathName; ExportPackage(input, fileName, ExportPackageOptions.Default); } public static void ExportPackage(string assetPathName, string fileName, ExportPackageOptions flags) { string[] input = new string[1]; input[0] = assetPathName; ExportPackage(input, fileName, flags); } [uei.ExcludeFromDocs] public static void ExportPackage(string[] assetPathNames, string fileName) { ExportPackage(assetPathNames, fileName, ExportPackageOptions.Default); } [NativeThrows] extern public static void ExportPackage(string[] assetPathNames, string fileName, [uei.DefaultValue("ExportPackageOptions.Default")] ExportPackageOptions flags); extern internal static string GetUniquePathNameAtSelectedPath(string fileName); [uei.ExcludeFromDocs] public static bool CanOpenForEdit(UnityEngine.Object assetObject) { return CanOpenForEdit(assetObject, StatusQueryOptions.UseCachedIfPossible); } public static bool CanOpenForEdit(UnityEngine.Object assetObject, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string assetPath = GetAssetOrScenePath(assetObject); return CanOpenForEdit(assetPath, statusOptions); } [uei.ExcludeFromDocs] public static bool CanOpenForEdit(string assetOrMetaFilePath) { return CanOpenForEdit(assetOrMetaFilePath, StatusQueryOptions.UseCachedIfPossible); } public static bool CanOpenForEdit(string assetOrMetaFilePath, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string message; return CanOpenForEdit(assetOrMetaFilePath, out message, statusOptions); } [uei.ExcludeFromDocs] public static bool CanOpenForEdit(UnityEngine.Object assetObject, out string message) { return CanOpenForEdit(assetObject, out message, StatusQueryOptions.UseCachedIfPossible); } public static bool CanOpenForEdit(UnityEngine.Object assetObject, out string message, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string assetPath = GetAssetOrScenePath(assetObject); return CanOpenForEdit(assetPath, out message, statusOptions); } [uei.ExcludeFromDocs] public static bool CanOpenForEdit(string assetOrMetaFilePath, out string message) { return CanOpenForEdit(assetOrMetaFilePath, out message, StatusQueryOptions.UseCachedIfPossible); } public static bool CanOpenForEdit(string assetOrMetaFilePath, out string message, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { return AssetModificationProcessorInternal.CanOpenForEdit(assetOrMetaFilePath, out message, statusOptions); } [uei.ExcludeFromDocs] public static bool IsOpenForEdit(UnityEngine.Object assetObject) { return IsOpenForEdit(assetObject, StatusQueryOptions.UseCachedIfPossible); } public static bool IsOpenForEdit(UnityEngine.Object assetObject, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string assetPath = GetAssetOrScenePath(assetObject); return IsOpenForEdit(assetPath, statusOptions); } [uei.ExcludeFromDocs] public static bool IsOpenForEdit(string assetOrMetaFilePath) { return IsOpenForEdit(assetOrMetaFilePath, StatusQueryOptions.UseCachedIfPossible); } public static bool IsOpenForEdit(string assetOrMetaFilePath, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string message; return IsOpenForEdit(assetOrMetaFilePath, out message, statusOptions); } [uei.ExcludeFromDocs] public static bool IsOpenForEdit(UnityEngine.Object assetObject, out string message) { return IsOpenForEdit(assetObject, out message, StatusQueryOptions.UseCachedIfPossible); } public static bool IsOpenForEdit(UnityEngine.Object assetObject, out string message, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string assetPath = GetAssetOrScenePath(assetObject); return IsOpenForEdit(assetPath, out message, statusOptions); } [uei.ExcludeFromDocs] public static bool IsOpenForEdit(string assetOrMetaFilePath, out string message) { return IsOpenForEdit(assetOrMetaFilePath, out message, StatusQueryOptions.UseCachedIfPossible); } public static bool IsOpenForEdit(string assetOrMetaFilePath, out string message, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { return AssetModificationProcessorInternal.IsOpenForEdit(assetOrMetaFilePath, out message, statusOptions); } [uei.ExcludeFromDocs] public static bool IsMetaFileOpenForEdit(UnityEngine.Object assetObject) { return IsMetaFileOpenForEdit(assetObject, StatusQueryOptions.UseCachedIfPossible); } public static bool IsMetaFileOpenForEdit(UnityEngine.Object assetObject, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string message; return IsMetaFileOpenForEdit(assetObject, out message, statusOptions); } [uei.ExcludeFromDocs] public static bool IsMetaFileOpenForEdit(UnityEngine.Object assetObject, out string message) { return IsMetaFileOpenForEdit(assetObject, out message, StatusQueryOptions.UseCachedIfPossible); } public static bool IsMetaFileOpenForEdit(UnityEngine.Object assetObject, out string message, [uei.DefaultValue("StatusQueryOptions.UseCachedIfPossible")] StatusQueryOptions statusOptions) { string assetPath = GetAssetOrScenePath(assetObject); string metaPath = AssetDatabase.GetTextMetaFilePathFromAssetPath(assetPath); return IsOpenForEdit(metaPath, out message, statusOptions); } public static T GetBuiltinExtraResource<T>(string path) where T : Object { return (T)GetBuiltinExtraResource(typeof(T), path); } [NativeThrows] [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] extern public static Object GetBuiltinExtraResource(Type type, string path); [NativeThrows] extern internal static string[] CollectAllChildren(string guid, string[] collection); internal extern static string assetFolderGUID { [FreeFunction("AssetDatabaseBindings::GetAssetFolderGUID")] get; } [FreeFunction("AssetDatabase::IsV1Enabled")] extern internal static bool IsV1Enabled(); [FreeFunction("AssetDatabase::IsV2Enabled")] extern internal static bool IsV2Enabled(); [FreeFunction("AssetDatabase::CloseCachedFiles")] extern internal static void CloseCachedFiles(); [NativeThrows] extern internal static string[] GetSourceAssetImportDependenciesAsGUIDs(string path); [NativeThrows] extern internal static string[] GetImportedAssetImportDependenciesAsGUIDs(string path); [NativeThrows] extern internal static string[] GetGuidOfPathLocationImportDependencies(string path); [FreeFunction("AssetDatabase::ReSerializeAssetsForced")] [PreventExecutionInState(AssetDatabasePreventExecution.kPreventForceReserializeAssets, PreventExecutionSeverity.PreventExecution_ManagedException, "Consider calling ForceReserializeAssets from menu style entry point.")] extern private static void ForceReserializeAssets(GUID[] guids, ForceReserializeAssetsOptions options); public static void ForceReserializeAssets(IEnumerable<string> assetPaths, ForceReserializeAssetsOptions options = ForceReserializeAssetsOptions.ReserializeAssetsAndMetadata) { if (EditorApplication.isPlaying) throw new Exception("AssetDatabase.ForceReserializeAssets cannot be used when in play mode"); HashSet<GUID> guidList = new HashSet<GUID>(); foreach (string path in assetPaths) { if (path == "") continue; if (InternalEditorUtility.IsUnityExtensionRegistered(path)) continue; bool rootFolder, readOnly; bool validPath = TryGetAssetFolderInfo(path, out rootFolder, out readOnly); if (validPath && (rootFolder || readOnly)) continue; GUID guid = GUIDFromAssetPath(path); if (!guid.Empty()) { guidList.Add(guid); } else { if (File.Exists(path)) { Debug.LogWarningFormat("Cannot reserialize file \"{0}\": the file is not in the AssetDatabase. Skipping.", path); } else { Debug.LogWarningFormat("Cannot reserialize file \"{0}\": the file does not exist. Skipping.", path); } } } GUID[] guids = new GUID[guidList.Count]; guidList.CopyTo(guids); ForceReserializeAssets(guids, options); } extern internal static System.Type GetTypeFromVisibleGUIDAndLocalFileIdentifier(GUID guid, long localId); [FreeFunction("AssetDatabase::GetGUIDAndLocalIdentifierInFile")] extern private static bool GetGUIDAndLocalIdentifierInFile(int instanceID, out GUID outGuid, out long outLocalId); public static bool TryGetGUIDAndLocalFileIdentifier(Object obj, out string guid, out long localId) { return TryGetGUIDAndLocalFileIdentifier(obj.GetInstanceID(), out guid, out localId); } public static bool TryGetGUIDAndLocalFileIdentifier(int instanceID, out string guid, out long localId) { GUID uguid; bool res = GetGUIDAndLocalIdentifierInFile(instanceID, out uguid, out localId); guid = uguid.ToString(); return res; } public static bool TryGetGUIDAndLocalFileIdentifier<T>(LazyLoadReference<T> assetRef, out string guid, out long localId) where T : UnityEngine.Object { return TryGetGUIDAndLocalFileIdentifier(assetRef.instanceID, out guid, out localId); } public static void ForceReserializeAssets() { ForceReserializeAssets(GetAllAssetPaths()); } [FreeFunction("AssetDatabase::RemoveObjectFromAsset")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingInWorkerProcess, PreventExecutionSeverity.PreventExecution_ManagedException, "AssetDatabase.RemoveObjectFromAsset() was called as part of running an import in a worker process.")] extern public static void RemoveObjectFromAsset([NotNull] Object objectToRemove); [PreventExecutionInState(AssetDatabasePreventExecution.kGatheringDependenciesFromSourceFile, PreventExecutionSeverity.PreventExecution_ManagedException, "Cannot call AssetDatabase.LoadObjectAsync during the gathering of import dependencies.")] [PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_ManagedException, "Cannot use AssetDatabase.LoadObjectAsync while assets are importing.")] extern public static AssetDatabaseLoadOperation LoadObjectAsync(string assetPath, long localId); [FreeFunction("AssetDatabase::GUIDFromExistingAssetPath")] extern internal static GUID GUIDFromExistingAssetPath(string path); [FreeFunction("::ImportPackage")] extern private static bool ImportPackage(string packagePath, ImportPackageOptions options); [FreeFunction("::ImportPackageWithOrigin")] extern private static bool ImportPackageWithOrigin(string packagePath, AssetOrigin origin, ImportPackageOptions options); //TODO: This API should be Obsoleted when there is time available to update all the uses of it in Package Manager packages public static void ImportPackage(string packagePath, bool interactive) { ImportPackage(packagePath, ImportPackageOptions.ImportDelayed | (interactive ? ImportPackageOptions.Default : ImportPackageOptions.NoGUI)); } internal static void ImportPackage(string packagePath, AssetOrigin origin, bool interactive) { ImportPackageWithOrigin(packagePath, origin, ImportPackageOptions.ImportDelayed | (interactive ? ImportPackageOptions.Default : ImportPackageOptions.NoGUI)); } internal static bool ImportPackageImmediately(string packagePath) { return ImportPackage(packagePath, ImportPackageOptions.NoGUI); } [FreeFunction("ApplicationDisallowAutoRefresh")] public static extern void DisallowAutoRefresh(); [FreeFunction("ApplicationAllowAutoRefresh")] public static extern void AllowAutoRefresh(); [FreeFunction("ApplicationDisableUpdating")] internal static extern void DisableUpdating(); [FreeFunction("ApplicationEnableUpdating")] internal static extern void EnableUpdating(bool forceSceneUpdate); public extern static UInt32 GlobalArtifactDependencyVersion { [FreeFunction("AssetDatabase::GetGlobalArtifactDependencyVersion")] get; } public extern static UInt32 GlobalArtifactProcessedVersion { [FreeFunction("AssetDatabase::GetGlobalArtifactProcessedVersion")] get; } [NativeThrows] private extern static ArtifactInfo[] GetArtifactInfos_Internal(GUID guid); private extern static ArtifactInfo[] GetCurrentRevisions_Internal(GUID[] guids); private extern static ArtifactInfo[] GetImportActivityWindowStartupData_Internal(ImportActivityWindowStartupData dataType); internal static ArtifactInfo[] GetCurrentRevisions(GUID[] guids) { var artifactInfos = GetCurrentRevisions_Internal(guids); return artifactInfos; } internal static ArtifactInfo[] GetImportActivityWindowStartupData(ImportActivityWindowStartupData dataType) { return GetImportActivityWindowStartupData_Internal(dataType); } internal static ArtifactInfo[] GetArtifactInfos(GUID guid) { var artifactInfos = GetArtifactInfos_Internal(guid); return artifactInfos; } [FreeFunction("AssetDatabase::ClearImporterOverride")] extern public static void ClearImporterOverride(string path); [FreeFunction("AssetDatabase::IsCacheServerEnabled")] public extern static bool IsCacheServerEnabled(); [FreeFunction("AssetDatabase::SetImporterOverride")] extern internal static void SetImporterOverrideInternal(string path, System.Type importer); public static void SetImporterOverride<T>(string path) where T : AssetImporter { if (GUIDFromExistingAssetPath(path).Empty()) { Debug.LogError( $"Cannot set Importer override at \"{path}\". No Asset found at that path."); return; } var availableImporters = GetAvailableImporters(path); if (availableImporters.Contains(typeof(T))) { SetImporterOverrideInternal(path, typeof(T)); } else { if (GetDefaultImporter(path) == typeof(T)) { ClearImporterOverride(path); Debug.LogWarning("This usage is deprecated. Use ClearImporterOverride to revert to the default Importer instead."); } else { Debug.LogError( $"Cannot set Importer override at {path} because {typeof(T).Name} is not a valid Importer for this asset."); } } } [FreeFunction("AssetDatabase::GetImporterOverride")] extern public static System.Type GetImporterOverride(string path); [Obsolete("GetAvailableImporterTypes() has been deprecated. Use GetAvailableImporters() instead (UnityUpgradable) -> GetAvailableImporters(*)", true)] public static Type[] GetAvailableImporterTypes(string path) { return GetAvailableImporters(path); } [FreeFunction("AssetDatabase::GetAvailableImporters")] extern public static Type[] GetAvailableImporters(string path); [FreeFunction("AssetDatabase::GetDefaultImporter")] extern public static Type GetDefaultImporter(string path); [FreeFunction("AcceleratorClientCanConnectTo")] public extern static bool CanConnectToCacheServer(string ip, UInt16 port); [FreeFunction("RefreshSettings")] private extern static void _RefreshSettings(); public static void RefreshSettings() => _RefreshSettings(); public static event Action<CacheServerConnectionChangedParameters> cacheServerConnectionChanged; [RequiredByNativeCode] private static void OnCacheServerConnectionChanged() { if (cacheServerConnectionChanged != null) { CacheServerConnectionChangedParameters param; cacheServerConnectionChanged(param); } } [FreeFunction("AcceleratorClientIsConnected")] private extern static bool _IsConnectedToCacheServer(); public static bool IsConnectedToCacheServer() => _IsConnectedToCacheServer(); [FreeFunction("AcceleratorClientResetReconnectTimer")] public extern static void ResetCacheServerReconnectTimer(); [FreeFunction("AcceleratorClientCloseConnection")] public extern static void CloseCacheServerConnection(); [FreeFunction()] public extern static string GetCacheServerAddress(); [FreeFunction()] public extern static UInt16 GetCacheServerPort(); [FreeFunction("AssetDatabase::GetCacheServerNamespacePrefix")] public extern static string GetCacheServerNamespacePrefix(); [FreeFunction("AssetDatabase::GetCacheServerEnableDownload")] public extern static bool GetCacheServerEnableDownload(); [FreeFunction("AssetDatabase::GetCacheServerEnableUpload")] public extern static bool GetCacheServerEnableUpload(); [FreeFunction("AssetDatabase::WaitForPendingCacheServerRequestsToComplete")] private extern static void _WaitForPendingCacheServerRequestsToComplete(); internal static void WaitForPendingCacheServerRequestsToComplete() => _WaitForPendingCacheServerRequestsToComplete(); [FreeFunction("AssetDatabase::IsDirectoryMonitoringEnabled")] public extern static bool IsDirectoryMonitoringEnabled(); [FreeFunction("AssetDatabase::RegisterCustomDependency")] [PreventExecutionInState(AssetDatabasePreventExecution.kPreventCustomDependencyChanges, PreventExecutionSeverity.PreventExecution_ManagedException, "Custom dependencies can only be removed when the assetdatabase is not importing.")] public extern static void RegisterCustomDependency(string dependency, Hash128 hashOfValue); [FreeFunction("AssetDatabase::UnregisterCustomDependencyPrefixFilter")] [PreventExecutionInState(AssetDatabasePreventExecution.kPreventCustomDependencyChanges, PreventExecutionSeverity.PreventExecution_ManagedException, "Custom dependencies can only be removed when the assetdatabase is not importing.")] public extern static UInt32 UnregisterCustomDependencyPrefixFilter(string prefixFilter); [FreeFunction("AssetDatabase::IsAssetImportProcess")] public extern static bool IsAssetImportWorkerProcess(); [FreeFunction("AssetDatabase::GetImporterType")] public extern static Type GetImporterType(GUID guid); [FreeFunction("AssetDatabase::GetImporterTypes")] public static extern Type[] GetImporterTypes(ReadOnlySpan<GUID> guids); //Since extern method overloads are not supported //this is the name we pick, but users end up being able //to call either of the overloads [FreeFunction("AssetDatabase::GetImporterTypesAtPaths")] private static extern Type[] GetImporterTypesAtPaths(string[] paths); public static Type GetImporterType(string assetPath) { return GetImporterTypeAtPath(assetPath); } //Since extern method overloads are not supported //this is the name we pick, but users end up being able //to call either of the overloads [FreeFunction("AssetDatabase::GetImporterTypeAtPath")] private static extern Type GetImporterTypeAtPath(string assetPath); public static Type[] GetImporterTypes(string[] paths) { return GetImporterTypesAtPaths(paths); } [RequiredByNativeCode] static string[] OnSourceAssetsModified(string[] changedAssets, string[] addedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { var assetMoveInfo = new AssetMoveInfo[movedAssets.Length]; Debug.Assert(movedAssets.Length == movedFromAssetPaths.Length); for (int i = 0; i < movedAssets.Length; i++) assetMoveInfo[i] = new AssetMoveInfo(movedFromAssetPaths[i], movedAssets[i]); var assetsReportedChanged = new HashSet<string>(); foreach (Type type in TypeCache.GetTypesDerivedFrom<AssetsModifiedProcessor>()) { var assetPostprocessor = Activator.CreateInstance(type) as AssetsModifiedProcessor; assetPostprocessor.assetsReportedChanged = assetsReportedChanged; assetPostprocessor.Internal_OnAssetsModified(changedAssets, addedAssets, deletedAssets, assetMoveInfo); assetPostprocessor.assetsReportedChanged = null; } return assetsReportedChanged.ToArray(); } public enum RefreshImportMode { InProcess = 0, OutOfProcessPerQueue = 1 } public extern static RefreshImportMode ActiveRefreshImportMode { [FreeFunction("AssetDatabase::GetRefreshImportMode")] get; [FreeFunction("AssetDatabase::SetRefreshImportMode")] set; } public extern static int DesiredWorkerCount { [FreeFunction("AssetDatabase::GetDesiredWorkerCount")] get; [FreeFunction("AssetDatabase::SetDesiredWorkerCount")] set; } [FreeFunction("AssetDatabase::ForceToDesiredWorkerCount")] public extern static void ForceToDesiredWorkerCount(); [NativeHeader("Modules/AssetDatabase/Editor/Public/AssetDatabaseTypes.h")] [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] internal struct WorkerStats { public int desiredWorkerCount; public int idleWorkerCount; public int importingWorkerCount; public int connectingWorkerCount; public int operationalWorkerCount; public int suspendedWorkerCount; } internal extern static WorkerStats GetWorkerStats(); // Binding only created for testing internal static int TestOnlyDeleteAllNonPrimaryArtifacts(Type[] importers, bool deleteUnusedContentFiles) { return DeleteAllNonPrimaryArtifacts_Importer(importers, deleteUnusedContentFiles); } private extern static int DeleteAllNonPrimaryArtifacts_Importer(Type[] importers, bool deleteUnusedContentFiles); // Binding only created for testing internal static int TestOnlyDeleteAllNonPrimaryArtifacts(ArtifactKey[] artifactKeys, bool deleteUnusedContentFiles) { return DeleteAllNonPrimaryArtifacts_ArtifactKey(artifactKeys, deleteUnusedContentFiles); } private extern static int DeleteAllNonPrimaryArtifacts_ArtifactKey(ArtifactKey[] artifactKeys, bool deleteUnusedContentFiles); // Binding only created for testing [FreeFunction("AssetDatabase::DeleteUnusedContentFiles")] internal extern static void TestOnlyDeleteUnusedContentFiles(); internal enum ImportWorkerModeFlags { kNoFlags = 0, kProfile = 1 << 0 }; // Import Worker Mode binding is just for testing [FreeFunction("AssetDatabase::SetImportWorkerModeFlags")] internal extern static void SetImportWorkerModeFlags(ImportWorkerModeFlags flags); [FreeFunction("AssetDatabase::ClearImportWorkerModeFlags")] internal extern static void ClearImportWorkerModeFlags(ImportWorkerModeFlags flags); [FreeFunction("AssetDatabase::GetImportWorkerModeFlags")] internal extern static ImportWorkerModeFlags GetImportWorkerModeFlags(); } }
UnityCsReference/Modules/AssetDatabase/Editor/ScriptBindings/AssetDatabase.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AssetDatabase/Editor/ScriptBindings/AssetDatabase.bindings.cs", "repo_id": "UnityCsReference", "token_count": 20325 }
377
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.AssetImporters; using UnityEngine; namespace UnityEditor { // Version for AssetImporterInspector derived editors internal abstract class AssetImporterTabbedEditor : AssetImporterEditor { protected string[] m_TabNames = null; private int m_ActiveEditorIndex = 0; /// <summary> /// The list of child inspectors. /// </summary> private BaseAssetImporterTabUI[] m_Tabs = null; public BaseAssetImporterTabUI activeTab { get; private set; } protected BaseAssetImporterTabUI[] tabs { get { return m_Tabs; } set { m_Tabs = value; } } public override void OnEnable() { base.OnEnable(); foreach (var tab in m_Tabs) { tab.OnEnable(); } m_ActiveEditorIndex = EditorPrefs.GetInt(this.GetType().Name + "ActiveEditorIndex", 0); if (activeTab == null) activeTab = m_Tabs[m_ActiveEditorIndex]; } void OnDestroy() { if (m_Tabs != null) { foreach (var tab in m_Tabs) { tab.OnDestroy(); } // destroy all the child tabs m_Tabs = null; activeTab = null; } } [Obsolete("UnityUpgradeable () -> DiscardChanges")] protected override void ResetValues() { DiscardChanges(); } public override void DiscardChanges() { base.DiscardChanges(); if (m_Tabs != null) { foreach (var tab in m_Tabs) { tab.ResetValues(); } } } public override void OnInspectorGUI() { serializedObject.Update(); extraDataSerializedObject?.Update(); // Always allow user to switch between tabs even when the editor is disabled, so they can look at all parts // of read-only assets using (new EditorGUI.DisabledScope(false)) // this doesn't enable the UI, but it seems correct to push the stack { GUI.enabled = true; using (new GUILayout.HorizontalScope()) { GUILayout.FlexibleSpace(); using (var check = new EditorGUI.ChangeCheckScope()) { m_ActiveEditorIndex = GUILayout.Toolbar(m_ActiveEditorIndex, m_TabNames, "LargeButton", GUI.ToolbarButtonSize.FitToContents); if (check.changed) { EditorPrefs.SetInt(GetType().Name + "ActiveEditorIndex", m_ActiveEditorIndex); activeTab = m_Tabs[m_ActiveEditorIndex]; activeTab.OnInspectorGUI(); } } GUILayout.FlexibleSpace(); } } // the activeTab can get destroyed when opening particular sub-editors (such as the Avatar configuration editor on the Rig tab) if (activeTab != null) { GUILayout.Space(EditorGUI.kSpacing); activeTab.OnInspectorGUI(); } extraDataSerializedObject?.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties(); // show a single Apply/Revert set of buttons for all the tabs ApplyRevertGUI(); } public override void OnPreviewSettings() { if (activeTab != null) { activeTab.OnPreviewSettings(); } } public override void OnInteractivePreviewGUI(Rect r, GUIStyle background) { if (activeTab != null) { activeTab.OnInteractivePreviewGUI(r, background); } } public override bool HasPreviewGUI() { if (activeTab == null) return false; return activeTab.HasPreviewGUI(); } protected override void Apply() { if (m_Tabs != null) { // tabs can do work before or after the application of changes in the serialization object foreach (var tab in m_Tabs) { tab.PreApply(); } base.Apply(); foreach (var tab in m_Tabs) { tab.PostApply(); } } } } }
UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/AssetImporterTabbedEditor.cs", "repo_id": "UnityCsReference", "token_count": 2497 }
378
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Obsolete("MovieImporter is removed. Use VideoClipImporter instead.", true)] public class MovieImporter { public float quality { get { return 1.0f; } set {} } public bool linearTexture { get { return false; } set {} } public float duration { get { return 1.0f; } } } }
UnityCsReference/Modules/AssetPipelineEditor/Public/MovieImporter.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/Public/MovieImporter.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 201 }
379
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Internal; namespace UnityEngine.Audio { [NativeHeader("Modules/Audio/Public/AudioMixerGroup.h")] public class AudioMixerGroup : Object, ISubAssetNotDuplicatable { // Make constructor internal internal AudioMixerGroup() {} [NativeProperty] public extern AudioMixer audioMixer { get; } } }
UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioMixerGroup.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioMixerGroup.bindings.cs", "repo_id": "UnityCsReference", "token_count": 191 }
380
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace UnityEditor.Audio { internal struct MixerParameterDefinition { public string name; public string description; public string units; public float displayScale; public float displayExponent; public float minRange; public float maxRange; public float defaultValue; } [StaticAccessor("AudioMixerDescriptionBindings", StaticAccessorType.DoubleColon)] [NativeHeader("Modules/AudioEditor/ScriptBindings/AudioMixerDescription.bindings.h")] internal partial class MixerEffectDefinitions { private extern static void ClearDefinitionsRuntime(); extern private static void AddDefinitionRuntime(string name, MixerParameterDefinition[] parameters); extern public static string[] GetAudioEffectNames(); extern public static MixerParameterDefinition[] GetAudioEffectParameterDesc(string effectName); //Change to use effect public extern static bool EffectCanBeSidechainTarget(AudioMixerEffectController effect); } }
UnityCsReference/Modules/AudioEditor/ScriptBindings/AudioMixerDescription.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AudioEditor/ScriptBindings/AudioMixerDescription.bindings.cs", "repo_id": "UnityCsReference", "token_count": 399 }
381
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; using System.Runtime.Serialization; using UnityEngine; namespace UnityEditor.Build.Content { [Serializable] [UsedByNativeCode] [NativeHeader("Modules/BuildPipeline/Editor/Public/BuildUsageTagSet.h")] public class BuildUsageTagSet : ISerializable, IDisposable { private IntPtr m_Ptr; public BuildUsageTagSet() { m_Ptr = Internal_Create(); } ~BuildUsageTagSet() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (m_Ptr != IntPtr.Zero) { Internal_Destroy(m_Ptr); m_Ptr = IntPtr.Zero; } } [NativeMethod(IsThreadSafe = true)] private static extern IntPtr Internal_Create(); [NativeMethod(IsThreadSafe = true)] private static extern void Internal_Destroy(IntPtr ptr); [NativeMethod(IsThreadSafe = true)] public extern Hash128 GetHash128(); [NativeMethod(IsThreadSafe = true)] internal extern string SerializeToJson(); [NativeMethod(IsThreadSafe = true)] internal extern void DeserializeFromJson(string data); [ThreadSafe] internal extern byte[] SerializeToBinary(); [ThreadSafe] internal extern void DeserializeFromBinary([Out] byte[] data); [NativeMethod(IsThreadSafe = true)] internal extern string GetBuildUsageJson(ObjectIdentifier objectId); [NativeMethod(IsThreadSafe = true)] public extern ObjectIdentifier[] GetObjectIdentifiers(); [NativeMethod(IsThreadSafe = true)] public extern void UnionWith(BuildUsageTagSet other); [NativeMethod(IsThreadSafe = true)] public extern void FilterToSubset(ObjectIdentifier[] objectIds); public override bool Equals(object obj) { BuildUsageTagSet other = obj as BuildUsageTagSet; if (other == null) return false; return other.GetHash128() == GetHash128(); } public override int GetHashCode() { return GetHash128().GetHashCode(); } public void GetObjectData(System.Runtime.Serialization.SerializationInfo info, StreamingContext context) { byte[] data = SerializeToBinary(); info.AddValue("tags", data); } protected BuildUsageTagSet(System.Runtime.Serialization.SerializationInfo info, StreamingContext context) { m_Ptr = Internal_Create(); byte[] data = (byte[])info.GetValue("tags", typeof(byte[])); DeserializeFromBinary(data); } internal static class BindingsMarshaller { public static IntPtr ConvertToNative(BuildUsageTagSet buildUsageTagSet) => buildUsageTagSet.m_Ptr; } } }
UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildUsageTagSet.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildUsageTagSet.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1375 }
382
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.Modules; using UnityEditor.Build.Profile.Elements; using UnityEngine.UIElements; namespace UnityEditor.Build.Profile { [CustomEditor(typeof(BuildProfile))] internal class BuildProfileEditor : Editor { const string k_Uxml = "BuildProfile/UXML/BuildProfileEditor.uxml"; const string k_PlatformSettingPropertyName = "m_PlatformBuildProfile"; const string k_PlatformWarningHelpBox = "platform-warning-help-box"; const string k_BuildSettingsLabel = "build-settings-label"; const string k_PlatformSettingsBaseRoot = "platform-settings-base-root"; const string k_BuildDataLabel = "build-data-label"; const string k_SharedSettingsInfoHelpbox = "shared-settings-info-helpbox"; const string k_SharedSettingsInfoHelpboxButton = "shared-settings-info-helpbox-button"; const string k_SceneListFoldout = "scene-list-foldout"; const string k_SceneListFoldoutRoot = "scene-list-foldout-root"; const string k_SceneListFoldoutClassicSection = "scene-list-foldout-classic-section"; const string k_SceneListFoldoutClassicButton = "scene-list-foldout-classic-button"; const string k_CompilingWarningHelpBox = "compiling-warning-help-box"; const string k_VirtualTextureWarningHelpBox = "virtual-texture-warning-help-box"; BuildProfileSceneList m_SceneList; HelpBox m_CompilingWarningHelpBox; HelpBox m_VirtualTexturingHelpBox; BuildProfile m_Profile; public BuildProfileWindow parent { get; set; } public BuildProfileWorkflowState parentState { get; set; } public BuildProfileWorkflowState editorState { get; set; } public BuildProfileWorkflowState platformSettingsState { get; set; } internal BuildProfile buildProfile => m_Profile; IBuildProfileExtension m_PlatformExtension = null; public BuildProfileEditor() { editorState = new BuildProfileWorkflowState((next) => { if (editorState.buildAction == ActionState.Disabled) editorState.buildAndRunAction = ActionState.Disabled; if (editorState.additionalActions != next.additionalActions) editorState.additionalActions = next.additionalActions; parentState?.Apply(next); }); platformSettingsState = new BuildProfileWorkflowState((next) => { if (editorState.buildAction == ActionState.Disabled) next.buildAction = ActionState.Disabled; if (editorState.buildAndRunAction == ActionState.Disabled || next.buildAction == ActionState.Disabled) next.buildAndRunAction = ActionState.Disabled; editorState?.Apply(next); }); } public override VisualElement CreateInspectorGUI() { if (serializedObject.targetObject is not BuildProfile profile) { throw new InvalidOperationException("Editor object is not of type BuildProfile."); } m_Profile = profile; CleanupEventHandlers(); var root = new VisualElement(); var visualTree = EditorGUIUtility.LoadRequired(k_Uxml) as VisualTreeAsset; var windowUss = EditorGUIUtility.LoadRequired(Util.k_StyleSheet) as StyleSheet; visualTree.CloneTree(root); root.styleSheets.Add(windowUss); var noModuleFoundHelpBox = root.Q<HelpBox>(k_PlatformWarningHelpBox); var platformSettingsLabel = root.Q<Label>(k_BuildSettingsLabel); var platformSettingsBaseRoot = root.Q<VisualElement>(k_PlatformSettingsBaseRoot); var buildDataLabel = root.Q<Label>(k_BuildDataLabel); var sharedSettingsInfoHelpBox = root.Q<HelpBox>(k_SharedSettingsInfoHelpbox); m_VirtualTexturingHelpBox = root.Q<HelpBox>(k_VirtualTextureWarningHelpBox); m_CompilingWarningHelpBox = root.Q<HelpBox>(k_CompilingWarningHelpBox); m_VirtualTexturingHelpBox.text = TrText.invalidVirtualTexturingSettingMessage; m_CompilingWarningHelpBox.text = TrText.compilingMessage; platformSettingsLabel.text = TrText.platformSettings; buildDataLabel.text = TrText.buildData; sharedSettingsInfoHelpBox.text = TrText.sharedSettingsInfo; AddSceneList(root, profile); if (!BuildProfileContext.IsClassicPlatformProfile(profile)) sharedSettingsInfoHelpBox.Hide(); else { var button = root.Q<Button>(k_SharedSettingsInfoHelpboxButton); button.text = TrText.addBuildProfile; button.clicked += parent.DuplicateSelectedClassicProfile; } bool hasErrors = Util.UpdatePlatformRequirementsWarningHelpBox(noModuleFoundHelpBox, profile.moduleName, profile.subtarget); if (hasErrors) return root; EditorApplication.update += UpdateWarningsAndButtonStatesForActiveProfile; ShowPlatformSettings(profile, platformSettingsBaseRoot); return root; } /// <summary> /// Create modified GUI for shared setting amongst classic platforms. /// </summary> public VisualElement CreateLegacyGUI() { CleanupEventHandlers(); var root = new VisualElement(); var visualTree = EditorGUIUtility.LoadRequired(k_Uxml) as VisualTreeAsset; var windowUss = EditorGUIUtility.LoadRequired(Util.k_StyleSheet) as StyleSheet; visualTree.CloneTree(root); root.styleSheets.Add(windowUss); root.Q<HelpBox>(k_PlatformWarningHelpBox).Hide(); root.Q<Label>(k_BuildSettingsLabel).Hide(); root.Q<VisualElement>(k_PlatformSettingsBaseRoot).Hide(); root.Q<HelpBox>(k_VirtualTextureWarningHelpBox).Hide(); root.Q<HelpBox>(k_CompilingWarningHelpBox).Hide(); root.Q<Button>(k_SharedSettingsInfoHelpboxButton).Hide(); var sharedSettingsHelpbox = root.Q<HelpBox>(k_SharedSettingsInfoHelpbox); sharedSettingsHelpbox.text = TrText.sharedSettingsSectionInfo; var sectionLabel = root.Q<Label>(k_BuildDataLabel); sectionLabel.AddToClassList("text-large"); sectionLabel.text = TrText.sceneList; AddSceneList(root); return root; } void OnDisable() { CleanupEventHandlers(); if (m_PlatformExtension != null) m_PlatformExtension.OnDisable(); } internal void OnActivateClicked() { editorState.buildAndRunButtonDisplayName = platformSettingsState.buildAndRunButtonDisplayName; editorState.buildButtonDisplayName = platformSettingsState.buildButtonDisplayName; editorState.UpdateBuildActionStates(ActionState.Disabled, ActionState.Disabled); } void UpdateWarningsAndButtonStatesForActiveProfile() { if (!m_Profile.IsActiveBuildProfileOrPlatform()) return; bool isVirtualTexturingValid = BuildProfileModuleUtil.IsVirtualTexturingSettingsValid(m_Profile.buildTarget); bool isCompiling = EditorApplication.isCompiling || EditorApplication.isUpdating; UpdateHelpBoxVisibility(m_VirtualTexturingHelpBox, !isVirtualTexturingValid); UpdateHelpBoxVisibility(m_CompilingWarningHelpBox, isCompiling); if (!isVirtualTexturingValid || isCompiling) { editorState.UpdateBuildActionStates(ActionState.Disabled, ActionState.Disabled); } else { editorState.UpdateBuildActionStates(ActionState.Enabled, ActionState.Enabled); } } void UpdateHelpBoxVisibility(HelpBox helpBox, bool showHelpBox) { if (showHelpBox && helpBox.resolvedStyle.display == DisplayStyle.None) { helpBox.Show(); } else if (!showHelpBox && helpBox.resolvedStyle.display != DisplayStyle.None) { helpBox.Hide(); } } void ShowPlatformSettings(BuildProfile profile, VisualElement platformSettingsBaseRoot) { var platformProperties = serializedObject.FindProperty(k_PlatformSettingPropertyName); m_PlatformExtension = BuildProfileModuleUtil.GetBuildProfileExtension(profile.buildTarget); if (m_PlatformExtension != null) { var settings = m_PlatformExtension.CreateSettingsGUI( serializedObject, platformProperties, platformSettingsState); platformSettingsBaseRoot.Add(settings); } } void AddSceneList(VisualElement root, BuildProfile profile = null) { // On no build profile show EditorBuildSetting scene list, // classic platforms show read-only version. bool isGlobalSceneList = profile == null; bool isClassicPlatform = !isGlobalSceneList && BuildProfileContext.IsClassicPlatformProfile(profile); bool isEnable = isGlobalSceneList || !isClassicPlatform; var sceneListFoldout = root.Q<Foldout>(k_SceneListFoldout); sceneListFoldout.text = TrText.sceneList; m_SceneList = (isGlobalSceneList || isClassicPlatform) ? new BuildProfileSceneList() : new BuildProfileSceneList(profile); Undo.undoRedoEvent += m_SceneList.OnUndoRedo; var container = m_SceneList.GetSceneListGUI(sceneListFoldout, isEnable); container.SetEnabled(isEnable); root.Q<VisualElement>(k_SceneListFoldoutRoot).Add(container); if (isClassicPlatform) { // Bind Global Scene List button root.Q<VisualElement>(k_SceneListFoldoutClassicSection).Show(); var globalSceneListButton = root.Q<Button>(k_SceneListFoldoutClassicButton); globalSceneListButton.text = TrText.openSceneList; globalSceneListButton.clicked += () => { parent.OnClassicSceneListSelected(); }; } } void CleanupEventHandlers() { if (m_SceneList is not null) Undo.undoRedoEvent -= m_SceneList.OnUndoRedo; EditorApplication.update -= UpdateWarningsAndButtonStatesForActiveProfile; } } }
UnityCsReference/Modules/BuildProfileEditor/BuildProfileEditor.cs/0
{ "file_path": "UnityCsReference/Modules/BuildProfileEditor/BuildProfileEditor.cs", "repo_id": "UnityCsReference", "token_count": 4572 }
383
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using System.Text; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; using UnityEditor.Build.Reporting; namespace UnityEditor { internal class BuildReportRestService : ScriptableSingleton<BuildReportRestService> { public CancellationTokenSource m_cts; public HttpListener m_listener; public TaskScheduler m_mainThreadScheduler; public Thread m_listenerThread; public static Regex regex = new Regex(@"/unity/build-report/(?<reportid>\w+?)/(?<request>\w+)(?<args>(?:/\w*)+/?)?$"); public static Regex regexArgs = new Regex(@"/(?<type>\w+?)(?:/(?<index>\w+?))?(?:/(?<method>\w+?))?$"); public static BuildReport GetReport(string reportId) { if (reportId == "latest") return BuildReport.GetLatestReport(); return BuildReport.GetReport(new GUID(reportId)); } public BuildReportRestService() { } public string ProcessRequest(BuildReport report, string request, string args, HttpListenerContext context) { if (request == "report") return EditorJsonUtility.ToJson(report); if (request == "summary") return BuildReportRestAPI.GetSummaryResponse(report); if (request == "steps") return BuildReportRestAPI.GetStepsResponse(report); int depth = 0; try { depth = Int32.Parse(context.Request.QueryString["depth"]); } catch {}; // No ?depth=X if (request == "assets") return BuildReportRestAPI.GetAssetsResponse(report, args, depth); if (request == "files") return BuildReportRestAPI.GetFilesResponse(report, args, depth); if (request == "appendices") { Match matchArgs = regexArgs.Match(args); if (matchArgs.Success) { var type = matchArgs.Groups["type"]; var index = matchArgs.Groups["index"]; var method = matchArgs.Groups["method"]; if (type.Success && index.Success && method.Success) { string postData; using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) { postData = reader.ReadToEnd(); } return BuildReportRestAPI.GetAppendicesResponseWithMethod(report, type.ToString(), int.Parse(index.ToString()), method.ToString(), postData); } if (type.Success && index.Success) return BuildReportRestAPI.GetAppendicesResponseWithIndex(report, type.ToString(), int.Parse(index.ToString())); if (type.Success) return BuildReportRestAPI.GetAppendicesResponse(report, type.ToString()); } } return "{}"; } [InitializeOnLoadMethod] public static void BootStrapper() { BuildReportRestService.instance.Boot(); } public void RunServer() { m_listener = new HttpListener(); m_listener.Prefixes.Add("http://localhost:38000/unity/build-report/"); m_listener.Prefixes.Add("http://127.0.0.1:38000/unity/build-report/"); m_listener.Start(); while(!m_cts.IsCancellationRequested) { try{ HttpListenerContext context = m_listener.GetContext(); // We are only accepting local requests for the security reasons. if (!context.Request.IsLocal) continue; var host = context.Request.Headers["Host"]; // Protection from the DNS rebinding attacks (https://en.wikipedia.org/wiki/DNS_rebinding) if ( host != "localhost:38000" && host != "127.0.0.1:38000") continue; var split = context.Request.RawUrl.IndexOf("?"); string uri = split < 0 ? context.Request.RawUrl : context.Request.RawUrl.Substring(0, split); Match match = regex.Match(uri); string response = "{}"; if (match.Success) { Task t = new Task(() => { var report = GetReport(match.Groups["reportid"].ToString()); string request = match.Groups["request"].ToString(); string args = match.Groups["args"]?.ToString(); response = ProcessRequest(report, request, args, context); }); t.Start(m_mainThreadScheduler); m_cts = new CancellationTokenSource(); t.Wait(m_cts.Token); } byte[] buffer= System.Text.Encoding.UTF8.GetBytes(response); // Get a response stream and write the response to it. context.Response.ContentLength64 = buffer.Length; System.IO.Stream output = context.Response.OutputStream; output.Write(buffer,0,buffer.Length); output.Close(); } catch(TaskCanceledException) {} catch(HttpListenerException) {} catch(Exception e) { Debug.Log(e.Message); } } m_listener = null; } public void RunServerWithRetries(int retries) { for (int i=0; i<=retries && !m_cts.IsCancellationRequested; ++i) { try{ RunServer(); return; } catch(SocketException) { // We had an instances where on our infrastructure domain reload happened // and socket is still not free. In such a case we are retrying this multiple // times before giving up on starting server. for (int j=0; j<5 && !m_cts.IsCancellationRequested; ++j) Thread.Sleep(50); } catch(Exception e) { throw e; } } } public void Boot() {} public void OnEnable() { if (AssetDatabase.IsAssetImportWorkerProcess()) return; m_mainThreadScheduler = TaskScheduler.FromCurrentSynchronizationContext(); m_cts = new CancellationTokenSource(); m_listenerThread = new Thread(()=>RunServerWithRetries(20)); m_listenerThread.Start(); } public void OnDisable() { if (AssetDatabase.IsAssetImportWorkerProcess()) return; m_cts.Cancel(); m_listener.Abort(); m_listenerThread.Join(); m_cts.Dispose(); } } }
UnityCsReference/Modules/BuildReportingEditor/Managed/BuildReportRestService.cs/0
{ "file_path": "UnityCsReference/Modules/BuildReportingEditor/Managed/BuildReportRestService.cs", "repo_id": "UnityCsReference", "token_count": 4040 }
384
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditor.Analytics { [NativeHeader("Modules/UnityConnect/UnityConnectSettings.h")] [NativeHeader("Modules/UnityConnect/UnityAnalytics/UnityAnalyticsSettings.h")] [StaticAccessor("GetUnityAnalyticsSettings()", StaticAccessorType.Dot)] public static partial class AnalyticsSettings { public static extern bool enabled { get; set; } public static extern bool testMode { get; set; } public static extern bool initializeOnStartup { get; set; } public static bool deviceStatsEnabledInBuild { get { return hasCoreStatsInBuild; } } public extern static bool packageRequiringCoreStatsPresent { [NativeMethod("GetPackageRequiringCoreStatsPresent")] get; [NativeMethod("SetPackageRequiringCoreStatsPresent")] set; } [StaticAccessor("GetUnityConnectSettings()", StaticAccessorType.Dot)] public static extern string eventUrl { get; set; } [StaticAccessor("GetUnityConnectSettings()", StaticAccessorType.Dot)] public static extern string configUrl { get; set; } [StaticAccessor("GetUnityConnectSettings()", StaticAccessorType.Dot)] public static extern string dashboardUrl { get; set; } internal static extern void SetEnabledServiceWindow(bool enabled); internal static extern bool enabledForPlatform { get; } internal static extern void ApplyEnableSettings(BuildTarget target); public delegate bool RequireInBuildDelegate(); public static event RequireInBuildDelegate OnRequireInBuildHandler = null; [RequiredByNativeCode] internal static bool RequiresCoreStatsInBuild() { if (OnRequireInBuildHandler == null) return false; Delegate[] invokeList = OnRequireInBuildHandler.GetInvocationList(); for (int i = 0; i < invokeList.Length; ++i) { RequireInBuildDelegate func = (RequireInBuildDelegate)invokeList[i]; if (func()) { packageRequiringCoreStatsPresent = true; return true; } } return false; } [StaticAccessor("GetUnityConnectSettings()", StaticAccessorType.Dot)] internal static extern bool hasCoreStatsInBuild { get; } } }
UnityCsReference/Modules/CloudServicesSettingsEditor/Analytics/ScriptBindings/AnalyticsSettings.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/CloudServicesSettingsEditor/Analytics/ScriptBindings/AnalyticsSettings.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1066 }
385
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace Unity.Audio { [NativeType(Header = "Modules/DSPGraph/Public/DSPSampleProvider.bindings.h")] internal partial struct DSPSampleProviderInternal { [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe int Internal_ReadUInt8FromSampleProvider(void* provider, int format, void* buffer, int length); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe int Internal_ReadSInt16FromSampleProvider(void* provider, int format, void* buffer, int length); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe int Internal_ReadFloatFromSampleProvider(void* provider, void* buffer, int length); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe ushort Internal_GetChannelCount(void* provider); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe uint Internal_GetSampleRate(void* provider); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe int Internal_ReadUInt8FromSampleProviderById(uint providerId, int format, void* buffer, int length); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe int Internal_ReadSInt16FromSampleProviderById(uint providerId, int format, void* buffer, int length); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe int Internal_ReadFloatFromSampleProviderById(uint providerId, void* buffer, int length); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe ushort Internal_GetChannelCountById(uint providerId); [NativeMethod(IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] public static extern unsafe uint Internal_GetSampleRateById(uint providerId); } }
UnityCsReference/Modules/DSPGraph/Public/ScriptBindings/DSPSampleProvider.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/DSPGraph/Public/ScriptBindings/DSPSampleProvider.bindings.cs", "repo_id": "UnityCsReference", "token_count": 740 }
386
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace UnityEditor.DeviceSimulation { public abstract class DeviceSimulatorPlugin { internal string resolvedTitle; public DeviceSimulator deviceSimulator { get; internal set; } public abstract string title { get; } public virtual void OnCreate() { } public virtual void OnDestroy() { } public virtual VisualElement OnCreateUI() { return null; } } }
UnityCsReference/Modules/DeviceSimulatorEditor/Plugins/DeviceSimulatorPlugin.cs/0
{ "file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/Plugins/DeviceSimulatorPlugin.cs", "repo_id": "UnityCsReference", "token_count": 253 }
387
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine.Playables { internal static class DataPlayableBinding { public static PlayableBinding Create<TDataStream, TPlayer>(string name, Object key) where TDataStream : new() where TPlayer : Object { return PlayableBinding.CreateInternal(name, key, typeof(TPlayer), CreateDataOutput<TDataStream>); } private static PlayableOutput CreateDataOutput<TDataStream>(PlayableGraph graph, string name) where TDataStream : new() { return UnityEngine.Playables.DataPlayableOutput.Create<TDataStream>(graph, name); } } }
UnityCsReference/Modules/Director/ScriptBindings/DataPlayableBinding.cs/0
{ "file_path": "UnityCsReference/Modules/Director/ScriptBindings/DataPlayableBinding.cs", "repo_id": "UnityCsReference", "token_count": 290 }
388
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.UIElements; using UnityEditor.Connect; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.StyleSheets; using System.Linq; using System.Text.RegularExpressions; namespace UnityEditor.Toolbars { [EditorToolbarElement("Services/Account", typeof(DefaultMainToolbar))] sealed class AccountDropdown : EditorToolbarDropdown { readonly TextElement m_TextElement; readonly VisualElement m_ArrowElement; private readonly VisualElement m_AccountIconElement; bool m_LoggedIn; public AccountDropdown() { name = "AccountDropdown"; text = L10n.Tr("Sign in"); m_AccountIconElement = this.Q<Image>(className: EditorToolbar.elementIconClassName); m_AccountIconElement.AddToClassList("unity-icon-account"); m_TextElement = this.Q<TextElement>(className: EditorToolbar.elementLabelClassName); m_TextElement.style.flexGrow = 1; m_TextElement.style.whiteSpace = WhiteSpace.NoWrap; m_TextElement.style.unityTextOverflowPosition = TextOverflowPosition.End; m_ArrowElement = this.Q(className: arrowClassName); clicked += () => { if (m_LoggedIn) ShowUserMenu(worldBound); else UnityConnect.instance.ShowLogin(); }; RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); } void OnAttachedToPanel(AttachToPanelEvent evt) { EditorApplication.update += CheckAvailability; UnityConnect.instance.StateChanged += OnStateChange; OnStateChange(UnityConnect.instance.connectInfo); } void OnDetachFromPanel(DetachFromPanelEvent evt) { EditorApplication.update -= CheckAvailability; UnityConnect.instance.StateChanged += OnStateChange; } void CheckAvailability() { style.display = MPE.ProcessService.level == MPE.ProcessLevel.Main ? DisplayStyle.Flex : DisplayStyle.None; } void OnStateChange(ConnectInfo state) { if (state.ready) m_LoggedIn = !UnityConnect.instance.isDisableUserLogin && state.loggedIn; Refresh(); } void Refresh() { m_AccountIconElement.style.display = m_LoggedIn ? DisplayStyle.Flex : DisplayStyle.None; m_AccountIconElement.style.visibility = m_LoggedIn ? Visibility.Visible : Visibility.Hidden; if (m_LoggedIn) { m_TextElement.text = GetUserInitials(UnityConnect.instance.userInfo.displayName); m_TextElement.style.maxWidth = 80; m_TextElement.style.textOverflow = TextOverflow.Ellipsis; m_TextElement.style.unityTextAlign = TextAnchor.MiddleLeft; m_ArrowElement.style.display = DisplayStyle.Flex; SetEnabled(true); } else { text = L10n.Tr("Sign in"); m_TextElement.style.maxWidth = InitialStyle.maxWidth; m_TextElement.style.textOverflow = TextOverflow.Clip; m_TextElement.style.unityTextAlign = TextAnchor.MiddleCenter; m_ArrowElement.style.display = DisplayStyle.None; SetEnabled(UnityConnect.instance.connectInfo.online); } } void ShowUserMenu(Rect dropDownRect) { var menu = new GenericMenu(); if (UnityConnect.instance.online) { var accountUrl = UnityConnect.instance.GetConfigurationURL(CloudConfigUrl.CloudPortal); menu.AddItem(EditorGUIUtility.TrTextContent("My account"), false, () => UnityConnect.instance.OpenAuthorizedURLInWebBrowser(accountUrl)); } else { menu.AddDisabledItem(EditorGUIUtility.TrTextContent("My account")); } var name = $"{L10n.Tr("Sign out")} {UnityConnect.instance.userInfo.displayName}"; menu.AddItem(new GUIContent(name), false, () => UnityConnect.instance.Logout()); if (!Application.HasProLicense()) { menu.AddSeparator(""); if (UnityConnect.instance.online) menu.AddItem(EditorGUIUtility.TrTextContent("Upgrade your Unity plan"), false, () => Application.OpenURL("https://store.unity.com/")); else menu.AddDisabledItem(EditorGUIUtility.TrTextContent("Upgrade your Unity plan")); } menu.DropDown(dropDownRect, true); } internal static string GetUserInitials(string name) { if(string.IsNullOrEmpty(name)) return string.Empty; var nameElements = Regex.Replace(name, @"/\s+/g", " ", RegexOptions.IgnoreCase).Trim().Split(' '); nameElements = nameElements.Where(element => !string.IsNullOrEmpty(element) && Regex.IsMatch(element[0].ToString(), @"[A-Za-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]")).ToArray() ?? new string[0]; if (nameElements.Length > 1) return $"{ nameElements[0][0] }{ nameElements[nameElements.Length - 1][0] }".ToUpper(); else if (nameElements.Length == 1) return $"{ nameElements[0][0] }".ToUpper(); return string.Empty; } } }
UnityCsReference/Modules/EditorToolbar/ToolbarElements/AccountDropdown.cs/0
{ "file_path": "UnityCsReference/Modules/EditorToolbar/ToolbarElements/AccountDropdown.cs", "repo_id": "UnityCsReference", "token_count": 2628 }
389
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting;
UnityCsReference/Modules/GameCenter/Public/GameCenterServices.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/GameCenter/Public/GameCenterServices.bindings.cs", "repo_id": "UnityCsReference", "token_count": 75 }
390
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using System.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { internal class GroupDropArea : VisualElement, IDropTarget { public bool CanAcceptDrop(List<ISelectable> selection) { if (selection.Count == 0) return false; return !selection.Cast<GraphElement>().Any(ge => !(ge is Edge) && (ge == null || ge is Group || !ge.IsGroupable())); } public bool DragLeave(DragLeaveEvent evt, IEnumerable<ISelectable> selection, IDropTarget leftTarget, ISelection dragSource) { RemoveFromClassList("dragEntered"); return true; } public bool DragEnter(DragEnterEvent evt, IEnumerable<ISelectable> selection, IDropTarget enteredTarget, ISelection dragSource) { return true; } public bool DragExited() { RemoveFromClassList("dragEntered"); return false; } public bool DragPerform(DragPerformEvent evt, IEnumerable<ISelectable> selection, IDropTarget dropTarget, ISelection dragSource) { Group group = parent.GetFirstAncestorOfType<Group>(); List<GraphElement> elemsToAdd = selection .Cast<GraphElement>() .Where(e => e != group && !group.containedElements.Contains(e) && !(e.GetContainingScope() is Group) && e.IsGroupable()) .ToList(); // ToList required here as the enumeration might be done again *after* the elements are added to the group if (elemsToAdd.Any()) { group.AddElements(elemsToAdd); } RemoveFromClassList("dragEntered"); return true; } public bool DragUpdated(DragUpdatedEvent evt, IEnumerable<ISelectable> selection, IDropTarget dropTarget, ISelection dragSource) { Group group = parent.GetFirstAncestorOfType<Group>(); bool canDrop = false; foreach (ISelectable selectedElement in selection) { if (selectedElement == group || selectedElement is Edge) continue; var selectedGraphElement = selectedElement as GraphElement; bool dropCondition = selectedGraphElement != null && !group.containedElements.Contains(selectedGraphElement) && !(selectedGraphElement.GetContainingScope() is Group) && selectedGraphElement.IsGroupable(); if (dropCondition) { canDrop = true; } } if (canDrop) { AddToClassList("dragEntered"); } else { RemoveFromClassList("dragEntered"); } return true; } internal void OnStartDragging(IMouseEvent evt, IEnumerable<GraphElement> elements) { if (evt.shiftKey) { Group group = parent.GetFirstAncestorOfType<Group>(); group.RemoveElements(elements); } } } }
UnityCsReference/Modules/GraphViewEditor/Elements/GroupDropArea.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/GroupDropArea.cs", "repo_id": "UnityCsReference", "token_count": 1590 }
391
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { public class TokenNode : Node { private Pill m_Pill; public Texture icon { get { return m_Pill.icon; } set { m_Pill.icon = value; } } public Port input { get { return m_Pill.left as Port; } } public Port output { get { return m_Pill.right as Port; } } public TokenNode(Port input, Port output) : base("UXML/GraphView/TokenNode.uxml") { AddStyleSheetPath("StyleSheets/GraphView/TokenNode.uss"); m_Pill = this.Q<Pill>(name: "pill"); if (input != null) { m_Pill.left = input; } if (output != null) { m_Pill.right = output; } ClearClassList(); AddToClassList("token-node"); } public bool highlighted { get { return m_Pill.highlighted; } set { m_Pill.highlighted = value; } } } }
UnityCsReference/Modules/GraphViewEditor/Elements/TokenNode.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/TokenNode.cs", "repo_id": "UnityCsReference", "token_count": 739 }
392
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { internal class Inserter : Manipulator { private GraphView m_GraphView; private IInsertLocation m_InsertLocation; public Inserter() { } protected override void RegisterCallbacksOnTarget() { if (!(target is VisualElement && target is IInsertLocation)) { throw new InvalidOperationException("Manipulator can only be added to an IInsertLocation VisualElement"); } m_InsertLocation = target as IInsertLocation; target.RegisterCallback<MouseOverEvent>(OnMouseOver); target.RegisterCallback<MouseOutEvent>(OnMouseOut); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseOverEvent>(OnMouseOver); target.UnregisterCallback<MouseOutEvent>(OnMouseOut); ResetInsertLocation(); m_InsertLocation = null; } private void ResetInsertLocation() { if (m_GraphView != null && m_GraphView.currentInsertLocation == m_InsertLocation) { m_GraphView.currentInsertLocation = null; } m_GraphView = null; } private void OnMouseOver(MouseOverEvent evt) { if (evt.button != 0) return; // Keep track of the graphview in case the target is removed while being hovered over. m_GraphView = (target as VisualElement).GetFirstAncestorOfType<GraphView>(); if (m_GraphView != null) { m_GraphView.currentInsertLocation = m_InsertLocation; } } private void OnMouseOut(MouseOutEvent evt) { ResetInsertLocation(); } } }
UnityCsReference/Modules/GraphViewEditor/Manipulators/Inserter.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Manipulators/Inserter.cs", "repo_id": "UnityCsReference", "token_count": 898 }
393
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; namespace UnityEditor.Experimental.GraphView { [EditorWindowTitle(title = k_ToolName)] public class GraphViewBlackboardWindow : GraphViewToolWindow { Blackboard m_Blackboard; const string k_ToolName = "Blackboard"; protected override string ToolName => k_ToolName; new void OnEnable() { base.OnEnable(); OnGraphViewChanged(); } void OnDisable() { if (m_SelectedGraphView != null && m_Blackboard != null) { m_SelectedGraphView.ReleaseBlackboard(m_Blackboard); } } protected override void OnGraphViewChanging() { if (m_Blackboard != null) { if (m_SelectedGraphView != null) { m_SelectedGraphView.ReleaseBlackboard(m_Blackboard); } rootVisualElement.Remove(m_Blackboard); m_Blackboard = null; } } protected override void OnGraphViewChanged() { if (m_SelectedGraphView != null) { m_Blackboard = m_SelectedGraphView.GetBlackboard(); m_Blackboard.windowed = true; rootVisualElement.Add(m_Blackboard); } else { m_Blackboard = null; } } protected override bool IsGraphViewSupported(GraphView gv) { return gv.supportsWindowedBlackboard; } } }
UnityCsReference/Modules/GraphViewEditor/Windows/GraphViewBlackboardWindow.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Windows/GraphViewBlackboardWindow.cs", "repo_id": "UnityCsReference", "token_count": 868 }
394
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.CompilerServices; using Unity.Collections; namespace Unity.Hierarchy { /// <summary> /// Represents a collection of <see cref="HierarchyNode"/> and values of type <typeparamref name="T"/> with O(1) access time. /// </summary> public struct HierarchyNodeMapUnmanaged<T> : IDisposable where T : unmanaged { NativeSparseArray<HierarchyNode, T> m_Values; /// <summary> /// Whether or not this object is valid and uses memory. /// </summary> public bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_Values.IsCreated; } /// <summary> /// The number of elements that can be contained in the <see cref="HierarchyNodeMapUnmanaged{T}"/> without resizing. /// </summary> public int Capacity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_Values.Capacity; [MethodImpl(MethodImplOptions.AggressiveInlining)] set => m_Values.Capacity = value; } /// <summary> /// The number of elements contained in the <see cref="HierarchyNodeMapUnmanaged{T}"/>. /// </summary> public int Count => m_Values.Count; /// <summary> /// Gets or sets the value associated with the specified <see cref="HierarchyNode"/>. /// </summary> /// <param name="node">The hierarchy node.</param> /// <returns>The value associated with the specified <see cref="HierarchyNode"/>.</returns> public T this[in HierarchyNode node] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get => m_Values[node]; [MethodImpl(MethodImplOptions.AggressiveInlining)] set => m_Values[node] = value; } /// <summary> /// Constructs a new <see cref="HierarchyNodeMapUnmanaged{T}"/>. /// </summary> /// <param name="allocator">The memory allocator.</param> public HierarchyNodeMapUnmanaged(Allocator allocator) { m_Values = new NativeSparseArray<HierarchyNode, T>(KeyIndex, KeyEqual, allocator); } /// <summary> /// Constructs a new <see cref="HierarchyNodeMapUnmanaged{T}"/>. /// </summary> /// <param name="initValue">The value to use to initialize memory.</param> /// <param name="allocator">The memory allocator.</param> public HierarchyNodeMapUnmanaged(in T initValue, Allocator allocator) { m_Values = new NativeSparseArray<HierarchyNode, T>(in initValue, KeyIndex, KeyEqual, allocator); } /// <summary> /// Dispose this object and release its memory. /// </summary> public void Dispose() { m_Values.Dispose(); } /// <summary> /// Reserve enough memory to contain the specified number of elements. /// </summary> /// <param name="capacity">The requested capacity.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reserve(int capacity) { m_Values.Reserve(capacity); } /// <summary> /// Determine whether or not the <see cref="HierarchyNodeMapUnmanaged{T}"/> contains the specified <see cref="HierarchyNode"/>. /// </summary> /// <param name="node">The hierarchy node.</param> /// <returns><see langword="true"/> if the <see cref="HierarchyNodeMapUnmanaged{T}"/> contains the specified <see cref="HierarchyNode"/>, <see langword="false"/> otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsKey(in HierarchyNode node) { return m_Values.ContainsKey(in node); } /// <summary> /// Adds the specified <see cref="HierarchyNode"/> and value to the <see cref="HierarchyNodeMapUnmanaged{T}"/>. /// </summary> /// <param name="node">The hierarchy node.</param> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Add(in HierarchyNode node, in T value) { m_Values.Add(in node, in value); } /// <summary> /// Adds the specified <see cref="HierarchyNode"/> and value to the <see cref="HierarchyNodeMapUnmanaged{T}"/> without increasing capacity. /// </summary> /// <param name="node">The hierarchy node.</param> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AddNoResize(in HierarchyNode node, in T value) { m_Values.AddNoResize(in node, in value); } /// <summary> /// Attempts to add the specified <see cref="HierarchyNode"/> and value to the <see cref="HierarchyNodeMapUnmanaged{T}"/>. /// </summary> /// <param name="node">The hierarchy node.</param> /// <param name="value">The value.</param> /// <returns><see langword="true"/> if the <see cref="HierarchyNode"/>/value pair was added to the <see cref="HierarchyNodeMapUnmanaged{T}"/>, <see langword="false"/> otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAdd(in HierarchyNode node, in T value) { return m_Values.TryAdd(in node, in value); } /// <summary> /// Attempts to add the specified <see cref="HierarchyNode"/> and value to the <see cref="HierarchyNodeMapUnmanaged{T}"/> without increasing capacity. /// </summary> /// <param name="node">The hierarchy node.</param> /// <param name="value">The value.</param> /// <returns><see langword="true"/> if the <see cref="HierarchyNode"/>/value pair was added to the <see cref="HierarchyNodeMapUnmanaged{T}"/>, <see langword="false"/> otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAddNoResize(in HierarchyNode node, in T value) { return m_Values.TryAddNoResize(in node, in value); } /// <summary> /// Gets the value associated with the specified <see cref="HierarchyNode"/>. /// </summary> /// <param name="node">The hierarchy node.</param> /// <param name="value">The value.</param> /// <returns><see langword="true"/> if the <see cref="HierarchyNodeMapUnmanaged{T}"/> contains the specified <see cref="HierarchyNode"/>, <see langword="false"/> otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetValue(in HierarchyNode node, out T value) { return m_Values.TryGetValue(in node, out value); } /// <summary> /// Removes the value with the specified <see cref="HierarchyNode"/> from the <see cref="HierarchyNodeMapUnmanaged{T}"/>. /// </summary> /// <param name="node">The hierarchy node.</param> /// <returns><see langword="true"/> if the <see cref="HierarchyNode"/> is found and removed, <see langword="false"/> otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Remove(in HierarchyNode node) { return m_Values.Remove(in node); } /// <summary> /// Removes all <see cref="HierarchyNode"/> and values from the <see cref="HierarchyNodeMapUnmanaged{T}"/>. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clear() { m_Values.Clear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] static int KeyIndex(in HierarchyNode node) { return node.Id - 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool KeyEqual(in HierarchyNode lhs, in HierarchyNode rhs) { return lhs.Version == rhs.Version; } } }
UnityCsReference/Modules/HierarchyCore/Managed/HierarchyNodeMapUnmanaged.cs/0
{ "file_path": "UnityCsReference/Modules/HierarchyCore/Managed/HierarchyNodeMapUnmanaged.cs", "repo_id": "UnityCsReference", "token_count": 3326 }
395
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; namespace Unity.Hierarchy { /// <summary> /// Represents a hierarchy property ID. /// </summary> [NativeType(Header = "Modules/HierarchyCore/Public/HierarchyPropertyId.h")] [StructLayout(LayoutKind.Sequential)] readonly struct HierarchyPropertyId : IEquatable<HierarchyPropertyId> { const int k_HierarchyPropertyIdNull = 0; static readonly HierarchyPropertyId s_Null; readonly int m_Id; /// <summary> /// Represents a hierarchy property that is null or invalid. /// </summary> public static ref readonly HierarchyPropertyId Null => ref s_Null; /// <summary> /// The unique identification number of the hierarchy property. /// </summary> public int Id => m_Id; /// <summary> /// Creates a null property ID. /// </summary> public HierarchyPropertyId() { m_Id = k_HierarchyPropertyIdNull; } internal HierarchyPropertyId(int id) { m_Id = id; } public static bool operator ==(in HierarchyPropertyId lhs, in HierarchyPropertyId rhs) => lhs.Id == rhs.Id; public static bool operator !=(in HierarchyPropertyId lhs, in HierarchyPropertyId rhs) => !(lhs == rhs); public bool Equals(HierarchyPropertyId other) => other.Id == Id; public override string ToString() => $"{nameof(HierarchyPropertyId)}({(this == Null ? nameof(Null) : Id)})"; public override bool Equals(object obj) => obj is HierarchyPropertyId node && Equals(node); public override int GetHashCode() => Id.GetHashCode(); } }
UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyPropertyId.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyPropertyId.bindings.cs", "repo_id": "UnityCsReference", "token_count": 718 }
396
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine { // The contents of a GUI element. [StructLayout(LayoutKind.Sequential)] [Serializable] [NativeHeader("Modules/IMGUI/GUIContent.h")] [RequiredByNativeCode(Optional = true, GenerateProxy = true)] public class GUIContent { // MUST MATCH MEMORY LAYOUT IN GUICONTENT.CPP [SerializeField] string m_Text = string.Empty; [SerializeField] Texture m_Image; [SerializeField] string m_Tooltip = string.Empty; [SerializeField] string m_TextWithWhitespace = string.Empty; internal event Action OnTextChanged; private static readonly GUIContent s_Text = new GUIContent(); private static readonly GUIContent s_Image = new GUIContent(); private static readonly GUIContent s_TextImage = new GUIContent(); internal static string k_ZeroWidthSpace = "\u200B"; // The text contained. public string text { get { return m_Text; } set { if (m_Text == value) return; m_Text = value; textWithWhitespace = value; OnTextChanged?.Invoke(); } } internal string textWithWhitespace { get { return string.IsNullOrEmpty(m_TextWithWhitespace) ? k_ZeroWidthSpace : m_TextWithWhitespace; } set => //The NoWidthSpace unicode is added at the end of the string to make sure LineFeeds update the layout of the text. m_TextWithWhitespace = value + k_ZeroWidthSpace; } internal void SetTextWithoutNotify(string value) { m_Text = value; textWithWhitespace = value; } // The icon image contained. public Texture image { get { return m_Image; } set { m_Image = value; } } // The tooltip of this element. public string tooltip { get { return m_Tooltip; } set { m_Tooltip = value; } } // Constructor for GUIContent in all shapes and sizes public GUIContent() {} // Build a GUIContent object containing only text. public GUIContent(string text) : this(text, null, string.Empty) {} // Build a GUIContent object containing only an image. public GUIContent(Texture image) : this(string.Empty, image, string.Empty) {} // Build a GUIContent object containing both /text/ and an image. public GUIContent(string text, Texture image) : this(text, image, string.Empty) {} // Build a GUIContent containing some /text/. When the user hovers the mouse over it, the global GUI::ref::tooltip is set to the /tooltip/. public GUIContent(string text, string tooltip) : this(text, null, tooltip) {} // Build a GUIContent containing an image. When the user hovers the mouse over it, the global GUI::ref::tooltip is set to the /tooltip/. public GUIContent(Texture image, string tooltip) : this(string.Empty, image, tooltip) {} // Build a GUIContent that contains both /text/, an /image/ and has a /tooltip/ defined. When the user hovers the mouse over it, the global GUI::ref::tooltip is set to the /tooltip/. public GUIContent(string text, Texture image, string tooltip) { this.text = text; this.image = image; this.tooltip = tooltip; } // Build a GUIContent as a copy of another GUIContent. public GUIContent(GUIContent src) { text = src.m_Text; image = src.m_Image; tooltip = src.m_Tooltip; } // Shorthand for empty content. public static GUIContent none = new GUIContent(""); // *undocumented* internal int hash { get { int h = 0; if (!string.IsNullOrEmpty(m_Text)) h = m_Text.GetHashCode() * 37; return h; } } internal static GUIContent Temp(string t) { s_Text.m_Text = t; s_Text.textWithWhitespace = t; s_Text.m_Tooltip = string.Empty; return s_Text; } internal static GUIContent Temp(string t, string tooltip) { s_Text.m_Text = t; s_Text.textWithWhitespace = t; s_Text.m_Tooltip = tooltip; return s_Text; } internal static GUIContent Temp(Texture i) { s_Image.m_Image = i; s_Image.m_Tooltip = string.Empty; return s_Image; } internal static GUIContent Temp(Texture i, string tooltip) { s_Image.m_Image = i; s_Image.m_Tooltip = tooltip; return s_Image; } internal static GUIContent Temp(string t, Texture i) { s_TextImage.m_Text = t; s_Text.textWithWhitespace = t; s_TextImage.m_Image = i; return s_TextImage; } [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static void ClearStaticCache() { s_Text.m_Text = null; s_Text.m_TextWithWhitespace = null; s_Text.m_Tooltip = string.Empty; s_Image.m_Image = null; s_Image.m_Tooltip = string.Empty; s_Image.m_TextWithWhitespace = null; s_TextImage.m_Text = null; s_TextImage.m_Image = null; s_TextImage.m_TextWithWhitespace = null; } internal static GUIContent[] Temp(string[] texts) { GUIContent[] retval = new GUIContent[texts.Length]; for (int i = 0; i < texts.Length; i++) { retval[i] = new GUIContent(texts[i]); } return retval; } internal static GUIContent[] Temp(Texture[] images) { GUIContent[] retval = new GUIContent[images.Length]; for (int i = 0; i < images.Length; i++) { retval[i] = new GUIContent(images[i]); } return retval; } public override string ToString() { return text ?? tooltip ?? base.ToString(); } } }
UnityCsReference/Modules/IMGUI/GUIContent.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/GUIContent.cs", "repo_id": "UnityCsReference", "token_count": 3287 }
397
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace UnityEngine { // Utility class for making new GUI controls. [NativeHeader("Modules/IMGUI/GUIUtility.h"), NativeHeader("Modules/IMGUI/GUIManager.h"), NativeHeader("Runtime/Input/InputBindings.h"), NativeHeader("Runtime/Input/InputManager.h"), NativeHeader("Runtime/Camera/RenderLayers/GUITexture.h"), NativeHeader("Runtime/Utilities/CopyPaste.h")] public partial class GUIUtility { // Check to see if there's a modal IMGUI window that's currently open public static extern bool hasModalWindow { get; } [NativeProperty("GetGUIState().m_PixelsPerPoint", true, TargetType.Field)] internal static extern float pixelsPerPoint { [VisibleToOtherModules("UnityEngine.UIElementsModule")] get; [VisibleToOtherModules("UnityEngine.UIElementsModule")] set; } [NativeProperty("GetGUIState().m_OnGUIDepth", true, TargetType.Field)] internal static extern int guiDepth { [VisibleToOtherModules("UnityEngine.UIElementsModule")] get; } internal static extern Vector2 s_EditorScreenPointOffset { [NativeMethod("GetGUIState().GetGUIPixelOffset", true)] get; [NativeMethod("GetGUIState().SetGUIPixelOffset", true)] set; } [NativeProperty("GetGUIState().m_CanvasGUIState.m_IsMouseUsed", true, TargetType.Field)] internal static extern bool mouseUsed { get; set; } [StaticAccessor("GetInputManager()", StaticAccessorType.Dot)] internal static extern bool textFieldInput { get; set; } internal static extern bool manualTex2SRGBEnabled { [FreeFunction("GUITexture::IsManualTex2SRGBEnabled")] get; [FreeFunction("GUITexture::SetManualTex2SRGBEnabled")] set; } // Get access to the system-wide pasteboard. public static extern string systemCopyBuffer { [FreeFunction("GetCopyBuffer")] get; [FreeFunction("SetCopyBuffer")] set; } [FreeFunction("GetGUIState().GetControlID")] static extern int Internal_GetControlID(int hint, FocusType focusType, Rect rect); // Control counting is required by ReorderableList. Element rendering callbacks can change and use // different number of controls to represent an element each frame. We need a way to be able to track // if the control count changed from the last frame so we can recache those elements. internal static int s_ControlCount = 0; public static int GetControlID(int hint, FocusType focusType, Rect rect) { s_ControlCount++; return Internal_GetControlID(hint, focusType, rect); } [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static extern void BeginContainerFromOwner(ScriptableObject owner); [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static extern void BeginContainer(ObjectGUIState objectGUIState); [NativeMethod("EndContainer")] internal static extern void Internal_EndContainer(); [FreeFunction("GetSpecificGUIState(0).m_EternalGUIState->GetNextUniqueID")] internal static extern int GetPermanentControlID(); [StaticAccessor("GetUndoManager()", StaticAccessorType.Dot)] internal static extern void UpdateUndoName(); [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static extern int CheckForTabEvent(Event evt); [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static extern void SetKeyboardControlToFirstControlId(); [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static extern void SetKeyboardControlToLastControlId(); [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static extern bool HasFocusableControls(); [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal static extern bool OwnsId(int id); public static extern Rect AlignRectToDevice(Rect rect, out int widthInPixels, out int heightInPixels); // Need to reverse the dependency here when moving native legacy Input code out of Core module. [StaticAccessor("InputBindings", StaticAccessorType.DoubleColon)] internal extern static string compositionString { get; } // Need to reverse the dependency here when moving native legacy Input code out of Core module. [StaticAccessor("InputBindings", StaticAccessorType.DoubleColon)] internal extern static IMECompositionMode imeCompositionMode { get; [VisibleToOtherModules("UnityEngine.UIElementsModule")] set; } // Need to reverse the dependency here when moving native legacy Input code out of Core module. [StaticAccessor("InputBindings", StaticAccessorType.DoubleColon)] internal extern static Vector2 compositionCursorPos { get; set; } // This is used in sensitive alignment-related operations. Avoid calling this method if you can. internal static extern Vector3 Internal_MultiplyPoint(Vector3 point, Matrix4x4 transform); internal static extern bool GetChanged(); internal static extern void SetChanged(bool changed); internal static extern void SetDidGUIWindowsEatLastEvent(bool value); private static extern int Internal_GetHotControl(); private static extern int Internal_GetKeyboardControl(); private static extern void Internal_SetHotControl(int value); private static extern void Internal_SetKeyboardControl(int value); private static extern System.Object Internal_GetDefaultSkin(int skinMode); private static extern Object Internal_GetBuiltinSkin(int skin); private static extern void Internal_ExitGUI(); private static extern Vector2 InternalWindowToScreenPoint(Vector2 windowPoint); private static extern Vector2 InternalScreenToWindowPoint(Vector2 screenPoint); } }
UnityCsReference/Modules/IMGUI/GUIUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/GUIUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2360 }
398