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 UnityEditor.Build.Reporting;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.Pool;
using UnityEngine.Rendering;
namespace UnityEditor.Build.Rendering
{
class RenderPipelineGlobalSettingsStripper : IPreprocessBuildWithReport, IPostprocessBuildWithReport
{
public int callbackOrder => (int) ExecutionOrder.StripRenderPipelineGlobalSettingsAsset;
static bool s_IsCurrentRenderPipelineGlobalsSettingsDirty;
static bool s_IsGraphicsSettingsDirty;
public void OnPreprocessBuild(BuildReport report)
{
s_IsCurrentRenderPipelineGlobalsSettingsDirty = false;
s_IsGraphicsSettingsDirty = false;
var renderPipelineAssets = ListPool<RenderPipelineAsset>.Get();
var buildTargetGroupName = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget).ToString();
QualitySettings.GetAllRenderPipelineAssetsForPlatform(buildTargetGroupName, ref renderPipelineAssets);
if (renderPipelineAssets.Count > 0 && renderPipelineAssets[0] != null)
{
// Top level stripping, even if there are multiple pipelines registered into the project, as we are building we are making sure the only one that is being transferred into the player is the current one.
if (renderPipelineAssets[0].pipelineType != null)
{
var renderPipelineGlobalSettingsAsset = EditorGraphicsSettings.GetRenderPipelineGlobalSettingsAsset(renderPipelineAssets[0].pipelineType);
if (renderPipelineGlobalSettingsAsset != null)
{
s_IsGraphicsSettingsDirty = EditorUtility.IsDirty(GraphicsSettings.GetGraphicsSettings());
s_IsCurrentRenderPipelineGlobalsSettingsDirty = EditorUtility.IsDirty(renderPipelineGlobalSettingsAsset);
// The asset needs to be dirty, in order to tell the BuildPlayer to always transfer the latest state of the asset.
// The main reason is due to IRenderPipelineGraphicsSettings stripping from the user side.
if (!s_IsCurrentRenderPipelineGlobalsSettingsDirty)
EditorUtility.SetDirty(renderPipelineGlobalSettingsAsset);
GraphicsSettings.currentRenderPipelineGlobalSettings = renderPipelineGlobalSettingsAsset;
}
}
else
Debug.LogWarning($"{renderPipelineAssets[0].GetType().Name} must inherit from {nameof(RenderPipelineAsset)}<T> instead of {nameof(RenderPipelineAsset)} to benefit from {nameof(RenderPipelineGlobalSettingsStripper)}.");
}
ListPool<RenderPipelineAsset>.Release(renderPipelineAssets);
}
public void OnPostprocessBuild(BuildReport report)
{
if (GraphicsSettings.currentRenderPipelineGlobalSettings != null)
{
// Clean the previous dirty flag.
if (!s_IsCurrentRenderPipelineGlobalsSettingsDirty)
EditorUtility.ClearDirty(GraphicsSettings.currentRenderPipelineGlobalSettings);
// Set to null the asset, and clean the dirty flag
GraphicsSettings.currentRenderPipelineGlobalSettings = null;
if (!s_IsGraphicsSettingsDirty)
EditorUtility.ClearDirty(GraphicsSettings.GetGraphicsSettings());
}
}
}
}
| UnityCsReference/Editor/Mono/BuildPipeline/RenderPipeline/RenderPipelineGlobalSettingsStripper.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildPipeline/RenderPipeline/RenderPipelineGlobalSettingsStripper.cs",
"repo_id": "UnityCsReference",
"token_count": 1485
} | 262 |
// 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;
using UnityEngine.Bindings;
using UnityEngine.UIElements;
namespace UnityEditor.Build.Profile
{
/// <summary>
/// Handles displaying tooltip view for renaming build profile
/// items with text field
/// </summary>
[VisibleToOtherModules("UnityEditor.BuildProfileModule")]
internal class BuildProfileRenameOverlay
{
static readonly string k_ErrorMessage = $"A file name can't contain any of the following characters:\t{BuildProfileModuleUtil.GetFilenameInvalidCharactersStr()}";
TextField m_TextField;
Rect? m_ErrorRect = null;
Rect errorRect
{
get
{
if (m_ErrorRect == null)
m_ErrorRect = GUIUtility.GUIToScreenRect(m_TextField.worldBound);
return m_ErrorRect.Value;
}
}
public BuildProfileRenameOverlay(TextField textField)
{
m_TextField = textField;
}
public void OnNameChanged(string previousValue, string newValue)
{
// It's fine to call show and close tooltip on multiple frames
// since it only opens if not opened before. Also it only closes if
// not closed before
if (HasInvalidCharacterIndex(newValue))
{
// We can't use the text field's tooltip property since it's displayed
// automatically on hover. So we use the TooltipView to display the
// error message (same way as the RenameOverlay used for assets)
TooltipView.Show(k_ErrorMessage, errorRect);
m_TextField.SetValueWithoutNotify(previousValue);
// The cursor should be kept in place when adding an invalid character
var targetIndex = Mathf.Max(m_TextField.cursorIndex - 1, 0);
m_TextField.cursorIndex = targetIndex;
m_TextField.selectIndex = targetIndex;
}
else
{
TooltipView.ForceClose();
}
}
public void OnRenameEnd()
{
// Make sure tooltip is closed
TooltipView.ForceClose();
}
bool HasInvalidCharacterIndex(string value)
{
return value.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0;
}
}
}
| UnityCsReference/Editor/Mono/BuildProfile/BuildProfileRenameOverlay.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/BuildProfile/BuildProfileRenameOverlay.cs",
"repo_id": "UnityCsReference",
"token_count": 1098
} | 263 |
// 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 abstract class ScriptableBakedReflectionSystem : IScriptableBakedReflectionSystem
{
public int stageCount { get; }
public Hash128[] stateHashes { get; protected set; }
protected ScriptableBakedReflectionSystem(int stageCount)
{
this.stageCount = stageCount;
}
public virtual void Tick(SceneStateHash sceneStateHash, IScriptableBakedReflectionSystemStageNotifier handle) {}
public virtual void SynchronizeReflectionProbes() {}
public virtual void Clear() {}
public virtual void Cancel() {}
public virtual bool BakeAllReflectionProbes() { return false; }
protected virtual void Dispose(bool disposing) {}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| UnityCsReference/Editor/Mono/Camera/ScriptableBakedReflectionSystem.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Camera/ScriptableBakedReflectionSystem.cs",
"repo_id": "UnityCsReference",
"token_count": 398
} | 264 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace Unity.CodeEditor
{
public interface IExternalCodeEditor
{
CodeEditor.Installation[] Installations { get; }
bool TryGetInstallationForPath(string editorPath, out CodeEditor.Installation installation);
void OnGUI();
void SyncIfNeeded(string[] addedFiles, string[] deletedFiles, string[] movedFiles, string[] movedFromFiles, string[] importedFiles);
void SyncAll();
void Initialize(string editorInstallationPath);
bool OpenProject(string filePath = "", int line = -1, int column = -1);
}
}
| UnityCsReference/Editor/Mono/CodeEditor/IExternalCodeEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/CodeEditor/IExternalCodeEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 232
} | 265 |
// 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.EditorTools;
using UnityEditor.Snap;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor.UIElements;
using Object = UnityEngine.Object;
namespace UnityEditor.Actions
{
public static class ContextMenuUtility
{
static void AddAction(DropdownMenu menu, string path, Action action, bool active = true)
{
menu.AppendAction(path, _ => action?.Invoke(),
_ => active ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled);
}
public static void AddMenuItem(DropdownMenu menu, string menuItemPath, string contextMenuPath = "")
{
AddMenuItemWithContext(menu, Selection.objects, menuItemPath, contextMenuPath);
}
public static void AddMenuItemWithContext(DropdownMenu menu, IEnumerable<Object> context, string menuItemPath, string contextMenuPath = "")
{
var contextArray = ToArray(context);
var enabled = Menu.GetEnabledWithContext(menuItemPath, contextArray);
AddMenuItemWithContext(menu, context, enabled, menuItemPath, contextMenuPath);
}
internal static void AddMenuItemWithContext(DropdownMenu menu, IEnumerable<Object> context, bool enabled, string menuItemPath, string contextMenuPath = "")
{
var contextArray = ToArray(context);
string shortcut = Menu.GetHotkey(menuItemPath);
string path = (string.IsNullOrEmpty(contextMenuPath) ? menuItemPath : contextMenuPath)
+ (string.IsNullOrEmpty(shortcut) ? "" : " " + shortcut);
AddAction(menu, path,
() => { EditorApplication.delayCall += () => ExecuteMenuItem(contextArray, menuItemPath); }, enabled);
}
static void ExecuteMenuItem(Object[] context, string menuItemPath)
{
// Claudia Antoun, 05-16-23, can safely be removed when UW-153 is fixed.
if (SceneView.lastActiveSceneView != null)
SceneView.lastActiveSceneView.Focus();
EditorApplication.ExecuteMenuItemWithTemporaryContext(menuItemPath, context);
}
public static void AddMenuItemsForType<T>(DropdownMenu menu, IEnumerable<T> targets) where T : Object
{
AddMenuItemsForType(menu, typeof(T), targets);
}
public static void AddMenuItemsForType(DropdownMenu menu, Type type, IEnumerable<Object> targets, string submenu = "")
{
var componentName = type.Name;
Menu.UpdateContextMenu(ToArray(targets), 0);
AddMenuItems(menu, componentName, Menu.GetMenuItems($"CONTEXT/{componentName}/", false, true), targets, submenu);
}
static void AddMenuItems(DropdownMenu menu, string componentName, ScriptingMenuItem[] items, IEnumerable<Object> targets, string submenu)
{
string context = $"CONTEXT/{componentName}/";
if (!string.IsNullOrEmpty(submenu) && submenu[^1] != '/')
submenu += '/';
int lastItemPriority = -1;
foreach (var menuItem in items)
{
var menuPath = menuItem.path;
var newPath = $"{submenu}{menuPath.Substring(context.Length)}";
// Add separator between items with priority differing by over 10 points
if (lastItemPriority != -1 && menuItem.priority > lastItemPriority + 10)
menu.AppendSeparator(newPath.Substring(0, newPath.LastIndexOf('/') + 1));
lastItemPriority = menuItem.priority;
if (!menuItem.isSeparator)
AddMenuItemWithContext(menu, targets, menuPath, newPath);
}
}
static void AddGameObjectClipboardEntriesTo(DropdownMenu menu)
{
var isThereGameObjectInSelection = Selection.gameObjects.Length > 0;
var isPasteEnabled = CutBoard.CanGameObjectsBePasted() || Unsupported.CanPasteGameObjectsFromPasteboard();
AddClipboardEntriesTo(menu, isThereGameObjectInSelection, isThereGameObjectInSelection, isPasteEnabled, isThereGameObjectInSelection, isThereGameObjectInSelection);
}
public static void AddClipboardEntriesTo(DropdownMenu menu)
{
var isThereGameObjectInSelection = Selection.gameObjects.Length > 0;
var isPasteEnabled = GUIUtility.systemCopyBuffer.Length > 0;
AddClipboardEntriesTo(menu, isThereGameObjectInSelection, isThereGameObjectInSelection, isPasteEnabled, isThereGameObjectInSelection, isThereGameObjectInSelection);
}
public static void AddClipboardEntriesTo(DropdownMenu menu, bool cutEnabled, bool copyEnabled, bool pasteEnabled, bool duplicateEnabled, bool deleteEnabled)
{
AddMenuItemWithContext(menu, null, cutEnabled, "Edit/Cut", "Cut");
AddMenuItemWithContext(menu, null, copyEnabled, "Edit/Copy", "Copy");
AddMenuItemWithContext(menu, null, pasteEnabled, "Edit/Paste", "Paste");
AddMenuItemWithContext(menu, null, duplicateEnabled, "Edit/Duplicate", "Duplicate");
AddMenuItemWithContext(menu, null, deleteEnabled, "Edit/Delete", "Delete");
}
public static void AddComponentEntriesTo(DropdownMenu menu)
{
var editors = ActiveEditorTracker.sharedTracker.activeEditors;
foreach (var editor in editors)
{
var type = editor.target.GetType();
if (type == typeof(GameObject) || type == typeof(Material))
continue;
Menu.UpdateContextMenu(editor.targets, 0);
var items = Menu.GetMenuItems($"CONTEXT/{type.Name}/", false, true);
if (items.Length == 0)
continue;
AddMenuItems(menu, type.Name, items, editor.targets, type.Name);
}
}
public static void AddGameObjectEntriesTo(DropdownMenu menu)
{
bool hasSelectedGO = Selection.gameObjects.Length > 0;
bool hasSelectedExactlyOneGO = Selection.gameObjects.Length == 1;
AddGameObjectClipboardEntriesTo(menu);
menu.AppendSeparator();
AddMenuItemWithContext(menu, null, "GameObject/Move To View", "Move to View");
AddMenuItemWithContext(menu, null, "GameObject/Align With View", "Align with View");
AddAction(menu, "Move to Grid Position", Shortcuts.PushToGrid, hasSelectedGO);
menu.AppendSeparator();
AddAction(menu,
SceneVisibilityState.isolation ? "Exit Isolation" : "Isolate",
SceneVisibilityManager.ToggleIsolateSelectionShortcut,
SceneVisibilityState.isolation || hasSelectedGO);
menu.AppendSeparator();
AddMenuItemWithContext(menu, null, "Component/Add...", "Add Component...");
AddMenuItemWithContext(menu, null, "Assets/Properties...", "Properties...");
// Prefab menu items that only make sense if a single object is selected.
var listOfSceneHierarchyWindows = SceneHierarchyWindow.GetAllSceneHierarchyWindows();
if (hasSelectedExactlyOneGO && listOfSceneHierarchyWindows.Count > 0)
listOfSceneHierarchyWindows[0].sceneHierarchy?.PopulateDropdownMenuWithPrefabMenuItems(menu);
// Component entries
if (hasSelectedGO)
{
menu.AppendSeparator();
AddComponentEntriesTo(menu);
}
}
internal static DropdownMenu CreateActionMenu()
{
var contextMenu = new DropdownMenu();
EditorToolManager.activeToolContext.PopulateMenu(contextMenu);
AddMenuItemsForType(contextMenu, ToolManager.activeContextType, EditorToolManager.activeToolContext.targets);
EditorToolManager.activeTool.PopulateMenu(contextMenu);
AddMenuItemsForType(contextMenu, ToolManager.activeToolType, EditorToolManager.activeTool.targets);
return contextMenu;
}
internal static void ShowActionMenu()
{
if (Event.current == null)
return;
var dropdownMenu = CreateActionMenu();
if (dropdownMenu.MenuItems().Count == 0)
AddAction(dropdownMenu, "No Actions for this Context", null, false);
dropdownMenu.DoDisplayEditorMenu(new Rect(Event.current.mousePosition, Vector2.zero));
}
static T[] ToArray<T>(IEnumerable<T> enumerable) where T : Object
{
if (enumerable == null)
return null;
if (enumerable is T[] arr)
return arr;
var size = 0;
foreach (var item in enumerable)
size++;
T[] items = new T[size];
var index = 0;
foreach (var item in enumerable)
{
items[index] = item;
index++;
}
return items;
}
}
}
| UnityCsReference/Editor/Mono/ContextMenuUtility.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ContextMenuUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 3930
} | 266 |
// 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
{
[InitializeOnLoad]
internal class DrivenRectTransformUndo
{
// Static constructor
static DrivenRectTransformUndo()
{
Undo.willFlushUndoRecord += ForceUpdateCanvases;
// After undo or redo performed, the 'driven values' & 'driven properties mask' need to be updated.
Undo.undoRedoEvent += OnUndoRedoPerformed;
}
static void ForceUpdateCanvases()
{
Canvas.ForceUpdateCanvases();
}
static void OnUndoRedoPerformed(in UndoRedoInfo info)
{
Canvas.ForceUpdateCanvases();
}
}
}
| UnityCsReference/Editor/Mono/DrivenRectTransformUndo.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/DrivenRectTransformUndo.cs",
"repo_id": "UnityCsReference",
"token_count": 349
} | 267 |
// 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;
using UnityEngine.Internal;
using UnityEngine.Bindings;
using Object = UnityEngine.Object;
namespace UnityEditor
{
// Custom mouse cursor shapes used with EditorGUIUtility.AddCursorRect.
// Must Match EditorWindow::MouseCursor
public enum MouseCursor
{
// Normal pointer arrow
Arrow = 0,
// Text cursor
Text = 1,
// Vertical resize arrows
ResizeVertical = 2,
// Horizontal resize arrows
ResizeHorizontal = 3,
// Arrow with a Link badge (for assigning pointers)
Link = 4,
// Arrow with small arrows for indicating sliding at number fields
SlideArrow = 5,
// Resize up-right for window edges
ResizeUpRight = 6,
// Resize up-Left for window edges.
ResizeUpLeft = 7,
// Arrow with the move symbol next to it for the sceneview
MoveArrow = 8,
// Arrow with the rotate symbol next to it for the sceneview
RotateArrow = 9,
// Arrow with the scale symbol next to it for the sceneview
ScaleArrow = 10,
// Arrow with the plus symbol next to it
ArrowPlus = 11,
// Arrow with the minus symbol next to it
ArrowMinus = 12,
// Cursor with a dragging hand for pan
Pan = 13,
// Cursor with an eye for orbit
Orbit = 14,
// Cursor with a magnifying glass for zoom
Zoom = 15,
// Cursor with an eye and stylized arrow keys for FPS navigation
FPS = 16,
// The current user defined cursor
CustomCursor = 17,
// Split resize up down arrows
SplitResizeUpDown = 18,
// Split resize left right arrows
SplitResizeLeftRight = 19,
// The requested action will not be carried out
NotAllowed = 20,
}
// User message types.
public enum MessageType
{
// Neutral message
None = 0,
// Info message
Info = 1,
// Warning message
Warning = 2,
// Error message
Error = 3
}
// Enum that selects which skin to return from EditorGUIUtility.GetBuiltinSkin
public enum EditorSkin
{
// The skin used for game views.
Game = 0,
// The skin used for inspectors.
Inspector = 1,
// The skin used for scene views.
Scene = 2
}
[NativeHeader("Editor/Src/EditorResources.h"),
NativeHeader("Runtime/Graphics/Texture2D.h"),
NativeHeader("Runtime/Graphics/RenderTexture.h"),
NativeHeader("Modules/TextRendering/Public/Font.h"),
NativeHeader("Editor/Src/Utility/EditorGUIUtility.h")]
public partial class EditorGUIUtility
{
public static extern string SerializeMainMenuToString();
public static extern void SetMenuLocalizationTestMode(bool onoff);
// Set icons rendered as part of [[GUIContent]] to be rendered at a specific size.
public static extern void SetIconSize(Vector2 size);
// Get a white texture.
public static extern Texture2D whiteTexture {[NativeMethod("GetWhiteTexture")] get; }
// Exactly the same as GUIUtility.systemCopyBuffer, but for some reason done
// as a separate public API :(
public new static string systemCopyBuffer
{
get => GUIUtility.systemCopyBuffer;
set => GUIUtility.systemCopyBuffer = value;
}
internal static extern int skinIndex
{
[FreeFunction("GetEditorResources().GetSkinIdx")] get;
[FreeFunction("GetEditorResources().SetSkinIdx")] set;
}
public static extern void SetWantsMouseJumping(int wantz);
// Iterates over cameras and counts the ones that would render to a specified screen (doesn't involve culling)
public static extern bool IsDisplayReferencedByCameras(int displayIndex);
// Send an input event into the game.
public static extern void QueueGameViewInputEvent(Event evt);
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("RenderGameViewCameras is no longer supported.Consider rendering cameras manually.", true)]
public static void RenderGameViewCameras(RenderTexture target, int targetDisplay, Rect screenRect, Vector2 mousePosition, bool gizmos) {}
internal static extern Object GetScript(string scriptClass);
public static extern void SetIconForObject([NotNull] Object obj, Texture2D icon);
[NativeThrows]
internal static extern Object GetBuiltinExtraResource(Type type, string path);
internal static extern BuiltinResource[] GetBuiltinResourceList(int classID);
internal static extern AssetBundle GetEditorAssetBundle();
internal static extern AssetBundle ReloadEditorAssetBundle();
internal static extern void SetRenderTextureNoViewport(RenderTexture rt);
internal static extern void SetVisibleLayers(int layers);
internal static extern void SetLockedLayers(int layers);
internal static extern bool IsGizmosAllowedForObject(Object obj);
internal static extern void SetCurrentViewCursor(Texture2D texture, Vector2 hotspot, MouseCursor type);
internal static extern void ClearCurrentViewCursor();
internal static extern void CleanCache(string text);
internal static extern void SetSearchIndexOfControlIDList(int index);
internal static extern int GetSearchIndexOfControlIDList();
internal static extern bool CanHaveKeyboardFocus(int id);
// Duplicate of SetDefaultFont in UnityEngine. We need to call it from editor code as well,
// while keeping both internal.
internal static extern void SetDefaultFont(Font font);
public static extern Texture2D GetIconForObject([NotNull] Object obj);
// Render all ingame cameras bound to a specific Display.
internal static extern void RenderPlayModeViewCamerasInternal(RenderTexture target, int targetDisplay, Vector2 mousePosition, bool gizmos, bool renderIMGUI);
internal static extern void SetupWindowSpaceAndVSyncInternal(Rect screenRect);
internal static extern void PerformTonemappingForGameView();
internal static extern void DrawTextureHdrSupport(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder,
int rightBorder, int topBorder, int bottomBorder, Color color, Material mat, int pass, bool resetLinearToSrgbIfHdrActive);
private static extern Texture2D FindTextureByName(string name);
private static extern Texture2D FindTextureByType([NotNull] Type type);
internal static extern string GetObjectNameWithInfo(Object obj);
private static extern string GetTypeNameWithInfo(string typeName, int instanceID);
private static extern void Internal_SetupEventValues(object evt);
private static extern Vector2 Internal_GetIconSize();
private static extern bool Internal_GetKeyboardRect(int id, out Rect rect);
private static extern void Internal_MoveKeyboardFocus(bool forward);
private static extern int Internal_GetNextKeyboardControlID(bool forward);
private static extern void Internal_AddCursorRect(Rect r, MouseCursor m, int controlID);
// preview materials handling
internal enum PreviewType
{
Color,
ColorVT,
Alpha,
AlphaVT,
Transparent,
TransparentVT,
Normalmap,
NormalmapVT,
LightmapRGBM,
LightmapDoubleLDR,
LightmapFullHDR,
GUITextureClipVertically,
}
internal static extern Material GetPreviewMaterial(PreviewType type);
}
[NativeHeader("Editor/Src/InspectorExpandedState.h"),
StaticAccessor("GetInspectorExpandedState().GetSessionState()", StaticAccessorType.Dot)]
public class SessionState
{
[ExcludeFromDocs] public SessionState() {}
public static extern void SetBool(string key, bool value);
public static extern bool GetBool(string key, bool defaultValue);
public static extern void EraseBool(string key);
public static extern void SetFloat(string key, float value);
public static extern float GetFloat(string key, float defaultValue);
public static extern void EraseFloat(string key);
public static extern void SetInt(string key, int value);
public static extern int GetInt(string key, int defaultValue);
public static extern void EraseInt(string key);
public static extern void SetString(string key, string value);
public static extern string GetString(string key, string defaultValue);
public static extern void EraseString(string key);
public static extern void SetVector3(string key, Vector3 value);
public static extern Vector3 GetVector3(string key, Vector3 defaultValue);
public static extern void EraseVector3(string key);
public static extern void EraseIntArray(string key);
public static extern void SetIntArray(string key, int[] value);
[return:Unmarshalled]
public static extern int[] GetIntArray(string key, [Unmarshalled]int[] defaultValue);
}
}
| UnityCsReference/Editor/Mono/EditorGUIUtility.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/EditorGUIUtility.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 3413
} | 268 |
// 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 Debug = UnityEngine.Debug;
using UnityEngine.Bindings;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using UnityEditor.Build;
using UnityEditor.Build.Profile;
using UnityEngine;
namespace UnityEditor
{
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
public enum StandaloneBuildSubtarget
{
// *undocumented*
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
Default = 0,
Player = 2,
Server = 1
}
namespace Build
{
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum OverrideTextureCompression
{
NoOverride = 0,
ForceUncompressed = 1,
ForceFastCompressor = 2,
ForceNoCrunchCompression = 3,
}
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum Il2CppCodeGeneration
{
OptimizeSpeed = 0,
OptimizeSize = 1
}
}
/// Target PS4 build platform.
///
/// SA: EditorUserBuildSettings.ps4BuildSubtarget.
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum PS4BuildSubtarget
{
/// Build package that it's hosted on the PC
/// SA: EditorUserBuildSettings.ps4BuildSubtarget.
PCHosted = 0,
/// Build a package suited for TestKit testing
/// SA: EditorUserBuildSettings.ps4BuildSubtarget.
Package = 1,
Iso = 2,
GP4Project = 3,
}
/// Target PS4 build Hardware Target.
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum PS4HardwareTarget
{
/// Target only Base hardware (works identically on Neo hardware)
BaseOnly = 0,
/// Obsolete. Use PS4ProAndBase instead.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Enum member PS4HardwareTarget.NeoAndBase has been deprecated. Use PS4HardwareTarget.ProAndBase instead (UnityUpgradable) -> ProAndBase", true)]
NeoAndBase = 1,
/// Target PS4 Pro hardware, also must work on Base hardware
ProAndBase = 1,
}
// Target Xbox build type.
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
public enum XboxBuildSubtarget
{
// Development player
Development = 0,
// Master player (submission-proof)
Master = 1,
// Debug player (for building with source code)
Debug = 2,
}
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
[Obsolete("The XDK Xbox One platform was removed in 2021.1", true)]
public enum XboxOneDeployMethod
{
// copies files to the kit
Push = 0,
// PC network share loose files to the kit
RunFromPC = 2,
// Build Xbox One Package
Package = 3,
// Build Xbox One Package - if installed only install launch chunk for testing
PackageStreaming = 4,
}
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
[Obsolete("The XDK Xbox One platform was removed in 2021.1", false)]
public enum XboxOneDeployDrive
{
Default = 0,
Retail = 1,
Development = 2,
Ext1 = 3,
Ext2 = 4,
Ext3 = 5,
Ext4 = 6,
Ext5 = 7,
Ext6 = 8,
Ext7 = 9
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("UnityEditor.AndroidBuildSubtarget has been deprecated. Use UnityEditor.MobileTextureSubtarget instead (UnityUpgradable)", true)]
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum AndroidBuildSubtarget
{
Generic = -1,
DXT = -1,
PVRTC = -1,
ATC = -1,
ETC = -1,
ETC2 = -1,
ASTC = -1,
}
public enum AndroidCreateSymbols
{
Disabled,
Public,
Debugging
}
// Target texture build platform.
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
public enum MobileTextureSubtarget
{
// Don't override texture compression.
Generic = 0,
// S3 texture compression, nonspecific to DXT variant. Supported on devices running Nvidia Tegra2 platform, including Motorala Xoom, Motorola Atrix, Droid Bionic, and others.
DXT = 1,
// PowerVR texture compression. Available in devices running PowerVR SGX530/540 GPU, such as Motorola DROID series; Samsung Galaxy S, Nexus S, and Galaxy Tab; and others.
PVRTC = 2,
[System.Obsolete("UnityEditor.MobileTextureSubtarget.ATC has been deprecated. Use UnityEditor.MobileTextureSubtarget.ETC instead (UnityUpgradable) -> UnityEditor.MobileTextureSubtarget.ETC", true)]
ATC = 3,
// ETC1 texture compression (or RGBA16 for textures with alpha), supported by all devices.
ETC = 4,
// ETC2/EAC texture compression, supported by GLES 3.0 devices
ETC2 = 5,
// Adaptive Scalable Texture Compression
ASTC = 6,
}
[Obsolete("AndroidETC2Fallback is obsolete and has no effect. It will be removed in a subsequent Unity release.")]
public enum AndroidETC2Fallback
{
// 32-bit uncompressed
Quality32Bit = 0,
// 16-bit uncompressed
Quality16Bit = 1,
// 32-bit uncompressed, downscaled 2x
Quality32BitDownscaled = 2,
}
// Target texture build platform.
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
public enum WebGLTextureSubtarget
{
// Don't override texture compression.
Generic = 0,
// S3 texture compression, nonspecific to DXT variant, supported by desktop browsers
DXT = 1,
// ETC2/EAC texture compression, supported by mobile devices
ETC2 = 3,
// Adaptive Scalable Texture Compression, supported by mobile devices
ASTC = 4,
}
// Client browser type
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
public enum WebGLClientBrowserType
{
Default = 0,
Edge = 1,
Safari = 2,
Firefox = 3,
Chrome = 4,
Chromium = 5
}
// Client browser type
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
public enum WebGLClientPlatform
{
Desktop = 0,
Android = 1,
iOS = 2
}
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
[Obsolete("WSASubtarget is obsolete and has no effect. It will be removed in a subsequent Unity release.")]
public enum WSASubtarget
{
AnyDevice = 0,
PC = 1,
Mobile = 2,
HoloLens = 3
}
// *undocumented*
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum WSASDK
{
// *undocumented*
SDK80 = 0,
// *undocumented*
SDK81 = 1,
// *undocumented*
PhoneSDK81 = 2,
// *undocumented*
UniversalSDK81 = 3,
// *undocumented*
UWP = 4,
}
// *undocumented*
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum WSAUWPBuildType
{
XAML = 0,
D3D = 1,
ExecutableOnly = 2,
}
// *undocumented*
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum WSABuildAndRunDeployTarget
{
/// *undocumented*
LocalMachine = 0,
/// *undocumented*
[System.Obsolete("UnityEditor.WSABuildAndRunDeployTarget.WindowsPhone is obsolete.", true)]
WindowsPhone = 1,
/// *undocumented*
DevicePortal = 2
}
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum WindowsBuildAndRunDeployTarget
{
LocalMachine = 0,
DevicePortal = 2
}
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum WSABuildType
{
Debug = 0,
Release = 1,
Master = 2
}
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum XcodeBuildConfig
{
Debug = 0,
Release = 1,
}
[Obsolete("iOSBuildType is obsolete. Use XcodeBuildConfig instead (UnityUpgradable) -> XcodeBuildConfig", true)]
public enum iOSBuildType
{
Debug = 0,
Release = 1,
}
[NativeType(Header = "Runtime/Serialize/BuildTarget.h")]
internal enum Compression
{
None = 0,
Lz4 = 2,
Lz4HC = 3,
}
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum AndroidBuildSystem
{
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Internal build system has been deprecated. Use Gradle instead (UnityUpgradable) -> UnityEditor.AndroidBuildSystem.Gradle", true)]
Internal = 0,
Gradle = 1,
[System.ComponentModel.EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("ADT/eclipse project export for Android is no longer supported - please use Gradle export instead", true)]
ADT = 2,
/// *undocumented*
VisualStudio = 3,
}
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum AndroidBuildType
{
Debug = 0,
Development = 1,
Release = 2,
}
// *undocumented*
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
internal enum AppleBuildAndRunType
{
Xcode = 0,
Xcodebuild = 1,
iOSDeploy = 2,
}
// We used this value to control if minification is enabled and what tool to use separately for release and debug builds.
// With the Android Gradle Plugin changes in 3.4 the tool which will be used is the same for release and debug now
[Obsolete("AndroidMinification enum is obsolete.", true)]
public enum AndroidMinification
{
None = 0,
Proguard = 1,
Gradle = 2,
}
// *undocumented*
[NativeType(Header = "Editor/Src/EditorOnlyPlayerSettings.h")]
internal struct SwitchShaderCompilerConfig
{
internal int glslcDebugLevel;
internal string debugInfoOutputPath;
internal bool triggerGraphicsDebuggersConfigUpdate;
}
// *undocumented*
[NativeType(Header = "Editor/Src/EditorUserBuildSettings.h")]
public enum SwitchRomCompressionType
{
None = 0,
Lz4 = 1,
}
[NativeHeader("Editor/Src/EditorUserBuildSettings.h")]
[StaticAccessor("GetEditorUserBuildSettings()", StaticAccessorType.Dot)]
public partial class EditorUserBuildSettings : Object
{
internal const string kSettingArchitecture = "Architecture";
private EditorUserBuildSettings() {}
internal static extern AppleBuildAndRunType appleBuildAndRunType { get; set; }
internal static extern string appleDeviceId { get; set; }
// The currently selected build target group.
public static extern BuildTargetGroup selectedBuildTargetGroup { get; set; }
[NativeMethod("GetSelectedSubTargetFor")]
internal static extern int GetSelectedSubtargetFor(BuildTarget target);
[NativeMethod("SetSelectedSubTargetFor")]
internal static extern void SetSelectedSubtargetFor(BuildTarget target, int subtarget);
[NativeMethod("GetActiveSubTargetFor")]
internal static extern int GetActiveSubtargetFor(BuildTarget target);
public static BuildTarget selectedStandaloneTarget
{
get { return internal_SelectedStandaloneTarget; }
set
{
string platformName = BuildPipeline.GetBuildTargetName(value);
var architecture = GetPlatformSettings(platformName, kSettingArchitecture).ToLower();
switch (value)
{
case BuildTarget.StandaloneWindows:
if (architecture != "x86")
SetPlatformSettings(platformName, kSettingArchitecture, OSArchitecture.x86.ToString());
break;
case BuildTarget.StandaloneWindows64:
if (architecture != "x64" && architecture != "arm64")
SetPlatformSettings(platformName, kSettingArchitecture, OSArchitecture.x64.ToString());
break;
}
internal_SelectedStandaloneTarget = value;
}
}
private static extern BuildTarget internal_SelectedStandaloneTarget
{
[NativeMethod("GetSelectedStandaloneTarget")]
get;
[NativeMethod("SetSelectedStandaloneTargetFromBindings")]
set;
}
internal static extern StandaloneBuildSubtarget selectedStandaloneBuildSubtarget
{
[NativeMethod("GetSelectedStandaloneBuildSubtarget")]
get;
[NativeMethod("SetSelectedStandaloneBuildSubtarget")]
set;
}
public static extern StandaloneBuildSubtarget standaloneBuildSubtarget
{
[NativeMethod("GetActiveStandaloneBuildSubtarget")]
get;
[NativeMethod("SetActiveStandaloneBuildSubtarget")]
set;
}
///PS4 Build Subtarget
public static extern PS4BuildSubtarget ps4BuildSubtarget
{
[NativeMethod("GetSelectedPS4BuildSubtarget")]
get;
[NativeMethod("SetSelectedPS4BuildSubtarget")]
set;
}
///PS4 Build Hardware Target
public static extern PS4HardwareTarget ps4HardwareTarget
{
[NativeMethod("GetPS4HardwareTarget")]
get;
[NativeMethod("SetPS4HardwareTarget")]
set;
}
// Are null references actively checked?
public static extern bool explicitNullChecks { get; set; }
// Are divide by zeros actively checked?
public static extern bool explicitDivideByZeroChecks { get; set; }
public static extern bool explicitArrayBoundsChecks { get; set; }
// Should we write out submission materials when building?
public static extern bool needSubmissionMaterials { get; set; }
[Obsolete("EditorUserBuildSettings.compressWithPsArc is obsolete and has no effect. It will be removed in a subsequent Unity release.")]
public static bool compressWithPsArc { get => false; set {} }
// Should we force an install on the build package, even if there are validation errors
public static extern bool forceInstallation { get; set; }
// Should we move the package to the Bluray disc outer edge (larger ISO, but faster loading)
public static extern bool movePackageToDiscOuterEdge { get; set; }
// Should we compress files added to the package file
public static extern bool compressFilesInPackage { get; set; }
// Headless Mode
[Obsolete("Use EditorUserBuildSettings.standaloneBuildSubtarget instead.")]
public static bool enableHeadlessMode
{
get => standaloneBuildSubtarget == StandaloneBuildSubtarget.Server;
set => standaloneBuildSubtarget = value ? StandaloneBuildSubtarget.Server : StandaloneBuildSubtarget.Player;
}
// Scripts only build
public static extern bool buildScriptsOnly { get; set; }
// 0..X levels are all considered part of the launch set of streaming install chunks
[Obsolete("The XDK Xbox One platform was removed in 2021.1", true)]
public static extern int streamingInstallLaunchRange { get; set; }
//XboxOne Build subtarget
[Obsolete("The XDK Xbox One platform was removed in 2021.1", true)]
public static extern XboxBuildSubtarget xboxBuildSubtarget
{
[NativeMethod("GetSelectedXboxBuildSubtarget")]
get;
[NativeMethod("SetSelectedXboxBuildSubtarget")]
set;
}
//selected Xbox One Deploy Method
[Obsolete("The XDK Xbox One platform was removed in 2021.1", true)]
public static extern XboxOneDeployMethod xboxOneDeployMethod
{
[NativeMethod("GetSelectedXboxOneDeployMethod")]
get;
[NativeMethod("SetSelectedXboxOneDeployMethod")]
set;
}
//selected Xbox One Deployment Drive
[Obsolete("The XDK Xbox One platform was removed in 2021.1", false)]
public static extern XboxOneDeployDrive xboxOneDeployDrive
{
[NativeMethod("GetSelectedXboxOneDeployDrive")]
get;
[NativeMethod("SetSelectedXboxOneDeployDrive")]
set;
}
[Obsolete("xboxOneUsername is deprecated, it is unnecessary and non-functional.")]
public static string xboxOneUsername { get; set; }
[Obsolete("xboxOneNetworkSharePath is deprecated, it is unnecessary and non-functional.")]
public static string xboxOneNetworkSharePath { get; set; }
// Transitive property used when adding debug ports to the
// manifest for our test systems. This is required to
// allow the XboxOne to open the required ports in its
// manifest.
[Obsolete("The XDK Xbox One platform was removed in 2021.1", false)]
public static string xboxOneAdditionalDebugPorts { get; set; }
[Obsolete("The XDK Xbox One platform was removed in 2021.1", false)]
public static bool xboxOneRebootIfDeployFailsAndRetry { get; set; }
// Android platform options.
public static extern MobileTextureSubtarget androidBuildSubtarget
{
[NativeMethod("GetSelectedAndroidBuildTextureSubtarget")]
get;
[NativeMethod("SetSelectedAndroidBuildSubtarget")]
set;
}
// WebGL platform options.
public static extern WebGLTextureSubtarget webGLBuildSubtarget
{
[NativeMethod("GetSelectedWebGLBuildTextureSubtarget")]
get;
[NativeMethod("SetSelectedWebGLBuildSubtarget")]
set;
}
public static extern string webGLClientBrowserPath { get; set; }
public static extern WebGLClientBrowserType webGLClientBrowserType
{
[NativeMethod("GetWebGLClientBrowserType")]
get;
[NativeMethod("SetWebGLClientBrowserType")]
set;
}
public static extern WebGLClientPlatform webGLClientPlatform
{
[NativeMethod("GetWebGLClientPlatform")]
get;
[NativeMethod("SetWebGLClientPlatform")]
set;
}
//Compression set/get methods for the map containing type for BuildTargetGroup
internal static Compression GetCompressionType(BuildTargetGroup targetGroup)
{
return (Compression)GetCompressionTypeInternal(targetGroup);
}
[NativeMethod("GetSelectedCompressionType")]
private static extern int GetCompressionTypeInternal(BuildTargetGroup targetGroup);
internal static void SetCompressionType(BuildTargetGroup targetGroup, Compression type)
{
SetCompressionTypeInternal(targetGroup, (int)type);
}
[NativeMethod("SetSelectedCompressionType")]
private static extern void SetCompressionTypeInternal(BuildTargetGroup targetGroup, int type);
[Obsolete("androidETC2Fallback is obsolete and has no effect. It will be removed in a subsequent Unity release.")]
public static AndroidETC2Fallback androidETC2Fallback
{
get { return AndroidETC2Fallback.Quality32Bit; }
set { }
}
public static extern AndroidBuildSystem androidBuildSystem { get; set; }
public static extern AndroidBuildType androidBuildType { get; set; }
[Obsolete("androidUseLegacySdkTools has been deprecated. It does not have any effect.")]
public static extern bool androidUseLegacySdkTools { get; set; }
[Obsolete("androidCreateSymbolsZip has been deprecated. Use UnityEditor.Android.DebugSymbols.level property")]
public static bool androidCreateSymbolsZip
{
get => androidCreateSymbols != AndroidCreateSymbols.Disabled;
set => androidCreateSymbols = value ? AndroidCreateSymbols.Public : AndroidCreateSymbols.Disabled;
}
[Obsolete("androidCreateSymbols has been deprecated. Use UnityEditor.Android.DebugSymbols.level property")]
public static extern AndroidCreateSymbols androidCreateSymbols { get; set; }
// *undocumented*
// NOTE: This setting should probably not be a part of the public API as is. Atm it is used by playmode tests
// and applied during build post-processing. We will however move towards separating building and launching
// which makes it unclear when connections should be attempted. In the future, the DeploymentTargets
// API will most likely support connecting to named external devices, which might make this setting obsolete.
internal static extern string androidDeviceSocketAddress { get; set; }
internal static extern string androidCurrentDeploymentTargetId { get; set; }
[Obsolete("EditorUserBuildSettings.wsaSubtarget is obsolete and has no effect. It will be removed in a subsequent Unity release.")]
public static WSASubtarget wsaSubtarget
{
get => WSASubtarget.AnyDevice;
set {}
}
[Obsolete("EditorUserBuildSettings.wsaSDK is obsolete and has no effect.It will be removed in a subsequent Unity release.")]
public static extern WSASDK wsaSDK
{
[NativeMethod("GetSelectedWSASDK")]
get;
[NativeMethod("SetSelectedWSASDK")]
set;
}
// *undocumented*
public static extern WSAUWPBuildType wsaUWPBuildType
{
[NativeMethod("GetSelectedWSAUWPBuildType")]
get;
[NativeMethod("SetSelectedWSAUWPBuildType")]
set;
}
public static extern string wsaUWPSDK
{
[NativeMethod("GetSelectedWSAUWPSDK")]
get;
[NativeMethod("SetSelectedWSAUWPSDK")]
set;
}
public static extern string wsaMinUWPSDK
{
[NativeMethod("GetSelectedWSAMinUWPSDK")]
get;
[NativeMethod("SetSelectedWSAMinUWPSDK")]
set;
}
public static extern string wsaArchitecture
{
[NativeMethod("GetSelectedWSAArchitecture")]
get;
[NativeMethod("SetSelectedWSAArchitecture")]
set;
}
public static extern string wsaUWPVisualStudioVersion
{
[NativeMethod("GetSelectedWSAUWPVSVersion")]
get;
[NativeMethod("SetSelectedWSAUWPVSVersion")]
set;
}
public static extern string windowsDevicePortalAddress
{
[NativeMethod("GetWindowsDevicePortalAddress")]
get;
[NativeMethod("SetWindowsDevicePortalAddress")]
set;
}
public static extern string windowsDevicePortalUsername
{
[NativeMethod("GetWindowsDevicePortalUsername")]
get;
[NativeMethod("SetWindowsDevicePortalUsername")]
set;
}
// WDP password is not to be saved with other settings and only stored in memory until Editor is closed
public static string windowsDevicePortalPassword
{
get
{
var profile = BuildProfileContext.GetActiveOrClassicBuildProfile(BuildTarget.NoTarget, StandaloneBuildSubtarget.Default, SharedPlatformSettings.k_SettingWindowsDevicePortalPassword);
if (profile != null)
{
var settings = profile.platformBuildProfile;
return settings.GetSharedSetting(SharedPlatformSettings.k_SettingWindowsDevicePortalPassword);
}
return null;
}
set
{
var profile = BuildProfileContext.GetActiveOrClassicBuildProfile(BuildTarget.NoTarget, StandaloneBuildSubtarget.Default, SharedPlatformSettings.k_SettingWindowsDevicePortalPassword);
if (profile == null)
return;
if (profile.buildTarget == BuildTarget.NoTarget)
{
var sharedPlatformSettings = profile.platformBuildProfile as SharedPlatformSettings;
// This will sync the value to applicable classic profiles through the shared profile.
sharedPlatformSettings.windowsDevicePortalPassword = value;
}
else
{
var settings = profile.platformBuildProfile;
// SetSharedSetting() is used to avoid having to cast the active custom profile to platform profiles.
// This only changes the value in the active custom profile and has no effect on syncing.
settings.SetSharedSetting(SharedPlatformSettings.k_SettingWindowsDevicePortalPassword, value);
}
}
}
// *undocumented*
public static extern WSABuildAndRunDeployTarget wsaBuildAndRunDeployTarget
{
[NativeMethod("GetSelectedWSABuildAndRunDeployTarget")]
get;
[NativeMethod("SetSelectedWSABuildAndRunDeployTarget")]
set;
}
public static extern WindowsBuildAndRunDeployTarget windowsBuildAndRunDeployTarget
{
[NativeMethod("GetSelectedWindowsBuildAndRunDeployTarget")]
get;
[NativeMethod("SetSelectedWindowsBuildAndRunDeployTarget")]
set;
}
public static extern int overrideMaxTextureSize { get; set; }
public static extern Build.OverrideTextureCompression overrideTextureCompression { get; set; }
// The currently active build target.
public static extern BuildTarget activeBuildTarget { get; }
// The currently active build target.
internal static extern BuildTargetGroup activeBuildTargetGroup { get; }
[NativeMethod("SwitchActiveBuildTargetSync")]
internal static extern bool SwitchActiveBuildTargetAndSubtarget(BuildTarget target, int subtarget);
public static bool SwitchActiveBuildTarget(BuildTargetGroup targetGroup, BuildTarget target)
=> SwitchActiveBuildTargetAndSubtarget(target, EditorUserBuildSettings.GetActiveSubtargetFor(target));
[NativeMethod("SwitchActiveBuildTargetAsync")]
internal static extern bool SwitchActiveBuildTargetAndSubtargetAsync(BuildTarget target, int subtarget);
public static bool SwitchActiveBuildTargetAsync(BuildTargetGroup targetGroup, BuildTarget target)
=> SwitchActiveBuildTargetAndSubtargetAsync(target, EditorUserBuildSettings.GetActiveSubtargetFor(target));
public static bool SwitchActiveBuildTarget(NamedBuildTarget namedBuildTarget, BuildTarget target) =>
BuildPlatforms.instance.BuildPlatformFromNamedBuildTarget(namedBuildTarget).SetActive(target);
// This is used by tests -- note that it does tell the editor that current platform is X, without
// validating if support for it is installed. However it does not do things like script recompile
// or domain reload -- generally only useful for asset import testing.
[NativeMethod("SwitchActiveBuildTargetSyncNoCheck")]
internal static extern bool SwitchActiveBuildTargetAndSubtargetNoCheck(BuildTarget target, int subtarget);
internal static bool SwitchActiveBuildTargetNoCheck(BuildTarget target)
=> SwitchActiveBuildTargetAndSubtargetNoCheck(target, EditorUserBuildSettings.GetActiveSubtargetFor(target));
// DEFINE directives for the compiler.
public static extern string[] activeScriptCompilationDefines
{
[NativeMethod("GetActiveScriptCompilationDefinesBindingMethod")]
get;
}
// Get the current location for the build.
public static extern string GetBuildLocation(BuildTarget target);
// Set a new location for the build.
public static extern void SetBuildLocation(BuildTarget target, string location);
public static void SetPlatformSettings(string platformName, string name, string value)
{
string buildTargetGroup = BuildPipeline.GetBuildTargetGroupName(BuildPipeline.GetBuildTargetByName(platformName));
SetPlatformSettings(buildTargetGroup, platformName, name, value);
}
public static extern void SetPlatformSettings(string buildTargetGroup, string buildTarget, string name, string value);
public static string GetPlatformSettings(string platformName, string name)
{
string buildTargetGroup = BuildPipeline.GetBuildTargetGroupName(BuildPipeline.GetBuildTargetByName(platformName));
return GetPlatformSettings(buildTargetGroup, platformName, name);
}
public static extern string GetPlatformSettings(string buildTargetGroup, string platformName, string name);
// Enables a development build.
public static extern bool development { get; set; }
[Obsolete("Use PlayerSettings.SetIl2CppCodeGeneration and PlayerSettings.GetIl2CppCodeGeneration instead.", true)]
public static Build.Il2CppCodeGeneration il2CppCodeGeneration
{
get { return Build.Il2CppCodeGeneration.OptimizeSpeed; }
set { Debug.LogWarning("EditorUserBuildSettings.il2CppCodeGeneration is obsolete. Please use PlayerSettings.SetIl2CppCodeGeneration and PlayerSettings.GetIl2CppCodeGeneration instead." ); }
}
[Obsolete("Building with pre-built Engine option is no longer supported.", true)]
public static bool webGLUsePreBuiltUnityEngine
{
get { return false; }
set {}
}
// Start the player with a connection to the profiler.
public static extern bool connectProfiler { get; set; }
// Build the player with deep profiler support.
public static extern bool buildWithDeepProfilingSupport { get; set; }
// Enable source-level debuggers to connect.
public static extern bool allowDebugging { get; set; }
// Wait for player connection on start
public static extern bool waitForPlayerConnection { get; set; }
// Export as Android Google Project instead of building it
public static extern bool exportAsGoogleAndroidProject { get; set; }
// Build Google Play App Bundle
public static extern bool buildAppBundle { get; set; }
// Symlink runtime libraries with an iOS Xcode project.
[Obsolete("EditorUserBuildSettings.symlinkLibraries is obsolete. Use EditorUserBuildSettings.symlinkSources instead (UnityUpgradable) -> [UnityEditor] EditorUserBuildSettings.symlinkSources", false)]
public static bool symlinkLibraries
{
get => symlinkSources;
set => symlinkSources = value;
}
public static extern bool symlinkSources { get; set; }
// Symlink trampoline for iOS Xcode project.
internal static extern bool symlinkTrampoline { get; set; }
public static extern XcodeBuildConfig iOSXcodeBuildConfig
{
[NativeMethod("GetIOSXcodeBuildConfig")] get;
[NativeMethod("SetIOSXcodeBuildConfig")] set;
}
public static extern XcodeBuildConfig macOSXcodeBuildConfig
{
[NativeMethod("GetMacOSXcodeBuildConfig")] get;
[NativeMethod("SetMacOSXcodeBuildConfig")] set;
}
[Obsolete("iOSBuildConfigType is obsolete. Use iOSXcodeBuildConfig instead (UnityUpgradable) -> iOSXcodeBuildConfig", true)]
public static iOSBuildType iOSBuildConfigType
{
// note that the actual values of iOSBuildType and XcodeBuildConfig agree
get => (iOSBuildType)iOSXcodeBuildConfig;
set => iOSXcodeBuildConfig = (XcodeBuildConfig)value;
}
// Create a .nsp ROM file out of the loose-files .nspd folder
public static extern bool switchCreateRomFile
{
[NativeMethod("GetCreateRomFileForSwitch")]
get;
[NativeMethod("SetCreateRomFileForSwitch")]
set;
}
public static extern bool switchEnableRomCompression
{
[NativeMethod("GetEnableRomCompressionForSwitch")]
get;
[NativeMethod("SetEnableRomCompressionForSwitch")]
set;
}
public static extern bool switchSaveADF
{
[NativeMethod("GetSaveADFForSwitch")]
get;
[NativeMethod("SetSaveADFForSwitch")]
set;
}
public static extern SwitchRomCompressionType switchRomCompressionType
{
[NativeMethod("GetRomCompressionTypeForSwitch")]
get;
[NativeMethod("SetRomCompressionTypeForSwitch")]
set;
}
public static extern int switchRomCompressionLevel
{
[NativeMethod("GetRomCompressionLevelForSwitch")]
get;
[NativeMethod("SetRomCompressionLevelForSwitch")]
set;
}
public static extern string switchRomCompressionConfig
{
[NativeMethod("GetRomCompressionConfigForSwitch")]
get;
[NativeMethod("SetRomCompressionConfigForSwitch")]
set;
}
// Enable linkage of NVN Graphics Debugger for Nintendo Switch.
public static extern bool switchNVNGraphicsDebugger
{
[NativeMethod("GetNVNGraphicsDebuggerForSwitch")]
get;
[NativeMethod("SetNVNGraphicsDebuggerForSwitch")]
set;
}
// Generate Nintendo Switch shader info for shader source visualization and profiling in NVN Graphics Debugger or Low-Level Graphics Debugger (LLGD)
public static extern bool generateNintendoSwitchShaderInfo
{
[NativeMethod("GetGenerateNintendoSwitchShaderInfo")]
get;
[NativeMethod("SetGenerateNintendoSwitchShaderInfo")]
set;
}
// Enable shader debugging using NVN Graphics Debugger
public static extern bool switchNVNShaderDebugging
{
[NativeMethod("GetNVNShaderDebugging")]
get;
[NativeMethod("SetNVNShaderDebugging")]
set;
}
// Enable shader debugging using NVN Graphics Debugger
public static extern bool switchNVNAftermath
{
[NativeMethod("GetNVNAftermath")]
get;
[NativeMethod("SetNVNAftermath")]
set;
}
// Enable debug validation of NVN drawcalls
[Obsolete("switchNVNDrawValidation is deprecated, use switchNVNDrawValidation_Heavy instead.")]
public static bool switchNVNDrawValidation
{
get { return switchNVNDrawValidation_Heavy; }
set { switchNVNDrawValidation_Heavy = value; }
}
public static extern bool switchNVNDrawValidation_Light
{
[NativeMethod("GetNVNDrawValidationLight")]
get;
[NativeMethod("SetNVNDrawValidationLight")]
set;
}
public static extern bool switchNVNDrawValidation_Heavy
{
[NativeMethod("GetNVNDrawValidationHeavy")]
get;
[NativeMethod("SetNVNDrawValidationHeavy")]
set;
}
// Enable linkage of the Memory Tracker tool for Nintendo Switch.
public static extern bool switchEnableMemoryTracker
{
[NativeMethod("GetEnableMemoryTrackerForSwitch")]
get;
[NativeMethod("SetEnableMemoryTrackerForSwitch")]
set;
}
// On startup the application waits for Memory Tracker to connect.
public static extern bool switchWaitForMemoryTrackerOnStartup
{
[NativeMethod("GetWaitForSwitchMemoryTrackerOnStartup")]
get;
[NativeMethod("SetWaitForSwitchMemoryTrackerOnStartup")]
set;
}
// Enable linkage of DebugPad functionality for Nintendo Switch.
public static extern bool switchEnableDebugPad
{
[NativeMethod("GetEnableDebugPadForSwitch")]
get;
[NativeMethod("SetEnableDebugPadForSwitch")]
set;
}
[Obsolete("EditorUserBuildSettings.switchRedirectWritesToHostMount is obsolete. Use EditorUserBuildSettings.switchEnableHostIO instead (UnityUpgradable) -> switchEnableHostIO", false)]
public static bool switchRedirectWritesToHostMount
{
get => switchEnableHostIO;
set => switchEnableHostIO = value;
}
// Redirect attempts to write to "rom:" mount, to "host:" mount for Nintendo Switch (for debugging and tests only)
public static extern bool switchEnableHostIO
{
[NativeMethod("GetEnableHostIOForSwitch")]
get;
[NativeMethod("SetEnableHostIOForSwitch")]
set;
}
// Enable using the HTC devkit connection for script debugging
public static extern bool switchHTCSScriptDebugging
{
[NativeMethod("GetHTCSScriptDebuggingForSwitch")]
get;
[NativeMethod("SetHTCSScriptDebuggingForSwitch")]
set;
}
public static extern bool switchUseLegacyNvnPoolAllocator
{
[NativeMethod("GetUseLegacyNvnPoolAllocatorForSwitch")]
get;
[NativeMethod("SetUseLegacyNvnPoolAllocatorForSwitch")]
set;
}
internal static extern SwitchShaderCompilerConfig switchShaderCompilerConfig
{
[NativeMethod("GetSwitchShaderCompilerConfig")]
get;
[NativeMethod("SetSwitchShaderCompilerConfig")]
set;
}
// Place the built player in the build folder.
public static extern bool installInBuildFolder { get; set; }
public static bool waitForManagedDebugger
{
get
{
return GetPlatformSettings("Editor", BuildProfilePlatformSettingsBase.k_SettingWaitForManagedDebugger) == "true";
}
set
{
SetPlatformSettings("Editor", BuildProfilePlatformSettingsBase.k_SettingWaitForManagedDebugger, value.ToString().ToLower());
}
}
public static int managedDebuggerFixedPort
{
get
{
if (Int32.TryParse(GetPlatformSettings("Editor", BuildProfilePlatformSettingsBase.k_SettingManagedDebuggerFixedPort), out int value)) {
if (0 < value && value <= 65535)
{
return value;
}
}
return 0;
}
set
{
SetPlatformSettings("Editor", BuildProfilePlatformSettingsBase.k_SettingManagedDebuggerFixedPort, value.ToString().ToLower());
}
}
internal static extern bool isBuildProfileAvailable { get; set; }
internal static extern void CopyFromBuildProfile(ScriptableObject buildProfile);
internal static extern void CopyToBuildProfile(ScriptableObject buildProfile);
}
}
| UnityCsReference/Editor/Mono/EditorUserBuildSettings.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/EditorUserBuildSettings.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 16271
} | 269 |
// 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.Internal;
namespace UnityEditor
{
internal partial class ExternalPlayModeView : EditorWindow, IGameViewSizeMenuUser
{
MonoReloadableIntPtr m_NativeContextPtr;
public string playerLaunchPath
{
get { return m_PlayerLaunchPath; }
set
{
m_PlayerLaunchPath = value;
Internal_SetPlayerLaunchPath(m_NativeContextPtr.m_IntPtr, m_PlayerLaunchPath);
}
}
string m_PlayerLaunchPath;
static GameViewSizeGroupType currentSizeGroupType => GameViewSizes.instance.currentGroupType;
private ExternalPlayModeView() {}
public static ExternalPlayModeView CreateExternalPlayModeView()
{
ExternalPlayModeView win = EditorWindow.CreateWindow<ExternalPlayModeView>();
win.m_NativeContextPtr.m_IntPtr = Internal_InitWindow();
return win;
}
public void AttachProcess()
{
AttachWindow_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle, GetTabRect());
}
public void KillProcess()
{
DestroyWindow_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle);
}
/*
* Returns the Rect that the external process should render itself in. Must be inside the external playmode view window
* and below any controls on the window.
*/
private Rect GetTabRect()
{
Rect hostWindowScreenPosition = m_Parent.window.position;
Rect inTabPosition = m_Parent.windowPosition;
Rect usePosition = new Rect(hostWindowScreenPosition);
usePosition.x += inTabPosition.x;
usePosition.y += inTabPosition.y;
usePosition.width = inTabPosition.width;
usePosition.height = inTabPosition.height;
float yAdjust = EditorGUI.kTabButtonHeight + EditorGUI.kWindowToolbarHeight + EditorGUI.kSpacing;
float borderSize = EditorGUI.kSpacing;
usePosition.y += yAdjust;
usePosition.height -= (yAdjust + borderSize);
usePosition.x += borderSize;
usePosition.width -= borderSize * 2;
if (m_Parent.window.IsMainWindow())
{
// Need to move farther down when docked with the main editor window. Why?
float adjust = EditorGUI.kTabButtonHeight + EditorGUI.kSpacing;
usePosition.y += adjust;
usePosition.height -= adjust * 2;
}
return usePosition;
}
private void DoToolbarGUI()
{
GUILayout.BeginHorizontal(EditorStyles.toolbar);
{
GUILayout.Label(m_PlayerLaunchPath);
EditorGUILayout.GameViewSizePopup(currentSizeGroupType, 0, this, EditorStyles.toolbarPopup, GUILayout.Width(160f));
}
GUILayout.EndHorizontal();
}
private void OnGUI()
{
DoToolbarGUI();
}
internal override void OnResized()
{
if (m_Parent.window == null)
return;
ResizeWindow_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle, GetTabRect());
}
private void OnDestroy()
{
DestroyWindow_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle);
}
private void OnBecameInvisible()
{
if (m_Parent.window == null)
return;
OnBecameInvisible_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle);
}
private void OnBecameVisible()
{
if (m_Parent.window == null)
return;
OnBecameVisible_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle, GetTabRect());
}
private void OnTabNewWindow()
{
if (m_Parent.window == null)
return;
AddedAsTab_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle, GetTabRect());
}
private void OnAddedAsTab()
{
if (m_Parent.window == null)
return;
AddedAsTab_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle, GetTabRect());
}
private void OnBeforeRemovedAsTab()
{
if (m_Parent.window == null)
return;
BeforeRemoveTab_Native(m_NativeContextPtr.m_IntPtr, m_Parent.nativeHandle);
}
[ExcludeFromDocs]
public void SizeSelectionCallback(int indexClicked, object objectSelected)
{
//TODO handle selection of aspect ratio.
// We need to pass a message to our hosted process and tell it to change to a compatible resolution based on our selection.
}
[ExcludeFromDocs]
public bool lowResolutionForAspectRatios
{
get { return true; }
set {}
}
[ExcludeFromDocs]
public bool forceLowResolutionAspectRatios
{
get { return false; }
}
[ExcludeFromDocs]
public bool vSyncEnabled
{
get { return false; }
set {}
}
}
}
| UnityCsReference/Editor/Mono/ExternalPlayModeView/ExternalPlayModeView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ExternalPlayModeView/ExternalPlayModeView.cs",
"repo_id": "UnityCsReference",
"token_count": 2516
} | 270 |
// 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 GITextureType = UnityEngineInternal.GITextureType;
using LightmapType = UnityEngineInternal.LightmapType;
namespace UnityEditor
{
[NativeHeader("Editor/Src/GI/Enlighten/Visualisers/VisualisationManager.h")]
internal enum GITextureAvailability
{
GITextureUnknown = 0,
GITextureNotAvailable = 1,
GITextureLoading = 2,
GITextureAvailable = 3,
GITextureAvailabilityCount = 4
}
[NativeHeader("Editor/Src/GI/Enlighten/Visualisers/VisualisationManager.h")]
internal struct VisualisationGITexture
{
[NativeName("m_Type")]
public GITextureType type;
[NativeName("m_Availability")]
public GITextureAvailability textureAvailability;
[NativeName("m_Texture")]
public Texture2D texture;
[NativeName("m_Hash")]
public Hash128 hash;
[NativeName("m_ContentsHash")]
public Hash128 contentHash;
}
internal sealed partial class LightmapVisualization
{
[NativeHeader("Editor/Src/EditorSettings.h")]
[StaticAccessor("GetEditorSettings()", StaticAccessorType.Dot)]
[NativeName("ShowLightmapResolutionOverlay")]
public static extern bool showResolution { get; set; }
[NativeHeader("Editor/Src/Lightmapping.h")]
[FreeFunction]
[NativeName("GetLightmapLODLevelScale_Internal")]
internal extern static float GetLightmapLODLevelScale(UnityEngine.Renderer renderer);
}
internal sealed partial class LightmapVisualizationUtility
{
static readonly PrefColor kUVColor = new PrefColor("Lightmap Preview/UV Color", 51f / 255f, 111f / 255f, 244f / 255f, 1f);
static readonly PrefColor kSelectedUVColor = new PrefColor("Lightmap Preview/Selected UV Color", 250f / 255f, 250f / 255f, 0f, 1f);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
internal extern static bool IsTextureTypeEnabled(GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
internal extern static bool IsBakedTextureType(GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
internal extern static bool IsAtlasTextureType(GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static VisualisationGITexture[] GetRealtimeGITextures(GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static VisualisationGITexture GetRealtimeGITexture(Hash128 inputSystemHash, GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static VisualisationGITexture GetBakedGITexture(int lightmapIndex, int instanceId, GITextureType textureType, bool useInteractiveLightBakingData);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static VisualisationGITexture GetSelectedObjectGITexture(GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static Hash128 GetBakedGITextureHash(int lightmapIndex, int instanceId, GITextureType textureType, bool useInteractiveLightBakingData);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static Hash128 GetRealtimeGITextureHash(Hash128 inputSystemHash, GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static Hash128 GetSelectedObjectGITextureHash(GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static GameObject[] GetRealtimeGITextureRenderers(Hash128 inputSystemHash);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static GameObject[] GetBakedGITextureRenderers(int lightmapIndex, bool useInteractiveLightBakingData);
[NativeHeader("Runtime/GI/RenderOverlay.h")]
[FreeFunction("DrawTextureWithUVOverlay")]
public extern static void DrawTextureWithUVOverlay(Texture2D texture, GameObject selectedGameObject, GameObject[] gameObjects, Rect drawableArea, Rect position, GITextureType textureType, Color uvColor, Color selectedUVColor, float exposure, bool useInteractiveLightBakingData);
public static void DrawTextureWithUVOverlay(Texture2D texture, GameObject selectedGameObject, GameObject[] gameObjects, Rect drawableArea, Rect position, GITextureType textureType, float exposure, bool useInteractiveLightBakingData)
{
DrawTextureWithUVOverlay(texture, selectedGameObject, gameObjects, drawableArea, position, textureType, kUVColor, kSelectedUVColor, exposure, useInteractiveLightBakingData);
}
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
public extern static LightmapType GetLightmapType(GITextureType textureType);
[StaticAccessor("VisualisationManager::Get()", StaticAccessorType.Arrow)]
[NativeName("GetLightmapST")]
public extern static Vector4 GetLightmapTilingOffset(LightmapType lightmapType);
}
}
| UnityCsReference/Editor/Mono/GI/LightmapVisualization.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GI/LightmapVisualization.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1952
} | 271 |
// 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.Presets;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityEditor
{
internal class AssetPopupBackend
{
public static void AssetPopup<T>(SerializedProperty serializedProperty, GUIContent label, string fileExtension, string defaultFieldName) where T : Object, new()
{
bool orignalShowMixedValue = EditorGUI.showMixedValue;
EditorGUI.showMixedValue = serializedProperty.hasMultipleDifferentValues;
var typeName = serializedProperty.objectReferenceTypeString;
GUIContent buttonContent;
if (serializedProperty.hasMultipleDifferentValues)
buttonContent = EditorGUI.mixedValueContent;
else if (serializedProperty.objectReferenceValue != null)
buttonContent = GUIContent.Temp(serializedProperty.objectReferenceStringValue);
else
buttonContent = GUIContent.Temp(defaultFieldName);
Rect buttonRect;
if (AudioMixerEffectGUI.PopupButton(label, buttonContent, EditorStyles.popup, out buttonRect)) // move & rename PopupButton..
ShowAssetsPopupMenu<T>(buttonRect, typeName, serializedProperty, fileExtension, defaultFieldName);
EditorGUI.showMixedValue = orignalShowMixedValue;
}
public static void AssetPopup<T>(SerializedProperty serializedProperty, GUIContent label, string fileExtension) where T : Object, new()
{
AssetPopup<T>(serializedProperty, label, fileExtension, "Default");
}
private class DoCreateNewAsset : ProjectWindowCallback.EndNameEditAction
{
private SerializedObject m_Object;
private SerializedProperty m_Property;
public void SetProperty(SerializedProperty property)
{
m_Object = new SerializedObject(property.serializedObject.targetObject);
m_Property = m_Object.FindProperty(property.propertyPath);
}
public override void Action(int instanceId, string pathName, string resourceFile)
{
var obj = EditorUtility.InstanceIDToObject(instanceId);
AssetDatabase.CreateAsset(obj, AssetDatabase.GenerateUniqueAssetPath(pathName));
ProjectWindowUtil.FrameObjectInProjectWindow(instanceId);
m_Property.objectReferenceValue = obj;
m_Property.serializedObject.ApplyModifiedProperties();
m_Property.serializedObject.Dispose();
m_Property.Dispose();
m_Object.Dispose();
}
public override void Cancelled(int instanceId, string pathName, string resourceFile)
{
Selection.activeObject = m_Property.serializedObject.targetObject;
m_Property.serializedObject.Dispose();
m_Property.Dispose();
m_Object.Dispose();
}
}
internal static void ShowAssetsPopupMenu<T>(Rect buttonRect, string typeName, SerializedProperty serializedProperty, string fileExtension, string defaultFieldName) where T : Object, new()
{
GenericMenu gm = new GenericMenu();
int selectedInstanceID = serializedProperty.objectReferenceValue != null ? serializedProperty.objectReferenceValue.GetInstanceID() : 0;
bool foundDefaultAsset = false;
var type = UnityEditor.UnityType.FindTypeByName(typeName);
int classID = type != null ? type.persistentTypeID : 0;
BuiltinResource[] resourceList = null;
// Check the assets for one that matches the default name.
if (classID > 0)
{
resourceList = EditorGUIUtility.GetBuiltinResourceList(classID);
foreach (var resource in resourceList)
{
if (resource.m_Name == defaultFieldName)
{
gm.AddItem(new GUIContent(resource.m_Name), resource.m_InstanceID == selectedInstanceID, AssetPopupMenuCallback, new object[] { resource.m_InstanceID, serializedProperty });
resourceList = resourceList.Where(x => x != resource).ToArray();
foundDefaultAsset = true;
break;
}
}
}
// If no defalut asset was found, add defualt null value.
if (!foundDefaultAsset)
{
gm.AddItem(new GUIContent(defaultFieldName), selectedInstanceID == 0, AssetPopupMenuCallback, new object[] { 0, serializedProperty });
}
// Add items from asset database
foreach (var property in AssetDatabase.FindAllAssets(new SearchFilter() { classNames = new[] { typeName } }))
{
gm.AddItem(new GUIContent(property.name), property.instanceID == selectedInstanceID, AssetPopupMenuCallback, new object[] { property.instanceID, serializedProperty });
}
// Add builtin items, except for the already added default item.
if (classID > 0 && resourceList != null)
{
foreach (var resource in resourceList)
{
gm.AddItem(new GUIContent(resource.m_Name), resource.m_InstanceID == selectedInstanceID, AssetPopupMenuCallback, new object[] { resource.m_InstanceID, serializedProperty });
}
}
var target = serializedProperty.serializedObject.targetObject;
bool isPreset = Preset.IsEditorTargetAPreset(target);
// the preset object is destroyed with the inspector, and nothing new can be created that needs this link. Fix for case 1208437
if (!isPreset)
{
// Create item
gm.AddSeparator("");
gm.AddItem(EditorGUIUtility.TrTextContent("Create New..."), false, delegate
{
var newAsset = Activator.CreateInstance<T>();
var doCreate = ScriptableObject.CreateInstance<DoCreateNewAsset>();
doCreate.SetProperty(serializedProperty);
ProjectWindowUtil.StartNameEditingIfProjectWindowExists(newAsset.GetInstanceID(), doCreate, "New " + typeName + "." + fileExtension, AssetPreview.GetMiniThumbnail(newAsset), null);
});
}
gm.DropDown(buttonRect);
}
static void ShowAssetsPopupMenu<T>(Rect buttonRect, string typeName, SerializedProperty serializedProperty, string fileExtension) where T : Object, new()
{
ShowAssetsPopupMenu<T>(buttonRect, typeName, serializedProperty, fileExtension, "Default");
}
static void AssetPopupMenuCallback(object userData)
{
var data = userData as object[];
var instanceID = (int)data[0];
var serializedProperty = (SerializedProperty)data[1];
serializedProperty.objectReferenceValue = EditorUtility.InstanceIDToObject(instanceID);
serializedProperty.m_SerializedObject.ApplyModifiedProperties();
}
}
}
| UnityCsReference/Editor/Mono/GUI/AssetPopupBackend.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/AssetPopupBackend.cs",
"repo_id": "UnityCsReference",
"token_count": 3123
} | 272 |
// 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.Reflection;
namespace UnityEditor
{
public sealed partial class EditorGUI
{
// Common GUIContents used for EditorGUI controls.
internal sealed class GUIContents
{
// The settings dropdown icon top right in a component
[IconName("_Popup")]
internal static GUIContent titleSettingsIcon { get; private set; }
// The help icon in a component
[IconName("_Help")]
internal static GUIContent helpIcon { get; private set; }
// We use a static constructor to lazily initialize all static properties. This is useful because changed image files can then
// be picked up on assembly reload.
static GUIContents()
{
// Run through each static property and initialize it using the
// filename provided in the IconName Attribute.
PropertyInfo[] propertyInfos = typeof(GUIContents).GetProperties(System.Reflection.BindingFlags.Static | BindingFlags.NonPublic);
foreach (PropertyInfo property in propertyInfos)
{
IconName[] iconNames = (IconName[])property.GetCustomAttributes(typeof(IconName), false);
if (iconNames.Length > 0)
{
string name = iconNames[0].name;
GUIContent content = EditorGUIUtility.IconContent(name);
property.SetValue(null, content, null);
}
}
}
private class IconName : System.Attribute
{
private string m_Name;
public IconName(string name)
{
this.m_Name = name;
}
public virtual string name
{
get { return m_Name; }
}
}
}
}
}
| UnityCsReference/Editor/Mono/GUI/EditorGUIContents.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/EditorGUIContents.cs",
"repo_id": "UnityCsReference",
"token_count": 1001
} | 273 |
// 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
{
/// <summary>
/// Context menu apply/revert extension hook for object in prefab editing mode.
/// </summary>
public interface IApplyRevertPropertyContextMenuItemProvider
{
/// <summary>
/// Called as the context menu is being built to retrieve the method to be called (if any) when the user select the 'revert' menu item.
/// </summary>
/// <param name="property"></param>
/// <param name="revertMethod"></param>
/// <returns>false if a revert menu item is not meant to be shown</returns>
bool TryGetRevertMethodForFieldName(SerializedProperty property, out Action<SerializedProperty> revertMethod);
/// <summary>
/// Called as the context menu is being built to retrieve the method to be called (if any) when the user select the 'apply' menu item.
/// </summary>
/// <param name="property"></param>
/// <param name="applyMethod"></param>
/// <returns>false if an apply menu item is not meant to be shown</returns>
bool TryGetApplyMethodForFieldName(SerializedProperty property, out Action<SerializedProperty> applyMethod);
/// <summary>
///
/// </summary>
/// <returns></returns>
string GetSourceTerm();
/// <summary>
///
/// </summary>
/// <param name="comp"></param>
/// <returns></returns>
string GetSourceName(Component comp);
}
}
| UnityCsReference/Editor/Mono/GUI/IApplyRevertPropertyContextMenuItemProvider.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/IApplyRevertPropertyContextMenuItemProvider.cs",
"repo_id": "UnityCsReference",
"token_count": 593
} | 274 |
// 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 UnityEditor.IMGUI.Controls;
using UnityEngine;
using UnityEngine.Scripting;
namespace UnityEditor
{
internal class PackageExport : EditorWindow
{
[SerializeField] private ExportPackageItem[] m_ExportPackageItems;
[SerializeField] private bool m_IncludeDependencies = true;
[SerializeField] private TreeViewState m_TreeViewState;
[NonSerialized] private PackageExportTreeView m_Tree;
[NonSerialized] private bool m_DidScheduleUpdate = false;
public ExportPackageItem[] items { get { return m_ExportPackageItems; } }
internal static class Styles
{
public static GUIStyle title = "LargeBoldLabel";
public static GUIStyle bottomBarBg = "ProjectBrowserBottomBarBg";
public static GUIStyle topBarBg = "OT TopBar";
public static GUIStyle loadingTextStyle = "CenteredLabel";
public static GUIContent allText = EditorGUIUtility.TrTextContent("All");
public static GUIContent noneText = EditorGUIUtility.TrTextContent("None");
public static GUIContent includeDependenciesText = EditorGUIUtility.TrTextContent("Include dependencies");
public static GUIContent header = EditorGUIUtility.TrTextContent("Items to Export");
}
public PackageExport()
{
// Initial pos and minsize
position = new Rect(100, 100, 400, 300);
minSize = new Vector2(350, 350);
}
// Called from from menu
[RequiredByNativeCode]
static internal void ShowExportPackage()
{
GetWindow<PackageExport>(true, "Exporting package").RefreshAssetList();
}
internal static IEnumerable<ExportPackageItem> GetAssetItemsForExport(ICollection<string> guids, bool includeDependencies)
{
// if nothing is selected, export all
if (0 == guids.Count)
{
string[] temp = new string[0]; // <--- I dont get this API
guids = new HashSet<string>(AssetDatabase.CollectAllChildren(AssetDatabase.assetFolderGUID, temp));
}
ExportPackageItem[] assets = PackageUtility.BuildExportPackageItemsListWithPackageManagerWarning(guids.ToArray(), includeDependencies, true);
// If any scripts are included, add all scripts with dependencies
if (includeDependencies && assets.Any(asset => UnityEditorInternal.InternalEditorUtility.IsScriptOrAssembly(asset.assetPath)))
{
assets = PackageUtility.BuildExportPackageItemsListWithPackageManagerWarning(
guids.Union(UnityEditorInternal.InternalEditorUtility.GetAllScriptGUIDs()).ToArray(), includeDependencies, true);
}
// If the user exports the root Assets folder, we need to remove it from the list
// explicitly, as it doesnt make sense
assets = assets.Where(val => val.assetPath != "Assets").ToArray();
return assets;
}
void RefreshAssetList()
{
m_ExportPackageItems = null;
}
bool HasValidAssetList()
{
return m_ExportPackageItems != null;
}
bool CheckAssetExportList()
{
if (m_ExportPackageItems.Length == 0)
{
GUILayout.Space(20f);
GUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label("Nothing to export!", EditorStyles.boldLabel);
GUILayout.Label("No assets to export were found in your project.", "WordWrappedLabel");
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("OK"))
{
Close();
GUIUtility.ExitGUI();
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
return true;
}
return false;
}
public void OnDestroy()
{
UnscheduleBuildAssetList();
}
public void OnGUI()
{
if (!HasValidAssetList())
{
ScheduleBuildAssetList();
}
else if (CheckAssetExportList())
{
return;
}
using (new EditorGUI.DisabledScope(!HasValidAssetList()))
{
TopArea();
TopButtonsArea();
}
TreeViewArea(!HasValidAssetList());
using (new EditorGUI.DisabledScope(!HasValidAssetList()))
{
BottomArea();
}
}
void TopArea()
{
float totalTopHeight = 53f;
Rect r = GUILayoutUtility.GetRect(position.width, totalTopHeight);
// Background
GUI.Label(r, GUIContent.none, Styles.topBarBg);
// Header
Rect titleRect = new Rect(r.x + 5f, r.yMin, r.width, r.height);
GUI.Label(titleRect, Styles.header, Styles.title);
}
void TopButtonsArea()
{
// Background
GUILayout.BeginVertical();
GUILayout.Space(8);
GUILayout.BeginHorizontal();
GUILayout.Space(10);
if (GUILayout.Button(Styles.allText, GUILayout.Width(50)))
{
m_Tree.SetAllEnabled(PackageExportTreeView.EnabledState.All);
}
if (GUILayout.Button(Styles.noneText, GUILayout.Width(50)))
{
m_Tree.SetAllEnabled(PackageExportTreeView.EnabledState.None);
}
GUILayout.Space(10);
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.EndVertical();
}
void BottomArea()
{
// Background
GUILayout.BeginVertical(Styles.bottomBarBg);
GUILayout.Space(8);
GUILayout.BeginHorizontal();
GUILayout.Space(10);
EditorGUI.BeginChangeCheck();
m_IncludeDependencies = GUILayout.Toggle(m_IncludeDependencies, Styles.includeDependenciesText);
if (EditorGUI.EndChangeCheck())
{
RefreshAssetList();
}
GUILayout.FlexibleSpace();
if (GUILayout.Button(EditorGUIUtility.TrTextContent("Export...")))
{
string invalidChars = EditorUtility.GetInvalidFilenameChars();
var selectedItemWithInvalidChar = m_ExportPackageItems.FirstOrDefault(item => Path.GetFileNameWithoutExtension(item.assetPath).IndexOfAny(invalidChars.ToCharArray()) != -1 && item.enabledStatus > 0);
if (selectedItemWithInvalidChar != null && !EditorUtility.DisplayDialog(L10n.Tr("Cross platform incompatibility"), L10n.Tr($"The asset “{Path.GetFileNameWithoutExtension(selectedItemWithInvalidChar.assetPath)}” contains one or more characters that are not compatible across platforms: {invalidChars}"), L10n.Tr("I understand"), L10n.Tr("Cancel")))
{
GUIUtility.ExitGUI();
return;
}
Export();
GUIUtility.ExitGUI();
}
GUILayout.Space(10);
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.EndVertical();
}
private void TreeViewArea(bool showLoadingScreen)
{
Rect treeAreaRect = GUILayoutUtility.GetRect(1, 9999, 1, 99999);
if (showLoadingScreen)
{
GUI.Label(treeAreaRect, "Loading...", Styles.loadingTextStyle);
return;
}
if (m_ExportPackageItems != null && m_ExportPackageItems.Length > 0)
{
if (m_TreeViewState == null)
m_TreeViewState = new TreeViewState();
if (m_Tree == null)
m_Tree = new PackageExportTreeView(this, m_TreeViewState, new Rect());
m_Tree.OnGUI(treeAreaRect);
}
}
private void Export()
{
string fileName = EditorUtility.SaveFilePanel("Export package ...", "", "", "unitypackage");
if (fileName != "")
{
// build guid list
List<string> guids = new List<string>();
foreach (ExportPackageItem ai in m_ExportPackageItems)
{
if (ai.enabledStatus > 0)
guids.Add(ai.guid);
}
PackageUtility.ExportPackage(guids.ToArray(), fileName);
Close();
GUIUtility.ExitGUI();
}
}
private void ScheduleBuildAssetList()
{
if (!m_DidScheduleUpdate)
{
EditorApplication.update += BuildAssetList;
m_DidScheduleUpdate = true;
}
}
private void UnscheduleBuildAssetList()
{
if (m_DidScheduleUpdate)
{
m_DidScheduleUpdate = false;
EditorApplication.update -= BuildAssetList;
}
}
private void BuildAssetList()
{
UnscheduleBuildAssetList();
m_ExportPackageItems = GetAssetItemsForExport(Selection.assetGUIDsDeepSelection, m_IncludeDependencies).ToArray();
// GUI is reconstructed in OnGUI (when needed)
m_Tree = null;
m_TreeViewState = null;
Repaint();
}
}
}
| UnityCsReference/Editor/Mono/GUI/PackageExport.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/PackageExport.cs",
"repo_id": "UnityCsReference",
"token_count": 4939
} | 275 |
// 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 void SliderWithTexture(
GUIContent label,
SerializedProperty property,
float sliderMin, float sliderMax,
float power,
Texture2D sliderBackground,
params GUILayoutOption[] options
)
{
var rect = s_LastRect = GetSliderRect(false, options);
EditorGUI.SliderWithTexture(rect, label, property, sliderMin, sliderMax, power, sliderBackground);
}
internal static float SliderWithTexture(
GUIContent label,
float sliderValue, float sliderMin, float sliderMax,
string formatString,
Texture2D sliderBackground,
params GUILayoutOption[] options
)
{
return SliderWithTexture(
label, sliderValue, sliderMin, sliderMax, formatString, sliderMin, sliderMax, sliderBackground
);
}
internal static float SliderWithTexture(
GUIContent label,
float sliderValue, float sliderMin, float sliderMax,
string formatString, float textFieldMin, float textFieldMax,
Texture2D sliderBackground,
params GUILayoutOption[] options
)
{
var rect = s_LastRect = GetSliderRect(false, options);
return EditorGUI.SliderWithTexture(
rect, label, sliderValue, sliderMin, sliderMax, formatString, textFieldMin, textFieldMax, 1f, sliderBackground
);
}
}
public sealed partial class EditorGUI
{
internal static void SliderWithTexture(
Rect position,
GUIContent label,
SerializedProperty property,
float sliderMin, float sliderMax,
float power,
Texture2D sliderBackground
)
{
label = BeginProperty(position, label, property);
BeginChangeCheck();
var formatString = property.propertyType == SerializedPropertyType.Integer ?
kIntFieldFormatString : kFloatFieldFormatString;
var newValue = SliderWithTexture(
position, label, property.floatValue, sliderMin, sliderMax, formatString, sliderMin, sliderMax, power, sliderBackground
);
if (EndChangeCheck())
property.floatValue = newValue;
EndProperty();
}
internal static float SliderWithTexture(
Rect rect,
GUIContent label,
float sliderValue, float sliderMin, float sliderMax,
string formatString,
Texture2D sliderBackground,
params GUILayoutOption[] options
)
{
return SliderWithTexture(
rect, label, sliderValue, sliderMin, sliderMax, formatString, sliderMin, sliderMax, 1f, sliderBackground
);
}
internal static float SliderWithTexture(
Rect position,
GUIContent label,
float sliderValue, float sliderMin, float sliderMax,
string formatString, float textFieldMin, float textFieldMax,
float power,
Texture2D sliderBackground
)
{
int id = GUIUtility.GetControlID(s_SliderHash, FocusType.Keyboard, position);
var controlRect = PrefixLabel(position, id, label);
var dragZone =
LabelHasContent(label)
? EditorGUIUtility.DragZoneRect(position)
: default(Rect); // Ensure dragzone is empty when we have no label
return DoSlider(
controlRect, dragZone, id, sliderValue, sliderMin, sliderMax, formatString, textFieldMin, textFieldMax, power, 1f,
EditorStyles.numberField, "ColorPickerSliderBackground", "ColorPickerHorizThumb", sliderBackground, null
);
}
}
}
| UnityCsReference/Editor/Mono/GUI/SliderWithTexture.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/SliderWithTexture.cs",
"repo_id": "UnityCsReference",
"token_count": 1832
} | 276 |
// 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.SceneManagement;
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using System.Linq;
using System.Collections.Generic;
using UnityEditor.IMGUI.Controls;
using UnityEngine.Assertions;
using UnityEngine.Profiling;
using Object = UnityEngine.Object;
namespace UnityEditor
{
// GameObjectTreeViewDataSource only fetches current visible items of the scene tree, because we derive from LazyTreeViewDataSource
// Note: every time a Item's expanded state changes FetchData is called
internal class GameObjectTreeViewDataSource : LazyTreeViewDataSource
{
const double k_LongFetchTime = 0.05; // How much time is considered to be a long fetch
const double k_FetchDelta = 0.1; // How much time between long fetches is acceptable.
const int k_MaxDelayedFetch = 5; // How many consecutive fetches can be delayed.
const HierarchyType k_HierarchyType = HierarchyType.GameObjects;
const int k_DefaultStartCapacity = 1000;
int m_RootInstanceID;
string m_SearchString = "";
readonly SearchService.SceneSearchSessionHandler m_SearchSessionHandler = new SearchService.SceneSearchSessionHandler();
SearchableEditorWindow.SearchModeHierarchyWindow m_SearchMode = 0; // 0 = All
double m_LastFetchTime = 0.0;
int m_DelayedFetches = 0;
bool m_NeedsChildParentReferenceSetup;
bool m_RowsPartiallyInitialized;
int m_RowCount;
List<TreeViewItem> m_ListOfRows; // We need the generic List type in this class for Add/RemoveRange and Sorting (m_Rows is IList)
List<GameObjectTreeViewItem> m_StickySceneHeaderItems = new List<GameObjectTreeViewItem>();
internal event System.Action beforeReloading;
public HierarchySorting sortingState = new TransformSorting();
public List<GameObjectTreeViewItem> sceneHeaderItems { get { return m_StickySceneHeaderItems; } }
public string searchString
{
get
{
return m_SearchString;
}
set
{
if (string.IsNullOrEmpty(value) && !string.IsNullOrEmpty(m_SearchString))
ClearSearchFilter();
m_SearchString = value;
}
}
public SearchableEditorWindow.SearchModeHierarchyWindow searchMode { get { return m_SearchMode; } set { m_SearchMode = value; } }
public bool isFetchAIssue { get { return m_DelayedFetches >= k_MaxDelayedFetch; } }
public Scene[] scenes { get; set; }
public GameObjectTreeViewDataSource(TreeViewController treeView, int rootInstanceID, bool showRoot, bool rootItemIsCollapsable)
: base(treeView)
{
m_RootInstanceID = rootInstanceID;
showRootItem = showRoot;
rootIsCollapsable = rootItemIsCollapsable;
}
internal void SetupChildParentReferencesIfNeeded()
{
// Ensure all rows are initialized (not only the visible)
EnsureFullyInitialized();
// We delay the calling SetChildParentReferences until needed to ensure fast reloading of
// the game object hierarchy (in playmode this prevent hiccups for large scenes)
if (m_NeedsChildParentReferenceSetup)
{
m_NeedsChildParentReferenceSetup = false;
TreeViewUtility.SetChildParentReferences(GetRows(), m_RootItem);
}
}
public void EnsureFullyInitialized()
{
if (m_RowsPartiallyInitialized)
{
InitializeFull();
m_RowsPartiallyInitialized = false;
}
}
override public int rowCount
{
get
{
return m_RowCount;
}
}
public override void RevealItem(int itemID)
{
// Optimization: Only spend time on revealing item if it is part of the Hierarchy
if (IsValidHierarchyInstanceID(itemID))
base.RevealItem(itemID);
}
public override void RevealItems(int[] itemIDs)
{
// Optimization: Only spend time on revealing item if it is part of the Hierarchy
HashSet<int> validItemIDs = new HashSet<int>();
foreach (var itemID in itemIDs)
{
if (IsValidHierarchyInstanceID(itemID))
validItemIDs.Add(itemID);
}
// Get existing expanded in hashset
HashSet<int> expandedSet = new HashSet<int>(expandedIDs);
int orgSize = expandedSet.Count;
IHierarchyProperty propertyIterator = CreateHierarchyProperty();
int[] ancestors = propertyIterator.FindAllAncestors(validItemIDs.ToArray());
// Add all parents above id
foreach (var itemID in ancestors)
{
expandedSet.Add(itemID);
}
if (orgSize != expandedSet.Count)
{
// Bulk set expanded ids (is sorted in SetExpandedIDs)
SetExpandedIDs(expandedSet.ToArray());
// Refresh immediately if any Item was expanded
if (m_NeedRefreshRows)
FetchData();
}
}
override public bool IsRevealed(int id)
{
return GetRow(id) != -1;
}
private bool IsValidHierarchyInstanceID(int instanceID)
{
//Get is persistent without loading object
var obj = InternalEditorUtility.GetObjectFromInstanceID(instanceID);
if (obj != null ? EditorUtility.IsPersistent(obj) : AssetDatabase.Contains(instanceID))
return false;
if (SceneHierarchy.IsSceneHeaderInHierarchyWindow(EditorSceneManager.GetSceneByHandle(instanceID)))
return true;
if (InternalEditorUtility.GetTypeWithoutLoadingObject(instanceID) == typeof(GameObject))
return true;
return false;
}
HierarchyProperty FindHierarchyProperty(int instanceID)
{
// Optimization: Prevent search by early out if 'id' is not a game object (or scene handle)
if (!IsValidHierarchyInstanceID(instanceID))
return null;
HierarchyProperty property = CreateHierarchyProperty();
if (property.Find(instanceID, m_TreeView.state.expandedIDs.ToArray()))
return property;
return null;
}
override public int GetRow(int id)
{
bool isSearching = !string.IsNullOrEmpty(m_SearchString);
if (isSearching)
return base.GetRow(id);
// We read from the backend directly instead of using GetRows()
// because we might not yet have initialized tree view after creating a new
// game object. GetRows also needs full init which we want to prevent
HierarchyProperty property = FindHierarchyProperty(id);
if (property != null)
return property.row;
return -1;
}
override public TreeViewItem GetItem(int row)
{
return m_Rows[row];
}
public override IList<TreeViewItem> GetRows()
{
InitIfNeeded();
EnsureFullyInitialized();
return m_Rows;
}
override public TreeViewItem FindItem(int id)
{
// Since this is a LazyTreeViewDataSource that only knows about expanded items
// we need to reveal the item before searching for it (expand its ancestors)
RevealItem(id);
// Since RevealItem can have reloaded data because items was revealed we need to make
// sure that parent child references is set up
SetupChildParentReferencesIfNeeded();
return base.FindItem(id);
}
bool AreScenesValid(Scene[] customScenes)
{
if (customScenes == null)
return false;
foreach (var scene in customScenes)
if (!scene.IsValid())
return false;
return true;
}
internal HierarchyProperty CreateHierarchyProperty()
{
HierarchyProperty property = new HierarchyProperty(k_HierarchyType);
property.alphaSorted = IsUsingAlphaSort();
property.showSceneHeaders = ShouldShowSceneHeaders();
if (SceneHierarchyHooks.provideSubScenes != null)
property.SetSubScenes(SceneHierarchyHooks.provideSubScenes());
if (AreScenesValid(scenes))
property.SetCustomScenes(scenes);
return property;
}
internal bool ShouldShowSceneHeaders()
{
// Don't show headers if there's a single scene and it's a preview scene.
return (scenes == null || scenes.Length != 1 || !EditorSceneManager.IsPreviewScene(scenes[0]));
}
void CreateRootItem(HierarchyProperty property)
{
int rootDepth = 0; // hiddden
if (property.isValid)
{
// Game Object sub tree
m_RootItem = new GameObjectTreeViewItem(m_RootInstanceID, rootDepth, null, property.name);
}
else
{
// All game objects
m_RootItem = new GameObjectTreeViewItem(m_RootInstanceID, rootDepth, null, "RootOfAll");
}
}
void ClearSearchFilter()
{
var property = CreateHierarchyProperty();
property.SetSearchFilter("", 0); // 0 = All
m_SearchSessionHandler.EndSession();
}
public override void FetchData()
{
beforeReloading?.Invoke();
Profiler.BeginSample("SceneHierarchyWindow.FetchData");
m_RowsPartiallyInitialized = false;
double fetchStartTime = EditorApplication.timeSinceStartup;
HierarchyProperty property = CreateHierarchyProperty();
if (m_RootInstanceID != 0)
{
bool found = property.Find(m_RootInstanceID, null);
if (!found)
{
Debug.LogError("Root gameobject with id " + m_RootInstanceID + " not found!!");
m_RootInstanceID = 0;
property.Reset();
}
}
CreateRootItem(property);
// Must be set before SetSelection (they calls GetRows which will fetch again if m_NeedRefreshVisibleFolders = true)
m_NeedRefreshRows = false;
m_NeedsChildParentReferenceSetup = true;
bool subTreeWanted = m_RootInstanceID != 0;
bool isSearching = !string.IsNullOrEmpty(m_SearchString);
if (isSearching)
{
m_SearchSessionHandler.BeginSession(() => new SearchService.SceneSearchContext {rootProperty = property});
}
if (isSearching || subTreeWanted)
{
InitializeProgressivly(property, subTreeWanted, isSearching);
}
else
{
// We delay the setup of the full data and calling SetChildParentReferences to ensure fast reloading of
// the game object hierarchy
InitializeMinimal();
}
double fetchEndTime = EditorApplication.timeSinceStartup;
double fetchTotalTime = fetchEndTime - fetchStartTime;
double fetchDeltaTime = fetchEndTime - m_LastFetchTime;
// If we have two relatively close consecutive fetches check execution time.
if (fetchDeltaTime > k_FetchDelta && fetchTotalTime > k_LongFetchTime)
m_DelayedFetches++;
else
m_DelayedFetches = 0;
m_LastFetchTime = fetchStartTime;
// We want to reset selection on copy/duplication/delete
m_TreeView.SetSelection(Selection.instanceIDs, false); // use false because we might just be expanding/collapsing a Item (which would prevent collapsing a Item with a selected child)
CreateSceneHeaderItems();
if (SceneHierarchy.s_Debug)
Debug.Log("Fetch time: " + fetchTotalTime * 1000.0 + " ms, alphaSort = " + IsUsingAlphaSort());
Profiler.EndSample();
}
public override bool CanBeParent(TreeViewItem item)
{
// Ensure parent child-parent references are setup if requesting parent information
SetupChildParentReferencesIfNeeded();
return base.CanBeParent(item);
}
bool IsUsingAlphaSort()
{
return sortingState.GetType() == typeof(AlphabeticalSorting);
}
static void Resize(List<TreeViewItem> list, int count)
{
int cur = list.Count;
if (count < cur)
list.RemoveRange(count, cur - count);
else if (count > cur)
{
if (count > list.Capacity) // this bit is purely an optimisation, to avoid multiple automatic capacity changes.
list.Capacity = count + 20; // add some extra to prevent alloc'ing when adding to list
list.AddRange(Enumerable.Repeat(default(TreeViewItem), count - cur)); // add range is nulls
}
}
private void ResizeItemList(int count)
{
AllocateBackingArrayIfNeeded();
if (m_ListOfRows.Count != count)
{
Resize(m_ListOfRows, count);
Assert.AreEqual(m_ListOfRows.Count, count, "List of rows count incorrect");
}
}
private void AllocateBackingArrayIfNeeded()
{
if (m_Rows == null)
{
int startCapacity = m_RowCount > k_DefaultStartCapacity ? m_RowCount : k_DefaultStartCapacity;
m_ListOfRows = new List<TreeViewItem>(startCapacity);
m_Rows = m_ListOfRows;
}
}
private void InitializeMinimal()
{
int[] expanded = m_TreeView.state.expandedIDs.ToArray();
HierarchyProperty property = CreateHierarchyProperty();
m_RowCount = property.CountRemaining(expanded);
ResizeItemList(m_RowCount);
property.Reset();
if (SceneHierarchy.s_Debug)
Log("Init minimal (" + m_RowCount + ") num scenes " + SceneManager.sceneCount);
int firstRow, lastRow;
m_TreeView.gui.GetFirstAndLastRowVisible(out firstRow, out lastRow);
InitializeRows(property, firstRow, lastRow);
m_RowsPartiallyInitialized = true;
}
void InitializeFull()
{
if (SceneHierarchy.s_Debug)
Log("Init full (" + m_RowCount + ")");
HierarchyProperty property = CreateHierarchyProperty();
m_RowCount = property.CountRemaining(m_TreeView.state.expandedIDs.ToArray());
ResizeItemList(m_RowCount);
property.Reset();
InitializeRows(property, 0, m_RowCount - 1);
}
// Used for search results, sub tree view (of e.g. a prefab) and custom sorting
void InitializeProgressivly(HierarchyProperty property, bool subTreeWanted, bool isSearching)
{
AllocateBackingArrayIfNeeded();
int minAllowedDepth = subTreeWanted ? property.depth + 1 : 0;
if (!isSearching)
{
// Subtree setup
int row = 0;
int[] expanded = expandedIDs.ToArray();
int subtractDepth = subTreeWanted ? property.depth + 1 : 0;
while (property.NextWithDepthCheck(expanded, minAllowedDepth))
{
var item = EnsureCreatedItem(row);
InitTreeViewItem(item, property, property.hasChildren, property.depth - subtractDepth);
row++;
}
m_RowCount = row;
}
else // Searching
{
m_RowCount = InitializeSearchResults(property, minAllowedDepth);
}
// Now shrink to fit if needed
ResizeItemList(m_RowCount);
}
// Returns number of rows in search result
int InitializeSearchResults(HierarchyProperty property, int minAllowedDepth)
{
// Search setup
const bool kShowItemHasChildren = false;
const int kItemDepth = 0;
int currentSceneHandle = -1;
int row = 0;
var searchFilter = SearchableEditorWindow.CreateFilter(searchString, (SearchableEditorWindow.SearchMode)m_SearchMode);
var searchContext = (SearchService.SceneSearchContext)m_SearchSessionHandler.context;
searchContext.searchFilter = searchFilter;
searchContext.rootProperty = property;
m_SearchSessionHandler.BeginSearch(searchString);
var headerRows = new List<int>();
while (property.NextWithDepthCheck(null, minAllowedDepth))
{
if (!m_SearchSessionHandler.Filter(m_SearchString, property))
{
property.SetFilteredVisibility(false);
continue;
}
property.SetFilteredVisibility(true);
var item = EnsureCreatedItem(row);
// Add scene headers when encountering a new scene (and it's not a header in itself)
if (AddSceneHeaderToSearchIfNeeded(item, property, ref currentSceneHandle))
{
row++;
headerRows.Add(row);
if (property.isSceneHeader)
continue; // no need to add it
item = EnsureCreatedItem(row); // prepare for item below
}
InitTreeViewItem(item, property, kShowItemHasChildren, kItemDepth);
row++;
}
m_SearchSessionHandler.EndSearch();
int numRows = row;
// Now sort scene section
if (headerRows.Count > 0)
{
int currentSortStart = headerRows[0];
for (int i = 1; i < headerRows.Count; i++)
{
int count = headerRows[i] - currentSortStart - 1;
m_ListOfRows.Sort(currentSortStart, count, new TreeViewItemAlphaNumericSort());
currentSortStart = headerRows[i];
}
// last section
m_ListOfRows.Sort(currentSortStart, numRows - currentSortStart, new TreeViewItemAlphaNumericSort());
}
return numRows;
}
bool AddSceneHeaderToSearchIfNeeded(GameObjectTreeViewItem item, HierarchyProperty property, ref int currentSceneHandle)
{
if (PrefabStageUtility.GetCurrentPrefabStage() != null)
return false;
Scene scene = property.GetScene();
if (currentSceneHandle != scene.handle)
{
currentSceneHandle = scene.handle;
InitTreeViewItem(item, scene.handle, scene, true, 0, null, false, 0);
return true;
}
return false;
}
GameObjectTreeViewItem EnsureCreatedItem(int row)
{
if (row >= m_Rows.Count)
m_Rows.Add(null);
var item = (GameObjectTreeViewItem)m_Rows[row];
if (item == null)
{
item = new GameObjectTreeViewItem(0, 0, null, null);
m_Rows[row] = item;
}
return item;
}
void InitializeRows(HierarchyProperty property, int firstRow, int lastRow)
{
property.Reset();
int[] expanded = expandedIDs.ToArray();
// Skip items if needed
if (firstRow > 0)
{
int numRowsToSkip = firstRow;
if (!property.Skip(numRowsToSkip, expanded))
Debug.LogError("Failed to skip " + numRowsToSkip);
}
// Fetch visible items
int row = firstRow;
while (property.Next(expanded) && row <= lastRow)
{
var item = EnsureCreatedItem(row);
InitTreeViewItem(item, property, property.hasChildren, property.depth);
row++;
}
}
private void InitTreeViewItem(GameObjectTreeViewItem item, HierarchyProperty property, bool itemHasChildren, int itemDepth)
{
InitTreeViewItem(item, property.instanceID, property.GetScene(), property.isSceneHeader, property.colorCode, property.pptrValue, itemHasChildren, itemDepth);
}
private void InitTreeViewItem(GameObjectTreeViewItem item, int itemID, Scene scene, bool isSceneHeader, int colorCode, Object pptrObject, bool hasChildren, int depth)
{
item.children = null;
item.id = itemID;
item.depth = depth;
item.parent = null;
item.icon = null;
if (isSceneHeader)
item.displayName = string.IsNullOrEmpty(scene.name) ? "Untitled" : scene.name;
else
item.displayName = null; // For GameObject, name is empty as the name gets set from the objectPPTR if the Item is used in GameObjectTreeViewGUI.
item.colorCode = colorCode;
item.objectPPTR = pptrObject;
item.isSceneHeader = isSceneHeader;
item.scene = scene;
item.lazyInitializationDone = false;
item.showPrefabModeButton = false;
item.overlayIcon = null;
if (hasChildren)
{
item.children = CreateChildListForCollapsedParent(); // add a dummy child in children list to ensure we show the collapse arrow (because we do not fetch data for collapsed items)
}
}
protected override void GetParentsAbove(int id, HashSet<int> parentsAbove)
{
if (!IsValidHierarchyInstanceID(id))
return;
IHierarchyProperty propertyIterator = CreateHierarchyProperty();
if (propertyIterator.Find(id, null))
{
while (propertyIterator.Parent())
{
parentsAbove.Add((propertyIterator.instanceID));
}
}
}
// Should return the items that have children from id and below
protected override void GetParentsBelow(int id, HashSet<int> parentsBelow)
{
// Add all children expanded ids to hashset
if (!IsValidHierarchyInstanceID(id))
return;
IHierarchyProperty search = CreateHierarchyProperty();
if (search.Find(id, null))
{
parentsBelow.Add(id);
int depth = search.depth;
while (search.Next(null) && search.depth > depth)
{
if (search.hasChildren)
parentsBelow.Add(search.instanceID);
}
}
}
static void Log(string text)
{
//System.Console.WriteLine(text);
Debug.Log(text);
}
override public bool IsRenamingItemAllowed(TreeViewItem item)
{
GameObjectTreeViewItem goItem = item as GameObjectTreeViewItem;
if (goItem.isSceneHeader)
return false;
if (SubSceneGUI.IsUsingSubScenes() && SubSceneGUI.IsSubSceneHeader((GameObject)goItem.objectPPTR))
return false;
return true;
}
void CreateSceneHeaderItems()
{
m_StickySceneHeaderItems.Clear();
int numScenesInHierarchy = EditorSceneManager.sceneCount;
if (SubSceneGUI.IsUsingSubScenes())
{
for (int i = 0; i < numScenesInHierarchy; ++i)
{
Scene scene = SceneManager.GetSceneAt(i);
var subSceneInfo = SubSceneGUI.GetSubSceneInfo(scene);
if (subSceneInfo.isValid)
{
var item = new GameObjectTreeViewItem(0, 0, null, null);
var transform = subSceneInfo.transform;
GameObject gameObject = transform.gameObject;
int depth = SubSceneGUI.CalculateHierarchyDepthOfSubScene(subSceneInfo);
InitTreeViewItem(item, gameObject.GetInstanceID(), subSceneInfo.scene, false, 0, gameObject, false, depth);
m_StickySceneHeaderItems.Add(item);
}
else
{
var item = new GameObjectTreeViewItem(0, 0, null, null);
InitTreeViewItem(item, scene.handle, scene, true, 0, null, false, 0);
m_StickySceneHeaderItems.Add(item);
}
}
}
else
{
for (int i = 0; i < numScenesInHierarchy; ++i)
{
Scene scene = SceneManager.GetSceneAt(i);
var item = new GameObjectTreeViewItem(0, 0, null, null);
InitTreeViewItem(item, scene.handle, scene, true, 0, null, false, 0);
m_StickySceneHeaderItems.Add(item);
}
}
}
public Scene GetLastScene()
{
if (scenes != null)
{
for (int i = scenes.Length - 1; i >= 0; i--)
if (scenes[i].isLoaded && !scenes[i].isSubScene)
return scenes[i];
}
for (int i = SceneManager.sceneCount - 1; i >= 0; i--)
if (SceneManager.GetSceneAt(i).isLoaded && !SceneManager.GetSceneAt(i).isSubScene)
return SceneManager.GetSceneAt(i);
Assert.IsTrue(false, "No loaded scene could be found");
return new Scene();
}
}
}
| UnityCsReference/Editor/Mono/GUI/TreeView/GameObjectTreeViewDataSource.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/GameObjectTreeViewDataSource.cs",
"repo_id": "UnityCsReference",
"token_count": 12525
} | 277 |
// 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
{
class TreeViewControlGUI : TreeViewGUI
{
readonly TreeView m_Owner;
List<Rect> m_RowRects; // If m_RowRects is null fixed row height is used
Rect[] m_CellRects; // Allocated once and reused
const float k_BackgroundWidth = 100000f; // The TreeView can have a horizontal scrollbar so ensure to fill out the entire width of the background
public float borderWidth = 1f;
public TreeViewControlGUI(TreeViewController treeView, TreeView owner)
: base(treeView)
{
m_Owner = owner;
cellMargin = MultiColumnHeader.DefaultGUI.columnContentMargin;
}
public void RefreshRowRects(IList<TreeViewItem> rows)
{
if (m_RowRects == null)
m_RowRects = new List<Rect>(rows.Count);
if (m_RowRects.Capacity < rows.Count)
m_RowRects.Capacity = rows.Count;
m_RowRects.Clear();
float curY = k_TopRowMargin;
for (int row = 0; row < rows.Count; ++row)
{
float height = m_Owner.GetCustomRowHeight(row, rows[row]);
m_RowRects.Add(new Rect(0f, curY, 1f, height)); // row width is updatd to the actual visibleRect of the TreeView's scrollview on the fly
curY += height;
}
}
public float cellMargin { get; set; }
public float foldoutWidth
{
get { return foldoutStyleWidth; }
}
public int columnIndexForTreeFoldouts { get; set; } // column 0 is the default column for the tree foldouts
public float totalHeight
{
get { return (useCustomRowRects ? customRowsTotalHeight : base.GetTotalSize().y) + (m_Owner.multiColumnHeader != null ? m_Owner.multiColumnHeader.height : 0f); }
}
public override Vector2 GetTotalSize()
{
Vector2 contentSize = useCustomRowRects ? new Vector2(1, customRowsTotalHeight) : base.GetTotalSize();
// If we have multi column state we use the width of the columns so we show the horizontal scrollbar if needed
if (m_Owner.multiColumnHeader != null)
contentSize.x = Mathf.Floor(m_Owner.multiColumnHeader.state.widthOfAllVisibleColumns);
return contentSize;
}
bool useCustomRowRects
{
get { return m_RowRects != null; }
}
float customRowsTotalHeight
{
get
{
return
(m_RowRects.Count > 0 ? m_RowRects[m_RowRects.Count - 1].yMax : 0f) + k_BottomRowMargin
- (m_TreeView.expansionAnimator.isAnimating ? m_TreeView.expansionAnimator.deltaHeight : 0f);
}
}
// We only override DrawIconAndLabel (and not OnRowGUI) so the user only have to care about item content rendering; and not drag marker rendering, renaming and foldout button
protected override void OnContentGUI(Rect rect, int row, TreeViewItem item, string label, bool selected, bool focused, bool useBoldFont, bool isPinging)
{
// We do not support pinging in the TreeView (to simplify api)
if (isPinging)
return;
// Make sure the GUI contents for each row is starting with its own controlID unique to its item. This prevents key-focus of a control (e.g a float field)
// to jump from row to row when mouse scrolling (due to culling of rows and the assigning of controlIDs in call-order)
GUIUtility.GetControlID(TreeViewController.GetItemControlID(item), FocusType.Passive);
if (m_Owner.m_OverriddenMethods.hasRowGUI)
{
var args = new RowGUIArgs
{
rowRect = rect,
row = row,
item = item,
label = label,
selected = selected,
focused = focused,
isRenaming = IsRenaming(item.id),
};
// For multi column header we call OnRowGUI for each cell with the cell rect
if (m_Owner.multiColumnHeader != null)
{
//args.columnInfo = m_ColumnInfo;
var visibleColumns = m_Owner.multiColumnHeader.state.visibleColumns;
if (m_CellRects == null || m_CellRects.Length != visibleColumns.Length)
m_CellRects = new Rect[visibleColumns.Length];
var columns = m_Owner.multiColumnHeader.state.columns;
var columnRect = args.rowRect;
for (int i = 0; i < visibleColumns.Length; ++i)
{
var columnData = columns[visibleColumns[i]];
columnRect.width = columnData.width;
m_CellRects[i] = columnRect;
// Use cell margins for all columns except the column with the tree view foldouts
// since that column assumes full cell rect for rename overlay placement
if (columnIndexForTreeFoldouts != visibleColumns[i])
{
m_CellRects[i].x += cellMargin;
m_CellRects[i].width -= 2 * cellMargin;
}
columnRect.x += columnData.width;
}
args.columnInfo = new RowGUIArgs.MultiColumnInfo(m_Owner.multiColumnHeader.state, m_CellRects);
}
m_Owner.RowGUI(args);
}
else
{
// Default item gui
base.OnContentGUI(rect, row, item, label, selected, focused, useBoldFont, false);
}
}
internal void DefaultRowGUI(RowGUIArgs args)
{
base.OnContentGUI(args.rowRect, args.row, args.item, args.label, args.selected, args.focused, false, false);
}
protected override Rect DoFoldout(Rect rowRect, TreeViewItem item, int row)
{
// For multicolumn setup we need to ensure foldouts are clipped so they are not in the next column
if (m_Owner.multiColumnHeader != null)
return DoMultiColumnFoldout(rowRect, item, row);
return base.DoFoldout(rowRect, item, row);
}
Rect DoMultiColumnFoldout(Rect rowRect, TreeViewItem item, int row)
{
if (!m_Owner.multiColumnHeader.IsColumnVisible(columnIndexForTreeFoldouts))
return new Rect();
Rect cellRect = m_Owner.GetCellRectForTreeFoldouts(rowRect);
// Clip foldout arrow if the cell is not big enough
if (GetContentIndent(item) > cellRect.width)
{
GUIClip.Push(cellRect, Vector2.zero, Vector2.zero, false);
cellRect.x = cellRect.y = 0f; // set guiclip coords
Rect foldoutRect = base.DoFoldout(cellRect, item, row);
GUIClip.Pop();
return foldoutRect;
}
return base.DoFoldout(cellRect, item, row);
}
public override Rect GetRenameRect(Rect rowRect, int row, TreeViewItem item)
{
if (m_Owner.m_OverriddenMethods.hasGetRenameRect)
{
return m_Owner.GetRenameRect(rowRect, row, item);
}
return base.GetRenameRect(rowRect, row, item);
}
public Rect DefaultRenameRect(Rect rowRect, int row, TreeViewItem item)
{
return base.GetRenameRect(rowRect, row, item);
}
public override void BeginRowGUI()
{
base.BeginRowGUI();
if (m_Owner.isDragging && m_Owner.multiColumnHeader != null && columnIndexForTreeFoldouts > 0)
{
// Adjust insertion marker for multi column setups
int visibleColumnIndex = m_Owner.multiColumnHeader.GetVisibleColumnIndex(columnIndexForTreeFoldouts);
extraInsertionMarkerIndent = m_Owner.multiColumnHeader.GetColumnRect(visibleColumnIndex).x;
}
m_Owner.BeforeRowsGUI();
}
public override void EndRowGUI()
{
base.EndRowGUI();
m_Owner.AfterRowsGUI();
}
protected override void RenameEnded()
{
var renameState = m_TreeView.state.renameOverlay;
var renameEndedArgs = new RenameEndedArgs
{
acceptedRename = renameState.userAcceptedRename,
itemID = renameState.userData,
originalName = renameState.originalName,
newName = renameState.name
};
m_Owner.RenameEnded(renameEndedArgs);
}
public override Rect GetRowRect(int row, float rowWidth)
{
if (!useCustomRowRects)
{
return base.GetRowRect(row, rowWidth);
}
if (row < 0 || row >= m_RowRects.Count)
{
throw new ArgumentOutOfRangeException("row", string.Format("Input row index: {0} is invalid. Number of rows rects: {1}. (Number of rows: {2})", row, m_RowRects.Count, m_Owner.m_DataSource.rowCount));
}
Rect rowRect = m_RowRects[row];
rowRect.width = rowWidth;
return rowRect;
}
public override Rect GetRectForFraming(int row)
{
return GetRowRect(row, 1);
}
// Should return the row number of the first and last row thats fits in the pixel rect defined by top and height
public override void GetFirstAndLastRowVisible(out int firstRowVisible, out int lastRowVisible)
{
if (!useCustomRowRects)
{
base.GetFirstAndLastRowVisible(out firstRowVisible, out lastRowVisible);
return;
}
if (m_TreeView.data.rowCount == 0)
{
firstRowVisible = lastRowVisible = -1;
return;
}
var rowCount = m_TreeView.data.rowCount;
if (rowCount != m_RowRects.Count)
{
var errorMessage = string.Format(
"Number of rows does not match number of row rects. Did you remember to update the row rects when BuildRootAndRows was called? Number of rows: {0}, number of custom row rects: {1}. Falling back to fixed row height.",
rowCount, m_RowRects.Count);
m_RowRects = null;
throw new InvalidOperationException(errorMessage);
}
float topPixel = m_TreeView.state.scrollPos.y;
float heightInPixels = m_TreeView.GetTotalRect().height;
int firstVisible = -1;
int lastVisible = -1;
for (int i = 0; i < m_RowRects.Count; ++i)
{
bool visible = ((m_RowRects[i].y > topPixel && (m_RowRects[i].y < topPixel + heightInPixels))) ||
((m_RowRects[i].yMax > topPixel && (m_RowRects[i].yMax < topPixel + heightInPixels)));
if (visible)
{
if (firstVisible == -1)
firstVisible = i;
lastVisible = i;
}
}
if (firstVisible != -1 && lastVisible != -1)
{
firstRowVisible = firstVisible;
lastRowVisible = lastVisible;
}
else
{
firstRowVisible = 0;
lastRowVisible = rowCount - 1;
}
}
protected override void DrawItemBackground(Rect rect, int row, TreeViewItem item, bool selected, bool focused)
{
base.DrawItemBackground(rect, row, item, selected, focused);
// To ensure backgrounds are also animated when animating expansion we render the rows backgrounds individually here. When not animating expansion the backgrounds
// are rendered in one go in DrawAlternatingRowBackgrounds() which also handles background outside rows
if (m_Owner.showAlternatingRowBackgrounds && m_TreeView.animatingExpansion)
{
rect.width = k_BackgroundWidth;
var bgStyle = row % 2 == 0 ? DefaultStyles.backgroundEven : DefaultStyles.backgroundOdd;
bgStyle.Draw(rect, false, false, false, false);
}
}
public void DrawAlternatingRowBackgrounds()
{
if (Event.current.rawType != EventType.Repaint)
return;
// Render entire bg
float contentYMax = m_Owner.treeViewRect.height + m_Owner.state.scrollPos.y;
DefaultStyles.backgroundOdd.Draw(new Rect(0, 0, k_BackgroundWidth, contentYMax), false, false, false, false);
int first = 0;
var numRows = m_Owner.GetRows().Count;
if (numRows > 0)
{
int last;
GetFirstAndLastRowVisible(out first, out last);
if (first < 0 || first >= numRows)
return;
}
// Render every 2nd row for the entire background (we also show alternating colors below the last item)
Rect rowRect = new Rect(0, 0, 0, m_Owner.rowHeight);
for (int row = first; rowRect.yMax < contentYMax; row++)
{
if (row % 2 == 1)
continue;
if (row < numRows)
rowRect = m_Owner.GetRowRect(row);
else if (row > 0)
rowRect.y += rowRect.height * 2;
rowRect.width = k_BackgroundWidth;
DefaultStyles.backgroundEven.Draw(rowRect, false, false, false, false);
}
}
protected override bool DoFoldoutButton(Rect foldoutRect, bool expandedState, GUIStyle foldoutStyle)
{
if (m_Owner.foldoutOverride != null)
return m_Owner.foldoutOverride(foldoutRect, expandedState, foldoutStyle);
return base.DoFoldoutButton(foldoutRect, expandedState, foldoutStyle);
}
// Returns the rect available within the borders
public Rect DoBorder(Rect rect)
{
EditorGUI.DrawOutline(rect, borderWidth, EditorGUI.kSplitLineSkinnedColor.color);
return new Rect(rect.x + borderWidth, rect.y + borderWidth, rect.width - 2 * borderWidth, rect.height - 2 * borderWidth);
}
}
}
}
| UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlGUI.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewControl/TreeViewControlGUI.cs",
"repo_id": "UnityCsReference",
"token_count": 8414
} | 278 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.IMGUI.Controls;
using UnityEngine;
namespace UnityEditor.TreeViewExamples
{
internal class TreeViewTestWithCustomHeight
{
private BackendData m_BackendData;
private TreeViewController m_TreeView;
public TreeViewTestWithCustomHeight(EditorWindow editorWindow, BackendData backendData, Rect rect)
{
m_BackendData = backendData;
var state = new TreeViewState();
m_TreeView = new TreeViewController(editorWindow, state);
var gui = new TestGUICustomItemHeights(m_TreeView);
var dragging = new TestDragging(m_TreeView, m_BackendData);
var dataSource = new TestDataSource(m_TreeView, m_BackendData);
dataSource.onVisibleRowsChanged += gui.CalculateRowRects;
m_TreeView.Init(rect, dataSource, gui, dragging);
dataSource.SetExpanded(dataSource.root, true);
}
public void OnGUI(Rect rect)
{
int keyboardControl = GUIUtility.GetControlID(FocusType.Keyboard, rect);
m_TreeView.OnGUI(rect, keyboardControl);
}
}
} // UnityEditor
| UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWithCustomHeight.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUI/TreeView/TreeViewTests/TreeViewTestWithCustomHeight.cs",
"repo_id": "UnityCsReference",
"token_count": 519
} | 279 |
// 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 UnityEditorInternal;
using UnityEngine;
namespace UnityEditor
{
class UnifiedInspectView : BaseInspectView
{
Vector2 m_StacktraceScrollPos = new Vector2();
readonly List<IMGUIInstruction> m_Instructions = new List<IMGUIInstruction>();
BaseInspectView m_InstructionClipView;
BaseInspectView m_InstructionStyleView;
BaseInspectView m_InstructionPropertyView;
BaseInspectView m_InstructionLayoutView;
private BaseInspectView m_InstructionNamedControlView;
public UnifiedInspectView(GUIViewDebuggerWindow guiViewDebuggerWindow) : base(guiViewDebuggerWindow)
{
m_InstructionClipView = new GUIClipInspectView(guiViewDebuggerWindow);
m_InstructionStyleView = new StyleDrawInspectView(guiViewDebuggerWindow);
m_InstructionLayoutView = new GUILayoutInspectView(guiViewDebuggerWindow);
m_InstructionPropertyView = new GUIPropertyInspectView(guiViewDebuggerWindow);
m_InstructionNamedControlView = new GUINamedControlInspectView(guiViewDebuggerWindow);
}
public override void UpdateInstructions()
{
m_InstructionClipView.UpdateInstructions();
m_InstructionStyleView.UpdateInstructions();
m_InstructionLayoutView.UpdateInstructions();
m_InstructionPropertyView.UpdateInstructions();
m_InstructionNamedControlView.UpdateInstructions();
/*
This is an expensive operation, it will resolve the callstacks for all instructions.
Currently we marshall all instructions for every GUI Event.
This works okay for windows that doesn't repaint automatically.
We can optmize by only marshalling the visible instructions and caching it.
But I don't really think its needed right now.
*/
m_Instructions.Clear();
GUIViewDebuggerHelper.GetUnifiedInstructions(m_Instructions);
}
public override void ShowOverlay()
{
if (!isInstructionSelected)
{
debuggerWindow.ClearInstructionHighlighter();
return;
}
IMGUIInstruction instruction = m_Instructions[listViewState.row];
var viewForType = GetInspectViewForType(instruction.type);
viewForType.ShowOverlay();
}
protected override int GetInstructionCount()
{
return m_Instructions.Count;
}
protected override void DoDrawInstruction(ListViewElement el, int controlId)
{
IMGUIInstruction instruction = m_Instructions[el.row];
string listDisplayName = GetInstructionListName(el.row);
GUIContent tempContent = GUIContent.Temp(listDisplayName);
var rect = el.position;
rect.xMin += instruction.level * 10;
GUIViewDebuggerWindow.Styles.listItemBackground.Draw(rect, false, false, listViewState.row == el.row, false);
GUIViewDebuggerWindow.Styles.listItem.Draw(rect, tempContent, controlId, listViewState.row == el.row);
}
protected override void DrawInspectedStacktrace(float availableWidth)
{
IMGUIInstruction instruction = m_Instructions[listViewState.row];
m_StacktraceScrollPos = EditorGUILayout.BeginScrollView(m_StacktraceScrollPos, GUIViewDebuggerWindow.Styles.stacktraceBackground, GUILayout.ExpandHeight(false));
DrawStackFrameList(instruction.stack, availableWidth);
EditorGUILayout.EndScrollView();
}
internal override void DoDrawSelectedInstructionDetails(int selectedInstructionIndex)
{
IMGUIInstruction instruction = m_Instructions[selectedInstructionIndex];
var viewForType = GetInspectViewForType(instruction.type);
viewForType.DoDrawSelectedInstructionDetails(instruction.typeInstructionIndex);
}
internal override string GetInstructionListName(int index)
{
IMGUIInstruction instruction = m_Instructions[index];
//string listDisplayName = instruction.type + " #" + instruction.typeInstructionIndex;
//return listDisplayName;
var viewForType = GetInspectViewForType(instruction.type);
return viewForType.GetInstructionListName(instruction.typeInstructionIndex);
}
internal override void OnSelectedInstructionChanged(int index)
{
listViewState.row = index;
if (listViewState.row >= -0)
{
IMGUIInstruction instruction = m_Instructions[listViewState.row];
var viewForType = GetInspectViewForType(instruction.type);
viewForType.OnSelectedInstructionChanged(instruction.typeInstructionIndex);
ShowOverlay();
}
else
{
debuggerWindow.ClearInstructionHighlighter();
}
}
internal override void OnDoubleClickInstruction(int index)
{
IMGUIInstruction instruction = m_Instructions[index];
var viewForType = GetInspectViewForType(instruction.type);
viewForType.OnDoubleClickInstruction(instruction.typeInstructionIndex);
}
BaseInspectView GetInspectViewForType(InstructionType type)
{
switch (type)
{
case InstructionType.kStyleDraw:
return m_InstructionStyleView;
case InstructionType.kClipPop:
case InstructionType.kClipPush:
return m_InstructionClipView;
case InstructionType.kLayoutBeginGroup:
case InstructionType.kLayoutEndGroup:
case InstructionType.kLayoutEntry:
return m_InstructionLayoutView;
case InstructionType.kPropertyBegin:
case InstructionType.kPropertyEnd:
return m_InstructionPropertyView;
case InstructionType.kLayoutNamedControl:
return m_InstructionNamedControlView;
default:
throw new NotImplementedException("Unhandled InstructionType");
}
}
}
}
| UnityCsReference/Editor/Mono/GUIDebugger/UnifiedInspectView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GUIDebugger/UnifiedInspectView.cs",
"repo_id": "UnityCsReference",
"token_count": 2741
} | 280 |
// 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;
using UnityEditor;
using UnityEditor.Experimental;
using System.IO;
using System.Collections.Generic;
using UnityEngine.Experimental.Rendering;
/* Some notes on icon caches and loading
*
*
* Caches:
* Icon name to Texture2D:
* gNamedTextures (ObjectImages::Texture2DNamed): string to Texture2D
*
* InstanceID to Image
* gCachedThumbnails (AssetImporter::GetThumbnailForInstanceID) : where image is retrieved from Texture from gNamedTextures
* Used for setting icon for hierarchyProperty
*
* InstanceID to Texture2D
* ms_HackedCache (AssetDatabaseProperty::GetCachedAssetDatabaseIcon) : where tetxure2D icon is generated from the image from gCachedThumbnails
* Cache max size: 200
* Called from C# by AssetDatabase.GetCachedIcon (string assetpath)
*
*
*
*
Icon loading in editor_resources project:
- Texture2DNamed handles reading local files instead of editor resources bundle
Icon loading in other projects
- When reimport of asset (cpp): AssetDatabase::ImportAsset -> MonoImporter::GenerateAssetData -> ImageForMonoScript -> GetImageNames -> ObjectImages::Texture2DNamed
- IconContent -> LoadIconRequired -> LoadIcon -> LoadIconForSkin -> Load (EditorResources.iconsPath + name) as Texture2D;
- AssetDatabase.GetCachedIcon (assetpath) -> CPP -> AssetDatabaseProperty::GetCachedAssetDatabaseIcon
- InternalEditorUtility.GetIconForFile (filename) -> EditorGUIUtility.FindTexture("boo Script Icon") -> CPP -> ObjectImages::Texture2DNamed(cpp)
*/
namespace UnityEditorInternal
{
public class GenerateIconsWithMipLevels
{
private const string k_IconSourceFolder = "Assets/MipLevels For Icons/";
private const string k_IconTargetFolder = "Assets/Editor Default Resources/Icons/Processed";
private const string k_IconMipIdentifier = "@";
class InputData
{
public string sourceFolder;
public string targetFolder;
public string mipIdentifier;
public string mipFileExtension;
public readonly List<string> generatedFileNames = new List<string>(); // for internal use
}
private static InputData GetInputData()
{
return new InputData
{
sourceFolder = EditorResources.ExpandPath(k_IconSourceFolder),
targetFolder = EditorResources.ExpandPath(k_IconTargetFolder),
mipIdentifier = k_IconMipIdentifier,
mipFileExtension = "png"
};
}
// Called from BuildEditorAssetBundles
[RequiredByNativeCode]
public static void GenerateAllIconsWithMipLevels()
{
var data = GetInputData();
EnsureFolderIsCreated(data.targetFolder);
float startTime = Time.realtimeSinceStartup;
GenerateIconsWithMips(data);
Debug.Log(string.Format("Generated {0} icons with mip levels in {1} seconds", data.generatedFileNames.Count, Time.realtimeSinceStartup - startTime));
RemoveUnusedFiles(data.generatedFileNames);
AssetDatabase.Refresh(); // For some reason we creash if we dont refresh twice...
InternalEditorUtility.RepaintAllViews();
}
public static bool VerifyIconPath(string assetPath, bool logError)
{
if (string.IsNullOrEmpty(assetPath))
{
return false;
}
else if (assetPath.IndexOf(k_IconSourceFolder, StringComparison.Ordinal) < 0)
{
if (logError)
Debug.Log("Selection is not a valid mip texture, it should be located in: " + k_IconSourceFolder);
return false;
}
else if (assetPath.IndexOf(k_IconMipIdentifier, StringComparison.Ordinal) < 0)
{
if (logError)
Debug.Log("Selection does not have a valid mip identifier " + assetPath + " " + k_IconMipIdentifier);
return false;
}
return true;
}
// Refresh just one icon (Used in Editor Resources project, find it in Tools/)
[RequiredByNativeCode]
public static void GenerateSelectedIconsWithMips()
{
// If no selection do all
if (Selection.activeInstanceID == 0)
{
Debug.Log("Ensure to select a mip texture..." + Selection.activeInstanceID);
return;
}
int instanceID = Selection.activeInstanceID;
string assetPath = AssetDatabase.GetAssetPath(instanceID);
GenerateIconWithMipLevels(assetPath, null, null);
}
// Refresh just one icon with provided mip levels
public static void GenerateIconWithMipLevels(string assetPath, Dictionary<int, Texture2D> mipTextures, FileInfo fileInfo)
{
if (!VerifyIconPath(assetPath, true))
return;
float startTime = Time.realtimeSinceStartup;
var data = GetInputData();
string baseName = assetPath.Replace(data.sourceFolder, "");
baseName = baseName.Substring(0, baseName.LastIndexOf(data.mipIdentifier, StringComparison.Ordinal));
string cwd = new DirectoryInfo(data.sourceFolder).FullName;
List<string> assetPaths = GetIconAssetPaths(cwd, data.sourceFolder, data.mipIdentifier, data.mipFileExtension);
EnsureFolderIsCreated(data.targetFolder);
if (GenerateIcon(data, baseName, assetPaths, mipTextures, fileInfo))
Debug.Log(string.Format("Generated {0} icon with mip levels in {1} seconds", baseName, Time.realtimeSinceStartup - startTime));
InternalEditorUtility.RepaintAllViews();
}
// Search for the mip level encoded in the asset path
public static int MipLevelForAssetPath(string assetPath, string separator)
{
if (string.IsNullOrEmpty(assetPath) || string.IsNullOrEmpty(separator))
return -1;
int separatorIndex = assetPath.IndexOf(separator, StringComparison.Ordinal);
if (separatorIndex == -1)
{
Debug.LogError("\"" + separator + "\" could not be found in asset path: " + assetPath);
return -1;
}
int startIndex = separatorIndex + separator.Length;
int endIndex = assetPath.IndexOf(".", startIndex, StringComparison.Ordinal);
if (endIndex == -1)
{
Debug.LogError("Could not find path extension in asset path: " + assetPath);
return -1;
}
return Int32.Parse(assetPath.Substring(startIndex, endIndex - startIndex));
}
// Private section
//----------------
private static void GenerateIconsWithMips(InputData inputData)
{
string cwd = new DirectoryInfo(inputData.sourceFolder).FullName;
List<string> files = GetIconAssetPaths(cwd, inputData.sourceFolder, inputData.mipIdentifier, inputData.mipFileExtension);
if (files.Count == 0)
{
Debug.LogWarning("No mip files found for generating icons! Searching in: " + inputData.sourceFolder + ", for files with extension: " + inputData.mipFileExtension);
}
string[] baseNames = GetBaseNames(inputData, files);
// Base name is assumed to be like: "Assets/Icons/..."
foreach (string baseName in baseNames)
GenerateIcon(inputData, baseName, files, null, null);
}
private static bool GenerateIcon(InputData inputData, string baseName, List<string> assetPathsOfAllIcons, Dictionary<int, Texture2D> mipTextures, FileInfo sourceFileInfo)
{
//We need to create the folder before we Create the Asset.
//AssetDatabase.CreateFolder will trigger a Asset Garbage Collection and stack items are not preserved.
string generatedPath = inputData.targetFolder + "/" + baseName + " Icon" + ".asset";
if (sourceFileInfo != null && File.Exists(generatedPath))
{
var fileInfo = new FileInfo(generatedPath);
if (fileInfo.LastWriteTime > sourceFileInfo.LastWriteTime)
{
// The resulting MIPS is newer than the source. Nothing to do.
return false;
}
}
Debug.Log("Generating MIP levels for " + generatedPath);
EnsureFolderIsCreatedRecursively(Path.GetDirectoryName(generatedPath));
Texture2D iconWithMips = CreateIconWithMipLevels(inputData, baseName, assetPathsOfAllIcons, mipTextures);
if (iconWithMips == null)
{
Debug.Log("CreateIconWithMipLevels failed");
return false;
}
iconWithMips.name = baseName + " Icon" + ".png"; // asset name must have .png as extension (used when loading the icon, search for LoadIconForSkin)
// Write texture to disk
AssetDatabase.CreateAsset(iconWithMips, generatedPath);
inputData.generatedFileNames.Add(generatedPath);
return true;
}
private static Texture2D CreateIconWithMipLevels(InputData inputData, string baseName, List<string> assetPathsOfAllIcons, Dictionary<int, Texture2D> mipTextures)
{
List<string> allMipPaths = assetPathsOfAllIcons.FindAll(o => o.IndexOf('/' + baseName + inputData.mipIdentifier, StringComparison.Ordinal) >= 0);
List<Texture2D> allMips = new List<Texture2D>();
foreach (string path in allMipPaths)
{
int mipLevel = MipLevelForAssetPath(path, inputData.mipIdentifier);
Texture2D mip;
if (mipTextures != null && mipTextures.ContainsKey(mipLevel))
mip = mipTextures[mipLevel];
else
mip = GetTexture2D(path);
if (mip != null)
allMips.Add(mip);
else
Debug.LogError("Mip not found " + path);
}
// Sort the mips by size (largest mip first)
allMips.Sort(delegate(Texture2D first, Texture2D second)
{
if (first.width == second.width)
return 0;
else if (first.width < second.width)
return 1;
else
return -1;
});
int minResolution = 99999;
int maxResolution = 0;
foreach (Texture2D mip in allMips)
{
int width = mip.width;
if (width > maxResolution)
maxResolution = width;
if (width < minResolution)
minResolution = width;
}
if (maxResolution == 0)
return null;
// Create our icon
Texture2D iconWithMips = new Texture2D(maxResolution, maxResolution, GraphicsFormat.R8G8B8A8_SRGB, -1, TextureCreationFlags.MipChain);
// Add max mip
if (BlitMip(iconWithMips, allMips, 0))
iconWithMips.Apply(true);
else
return iconWithMips; // ERROR
// Keep for debugging
//Debug.Log ("Processing max mip file: " + inputData.GetMipFileName (baseName, maxResolution) );
// Now add the rest
int resolution = maxResolution;
for (int i = 1; i < iconWithMips.mipmapCount; i++)
{
resolution /= 2;
if (resolution < minResolution)
break;
BlitMip(iconWithMips, allMips, i);
}
iconWithMips.Apply(false, true);
return iconWithMips;
}
private static bool BlitMip(Texture2D iconWithMips, List<Texture2D> sortedTextures, int mipLevel)
{
if (mipLevel < 0 || mipLevel >= sortedTextures.Count)
{
Debug.LogError("Invalid mip level: " + mipLevel);
return false;
}
Texture2D tex = sortedTextures[mipLevel];
if (tex)
{
Blit(tex, iconWithMips, mipLevel);
return true;
}
else
{
Debug.LogError("No texture at mip level: " + mipLevel);
}
return false;
}
private static Texture2D GetTexture2D(string path)
{
return AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
}
static List<string> GetIconAssetPaths(string absolute, string folderPath, string mustHaveIdentifier, string extension)
{
Uri absoluteUri = new Uri(absolute);
List<string> files = new List<string>(Directory.GetFiles(absolute, "*." + extension, SearchOption.AllDirectories));
files.RemoveAll(o => o.IndexOf(mustHaveIdentifier, StringComparison.Ordinal) < 0); // // Remove all files that do not have the 'mustHaveIdentifier'
for (int i = 0; i < files.Count; ++i)
{
Uri fileUri = new Uri(files[i]);
Uri relativeUri = absoluteUri.MakeRelativeUri(fileUri);
files[i] = Uri.UnescapeDataString(folderPath + relativeUri);
}
return files;
}
static void Blit(Texture2D source, Texture2D dest, int mipLevel)
{
Color32[] pixels = source.GetPixels32();
for (int i = 0; i < pixels.Length; i++)
{
Color32 p = pixels[i];
if (p.a >= 3)
p.a -= 3;
pixels[i] = p;
}
dest.SetPixels32(pixels, mipLevel);
}
private static void EnsureFolderIsCreatedRecursively(string targetFolder)
{
if (AssetDatabase.GetMainAssetInstanceID(targetFolder) == 0)
{
EnsureFolderIsCreatedRecursively(Path.GetDirectoryName(targetFolder));
Debug.Log("Created target folder " + targetFolder);
AssetDatabase.CreateFolder(Path.GetDirectoryName(targetFolder), Path.GetFileName(targetFolder));
}
}
private static void EnsureFolderIsCreated(string targetFolder)
{
if (AssetDatabase.GetMainAssetInstanceID(targetFolder) == 0)
{
Debug.Log("Created target folder " + targetFolder);
AssetDatabase.CreateFolder(Path.GetDirectoryName(targetFolder), Path.GetFileName(targetFolder));
}
}
static void DeleteFile(string file)
{
if (AssetDatabase.GetMainAssetInstanceID(file) != 0)
{
Debug.Log("Deleted unused file: " + file);
AssetDatabase.DeleteAsset(file);
}
}
// Get rid of old icons in the Icons folder (with same filename as a generated icon)
static void RemoveUnusedFiles(List<string> generatedFiles)
{
foreach (string file in generatedFiles)
{
string deleteFile = file.Replace("Icons/Processed", "Icons");
deleteFile = deleteFile.Replace(".asset", ".png");
DeleteFile(deleteFile);
// Remove the d_ version as well
string fileName = Path.GetFileNameWithoutExtension(deleteFile);
if (!fileName.StartsWith("d_"))
{
deleteFile = deleteFile.Replace(fileName, ("d_" + fileName));
DeleteFile(deleteFile);
}
}
AssetDatabase.Refresh();
}
private static string[] GetBaseNames(InputData inputData, List<string> files)
{
string[] baseNames = new string[files.Count];
int startPos = inputData.sourceFolder.Length;
for (int i = 0; i < files.Count; ++i)
{
baseNames[i] = files[i].Substring(startPos, files[i].IndexOf(inputData.mipIdentifier, StringComparison.Ordinal) - startPos);
}
HashSet<string> hashset = new HashSet<string>(baseNames);
baseNames = new string[hashset.Count];
hashset.CopyTo(baseNames);
return baseNames;
}
}
} // namespace UnityEditor
| UnityCsReference/Editor/Mono/GenerateIconsWithMipLevels.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/GenerateIconsWithMipLevels.cs",
"repo_id": "UnityCsReference",
"token_count": 7637
} | 281 |
// 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.IMGUI.Controls
{
public class BoxBoundsHandle : PrimitiveBoundsHandle
{
[Obsolete("Use parameterless constructor instead.")]
public BoxBoundsHandle(int controlIDHint) : base(controlIDHint) {}
public BoxBoundsHandle() : base() {}
public UnityEngine.Vector3 size { get { return GetSize(); } set { SetSize(value); } }
protected override void DrawWireframe()
{
Handles.DrawWireCube(center, size);
}
}
}
| UnityCsReference/Editor/Mono/Handles/BoundsHandle/BoxBoundsHandle.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Handles/BoundsHandle/BoxBoundsHandle.cs",
"repo_id": "UnityCsReference",
"token_count": 250
} | 282 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor
{
public sealed partial class Handles
{
internal static Vector2 DoRectHandles(Quaternion rotation, Vector3 position, Vector2 size, bool handlesOnly)
{
Vector3 up = rotation * Vector3.up;
Vector3 right = rotation * Vector3.right;
float halfWidth = 0.5f * size.x;
float halfHeight = 0.5f * size.y;
if (!handlesOnly)
{
Vector3 topRight = position + up * halfHeight + right * halfWidth;
Vector3 bottomRight = position - up * halfHeight + right * halfWidth;
Vector3 bottomLeft = position - up * halfHeight - right * halfWidth;
Vector3 topLeft = position + up * halfHeight - right * halfWidth;
// Draw rectangle
DrawLine(topRight, bottomRight);
DrawLine(bottomRight, bottomLeft);
DrawLine(bottomLeft, topLeft);
DrawLine(topLeft, topRight);
}
// Give handles twice the alpha of the lines
Color origCol = color;
Color col = color;
col.a = Mathf.Clamp01(color.a * 2);
color = ToActiveColorSpace(col);
// Draw handles
halfHeight = SizeSlider(position, up, halfHeight);
halfHeight = SizeSlider(position, -up, halfHeight);
halfWidth = SizeSlider(position, right, halfWidth);
halfWidth = SizeSlider(position, -right, halfWidth);
size.x = Mathf.Max(0f, 2.0f * halfWidth);
size.y = Mathf.Max(0f, 2.0f * halfHeight);
color = origCol;
return size;
}
}
}
| UnityCsReference/Editor/Mono/Handles/RectHandle.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Handles/RectHandle.cs",
"repo_id": "UnityCsReference",
"token_count": 852
} | 283 |
// 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 interface IAudioPlatformProperties : IPlatformProperties
{
// The AudioImporterInspector.OnSampleSettingGUI method uses this property to determine whether or not to display UI
// to set sample rates. This property is true for all build targets except WebGL.
bool HasSampleRateSettings => true;
}
| UnityCsReference/Editor/Mono/IAudioPlatformProperties.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/IAudioPlatformProperties.cs",
"repo_id": "UnityCsReference",
"token_count": 133
} | 284 |
// 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.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEditor;
using UnityEditor.Modules;
namespace UnityEditor
{
internal class EditorPluginImporterExtension : DefaultPluginImporterExtension
{
internal enum EditorPluginCPUArchitecture
{
AnyCPU,
[InspectorName("Intel 64-bit")]
x86_64,
[InspectorName("Apple silicon / Arm64")]
ARM64
}
internal enum EditorPluginOSArchitecture
{
AnyOS,
[InspectorName("macOS")]
OSX,
Windows,
Linux
}
internal class EditorProperty : Property
{
public EditorProperty(GUIContent name, string key, object defaultValue)
: base(name, key, defaultValue, BuildPipeline.GetEditorTargetName())
{
}
internal override void Reset(PluginImporterInspector inspector)
{
string valueString = inspector.importer.GetEditorData(key);
ParseStringValue(inspector, valueString);
}
internal override void Apply(PluginImporterInspector inspector)
{
inspector.importer.SetEditorData(key, value.ToString());
}
}
internal class CPUProperty : Property
{
private readonly Func<Enum, bool> validArch;
public CPUProperty(GUIContent name, string key, EditorPluginCPUArchitecture defaultValue, Func<Enum, bool> validArch)
: base(name, key, defaultValue, BuildPipeline.GetEditorTargetName())
{
this.validArch = validArch;
}
internal override void Reset(PluginImporterInspector inspector)
{
string valueString = inspector.importer.GetEditorData(key);
ParseStringValue(inspector, valueString);
}
internal override void Apply(PluginImporterInspector inspector)
{
inspector.importer.SetEditorData(key, value.ToString());
}
internal override void OnGUI(PluginImporterInspector inspector)
{
value = EditorGUILayout.EnumPopup(name, (Enum)value, validArch, false);
}
}
private CPUProperty editorCPUProperty;
private EditorProperty editorOSProperty;
public EditorPluginImporterExtension() : base(null)
{
editorCPUProperty = new CPUProperty(EditorGUIUtility.TrTextContent("CPU", "The processor architectiure that this plugin is compatible with"), "CPU", EditorPluginCPUArchitecture.AnyCPU, (Enum e) => CanSelectArch(e));
editorOSProperty = new EditorProperty(EditorGUIUtility.TrTextContent("OS", "The Editor operating system that this plugin is compatible with"), "OS", EditorPluginOSArchitecture.AnyOS);
properties = new Property[] { editorOSProperty, editorCPUProperty };
}
public override void OnPlatformSettingsGUI(PluginImporterInspector inspector)
{
EditorGUI.BeginChangeCheck();
editorOSProperty.OnGUI(inspector);
editorCPUProperty.OnGUI(inspector);
if (EditorGUI.EndChangeCheck())
{
if (!CanSelectArch(editorCPUProperty.value as Enum))
editorCPUProperty.value = EditorPluginCPUArchitecture.AnyCPU;
hasModified = true;
}
}
private bool CanSelectArch(Enum value)
{
var arch = (EditorPluginCPUArchitecture)value;
var os = (EditorPluginOSArchitecture)editorOSProperty.value;
switch (os)
{
case EditorPluginOSArchitecture.AnyOS:
return arch == EditorPluginCPUArchitecture.AnyCPU;
case EditorPluginOSArchitecture.OSX:
case EditorPluginOSArchitecture.Windows:
return true;
case EditorPluginOSArchitecture.Linux:
return arch != EditorPluginCPUArchitecture.ARM64;
default:
return false;
}
}
}
}
| UnityCsReference/Editor/Mono/ImportSettings/EditorPluginImporterExtension.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ImportSettings/EditorPluginImporterExtension.cs",
"repo_id": "UnityCsReference",
"token_count": 1991
} | 285 |
// 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 UnityEditor.Compilation;
using UnityEditor.AssetImporters;
using UnityEditor.Scripting.ScriptCompilation;
using UnityEditorInternal;
using UnityEngine;
using AssemblyFlags = UnityEditor.Scripting.ScriptCompilation.AssemblyFlags;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[CustomEditor(typeof(AssemblyDefinitionImporter))]
[CanEditMultipleObjects]
internal class AssemblyDefinitionImporterInspector : AssetImporterEditor
{
internal class Styles
{
public static readonly GUIContent name = EditorGUIUtility.TrTextContent("Name", "The assembly name is used to generate a <name>.dll file on you disk.");
public static readonly GUIContent rootNamespace = EditorGUIUtility.TrTextContent("Root Namespace", "Specify the root namespace of the assembly.");
public static readonly GUIContent defineConstraints = EditorGUIUtility.TrTextContent("Define Constraints", "Specify constraints which determine if the assembly will be compiled or not. The assembly will compile whenever all constraints are met.");
public static readonly GUIContent versionDefines = EditorGUIUtility.TrTextContent("Version Defines", "Specify preprocessor symbols to define based on package, module or Unity versions.");
public static readonly GUIContent resource = EditorGUIUtility.TrTextContent("If resource", "Select 'Unity' or the package or module that you want to set a define for.");
public static readonly GUIContent version = EditorGUIUtility.TrTextContent("version is", "Specify the semantic version of your chosen module, package or Unity Version. You must use mathematical interval notation.");
public static readonly GUIContent define = EditorGUIUtility.TrTextContent("set define", "Specify the name you want this define to have. This define is only set if the expression's condition is satisfied.");
public static readonly GUIContent expressionOutcome = EditorGUIUtility.TrTextContent("Version expression outcome", "Shows the mathematical equation applied to the version number used determine if the symbol should be defined.");
public static readonly GUIContent references = EditorGUIUtility.TrTextContent("Assembly Definition References", "The list of assembly files that this assembly definition should reference.");
public static readonly GUIContent precompiledReferences = EditorGUIUtility.TrTextContent("Assembly References", "The list of Precompiled assemblies that this assembly definition should reference.");
public static readonly GUIContent generalOptions = EditorGUIUtility.TrTextContent("General Options");
public static readonly GUIContent allowUnsafeCode = EditorGUIUtility.TrTextContent("Allow 'unsafe' Code", "When enabled, the C# compiler for this assembly includes types or members that have the `unsafe` keyword.");
public static readonly GUIContent overrideReferences = EditorGUIUtility.TrTextContent("Override References", "When enabled, you can select which specific precompiled assemblies to refer to via a drop-down list that appears. When not enabled, this assembly definition refers to all auto-referenced precompiled assemblies.");
public static readonly GUIContent autoReferenced = EditorGUIUtility.TrTextContent("Auto Referenced", "When enabled, this assembly definition is automatically referenced in predefined assemblies.");
public static readonly GUIContent useGUIDs = EditorGUIUtility.TrTextContent("Use GUIDs", "Use GUIDs instead of assembly names for Assembly Definition References. Allows referenced assemblies to be renamed without having to update references.");
public static readonly GUIContent platforms = EditorGUIUtility.TrTextContent("Platforms", "Select which platforms include or exclude in the build that this assembly definition file is for.");
public static readonly GUIContent anyPlatform = EditorGUIUtility.TrTextContent("Any Platform");
public static readonly GUIContent includePlatforms = EditorGUIUtility.TrTextContent("Include Platforms");
public static readonly GUIContent excludePlatforms = EditorGUIUtility.TrTextContent("Exclude Platforms");
public static readonly GUIContent selectAll = EditorGUIUtility.TrTextContent("Select all");
public static readonly GUIContent deselectAll = EditorGUIUtility.TrTextContent("Deselect all");
public static readonly GUIContent loadError = EditorGUIUtility.TrTextContent("Load error");
public static readonly GUIContent noEngineReferences = EditorGUIUtility.TrTextContent("No Engine References", "When enabled, references to UnityEngine/UnityEditor will not be added when compiling this assembly.");
// This is used to make everything in reorderable list elements centered vertically.
public const int kCenterHeightOffset = 1;
public const int kValidityIconHeight = 16;
public const int kValidityIconWidth = 16;
static readonly Texture2D kValidDefineConstraint = EditorGUIUtility.FindTexture("Valid");
static readonly Texture2D kValidDefineConstraintHighDpi = EditorGUIUtility.FindTexture("Valid@2x");
static readonly Texture2D kInvalidDefineConstraint = EditorGUIUtility.FindTexture("Invalid");
static readonly Texture2D kInvalidDefineConstraintHighDpi = EditorGUIUtility.FindTexture("Invalid@2x");
public static Texture2D validDefineConstraint => EditorGUIUtility.pixelsPerPoint > 1 ? kValidDefineConstraintHighDpi : kValidDefineConstraint;
public static Texture2D invalidDefineConstraint => EditorGUIUtility.pixelsPerPoint > 1 ? kInvalidDefineConstraintHighDpi : kInvalidDefineConstraint;
static string kCompatibleTextTitle = L10n.Tr("Define constraints are met.");
static string kIncompatibleTextTitle = L10n.Tr("One or more define constraints are invalid or not met.");
public static string GetTitleTooltipFromDefineConstraintCompatibility(bool compatible)
{
return compatible ? kCompatibleTextTitle : kIncompatibleTextTitle;
}
static string kCompatibleTextIndividual = L10n.Tr("Define constraint is met.");
static string kIncompatibleTextIndividual = L10n.Tr("Define constraint is not met.");
static string kInvalidTextIndividual = L10n.Tr("Define constraint is invalid.");
public static string GetIndividualTooltipFromDefineConstraintStatus(DefineConstraintsHelper.DefineConstraintStatus status)
{
switch (status)
{
case DefineConstraintsHelper.DefineConstraintStatus.Compatible:
return kCompatibleTextIndividual;
case DefineConstraintsHelper.DefineConstraintStatus.Incompatible:
return kIncompatibleTextIndividual;
default:
return kInvalidTextIndividual;
}
}
}
GUIStyle m_TextStyle;
[Serializable]
internal class DefineConstraint
{
public string name;
}
[Serializable]
internal class AssemblyDefinitionReference
{
public string name;
public string serializedReference;
public AssemblyDefinitionAsset asset;
public void Load(string reference, bool useGUID)
{
var referencePath = CompilationPipeline.GetAssemblyDefinitionFilePathFromAssemblyReference(reference);
if (!string.IsNullOrEmpty(referencePath))
{
asset = AssetDatabase.LoadAssetAtPath<AssemblyDefinitionAsset>(referencePath);
if (useGUID)
{
var fileData = CustomScriptAssemblyData.FromJson(asset.text);
name = fileData.name;
}
}
}
}
[Serializable]
internal class PrecompiledReference
{
public string path = "";
public string fileName = "";
public string name = "";
}
class AssemblyDefinitionState : ScriptableObject
{
public string path => AssetDatabase.GetAssetPath(asset);
public string assemblyName;
public string rootNamespace;
public AssemblyDefinitionAsset asset;
public List<AssemblyDefinitionReference> references;
public List<PrecompiledReference> precompiledReferences;
public List<DefineConstraint> defineConstraints;
public List<VersionDefine> versionDefines;
public bool allowUnsafeCode;
public bool overrideReferences;
public bool useGUIDs;
public bool autoReferenced;
public bool compatibleWithAnyPlatform;
public bool[] platformCompatibility;
public bool noEngineReferences;
}
public static string UnityVersionTypeName
{
// This string must stay in sync with the native kUnityVersionTypeName in ScriptCompilationPipeline.cpp
get { return "Unity"; }
}
private readonly CachedVersionRangesFactory<SemVersion> m_SemVersionRanges = new CachedVersionRangesFactory<SemVersion>();
private readonly CachedVersionRangesFactory<UnityVersion> m_UnityVersionRanges = new CachedVersionRangesFactory<UnityVersion>();
ReorderableList m_ReferencesList;
ReorderableList m_PrecompiledReferencesList;
ReorderableList m_VersionDefineList;
ReorderableList m_DefineConstraints;
SerializedProperty m_AssemblyName;
SerializedProperty m_RootNamespace;
SerializedProperty m_AllowUnsafeCode;
SerializedProperty m_UseGUIDs;
SerializedProperty m_AutoReferenced;
SerializedProperty m_OverrideReferences;
SerializedProperty m_CompatibleWithAnyPlatform;
SerializedProperty m_PlatformCompatibility;
SerializedProperty m_NoEngineReferences;
private bool m_AssetIsReadonly;
Exception initializeException;
PrecompiledAssemblyProviderBase m_AssemblyProvider;
public override bool showImportedObject => false;
public override void OnEnable()
{
base.OnEnable();
//Ensure UIElements handles the IMGUI container with margins
alwaysAllowExpansion = true;
m_AssemblyName = extraDataSerializedObject.FindProperty("assemblyName");
InitializeReorderableLists();
m_SemVersionRanges.Clear();
m_UnityVersionRanges.Clear();
m_RootNamespace = extraDataSerializedObject.FindProperty("rootNamespace");
m_AllowUnsafeCode = extraDataSerializedObject.FindProperty("allowUnsafeCode");
m_UseGUIDs = extraDataSerializedObject.FindProperty("useGUIDs");
m_AutoReferenced = extraDataSerializedObject.FindProperty("autoReferenced");
m_OverrideReferences = extraDataSerializedObject.FindProperty("overrideReferences");
m_CompatibleWithAnyPlatform = extraDataSerializedObject.FindProperty("compatibleWithAnyPlatform");
m_PlatformCompatibility = extraDataSerializedObject.FindProperty("platformCompatibility");
m_NoEngineReferences = extraDataSerializedObject.FindProperty("noEngineReferences");
m_AssemblyProvider = EditorCompilationInterface.Instance.PrecompiledAssemblyProvider;
m_AssetIsReadonly = false;
foreach (var assetPath in targets.OfType<AssetImporter>().Select(i => i.assetPath))
{
try
{
using (var fs = File.Open(assetPath, FileMode.Open, FileAccess.Write)) { }
}
catch
{
// can't open in write mode, must be readonly
m_AssetIsReadonly = true;
}
}
AssemblyReloadEvents.afterAssemblyReload += AfterAssemblyReload;
}
public override void OnDisable()
{
base.OnDisable();
AssemblyReloadEvents.afterAssemblyReload -= AfterAssemblyReload;
}
void AfterAssemblyReload()
{
var selector = (ObjectSelector)WindowLayout.FindEditorWindowOfType(typeof(ObjectSelector));
if (selector != null && selector.hasFocus)
selector.Close();
}
public override void OnInspectorGUI()
{
if (initializeException != null)
{
ShowLoadErrorExceptionGUI(initializeException);
ApplyRevertGUI();
return;
}
extraDataSerializedObject.Update();
var platforms = CompilationPipeline.GetAssemblyDefinitionPlatforms();
using (new EditorGUI.DisabledScope(m_AssetIsReadonly))
{
if (targets.Length > 1)
{
if (m_AssetIsReadonly)
{
EditorGUILayout.LabelField("One of the selected assembly definition files is read-only.");
}
using (new EditorGUI.DisabledScope(true))
{
var value = string.Join(", ", extraDataTargets.Select(t => t.name).ToArray());
EditorGUILayout.TextField(Styles.name, value, EditorStyles.textField);
}
}
else
{
if (m_AssetIsReadonly)
{
EditorGUILayout.LabelField("The selected assembly definition file is read-only.");
}
EditorGUILayout.PropertyField(m_AssemblyName, Styles.name);
}
GUILayout.Space(6f);
// General Options
GUILayout.Label(Styles.generalOptions, EditorStyles.boldLabel);
EditorGUILayout.BeginVertical(GUI.skin.box);
EditorGUILayout.PropertyField(m_AllowUnsafeCode, Styles.allowUnsafeCode);
EditorGUILayout.PropertyField(m_AutoReferenced, Styles.autoReferenced);
EditorGUILayout.PropertyField(m_NoEngineReferences, Styles.noEngineReferences);
EditorGUILayout.PropertyField(m_OverrideReferences, Styles.overrideReferences);
EditorGUILayout.PropertyField(m_RootNamespace, Styles.rootNamespace);
EditorGUILayout.EndVertical();
GUILayout.Space(6f);
// ASMDEF References
GUILayout.Label(Styles.references, EditorStyles.boldLabel);
EditorGUILayout.BeginVertical(GUI.skin.box);
EditorGUI.BeginDisabled(m_ReferencesList.serializedProperty.arraySize == 0);
EditorGUILayout.PropertyField(m_UseGUIDs, Styles.useGUIDs);
EditorGUI.EndDisabled();
EditorGUILayout.EndVertical();
m_ReferencesList.DoLayoutList();
if (extraDataTargets.Any(data => ((AssemblyDefinitionState)data).references != null && ((AssemblyDefinitionState)data).references.Any(x => x.asset == null)))
{
EditorGUILayout.HelpBox("The grayed out assembly references are missing and will not be referenced during compilation.", MessageType.Info);
}
if (m_OverrideReferences.boolValue && !m_OverrideReferences.hasMultipleDifferentValues)
{
GUILayout.Label(Styles.precompiledReferences, EditorStyles.boldLabel);
UpdatePrecompiledReferenceListEntry();
m_PrecompiledReferencesList.DoLayoutList();
if (extraDataTargets.Any(data => ((AssemblyDefinitionState)data).precompiledReferences.Any(x => string.IsNullOrEmpty(x.path) && !string.IsNullOrEmpty(x.name))))
{
EditorGUILayout.HelpBox("The grayed out assembly references are missing and will not be referenced during compilation.", MessageType.Info);
}
}
GUILayout.Space(6f);
// Platforms
GUILayout.Label(Styles.platforms, EditorStyles.boldLabel);
EditorGUILayout.BeginVertical(GUI.skin.box);
using (var change = new EditorGUI.ChangeCheckScope())
{
EditorGUILayout.PropertyField(m_CompatibleWithAnyPlatform, Styles.anyPlatform);
if (change.changed)
{
// Invert state include/exclude compatibility of states that have the opposite compatibility,
// so all states are either include or exclude.
var compatibleWithAny = m_CompatibleWithAnyPlatform.boolValue;
var needToSwap = extraDataTargets.Cast<AssemblyDefinitionState>().Where(p => p.compatibleWithAnyPlatform != compatibleWithAny).ToList();
extraDataSerializedObject.ApplyModifiedProperties();
foreach (var state in needToSwap)
{
InversePlatformCompatibility(state);
}
extraDataSerializedObject.Update();
}
}
if (!m_CompatibleWithAnyPlatform.hasMultipleDifferentValues)
{
GUILayout.Label(m_CompatibleWithAnyPlatform.boolValue ? Styles.excludePlatforms : Styles.includePlatforms, EditorStyles.boldLabel);
for (int i = 0; i < platforms.Length; ++i)
{
SerializedProperty property;
if (i >= m_PlatformCompatibility.arraySize)
{
m_PlatformCompatibility.arraySize++;
property = m_PlatformCompatibility.GetArrayElementAtIndex(i);
property.boolValue = false;
}
else
{
property = m_PlatformCompatibility.GetArrayElementAtIndex(i);
}
EditorGUILayout.PropertyField(property, new GUIContent(platforms[i].DisplayName));
}
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
if (GUILayout.Button(Styles.selectAll))
{
var prop = m_PlatformCompatibility.GetArrayElementAtIndex(0);
var end = m_PlatformCompatibility.GetEndProperty();
do
{
prop.boolValue = true;
}
while (prop.Next(false) && !SerializedProperty.EqualContents(prop, end));
}
if (GUILayout.Button(Styles.deselectAll))
{
var prop = m_PlatformCompatibility.GetArrayElementAtIndex(0);
var end = m_PlatformCompatibility.GetEndProperty();
do
{
prop.boolValue = false;
}
while (prop.Next(false) && !SerializedProperty.EqualContents(prop, end));
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
EditorGUILayout.EndVertical();
GUILayout.Space(6f);
// Define Constraints
EditorGUILayout.BeginHorizontal();
GUILayout.Label(Styles.defineConstraints, EditorStyles.boldLabel);
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
if (m_DefineConstraints.serializedProperty.arraySize > 0)
{
var defineConstraintsCompatible = true;
var defines = GetDefines();
if (defines != null)
{
for (var i = 0; i < m_DefineConstraints.serializedProperty.arraySize && defineConstraintsCompatible; ++i)
{
var defineConstraint = m_DefineConstraints.serializedProperty.GetArrayElementAtIndex(i).FindPropertyRelative("name").stringValue;
if (DefineConstraintsHelper.GetDefineConstraintCompatibility(defines, defineConstraint) != DefineConstraintsHelper.DefineConstraintStatus.Compatible)
{
defineConstraintsCompatible = false;
}
}
var constraintValidityRect = new Rect(GUILayoutUtility.GetLastRect());
constraintValidityRect.x = constraintValidityRect.width - Styles.kValidityIconWidth / 4;
var image = defineConstraintsCompatible ? Styles.validDefineConstraint : Styles.invalidDefineConstraint;
var tooltip = Styles.GetTitleTooltipFromDefineConstraintCompatibility(defineConstraintsCompatible);
var content = new GUIContent(image, tooltip);
constraintValidityRect.width = Styles.kValidityIconWidth;
constraintValidityRect.height = Styles.kValidityIconHeight;
EditorGUI.LabelField(constraintValidityRect, content);
}
}
m_DefineConstraints.DoLayoutList();
GUILayout.Space(6f);
// Version Defines
EditorGUILayout.BeginVertical(GUI.skin.box);
GUILayout.Label(Styles.versionDefines, EditorStyles.boldLabel);
m_VersionDefineList.DoLayoutList();
EditorGUILayout.EndVertical();
}
extraDataSerializedObject.ApplyModifiedProperties();
ApplyRevertGUI();
}
protected override void Apply()
{
base.Apply();
// Do not write back to the asset if no asset can be found.
if (targets != null)
SaveAndUpdateAssemblyDefinitionStates(extraDataTargets.Cast<AssemblyDefinitionState>().ToArray());
}
static void InversePlatformCompatibility(AssemblyDefinitionState state)
{
var platforms = CompilationPipeline.GetAssemblyDefinitionPlatforms();
for (int i = 0; i < platforms.Length; ++i)
state.platformCompatibility[i] = !state.platformCompatibility[i];
}
void ShowLoadErrorExceptionGUI(Exception e)
{
if (m_TextStyle == null)
m_TextStyle = "ScriptText";
GUILayout.Label(Styles.loadError, EditorStyles.boldLabel);
Rect rect = GUILayoutUtility.GetRect(EditorGUIUtility.TempContent(e.Message), m_TextStyle);
EditorGUI.HelpBox(rect, e.Message, MessageType.Error);
}
protected override Type extraDataType => typeof(AssemblyDefinitionState);
protected override void InitializeExtraDataInstance(Object extraTarget, int targetIndex)
{
try
{
LoadAssemblyDefinitionState((AssemblyDefinitionState)extraTarget, ((AssetImporter)targets[targetIndex]).assetPath);
initializeException = null;
}
catch (Exception e)
{
initializeException = e;
}
}
void InitializeReorderableLists()
{
// Disable reordering for multi-editing for asmdefs
bool enableReordering = targets.Length == 1;
m_ReferencesList = new ReorderableList(extraDataSerializedObject, extraDataSerializedObject.FindProperty("references"), enableReordering, false, true, true);
m_ReferencesList.drawElementCallback = DrawReferenceListElement;
m_ReferencesList.onAddCallback += AddReferenceListElement;
m_ReferencesList.elementHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
m_ReferencesList.headerHeight = 3;
m_DefineConstraints = new ReorderableList(extraDataSerializedObject, extraDataSerializedObject.FindProperty("defineConstraints"), enableReordering, false, true, true);
m_DefineConstraints.drawElementCallback = DrawDefineConstraintListElement;
m_DefineConstraints.elementHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
m_DefineConstraints.headerHeight = 3;
m_PrecompiledReferencesList = new ReorderableList(extraDataSerializedObject, extraDataSerializedObject.FindProperty("precompiledReferences"), enableReordering, false, true, true);
m_PrecompiledReferencesList.drawElementCallback = DrawPrecompiledReferenceListElement;
m_PrecompiledReferencesList.onAddCallback = AddPrecompiledReferenceListElement;
m_PrecompiledReferencesList.elementHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
m_PrecompiledReferencesList.headerHeight = 3;
m_VersionDefineList = new ReorderableList(extraDataSerializedObject, extraDataSerializedObject.FindProperty("versionDefines"), enableReordering, false, true, true);
m_VersionDefineList.drawElementCallback = DrawVersionDefineListElement;
m_VersionDefineList.elementHeight = EditorGUIUtility.singleLineHeight * 4 + EditorGUIUtility.standardVerticalSpacing;
m_VersionDefineList.headerHeight = 3;
}
private void DrawDefineConstraintListElement(Rect rect, int index, bool isactive, bool isfocused)
{
var list = m_DefineConstraints.serializedProperty;
var defineConstraint = list.GetArrayElementAtIndex(index).FindPropertyRelative("name");
rect.height -= EditorGUIUtility.standardVerticalSpacing;
var textFieldRect = new Rect(rect.x, rect.y + Styles.kCenterHeightOffset, rect.width - ReorderableList.Defaults.dragHandleWidth, rect.height);
string noValue = L10n.Tr("(Missing)");
var label = string.IsNullOrEmpty(defineConstraint.stringValue) ? noValue : defineConstraint.stringValue;
bool mixed = defineConstraint.hasMultipleDifferentValues;
EditorGUI.showMixedValue = mixed;
var textFieldValue = EditorGUI.TextField(textFieldRect, mixed ? L10n.Tr("(Multiple Values)") : label);
EditorGUI.showMixedValue = false;
var defines = GetDefines();
if (defines != null)
{
var status = DefineConstraintsHelper.GetDefineConstraintCompatibility(defines, defineConstraint.stringValue);
var image = status == DefineConstraintsHelper.DefineConstraintStatus.Compatible ? Styles.validDefineConstraint : Styles.invalidDefineConstraint;
var content = new GUIContent(image, Styles.GetIndividualTooltipFromDefineConstraintStatus(status));
var constraintValidityRect = new Rect(rect.width + ReorderableList.Defaults.dragHandleWidth + Styles.kValidityIconWidth / 4, rect.y + Styles.kCenterHeightOffset, Styles.kValidityIconWidth, Styles.kValidityIconHeight);
EditorGUI.LabelField(constraintValidityRect, content);
}
if (!string.IsNullOrEmpty(textFieldValue) && textFieldValue != noValue)
{
defineConstraint.stringValue = textFieldValue;
}
}
private string[] GetDefines()
{
var responseFileDefinesFromAssemblyName = CompilationPipeline.GetResponseFileDefinesFromAssemblyName(m_AssemblyName.stringValue) ?? new string[0];
var definesFromAssemblyName = CompilationPipeline.GetDefinesFromAssemblyName(m_AssemblyName.stringValue) ?? new string[0];
var defines = definesFromAssemblyName.Concat(responseFileDefinesFromAssemblyName);
return defines.Distinct().ToArray();
}
private List<VersionMetaData> BuildListOfVersionDefineResourceOptions(string preselectedResourceName)
{
var versionDefineResourceOptions = EditorCompilationInterface.Instance.GetVersionMetaDatas().Values.ToList();
if (!string.IsNullOrEmpty(preselectedResourceName) && !versionDefineResourceOptions.Where(x => x.Name == preselectedResourceName).Any())
{
versionDefineResourceOptions.Add(new VersionMetaData(preselectedResourceName));
}
versionDefineResourceOptions.Insert(0, new VersionMetaData("Select..."));
// Make sure Unity is always second option (index 1).
for (int i = versionDefineResourceOptions.Count - 1; i >= 2; --i)
{
if (versionDefineResourceOptions[i].Name == UnityVersionTypeName)
{
var tmp = versionDefineResourceOptions[i];
versionDefineResourceOptions.RemoveAt(i);
versionDefineResourceOptions.Insert(1, tmp);
break;
}
}
return versionDefineResourceOptions;
}
private void DrawVersionDefineListElement(Rect rect, int index, bool isactive, bool isfocused)
{
var list = m_VersionDefineList.serializedProperty;
var versionDefineProp = list.GetArrayElementAtIndex(index);
var nameProp = versionDefineProp.FindPropertyRelative("name");
var expressionProp = versionDefineProp.FindPropertyRelative("expression");
var defineProp = versionDefineProp.FindPropertyRelative("define");
rect.height -= EditorGUIUtility.standardVerticalSpacing;
var versionedResourceOptions = BuildListOfVersionDefineResourceOptions(nameProp.stringValue);
int indexOfSelected = 0;
if (!string.IsNullOrEmpty(nameProp.stringValue))
{
indexOfSelected = versionedResourceOptions.IndexOf(versionedResourceOptions.Where(x => x.Name == nameProp.stringValue).First());
}
bool mixed = versionDefineProp.hasMultipleDifferentValues;
EditorGUI.showMixedValue = mixed;
string[] versionedResourceOptionsStrings = new string[versionedResourceOptions.Count];
for (int i = 0; i < versionedResourceOptions.Count; ++i)
{
if (string.IsNullOrEmpty(versionedResourceOptions[i].Version))
{
versionedResourceOptionsStrings[i] = versionedResourceOptions[i].Name;
}
else
{
versionedResourceOptionsStrings[i] = $"{versionedResourceOptions[i].Name} ({versionedResourceOptions[i].Version})";
}
}
var elementRect = new Rect(rect);
elementRect.height = EditorGUIUtility.singleLineHeight;
elementRect.y += 1;
var prefixLabel = EditorGUI.PrefixLabel(elementRect, Styles.resource);
int popupIndex = EditorGUI.AdvancedPopup(prefixLabel, indexOfSelected, versionedResourceOptionsStrings);
nameProp.stringValue = versionedResourceOptions[popupIndex].Name;
elementRect.y += EditorGUIUtility.singleLineHeight;
expressionProp.stringValue = EditorGUI.TextField(elementRect, Styles.version, expressionProp.stringValue);
elementRect.y += EditorGUIUtility.singleLineHeight;
defineProp.stringValue = EditorGUI.TextField(elementRect, Styles.define, defineProp.stringValue);
string expressionOutcome = null;
if (!string.IsNullOrEmpty(expressionProp.stringValue))
{
try
{
if (!string.IsNullOrEmpty(nameProp.stringValue) &&
nameProp.stringValue.Equals(UnityVersionTypeName, StringComparison.Ordinal))
{
var expression = m_UnityVersionRanges.GetExpression(expressionProp.stringValue);
expressionOutcome = expression.Expression.AppliedRule;
}
else
{
var expression = m_SemVersionRanges.GetExpression(expressionProp.stringValue);
expressionOutcome = expression.Expression.AppliedRule;
}
}
catch (Exception)
{
expressionOutcome = "Invalid";
}
}
elementRect.y += EditorGUIUtility.singleLineHeight;
EditorGUI.LabelField(elementRect, Styles.expressionOutcome, GUIContent.Temp(expressionOutcome));
EditorGUI.showMixedValue = false;
}
List<string> m_PrecompileReferenceListEntry;
private void UpdatePrecompiledReferenceListEntry()
{
var precompiledAssemblyNames = CompilationPipeline.GetPrecompiledAssemblyNames().ToList();
var currentReferencesProp = extraDataSerializedObject.FindProperty("precompiledReferences");
if (currentReferencesProp.arraySize > 0)
{
var prop = currentReferencesProp.GetArrayElementAtIndex(0);
var end = currentReferencesProp.GetEndProperty();
do
{
var fileName = prop.FindPropertyRelative("fileName").stringValue;
if (!string.IsNullOrEmpty(fileName))
precompiledAssemblyNames.Remove(fileName);
}
while (prop.Next(false) && !SerializedProperty.EqualContents(prop, end));
}
m_PrecompileReferenceListEntry = precompiledAssemblyNames
.OrderBy(x => x).ToList();
}
private void DrawPrecompiledReferenceListElement(Rect rect, int index, bool isactive, bool isfocused)
{
var precompiledReference = m_PrecompiledReferencesList.serializedProperty.GetArrayElementAtIndex(index);
var nameProp = precompiledReference.FindPropertyRelative("name");
var pathProp = precompiledReference.FindPropertyRelative("path");
var fileNameProp = precompiledReference.FindPropertyRelative("fileName");
rect.height -= EditorGUIUtility.standardVerticalSpacing;
GUIContent label = GUIContent.Temp(nameProp.stringValue);
bool mixed = nameProp.hasMultipleDifferentValues;
EditorGUI.showMixedValue = mixed;
bool hasValue = !string.IsNullOrEmpty(pathProp.stringValue);
if (!hasValue)
{
m_PrecompileReferenceListEntry.Insert(0, L10n.Tr("None"));
if (m_PrecompileReferenceListEntry.Count == 1)
{
label = EditorGUIUtility.TrTempContent("No possible references");
}
else
{
label = EditorGUIUtility.TrTempContent("None");
}
}
else
{
m_PrecompileReferenceListEntry.Insert(0, fileNameProp.stringValue);
}
int currentlySelectedIndex = 0;
EditorGUI.BeginDisabled(!hasValue && !string.IsNullOrEmpty(nameProp.stringValue));
int selectedIndex = EditorGUI.Popup(rect, label, currentlySelectedIndex, m_PrecompileReferenceListEntry.ToArray());
EditorGUI.EndDisabled();
if (selectedIndex > 0)
{
var selectedAssemblyName = m_PrecompileReferenceListEntry[selectedIndex];
var assembly = m_AssemblyProvider.GetPrecompiledAssemblies(
EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingWithAsserts,
EditorUserBuildSettings.activeBuildTarget)
.First(x => AssetPath.GetFileName(x.Path) == selectedAssemblyName);
nameProp.stringValue = selectedAssemblyName;
pathProp.stringValue = assembly.Path;
fileNameProp.stringValue = AssetPath.GetFileName(assembly.Path);
}
m_PrecompileReferenceListEntry.RemoveAt(0);
EditorGUI.showMixedValue = false;
}
[MenuItem("CONTEXT/AssemblyDefinitionImporter/Reset", secondaryPriority = 8)]
internal static void ContextReset(MenuCommand command)
{
var templatePath = AssetsMenuUtility.GetScriptTemplatePath(ScriptTemplate.AsmDef_NewAssembly);
Debug.Assert(!string.IsNullOrEmpty(templatePath));
var templateContent = File.ReadAllText(templatePath);
var importer = command.context as AssemblyDefinitionImporter;
if (importer != null)
{
var assetPath = importer.assetPath;
templateContent = ProjectWindowUtil.PreprocessScriptAssetTemplate(assetPath, templateContent);
File.WriteAllText(assetPath, templateContent);
AssetDatabase.ImportAsset(assetPath);
}
}
static void AddPrecompiledReferenceListElement(ReorderableList list)
{
list.serializedProperty.arraySize += 1;
var newProp = list.serializedProperty.GetArrayElementAtIndex(list.serializedProperty.arraySize - 1);
newProp.FindPropertyRelative("name").stringValue = string.Empty;
newProp.FindPropertyRelative("path").stringValue = string.Empty;
newProp.FindPropertyRelative("fileName").stringValue = string.Empty;
}
static void LoadAssemblyDefinitionState(AssemblyDefinitionState state, string path)
{
var asset = AssetDatabase.LoadAssetAtPath<AssemblyDefinitionAsset>(path);
if (asset == null)
return;
var data = CustomScriptAssemblyData.FromJsonNoFieldValidation(asset.text);
if (data == null)
return;
try
{
data.ValidateFields();
}
catch (Exception e)
{
Debug.LogException(e, asset);
}
state.asset = asset;
state.assemblyName = data.name;
state.rootNamespace = data.rootNamespace;
state.references = new List<AssemblyDefinitionReference>();
state.precompiledReferences = new List<PrecompiledReference>();
state.defineConstraints = new List<DefineConstraint>();
state.versionDefines = new List<VersionDefine>();
state.autoReferenced = data.autoReferenced;
state.allowUnsafeCode = data.allowUnsafeCode;
state.overrideReferences = data.overrideReferences;
state.noEngineReferences = data.noEngineReferences;
// If the .asmdef has no references (true for newly created .asmdef), then use GUIDs.
// Otherwise do not use GUIDs. This value might be changed below if any reference is a GUID.
state.useGUIDs = (data.references == null || data.references.Length == 0);
if (data.versionDefines != null)
{
foreach (var versionDefine in data.versionDefines)
{
state.versionDefines.Add(versionDefine);
}
}
if (data.defineConstraints != null)
{
foreach (var defineConstraint in data.defineConstraints)
{
state.defineConstraints.Add(new DefineConstraint
{
name = defineConstraint,
});
}
}
if (data.references != null)
{
foreach (var reference in data.references)
{
try
{
var assemblyDefinitionFile = new AssemblyDefinitionReference
{
name = reference,
serializedReference = reference
};
// If any references is a GUID, use GUIDs.
var isGuid = CompilationPipeline.GetAssemblyDefinitionReferenceType(reference) == AssemblyDefinitionReferenceType.Guid;
if (isGuid)
{
state.useGUIDs = true;
}
assemblyDefinitionFile.Load(reference, isGuid);
state.references.Add(assemblyDefinitionFile);
}
catch (AssemblyDefinitionException e)
{
Debug.LogException(e, asset);
state.references.Add(new AssemblyDefinitionReference());
}
}
}
var nameToPrecompiledReference = EditorCompilationInterface.Instance.PrecompiledAssemblyProvider
.GetPrecompiledAssemblies(
EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingWithAsserts,
EditorUserBuildSettings.activeBuildTarget)
.Where(x => (x.Flags & AssemblyFlags.UserAssembly) == AssemblyFlags.UserAssembly)
.Distinct()
.ToDictionary(x => AssetPath.GetFileName(x.Path), x => x);
foreach (var precompiledReferenceName in data.precompiledReferences ?? Enumerable.Empty<String>())
{
try
{
var precompiledReference = new PrecompiledReference
{
name = precompiledReferenceName,
};
PrecompiledAssembly assembly;
if (nameToPrecompiledReference.TryGetValue(precompiledReferenceName, out assembly))
{
precompiledReference.path = assembly.Path;
precompiledReference.fileName = AssetPath.GetFileName(assembly.Path);
}
state.precompiledReferences.Add(precompiledReference);
}
catch (AssemblyDefinitionException e)
{
Debug.LogException(e, asset);
state.precompiledReferences.Add(new PrecompiledReference());
}
}
var platforms = CompilationPipeline.GetAssemblyDefinitionPlatforms();
state.platformCompatibility = new bool[platforms.Length];
state.compatibleWithAnyPlatform = true;
string[] dataPlatforms = null;
if (data.includePlatforms != null && data.includePlatforms.Length > 0)
{
state.compatibleWithAnyPlatform = false;
dataPlatforms = data.includePlatforms;
}
else if (data.excludePlatforms != null && data.excludePlatforms.Length > 0)
{
state.compatibleWithAnyPlatform = true;
dataPlatforms = data.excludePlatforms;
}
if (dataPlatforms != null)
foreach (var platform in dataPlatforms)
{
var platformIndex = GetPlatformIndex(platforms, platform);
state.platformCompatibility[platformIndex] = true;
}
}
static void SaveAndUpdateAssemblyDefinitionStates(AssemblyDefinitionState[] states)
{
foreach (var state in states)
{
SaveAssemblyDefinitionState(state);
}
}
static void SaveAssemblyDefinitionState(AssemblyDefinitionState state)
{
var references = state.references;
var platforms = CompilationPipeline.GetAssemblyDefinitionPlatforms();
CustomScriptAssemblyData data = new CustomScriptAssemblyData();
data.name = state.assemblyName;
data.rootNamespace = state.rootNamespace;
if (state.useGUIDs)
{
data.references = references.Select(r =>
{
var guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(r.asset));
if (string.IsNullOrEmpty(guid))
return r.serializedReference;
return CompilationPipeline.GUIDToAssemblyDefinitionReferenceGUID(guid);
}).ToArray();
}
else
{
data.references = references.Select(r => r.name).ToArray();
}
data.defineConstraints = state.defineConstraints
.Where(x => !string.IsNullOrEmpty(x.name))
.Select(r => r.name)
.ToArray();
data.versionDefines = state.versionDefines.ToArray();
data.autoReferenced = state.autoReferenced;
data.overrideReferences = state.overrideReferences;
data.precompiledReferences = state.precompiledReferences
.Select(r => r.name).ToArray();
data.allowUnsafeCode = state.allowUnsafeCode;
data.noEngineReferences = state.noEngineReferences;
List<string> dataPlatforms = new List<string>();
for (int i = 0; i < platforms.Length; ++i)
{
if (state.platformCompatibility[i])
dataPlatforms.Add(platforms[i].Name);
}
if (dataPlatforms.Any())
{
if (state.compatibleWithAnyPlatform)
data.excludePlatforms = dataPlatforms.ToArray();
else
data.includePlatforms = dataPlatforms.ToArray();
}
var json = CustomScriptAssemblyData.ToJson(data);
File.WriteAllText(state.path, json);
AssetDatabase.ImportAsset(state.path);
}
static int GetPlatformIndex(AssemblyDefinitionPlatform[] platforms, string name)
{
for (int i = 0; i < platforms.Length; ++i)
{
if (string.Equals(platforms[i].Name, name, System.StringComparison.InvariantCultureIgnoreCase))
return i;
}
throw new System.ArgumentException(string.Format("Unknown platform '{0}'", name), name);
}
void DrawReferenceListElement(Rect rect, int index, bool selected, bool focused)
{
var assemblyDefinitionFile = m_ReferencesList.serializedProperty.GetArrayElementAtIndex(index);
var nameProp = assemblyDefinitionFile.FindPropertyRelative("name");
var assetProp = assemblyDefinitionFile.FindPropertyRelative("asset");
rect.height -= EditorGUIUtility.standardVerticalSpacing;
var label = string.IsNullOrEmpty(nameProp.stringValue) ? L10n.Tr("(Missing Reference)") : nameProp.stringValue;
using (var change = new EditorGUI.ChangeCheckScope())
{
EditorGUI.showMixedValue = assetProp.hasMultipleDifferentValues;
EditorGUI.BeginDisabled(!string.IsNullOrEmpty(nameProp.stringValue) && assetProp.objectReferenceValue == null);
var obj = EditorGUI.ObjectField(rect, EditorGUI.showMixedValue ? GUIContent.Temp("(Multiple Values)") : GUIContent.Temp(label), assetProp.objectReferenceValue, typeof(AssemblyDefinitionAsset), false);
EditorGUI.showMixedValue = false;
EditorGUI.EndDisabled();
if (change.changed && obj != null)
{
assetProp.objectReferenceValue = obj;
var data = CustomScriptAssemblyData.FromJson(((AssemblyDefinitionAsset)assetProp.objectReferenceValue).text);
nameProp.stringValue = data.name;
}
else if (change.changed && obj == null)
{
assetProp.objectReferenceValue = obj;
nameProp.stringValue = "";
}
}
}
void AddReferenceListElement(ReorderableList list)
{
list.serializedProperty.arraySize += 1;
var newProp = list.serializedProperty.GetArrayElementAtIndex(list.serializedProperty.arraySize - 1);
newProp.FindPropertyRelative("name").stringValue = string.Empty;
newProp.FindPropertyRelative("asset").objectReferenceValue = null;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/AssemblyDefinitionImporterInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/AssemblyDefinitionImporterInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 21940
} | 286 |
// 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.Collections.Generic;
using System.Linq;
using UnityEngine.Audio;
namespace UnityEditor
{
[CustomEditor(typeof(AudioSource))]
[CanEditMultipleObjects]
sealed class AudioSourceInspector : Editor
{
SerializedProperty m_AudioResource;
SerializedProperty m_PlayOnAwake;
SerializedProperty m_Volume;
SerializedProperty m_Pitch;
SerializedProperty m_Loop;
SerializedProperty m_Mute;
SerializedProperty m_Spatialize;
SerializedProperty m_SpatializePostEffects;
SerializedProperty m_Priority;
SerializedProperty m_DopplerLevel;
SerializedProperty m_MinDistance;
SerializedProperty m_MaxDistance;
SerializedProperty m_Pan2D;
SerializedProperty m_RolloffMode;
SerializedProperty m_BypassEffects;
SerializedProperty m_BypassListenerEffects;
SerializedProperty m_BypassReverbZones;
SerializedProperty m_OutputAudioMixerGroup;
SerializedObject m_LowpassObject;
class AudioCurveWrapper
{
public AudioCurveType type;
public GUIContent legend;
public int id;
public Color color;
public SerializedProperty curveProp;
public float rangeMin;
public float rangeMax;
public AudioCurveWrapper(AudioCurveType type, string legend, int id, Color color, SerializedProperty curveProp, float rangeMin, float rangeMax)
{
this.type = type;
this.legend = new GUIContent(legend);
this.id = id;
this.color = color;
this.curveProp = curveProp;
this.rangeMin = rangeMin;
this.rangeMax = rangeMax;
}
}
private AudioCurveWrapper[] m_AudioCurves;
CurveEditor m_CurveEditor = null;
Vector3 m_LastSourcePosition;
Vector3 m_LastListenerPosition;
const int kRolloffCurveID = 0;
const int kSpatialBlendCurveID = 1;
const int kSpreadCurveID = 2;
const int kLowPassCurveID = 3;
const int kReverbZoneMixCurveID = 4;
internal const float kMaxCutoffFrequency = 22000.0f;
const float EPSILON = 0.0001f;
static CurveEditorSettings m_CurveEditorSettings = new CurveEditorSettings();
internal static Color kRolloffCurveColor = new Color(0.90f, 0.30f, 0.20f, 1.0f);
internal static Color kSpatialCurveColor = new Color(0.25f, 0.70f, 0.20f, 1.0f);
internal static Color kSpreadCurveColor = new Color(0.25f, 0.55f, 0.95f, 1.0f);
internal static Color kLowPassCurveColor = new Color(0.80f, 0.25f, 0.90f, 1.0f);
internal static Color kReverbZoneMixCurveColor = new Color(0.70f, 0.70f, 0.20f, 1.0f);
internal bool[] m_SelectedCurves = new bool[0];
private enum AudioCurveType { Volume, SpatialBlend, Lowpass, Spread, ReverbZoneMix }
private bool m_Expanded3D = false;
internal static class Styles
{
public static GUIStyle labelStyle = "ProfilerBadge";
public static GUIContent rolloffLabel = EditorGUIUtility.TrTextContent("Volume Rolloff", "Which type of rolloff curve to use");
public static string controlledByCurveLabel = "Controlled by curve";
public static GUIContent audioResourceLabel = EditorGUIUtility.TrTextContent("Audio Resource", "The AudioResource asset played by the AudioSource. Can be undefined if the AudioSource is generating a live stream of audio via OnAudioFilterRead.");
public static GUIContent panStereoLabel = EditorGUIUtility.TrTextContent("Stereo Pan", "Only valid for Mono and Stereo AudioClips. Mono sounds will be panned at constant power left and right. Stereo sounds will have each left/right value faded up and down according to the specified pan value.");
public static GUIContent spatialBlendLabel = EditorGUIUtility.TrTextContent("Spatial Blend", "Sets how much this AudioSource is treated as a 3D source. 3D sources are affected by spatial position and spread. If 3D Pan Level is 0, all spatial attenuation is ignored.");
public static GUIContent reverbZoneMixLabel = EditorGUIUtility.TrTextContent("Reverb Zone Mix", "Sets how much of the signal this AudioSource is mixing into the global reverb associated with the zones. [0, 1] is a linear range (like volume) while [1, 1.1] lets you boost the reverb mix by 10 dB.");
public static GUIContent dopplerLevelLabel = EditorGUIUtility.TrTextContent("Doppler Level", "Specifies how much the pitch is changed based on the relative velocity between AudioListener and AudioSource.");
public static GUIContent spreadLabel = EditorGUIUtility.TrTextContent("Spread", "Sets the spread of a 3d sound in speaker space");
public static GUIContent outputMixerGroupLabel = EditorGUIUtility.TrTextContent("Output", "Set whether the sound should play through an Audio Mixer first or directly to the Audio Listener");
public static GUIContent volumeLabel = EditorGUIUtility.TrTextContent("Volume", "Sets the overall volume of the sound.");
public static GUIContent pitchLabel = EditorGUIUtility.TrTextContent("Pitch", "Sets the frequency of the sound. Use this to slow down or speed up the sound.");
public static GUIContent priorityLabel = EditorGUIUtility.TrTextContent("Priority", "Sets the priority of the source. Note that a sound with a larger priority value will more likely be stolen by sounds with smaller priority values.");
public static GUIContent spatializeLabel = EditorGUIUtility.TrTextContent("Spatialize", "Enables or disables custom spatialization for the AudioSource.");
public static GUIContent spatializePostEffectsLabel = EditorGUIUtility.TrTextContent("Spatialize Post Effects", "Determines if the custom spatializer is applied before or after the effect filters attached to the AudioSource. This flag only has an effect if the spatialize flag is enabled on the AudioSource.");
public static GUIContent priorityLeftLabel = EditorGUIUtility.TrTextContent("High");
public static GUIContent priorityRightLabel = EditorGUIUtility.TrTextContent("Low");
public static GUIContent spatialLeftLabel = EditorGUIUtility.TrTextContent("2D");
public static GUIContent spatialRightLabel = EditorGUIUtility.TrTextContent("3D");
public static GUIContent panLeftLabel = EditorGUIUtility.TrTextContent("Left");
public static GUIContent panRightLabel = EditorGUIUtility.TrTextContent("Right");
public static string xAxisLabel = L10n.Tr("Distance");
}
Vector3 GetSourcePos(Object target)
{
AudioSource source = (AudioSource)target;
if (source == null)
return new Vector3(0.0f, 0.0f, 0.0f);
return source.transform.position;
}
void OnEnable()
{
m_AudioResource = serializedObject.FindProperty("m_Resource");
m_PlayOnAwake = serializedObject.FindProperty("m_PlayOnAwake");
m_Volume = serializedObject.FindProperty("m_Volume");
m_Pitch = serializedObject.FindProperty("m_Pitch");
m_Loop = serializedObject.FindProperty("Loop");
m_Mute = serializedObject.FindProperty("Mute");
m_Spatialize = serializedObject.FindProperty("Spatialize");
m_SpatializePostEffects = serializedObject.FindProperty("SpatializePostEffects");
m_Priority = serializedObject.FindProperty("Priority");
m_DopplerLevel = serializedObject.FindProperty("DopplerLevel");
m_MinDistance = serializedObject.FindProperty("MinDistance");
m_MaxDistance = serializedObject.FindProperty("MaxDistance");
m_Pan2D = serializedObject.FindProperty("Pan2D");
m_RolloffMode = serializedObject.FindProperty("rolloffMode");
m_BypassEffects = serializedObject.FindProperty("BypassEffects");
m_BypassListenerEffects = serializedObject.FindProperty("BypassListenerEffects");
m_BypassReverbZones = serializedObject.FindProperty("BypassReverbZones");
m_OutputAudioMixerGroup = serializedObject.FindProperty("OutputAudioMixerGroup");
m_AudioCurves = new AudioCurveWrapper[]
{
new AudioCurveWrapper(AudioCurveType.Volume, "Volume", kRolloffCurveID, kRolloffCurveColor, serializedObject.FindProperty("rolloffCustomCurve"), 0, 1),
new AudioCurveWrapper(AudioCurveType.SpatialBlend, "Spatial Blend", kSpatialBlendCurveID, kSpatialCurveColor, serializedObject.FindProperty("panLevelCustomCurve"), 0, 1),
new AudioCurveWrapper(AudioCurveType.Spread, "Spread", kSpreadCurveID, kSpreadCurveColor, serializedObject.FindProperty("spreadCustomCurve"), 0, 1),
new AudioCurveWrapper(AudioCurveType.Lowpass, "Low-Pass", kLowPassCurveID, kLowPassCurveColor, null, 0, 1),
new AudioCurveWrapper(AudioCurveType.ReverbZoneMix, "Reverb Zone Mix", kReverbZoneMixCurveID, kReverbZoneMixCurveColor, serializedObject.FindProperty("reverbZoneMixCustomCurve"), 0, 1.1f)
};
m_CurveEditorSettings.hRangeMin = 0.0f;
m_CurveEditorSettings.vRangeMin = 0.0f;
m_CurveEditorSettings.vRangeMax = 1.1f;
m_CurveEditorSettings.hRangeMax = 1.0f;
m_CurveEditorSettings.vSlider = false;
m_CurveEditorSettings.hSlider = false;
TickStyle hTS = new TickStyle();
hTS.tickColor.color = new Color(0.0f, 0.0f, 0.0f, 0.15f);
hTS.distLabel = 30;
m_CurveEditorSettings.hTickStyle = hTS;
TickStyle vTS = new TickStyle();
vTS.tickColor.color = new Color(0.0f, 0.0f, 0.0f, 0.15f);
vTS.distLabel = 20;
m_CurveEditorSettings.vTickStyle = vTS;
m_CurveEditorSettings.undoRedoSelection = true;
m_CurveEditor = new CurveEditor(new Rect(0, 0, 1000, 100), new CurveWrapper[0], false);
m_CurveEditor.settings = m_CurveEditorSettings;
m_CurveEditor.margin = 25;
m_CurveEditor.SetShownHRangeInsideMargins(0.0f, 1.0f);
m_CurveEditor.SetShownVRangeInsideMargins(0.0f, 1.1f);
m_CurveEditor.ignoreScrollWheelUntilClicked = true;
m_LastSourcePosition = GetSourcePos(target);
m_LastListenerPosition = AudioUtil.GetListenerPos();
EditorApplication.update += Update;
m_Expanded3D = EditorPrefs.GetBool("AudioSourceExpanded3D", m_Expanded3D);
}
void OnDisable()
{
m_CurveEditor.OnDisable();
EditorApplication.update -= Update;
EditorPrefs.SetBool("AudioSourceExpanded3D", m_Expanded3D);
}
CurveWrapper[] GetCurveWrapperArray()
{
List<CurveWrapper> wrappers = new List<CurveWrapper>();
foreach (AudioCurveWrapper audioCurve in m_AudioCurves)
{
if (audioCurve.curveProp == null)
continue;
bool includeCurve = false;
AnimationCurve curve = audioCurve.curveProp.animationCurveValue;
// Special handling of volume rolloff curve
if (audioCurve.type == AudioCurveType.Volume)
{
AudioRolloffMode mode = (AudioRolloffMode)m_RolloffMode.enumValueIndex;
if (m_RolloffMode.hasMultipleDifferentValues)
{
includeCurve = false;
}
else if (mode == AudioRolloffMode.Custom)
{
includeCurve = !audioCurve.curveProp.hasMultipleDifferentValues;
}
else
{
includeCurve = !m_MinDistance.hasMultipleDifferentValues && !m_MaxDistance.hasMultipleDifferentValues;
if (mode == AudioRolloffMode.Linear)
curve = AnimationCurve.Linear(m_MinDistance.floatValue / m_MaxDistance.floatValue, 1.0f, 1.0f, 0.0f);
else if (mode == AudioRolloffMode.Logarithmic)
curve = Logarithmic(m_MinDistance.floatValue / m_MaxDistance.floatValue, 1.0f, 1.0f);
}
}
// All other curves
else
{
includeCurve = !audioCurve.curveProp.hasMultipleDifferentValues;
}
if (includeCurve)
{
if (curve.length == 0)
Debug.LogError(audioCurve.legend.text + " curve has no keys!");
else
wrappers.Add(GetCurveWrapper(curve, audioCurve));
}
}
return wrappers.ToArray();
}
private CurveWrapper GetCurveWrapper(AnimationCurve curve, AudioCurveWrapper audioCurve)
{
float colorMultiplier = !EditorGUIUtility.isProSkin ? 0.9f : 1.0f;
Color colorMult = new Color(colorMultiplier, colorMultiplier, colorMultiplier, 1);
CurveWrapper wrapper = new CurveWrapper();
wrapper.id = audioCurve.id;
wrapper.groupId = -1;
wrapper.color = audioCurve.color * colorMult;
wrapper.hidden = false;
wrapper.readOnly = false;
wrapper.renderer = new NormalCurveRenderer(curve);
wrapper.renderer.SetCustomRange(0.0f, 1.0f);
wrapper.getAxisUiScalarsCallback = GetAxisScalars;
wrapper.useScalingInKeyEditor = true;
wrapper.xAxisLabel = Styles.xAxisLabel;
wrapper.yAxisLabel = audioCurve.legend.text;
return wrapper;
}
// Callback for Curve Editor to get axis labels
public Vector2 GetAxisScalars()
{
return new Vector2(m_MaxDistance.floatValue, 1);
}
private static float LogarithmicValue(float distance, float minDistance, float rolloffScale)
{
if ((distance > minDistance) && (rolloffScale != 1.0f))
{
distance -= minDistance;
distance *= rolloffScale;
distance += minDistance;
}
if (distance < .000001f)
distance = .000001f;
return minDistance / distance;
}
/// A logarithmic curve starting at /timeStart/, /valueStart/ and ending at /timeEnd/, /valueEnd/
private static AnimationCurve Logarithmic(float timeStart, float timeEnd, float logBase)
{
float value, slope, s;
List<Keyframe> keys = new List<Keyframe>();
// Just plain set the step to 2 always. It can't really be any less,
// or the curvature will end up being imprecise in certain edge cases.
float step = 2;
timeStart = Mathf.Max(timeStart, 0.0001f);
for (float d = timeStart; d < timeEnd; d *= step)
{
// Add key w. sensible tangents
value = LogarithmicValue(d, timeStart, logBase);
s = d / 50.0f;
slope = (LogarithmicValue(d + s, timeStart, logBase) - LogarithmicValue(d - s, timeStart, logBase)) / (s * 2);
keys.Add(new Keyframe(d, value, slope, slope));
}
// last key
value = LogarithmicValue(timeEnd, timeStart, logBase);
s = timeEnd / 50.0f;
slope = (LogarithmicValue(timeEnd + s, timeStart, logBase) - LogarithmicValue(timeEnd - s, timeStart, logBase)) / (s * 2);
keys.Add(new Keyframe(timeEnd, value, slope, slope));
return new AnimationCurve(keys.ToArray());
}
private void Update()
{
// listener moved?
Vector3 sourcePos = GetSourcePos(target);
Vector3 listenerPos = AudioUtil.GetListenerPos();
if ((m_LastSourcePosition - sourcePos).sqrMagnitude > EPSILON || (m_LastListenerPosition - listenerPos).sqrMagnitude > EPSILON)
{
m_LastSourcePosition = sourcePos;
m_LastListenerPosition = listenerPos;
Repaint();
}
}
private void HandleLowPassFilter()
{
AudioCurveWrapper audioCurve = m_AudioCurves[kLowPassCurveID];
// Low pass filter present for all targets?
AudioLowPassFilter[] filterArray = new AudioLowPassFilter[targets.Length];
for (int i = 0; i < targets.Length; i++)
{
filterArray[i] = ((AudioSource)targets[i]).GetComponent<AudioLowPassFilter>();
if (filterArray[i] == null)
{
m_LowpassObject = null;
audioCurve.curveProp = null;
// Return if any of the GameObjects don't have an AudioLowPassFilter
return;
}
}
// All the GameObjects have an AudioLowPassFilter.
// If we don't have the corresponding SerializedObject and SerializedProperties, create them.
if (audioCurve.curveProp == null)
{
m_LowpassObject = new SerializedObject(filterArray);
audioCurve.curveProp = m_LowpassObject.FindProperty("lowpassLevelCustomCurve");
}
}
public override void OnInspectorGUI()
{
//Bug fix: 1018456 Moved the HandleLowPassFilter method before updating the serializedObjects
HandleLowPassFilter();
serializedObject.Update();
if (m_LowpassObject != null)
m_LowpassObject.Update();
UpdateWrappersAndLegend();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_AudioResource, Styles.audioResourceLabel);
EditorGUILayout.PropertyField(m_OutputAudioMixerGroup, Styles.outputMixerGroupLabel);
EditorGUILayout.PropertyField(m_Mute);
if (AudioUtil.canUseSpatializerEffect)
{
EditorGUILayout.PropertyField(m_Spatialize, Styles.spatializeLabel);
using (new EditorGUI.DisabledScope(!m_Spatialize.boolValue))
{
EditorGUILayout.PropertyField(m_SpatializePostEffects, Styles.spatializePostEffectsLabel);
}
}
EditorGUILayout.PropertyField(m_BypassEffects);
if (targets.Any(t => (t as AudioSource).outputAudioMixerGroup != null))
{
using (new EditorGUI.DisabledScope(true))
{
EditorGUILayout.PropertyField(m_BypassListenerEffects);
}
}
else
{
EditorGUILayout.PropertyField(m_BypassListenerEffects);
}
EditorGUILayout.PropertyField(m_BypassReverbZones);
EditorGUILayout.PropertyField(m_PlayOnAwake);
EditorGUILayout.PropertyField(m_Loop);
EditorGUILayout.Space();
EditorGUIUtility.sliderLabels.SetLabels(Styles.priorityLeftLabel, Styles.priorityRightLabel);
EditorGUILayout.IntSlider(m_Priority, 0, 256, Styles.priorityLabel);
EditorGUIUtility.sliderLabels.SetLabels(null, null);
EditorGUILayout.Space();
EditorGUILayout.Slider(m_Volume, 0f, 1.0f, Styles.volumeLabel);
EditorGUILayout.Space();
var resource = m_AudioResource.objectReferenceValue as AudioResource;
if (resource is AudioRandomContainer)
{
EditorGUILayout.Slider(m_Pitch, EPSILON, 3.0f, Styles.pitchLabel);
}
else
{
EditorGUILayout.Slider(m_Pitch, -3.0f, 3.0f, Styles.pitchLabel);
}
EditorGUILayout.Space();
EditorGUIUtility.sliderLabels.SetLabels(Styles.panLeftLabel, Styles.panRightLabel);
EditorGUILayout.Slider(m_Pan2D, -1f, 1f, Styles.panStereoLabel);
EditorGUIUtility.sliderLabels.SetLabels(null, null);
EditorGUILayout.Space();
// 3D Level control
EditorGUIUtility.sliderLabels.SetLabels(Styles.spatialLeftLabel, Styles.spatialRightLabel);
AnimProp(Styles.spatialBlendLabel, m_AudioCurves[kSpatialBlendCurveID].curveProp, 0.0f, 1.0f, false);
EditorGUIUtility.sliderLabels.SetLabels(null, null);
EditorGUILayout.Space();
// 3D Level control
AnimProp(Styles.reverbZoneMixLabel, m_AudioCurves[kReverbZoneMixCurveID].curveProp, 0.0f, 1.1f, false);
EditorGUILayout.Space();
m_Expanded3D = EditorGUILayout.Foldout(m_Expanded3D, "3D Sound Settings", true);
if (m_Expanded3D)
{
EditorGUI.indentLevel++;
Audio3DGUI();
EditorGUI.indentLevel--;
}
serializedObject.ApplyModifiedProperties();
if (m_LowpassObject != null)
m_LowpassObject.ApplyModifiedProperties();
}
private static void SetRolloffToTarget(SerializedProperty property, Object target)
{
property.SetToValueOfTarget(target);
property.serializedObject.FindProperty("rolloffMode").SetToValueOfTarget(target);
property.serializedObject.ApplyModifiedProperties();
EditorUtility.ForceReloadInspectors();
}
private void Audio3DGUI()
{
EditorGUILayout.Slider(m_DopplerLevel, 0.0f, 5.0f, Styles.dopplerLevelLabel);
// Spread control
AnimProp(Styles.spreadLabel, m_AudioCurves[kSpreadCurveID].curveProp, 0.0f, 360.0f, true);
// Rolloff mode
if (m_RolloffMode.hasMultipleDifferentValues ||
(m_RolloffMode.enumValueIndex == (int)AudioRolloffMode.Custom && m_AudioCurves[kRolloffCurveID].curveProp.hasMultipleDifferentValues)
)
{
EditorGUILayout.TargetChoiceField(m_AudioCurves[kRolloffCurveID].curveProp, Styles.rolloffLabel , SetRolloffToTarget);
}
else
{
EditorGUILayout.PropertyField(m_RolloffMode, Styles.rolloffLabel);
if ((AudioRolloffMode)m_RolloffMode.enumValueIndex != AudioRolloffMode.Custom)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_MinDistance);
if (EditorGUI.EndChangeCheck())
{
m_MinDistance.floatValue = Mathf.Clamp(m_MinDistance.floatValue, 0, m_MaxDistance.floatValue / 1.01f);
}
}
else
{
using (new EditorGUI.DisabledScope(true))
{
EditorGUILayout.LabelField(m_MinDistance.displayName, Styles.controlledByCurveLabel);
}
}
}
// Max distance control
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_MaxDistance);
if (EditorGUI.EndChangeCheck())
m_MaxDistance.floatValue = Mathf.Min(Mathf.Max(Mathf.Max(m_MaxDistance.floatValue, 0.01f), m_MinDistance.floatValue * 1.01f), 1000000.0f);
Rect r = GUILayoutUtility.GetAspectRect(1.333f, GUI.skin.textField);
r.xMin += EditorGUI.indent;
if (Event.current.type != EventType.Layout && Event.current.type != EventType.Used)
{
m_CurveEditor.rect = new Rect(r.x, r.y, r.width, r.height);
}
// Draw Curve Editor
UpdateWrappersAndLegend();
GUI.Label(m_CurveEditor.drawRect, GUIContent.none, "TextField");
m_CurveEditor.hRangeLocked = Event.current.shift;
m_CurveEditor.vRangeLocked = EditorGUI.actionKey;
m_CurveEditor.OnGUI();
// Draw current listener position
if (targets.Length == 1)
{
AudioSource t = (AudioSource)target;
AudioListener audioListener = (AudioListener)FindFirstObjectByType(typeof(AudioListener));
if (audioListener != null)
{
float distToListener = (AudioUtil.GetListenerPos() - t.transform.position).magnitude;
DrawLabel("Listener", distToListener, r);
}
}
// Draw legend
DrawLegend();
if (!m_CurveEditor.InLiveEdit())
{
// Check if any of the curves changed
foreach (AudioCurveWrapper audioCurve in m_AudioCurves)
{
if ((m_CurveEditor.GetCurveWrapperFromID(audioCurve.id) != null) && (m_CurveEditor.GetCurveWrapperFromID(audioCurve.id).changed))
{
AnimationCurve changedCurve = m_CurveEditor.GetCurveWrapperFromID(audioCurve.id).curve;
// Never save a curve with no keys
if (changedCurve.length > 0)
{
audioCurve.curveProp.animationCurveValue = changedCurve;
m_CurveEditor.GetCurveWrapperFromID(audioCurve.id).changed = false;
// Volume curve special handling
if (audioCurve.type == AudioCurveType.Volume)
m_RolloffMode.enumValueIndex = (int)AudioRolloffMode.Custom;
}
}
}
}
}
void UpdateWrappersAndLegend()
{
if (m_CurveEditor.InLiveEdit())
return;
// prevent rebuilding wrappers if any curve has changes
if (m_CurveEditor.animationCurves != null)
{
for (int i = 0; i < m_CurveEditor.animationCurves.Length; i++)
{
if (m_CurveEditor.animationCurves[i].changed)
return;
}
}
m_CurveEditor.animationCurves = GetCurveWrapperArray();
SyncShownCurvesToLegend(GetShownAudioCurves());
}
void DrawLegend()
{
List<Rect> legendRects = new List<Rect>();
List<AudioCurveWrapper> curves = GetShownAudioCurves();
Rect legendRect = GUILayoutUtility.GetRect(10, 40 * EditorGUIUtility.pixelsPerPoint);
legendRect.x += 4 + EditorGUI.indent;
legendRect.width -= 8 + EditorGUI.indent;
// Graph's position acts as reference for Legends
legendRect.y = m_CurveEditor.rect.y + m_CurveEditor.rect.height + 20;
int width = Mathf.Min(75, Mathf.FloorToInt(legendRect.width / curves.Count));
for (int i = 0; i < curves.Count; i++)
{
legendRects.Add(new Rect(legendRect.x + width * i, legendRect.y, width, legendRect.height));
}
bool resetSelections = false;
if (curves.Count != m_SelectedCurves.Length)
{
m_SelectedCurves = new bool[curves.Count];
resetSelections = true;
}
if (EditorGUIExt.DragSelection(legendRects.ToArray(), ref m_SelectedCurves, GUIStyle.none) || resetSelections)
{
// If none are selected, select all
bool someSelected = false;
for (int i = 0; i < curves.Count; i++)
{
if (m_SelectedCurves[i])
someSelected = true;
}
if (!someSelected)
{
for (int i = 0; i < curves.Count; i++)
{
m_SelectedCurves[i] = true;
}
}
SyncShownCurvesToLegend(curves);
}
for (int i = 0; i < curves.Count; i++)
{
EditorGUI.DrawLegend(legendRects[i], curves[i].color, curves[i].legend.text, m_SelectedCurves[i]);
if (curves[i].curveProp.hasMultipleDifferentValues)
{
GUI.Button(new Rect(legendRects[i].x, legendRects[i].y + 20, legendRects[i].width, 20), "Different");
}
}
}
private List<AudioCurveWrapper> GetShownAudioCurves()
{
return m_AudioCurves.Where(f => m_CurveEditor.GetCurveWrapperFromID(f.id) != null).ToList();
}
private void SyncShownCurvesToLegend(List<AudioCurveWrapper> curves)
{
if (curves.Count != m_SelectedCurves.Length)
return; // Selected curves in sync'ed later in this frame
for (int i = 0; i < curves.Count; i++)
m_CurveEditor.GetCurveWrapperFromID(curves[i].id).hidden = !m_SelectedCurves[i];
// Need to apply animation curves again to synch selections
m_CurveEditor.animationCurves = m_CurveEditor.animationCurves;
}
void DrawLabel(string label, float value, Rect r)
{
Vector2 size = Styles.labelStyle.CalcSize(new GUIContent(label));
size.x += 2;
Vector2 posA = m_CurveEditor.DrawingToViewTransformPoint(new Vector2(value / m_MaxDistance.floatValue, 0));
Vector2 posB = m_CurveEditor.DrawingToViewTransformPoint(new Vector2(value / m_MaxDistance.floatValue, 1));
GUI.BeginGroup(r);
Color temp = Handles.color;
Handles.color = new Color(1, 0, 0, 0.3f);
Handles.DrawLine(new Vector3(posA.x , posA.y, 0), new Vector3(posB.x , posB.y, 0));
Handles.DrawLine(new Vector3(posA.x + 1, posA.y, 0), new Vector3(posB.x + 1, posB.y, 0));
Handles.color = temp;
GUI.Label(new Rect(Mathf.Floor(posB.x - size.x / 2), 2, size.x, 15), label, Styles.labelStyle);
GUI.EndGroup();
}
internal static void AnimProp(GUIContent label, SerializedProperty prop, float min, float max, bool useNormalizedValue)
{
if (prop.hasMultipleDifferentValues)
{
EditorGUILayout.TargetChoiceField(prop, label);
return;
}
AnimationCurve curve = prop.animationCurveValue;
if (curve == null)
{
Debug.LogError(label.text + " curve is null!");
return;
}
else if (curve.length == 0)
{
Debug.LogError(label.text + " curve has no keys!");
return;
}
Rect position = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(position, label, prop);
if (curve.length != 1)
{
using (new EditorGUI.DisabledScope(true))
{
EditorGUI.LabelField(position, label.text, Styles.controlledByCurveLabel);
}
}
else
{
float f = useNormalizedValue ? Mathf.Lerp(min, max, curve.keys[0].value) : curve.keys[0].value;
f = MathUtils.DiscardLeastSignificantDecimal(f);
EditorGUI.BeginChangeCheck();
if (max > min)
f = EditorGUI.Slider(position, label, f, min, max);
else
f = EditorGUI.Slider(position, label, f, max, min);
if (EditorGUI.EndChangeCheck())
{
Keyframe kf = curve.keys[0];
kf.time = 0.0f;
kf.value = useNormalizedValue ? Mathf.InverseLerp(min, max, f) : f;
curve.MoveKey(0, kf);
}
}
EditorGUI.EndProperty();
prop.animationCurveValue = curve;
}
void OnSceneGUI()
{
if (!target)
return;
AudioSource source = (AudioSource)target;
Color tempColor = Handles.color;
if (source.enabled)
Handles.color = new Color(0.50f, 0.70f, 1.00f, 0.5f);
else
Handles.color = new Color(0.30f, 0.40f, 0.60f, 0.5f);
Vector3 position = source.transform.position;
EditorGUI.BeginChangeCheck();
float minDistance = Handles.RadiusHandle(Quaternion.identity, position, source.minDistance, true);
float maxDistance = Handles.RadiusHandle(Quaternion.identity, position, source.maxDistance, true);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(source, "AudioSource Distance");
source.minDistance = minDistance;
source.maxDistance = maxDistance;
}
Handles.color = tempColor;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/AudioSourceInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/AudioSourceInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 15946
} | 287 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.AnimatedValues;
using UnityEngine;
using UnityEditor;
using UnityEditor.Animations;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Object = UnityEngine.Object;
using System.Globalization;
namespace UnityEditor
{
[CustomEditor(typeof(BlendTree))]
internal class BlendTreeInspector : Editor
{
class Styles
{
public readonly GUIStyle background = "MeBlendBackground";
public readonly GUIStyle triangleLeft = "MeBlendTriangleLeft";
public readonly GUIStyle triangleRight = "MeBlendTriangleRight";
public readonly GUIStyle blendPosition = "MeBlendPosition";
public GUIStyle clickDragFloatFieldLeft = new GUIStyle(EditorStyles.miniTextField);
public GUIStyle clickDragFloatFieldRight = new GUIStyle(EditorStyles.miniTextField);
public GUIStyle clickDragFloatLabelLeft = new GUIStyle(EditorStyles.miniLabel);
public GUIStyle clickDragFloatLabelRight = new GUIStyle(EditorStyles.miniLabel);
public GUIStyle headerIcon = new GUIStyle();
public GUIStyle errorStyle = new GUIStyle(EditorStyles.wordWrappedLabel);
public GUIContent speedIcon = new GUIContent(EditorGUIUtility.IconContent("SpeedScale"));
public GUIContent mirrorIcon = new GUIContent(EditorGUIUtility.IconContent("Mirror"));
public Texture2D pointIcon = EditorGUIUtility.LoadIcon("blendKey");
public Texture2D pointIconSelected = EditorGUIUtility.LoadIcon("blendKeySelected");
public Texture2D pointIconOverlay = EditorGUIUtility.LoadIcon("blendKeyOverlay");
public Texture2D samplerIcon = EditorGUIUtility.LoadIcon("blendSampler");
public Color visBgColor;
public Color visWeightColor;
public Color visWeightShapeColor;
public Color visWeightLineColor;
public Color visPointColor;
public Color visPointEmptyColor;
public Color visPointOverlayColor;
public Color visSamplerColor;
public Styles()
{
errorStyle.alignment = TextAnchor.MiddleCenter;
speedIcon.tooltip = "Changes animation speed.";
mirrorIcon.tooltip = "Mirror animation.";
headerIcon.alignment = TextAnchor.MiddleCenter;
clickDragFloatFieldLeft.alignment = TextAnchor.MiddleLeft;
clickDragFloatFieldRight.alignment = TextAnchor.MiddleRight;
clickDragFloatLabelLeft.alignment = TextAnchor.MiddleLeft;
clickDragFloatLabelRight.alignment = TextAnchor.MiddleRight;
visBgColor = !EditorGUIUtility.isProSkin ? new Color(0.95f, 0.95f, 1.00f) : new Color(0.20f, 0.20f, 0.20f);
visWeightColor = !EditorGUIUtility.isProSkin ? new Color(0.50f, 0.60f, 0.90f, 0.80f) : new Color(0.65f, 0.75f, 1.00f, 0.65f);
visWeightShapeColor = !EditorGUIUtility.isProSkin ? new Color(0.40f, 0.65f, 1.00f, 0.15f) : new Color(0.40f, 0.65f, 1.00f, 0.12f);
visWeightLineColor = !EditorGUIUtility.isProSkin ? new Color(0 , 0 , 0 , 0.30f) : new Color(1 , 1 , 1 , 0.60f);
visPointColor = new Color(0.50f, 0.70f, 1.00f);
visPointEmptyColor = !EditorGUIUtility.isProSkin ? new Color(0.80f, 0.80f, 0.80f) : new Color(0.60f, 0.60f, 0.60f);
visPointOverlayColor = !EditorGUIUtility.isProSkin ? new Color(0 , 0 , 0 , 0.20f) : new Color(1 , 1 , 1 , 0.40f);
visSamplerColor = new Color(1.00f, 0.40f, 0.40f);
}
}
static Styles styles;
internal static AnimatorController currentController = null;
internal static Animator currentAnimator = null;
internal static BlendTree parentBlendTree = null;
internal static Action<BlendTree> blendParameterInputChanged = null;
private readonly int m_BlendAnimationID = "BlendAnimationIDHash".GetHashCode();
private readonly int m_ClickDragFloatID = "ClickDragFloatIDHash".GetHashCode();
private float m_DragAndDropDelta;
private float m_OriginMin;
private float m_OriginMax;
private UnityEditorInternal.ReorderableList m_ReorderableList;
private SerializedProperty m_Childs;
private SerializedProperty m_BlendParameter;
private SerializedProperty m_BlendParameterY;
private BlendTree m_BlendTree;
private SerializedProperty m_UseAutomaticThresholds;
private SerializedProperty m_NormalizedBlendValues;
private SerializedProperty m_MinThreshold;
private SerializedProperty m_MaxThreshold;
private SerializedProperty m_Name;
private SerializedProperty m_BlendType;
private AnimBool m_ShowGraph = new AnimBool();
private AnimBool m_ShowCompute = new AnimBool();
private AnimBool m_ShowAdjust = new AnimBool();
private bool m_ShowGraphValue = false;
private bool m_BlendValueManipulated = false;
private float[] m_Weights;
private const int kVisResolution = 64;
private Texture2D m_BlendTex = null;
private List<Texture2D> m_WeightTexs = new List<Texture2D>();
private string m_WarningMessage = null;
private PreviewBlendTree m_PreviewBlendTree;
private VisualizationBlendTree m_VisBlendTree;
private GameObject m_VisInstance = null;
private int ParameterCount { get { return m_BlendType.intValue > (int)BlendTreeType.Simple1D ? (m_BlendType.intValue < (int)BlendTreeType.Direct ? 2 : 0) : 1; } }
static internal void SetParameterValue(Animator animator, BlendTree blendTree, BlendTree parentBlendTree, string parameterName, float parameterValue)
{
bool liveLink = EditorApplication.isPlaying && animator != null && animator.enabled && animator.gameObject.activeInHierarchy;
if (liveLink)
animator.SetFloat(parameterName, parameterValue);
blendTree.SetInputBlendValue(parameterName, parameterValue);
if (blendParameterInputChanged != null)
blendParameterInputChanged(blendTree);
if (parentBlendTree != null)
{
parentBlendTree.SetInputBlendValue(parameterName, parameterValue);
if (blendParameterInputChanged != null)
blendParameterInputChanged(parentBlendTree);
}
}
static internal float GetParameterValue(Animator animator, BlendTree blendTree, string parameterName)
{
bool liveLink = EditorApplication.isPlaying && animator != null && animator.enabled && animator.gameObject.activeInHierarchy;
if (liveLink)
{
return animator.GetFloat(parameterName);
}
else
{
return blendTree.GetInputBlendValue(parameterName);
}
}
public void OnEnable()
{
m_Name = serializedObject.FindProperty("m_Name");
m_BlendParameter = serializedObject.FindProperty("m_BlendParameter");
m_BlendParameterY = serializedObject.FindProperty("m_BlendParameterY");
m_UseAutomaticThresholds = serializedObject.FindProperty("m_UseAutomaticThresholds");
m_NormalizedBlendValues = serializedObject.FindProperty("m_NormalizedBlendValues");
m_MinThreshold = serializedObject.FindProperty("m_MinThreshold");
m_MaxThreshold = serializedObject.FindProperty("m_MaxThreshold");
m_BlendType = serializedObject.FindProperty("m_BlendType");
}
void Init()
{
if (styles == null)
styles = new Styles();
if (m_BlendTree == null)
m_BlendTree = target as BlendTree;
if (styles == null)
styles = new Styles();
if (m_PreviewBlendTree == null)
m_PreviewBlendTree = new PreviewBlendTree();
if (m_VisBlendTree == null)
m_VisBlendTree = new VisualizationBlendTree();
if (m_Childs == null)
{
m_Childs = serializedObject.FindProperty("m_Childs");
m_ReorderableList = new UnityEditorInternal.ReorderableList(serializedObject, m_Childs);
m_ReorderableList.drawHeaderCallback = DrawHeader;
m_ReorderableList.drawElementCallback = DrawChild;
m_ReorderableList.onReorderCallback = EndDragChild;
m_ReorderableList.onAddDropdownCallback = AddButton;
m_ReorderableList.onRemoveCallback = RemoveButton;
if (m_BlendType.intValue == (int)BlendTreeType.Simple1D)
SortByThreshold();
m_ShowGraphValue = m_BlendType.intValue == (int)BlendTreeType.Direct ? m_Childs.arraySize >= 1 : m_Childs.arraySize >= 2;
m_ShowGraph.value = m_ShowGraphValue;
m_ShowAdjust.value = AllMotions();
m_ShowCompute.value = !m_UseAutomaticThresholds.boolValue;
m_ShowGraph.valueChanged.AddListener(Repaint);
m_ShowAdjust.valueChanged.AddListener(Repaint);
m_ShowCompute.valueChanged.AddListener(Repaint);
}
m_PreviewBlendTree.Init(m_BlendTree, currentAnimator);
bool hasInitVisIntance = false;
if (m_VisInstance == null)
{
GameObject go = (GameObject)EditorGUIUtility.Load("Avatar/DefaultAvatar.fbx");
m_VisInstance = (GameObject)EditorUtility.InstantiateForAnimatorPreview(go);
foreach (Renderer renderer in m_VisInstance.GetComponentsInChildren<Renderer>())
renderer.enabled = false;
hasInitVisIntance = true;
}
m_VisBlendTree.Init(m_BlendTree, m_VisInstance.GetComponent<Animator>());
if (hasInitVisIntance &&
(m_BlendType.intValue == (int)BlendTreeType.SimpleDirectional2D ||
m_BlendType.intValue == (int)BlendTreeType.FreeformDirectional2D ||
m_BlendType.intValue == (int)BlendTreeType.FreeformCartesian2D))
{
UpdateBlendVisualization();
ValidatePositions();
}
}
internal override void OnHeaderIconGUI(Rect iconRect)
{
Texture2D icon = AssetPreview.GetMiniThumbnail(target);
GUI.Label(iconRect, icon);
}
internal override void OnHeaderTitleGUI(Rect titleRect, string header)
{
serializedObject.Update();
Rect textFieldRect = titleRect;
textFieldRect.height = EditorGUI.kSingleLineHeight;
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = m_Name.hasMultipleDifferentValues;
string newName = EditorGUI.DelayedTextField(textFieldRect, m_Name.stringValue, EditorStyles.textField);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck() && !String.IsNullOrEmpty(newName))
{
foreach (Object obj in targets)
ObjectNames.SetNameSmart(obj, newName);
}
serializedObject.ApplyModifiedProperties();
}
internal override void OnHeaderControlsGUI()
{
EditorGUIUtility.labelWidth = 80;
serializedObject.Update();
EditorGUILayout.PropertyField(m_BlendType);
serializedObject.ApplyModifiedProperties();
}
private List<string> CollectParameters(AnimatorController controller)
{
List<string> parameterList = new List<string>();
if (controller != null)
{
AnimatorControllerParameter[] parameters = controller.parameters;
for (int i = 0; i < parameters.Length; i++)
{
AnimatorControllerParameter animatorParameter = parameters[i];
// only deal with floats
if (animatorParameter.type == AnimatorControllerParameterType.Float)
{
parameterList.Add(animatorParameter.name);
}
}
}
return parameterList;
}
private void ParameterGUI()
{
EditorGUILayout.BeginHorizontal();
// Label
if (ParameterCount > 1)
EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameters"));
else
EditorGUILayout.PrefixLabel(EditorGUIUtility.TempContent("Parameter"));
serializedObject.Update();
// Available parameters
// Populate parameters list and find indexes of used blend parameters
string currentParameter = m_BlendTree.blendParameter;
string currentParameterY = m_BlendTree.blendParameterY;
List<string> parameters = CollectParameters(currentController);
EditorGUI.BeginChangeCheck();
currentParameter = EditorGUILayout.DelayedTextFieldDropDown(currentParameter, parameters.ToArray());
if (EditorGUI.EndChangeCheck())
{
m_BlendParameter.stringValue = currentParameter;
}
if (ParameterCount > 1)
{
// Show second blend parameter
EditorGUI.BeginChangeCheck();
currentParameterY = EditorGUILayout.TextFieldDropDown(currentParameterY, parameters.ToArray());
if (EditorGUI.EndChangeCheck())
{
m_BlendParameterY.stringValue = currentParameterY;
}
}
serializedObject.ApplyModifiedProperties();
EditorGUILayout.EndHorizontal();
}
public override void OnInspectorGUI()
{
Init();
serializedObject.Update();
if (m_BlendType.intValue != (int)BlendTreeType.Direct)
{
// Parameters
ParameterGUI();
}
m_ShowGraphValue = m_BlendType.intValue == (int)BlendTreeType.Direct ? m_Childs.arraySize >= 1 : m_Childs.arraySize >= 2;
m_ShowGraph.target = m_ShowGraphValue;
m_UseAutomaticThresholds = serializedObject.FindProperty("m_UseAutomaticThresholds");
GUI.enabled = true;
if (EditorGUILayout.BeginFadeGroup(m_ShowGraph.faded))
{
if (m_BlendType.intValue == (int)BlendTreeType.Simple1D)
{
BlendGraph(EditorGUILayout.GetControlRect(false, 40, styles.background));
ThresholdValues();
}
else if (m_BlendType.intValue == (int)BlendTreeType.Direct)
{
for (int i = 0; i < m_BlendTree.recursiveBlendParameterCount; i++)
{
string eventName = m_BlendTree.GetRecursiveBlendParameter(i);
float eventMin = m_BlendTree.GetRecursiveBlendParameterMin(i);
float eventMax = m_BlendTree.GetRecursiveBlendParameterMax(i);
EditorGUI.BeginChangeCheck();
float eventValue = EditorGUILayout.Slider(eventName, GetParameterValue(currentAnimator, m_BlendTree, eventName), eventMin, eventMax);
if (EditorGUI.EndChangeCheck())
SetParameterValue(currentAnimator, m_BlendTree, parentBlendTree, eventName, eventValue);
}
}
else // 2D blend tree types
{
GUILayout.Space(1);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
Rect graphRect = GUILayoutUtility.GetAspectRect(1, GUILayout.MaxWidth(235));
GUI.Label(new Rect(graphRect.x - 1, graphRect.y - 1, graphRect.width + 2, graphRect.height + 2), GUIContent.none, EditorStyles.textField);
GUI.BeginGroup(graphRect);
graphRect.x = 0;
graphRect.y = 0;
BlendGraph2D(graphRect);
GUI.EndGroup();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
GUILayout.Space(5);
}
EditorGUILayout.EndFadeGroup();
if (m_ReorderableList != null)
{
m_ReorderableList.DoLayoutList();
}
if (m_BlendType.intValue == (int)BlendTreeType.Direct)
{
EditorGUILayout.PropertyField(m_NormalizedBlendValues, EditorGUIUtility.TempContent("Normalized Blend Values"));
}
if (m_ShowGraphValue)
{
GUILayout.Space(10);
AutoCompute();
}
serializedObject.ApplyModifiedProperties();
}
private void SetMinMaxThresholds()
{
float min = Mathf.Infinity;
float max = Mathf.NegativeInfinity;
for (int i = 0; i < m_Childs.arraySize; i++)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
min = (threshold.floatValue < min) ? threshold.floatValue : min;
max = (threshold.floatValue > max) ? threshold.floatValue : max;
}
m_MinThreshold.floatValue = m_Childs.arraySize > 0 ? min : 0;
m_MaxThreshold.floatValue = m_Childs.arraySize > 0 ? max : 1;
}
private void ThresholdValues()
{
Rect r = EditorGUILayout.GetControlRect();
Rect r1 = r;
Rect r2 = r;
r1.width /= 4;
r2.width /= 4;
r2.x = r.x + r.width - r2.width;
float min = m_MinThreshold.floatValue;
float max = m_MaxThreshold.floatValue;
EditorGUI.BeginChangeCheck();
min = ClickDragFloat(r1, min);
max = ClickDragFloat(r2, max, true);
if (EditorGUI.EndChangeCheck())
{
float newMin = Mathf.Min(min, max);
float newMax = Mathf.Max(min, max);
if (m_Childs.arraySize >= 2)
{
// Get first and last threshold properties.
SerializedProperty firstChild = m_Childs.GetArrayElementAtIndex(0);
SerializedProperty lastChild = m_Childs.GetArrayElementAtIndex(m_Childs.arraySize - 1);
SerializedProperty firstThreshold = firstChild.FindPropertyRelative("m_Threshold");
SerializedProperty lastThreshold = lastChild.FindPropertyRelative("m_Threshold");
// Store previous values.
float previousMin = firstThreshold.floatValue;
float previousMax = lastThreshold.floatValue;
// Set the new thresholds.
firstThreshold.floatValue = newMin;
lastThreshold.floatValue = newMax;
if (!m_UseAutomaticThresholds.boolValue)
{
// Since this isn't being automatically calculated, we need to scale the values.
int arraySize = m_Childs.arraySize;
for (int i = 1; i < arraySize - 1; ++i)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
float ratio = Mathf.InverseLerp(previousMin, previousMax, threshold.floatValue);
threshold.floatValue = Mathf.Lerp(newMin, newMax, ratio);
}
}
// Clamp the current blend value within the new boundaries.
float blendValue = GetParameterValue(currentAnimator, m_BlendTree, m_BlendTree.blendParameter);
blendValue = Mathf.Clamp(blendValue, newMin, newMax);
SetParameterValue(currentAnimator, m_BlendTree, parentBlendTree, m_BlendTree.blendParameter, blendValue);
}
// Set the new min/max thresholds.
m_MinThreshold.floatValue = newMin;
m_MaxThreshold.floatValue = newMax;
}
}
private static bool s_ClickDragFloatDragged;
private static float s_ClickDragFloatDistance;
public float ClickDragFloat(Rect position, float value)
{
return ClickDragFloat(position, value, false);
}
public float ClickDragFloat(Rect position, float value, bool alignRight)
{
bool changed;
// TODO: Why does the cursor change to arrow when editing the text?
string allowedCharacters = "inftynaeINFTYNAE0123456789.,-";
int id = EditorGUIUtility.GetControlID(m_ClickDragFloatID, FocusType.Keyboard, position);
Event evt = Event.current;
string str;
switch (evt.type)
{
case EventType.MouseUp:
if (GUIUtility.hotControl != id)
break;
evt.Use();
if (position.Contains(evt.mousePosition) && !s_ClickDragFloatDragged)
{
EditorGUIUtility.editingTextField = true;
}
else
{
GUIUtility.keyboardControl = 0;
GUIUtility.hotControl = 0;
s_ClickDragFloatDragged = false;
}
break;
case EventType.MouseDown:
if (GUIUtility.keyboardControl == id && EditorGUIUtility.editingTextField)
break;
if (position.Contains(evt.mousePosition))
{
evt.Use();
s_ClickDragFloatDragged = false;
s_ClickDragFloatDistance = 0f;
GUIUtility.hotControl = id;
GUIUtility.keyboardControl = id;
EditorGUIUtility.editingTextField = false;
}
else
{
GUIUtility.keyboardControl = 0;
GUIUtility.hotControl = 0;
s_ClickDragFloatDragged = false;
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl != id || EditorGUIUtility.editingTextField)
break;
s_ClickDragFloatDistance += Mathf.Abs(HandleUtility.niceMouseDelta);
if (s_ClickDragFloatDistance >= 5f)
{
s_ClickDragFloatDragged = true;
value += HandleUtility.niceMouseDelta * .03f;
value = MathUtils.RoundBasedOnMinimumDifference(value, .03f);
GUI.changed = true;
}
evt.Use();
break;
}
GUIStyle style = (GUIUtility.keyboardControl == id && EditorGUIUtility.editingTextField) ?
(alignRight ? styles.clickDragFloatFieldRight : styles.clickDragFloatFieldLeft) :
(alignRight ? styles.clickDragFloatLabelRight : styles.clickDragFloatLabelLeft);
if (GUIUtility.keyboardControl == id)
{
if (!EditorGUI.s_RecycledEditor.IsEditingControl(id))
{
str = EditorGUI.s_RecycledCurrentEditingString = value.ToString("g7", CultureInfo.InvariantCulture.NumberFormat);
}
else
{
str = EditorGUI.s_RecycledCurrentEditingString;
if (evt.type == EventType.ValidateCommand && evt.commandName == EventCommandNames.UndoRedoPerformed)
str = value.ToString("g7", CultureInfo.InvariantCulture.NumberFormat);
}
str = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position, str, style , allowedCharacters, out changed, false, false, false);
if (changed)
{
GUI.changed = true;
EditorGUI.s_RecycledCurrentEditingString = str;
string lowered = str.ToLower();
if (lowered == "inf" || lowered == "infinity")
{
value = Mathf.Infinity;
}
else if (lowered == "-inf" || lowered == "-infinity")
{
value = Mathf.NegativeInfinity;
}
else
{
str = str.Replace(',', '.');
if (!float.TryParse(str, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture.NumberFormat, out value))
{
value = 0;
return value;
}
if (System.Single.IsNaN(value))
value = 0;
}
}
}
else
{
str = value.ToString("g7", CultureInfo.InvariantCulture.NumberFormat);
str = EditorGUI.DoTextField(EditorGUI.s_RecycledEditor, id, position, str, style, allowedCharacters, out changed, false, false, false);
}
return value;
}
private void BlendGraph(Rect area)
{
// Adjust padding for rect
// (This is normally not needed anymore, but this style has some overdraw that needs to be compensated.)
area.xMin += 1;
area.xMax -= 1;
int sliderId = GUIUtility.GetControlID(m_BlendAnimationID, FocusType.Passive);
// get points array from child objects
int childCount = m_Childs.arraySize;
float[] points = new float[childCount];
for (int i = 0; i < childCount; i++)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
points[i] = threshold.floatValue;
}
// move points to GUI space
float min = Mathf.Min(points);
float max = Mathf.Max(points);
for (int i = 0; i < points.Length; i++)
{
points[i] = area.x + (Mathf.InverseLerp(min, max, points[i]) * area.width);
}
// get blend bar info
string currentParameter = m_BlendTree.blendParameter;
float blendBar = area.x + (Mathf.InverseLerp(min, max, GetParameterValue(currentAnimator, m_BlendTree, currentParameter)) * area.width);
Rect barRect = new Rect(blendBar - 4f, area.y, 9f, 42f);
Event evt = Event.current;
switch (evt.GetTypeForControl(sliderId))
{
case EventType.Repaint:
styles.background.Draw(area, GUIContent.none, false, false, false, false);
if (m_Childs.arraySize >= 2)
{
for (int i = 0; i < points.Length; i++)
{
// draw the animation triangle
float last = (i == 0) ? points[i] : points[i - 1];
float next = (i == points.Length - 1) ? points[i] : points[i + 1];
bool drawSelected = (m_ReorderableList.index == i);
DrawAnimation(points[i], last, next, drawSelected, area);
}
Color oldColor = Handles.color;
Handles.color = new Color(0f, 0f, 0f, 0.25f);
Handles.DrawLine(new Vector3(area.x, area.y + area.height, 0f), new Vector3(area.x + area.width, area.y + area.height, 0f));
Handles.color = oldColor;
// draw the current input bar
styles.blendPosition.Draw(barRect, GUIContent.none, false, false, false, false);
}
else
{
GUI.Label(area, EditorGUIUtility.TempContent("Please Add Motion Fields or Blend Trees"), styles.errorStyle);
}
break;
case EventType.MouseDown:
float curBlendValue = 0.0f;
if (barRect.Contains(evt.mousePosition))
{
evt.Use();
GUIUtility.hotControl = sliderId;
m_BlendValueManipulated = true;
// Get current blend value.
curBlendValue = GetParameterValue(currentAnimator, m_BlendTree, currentParameter);
}
else if (area.Contains(evt.mousePosition))
{
evt.Use();
GUIUtility.hotControl = sliderId;
GUIUtility.keyboardControl = sliderId;
// determine closest animation or blend tree
float clickPosition = evt.mousePosition.x;
float distance = Mathf.Infinity;
m_BlendValueManipulated = true;
for (int i = 0; i < points.Length; i++)
{
float last = (i == 0) ? points[i] : points[i - 1];
float next = (i == points.Length - 1) ? points[i] : points[i + 1];
if (Mathf.Abs(clickPosition - points[i]) < distance)
{
if (clickPosition < next && clickPosition > last)
{
distance = Mathf.Abs(clickPosition - points[i]);
m_ReorderableList.index = i;
m_BlendValueManipulated = false;
}
}
}
// turn off automatic thresholds
m_UseAutomaticThresholds.boolValue = false;
// Get current blend value.
if (!m_BlendValueManipulated)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(m_ReorderableList.index);
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
curBlendValue = threshold.floatValue;
}
}
// Get drag'n'drop infos.
float mouseBlendValue = (evt.mousePosition.x - area.x) / area.width;
mouseBlendValue = Mathf.LerpUnclamped(min, max, mouseBlendValue);
m_DragAndDropDelta = mouseBlendValue - curBlendValue;
m_OriginMin = min;
m_OriginMax = max;
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl != sliderId)
break;
evt.Use();
// Convert mouse position to blend space.
float newMouseBlendValue = (evt.mousePosition.x - area.x) / area.width;
newMouseBlendValue = Mathf.LerpUnclamped(m_OriginMin, m_OriginMax, newMouseBlendValue);
float newBlendValue = newMouseBlendValue - m_DragAndDropDelta;
if (m_BlendValueManipulated)
{
// the user is dragging the blend position
newBlendValue = Mathf.Clamp(newBlendValue, min, max);
SetParameterValue(currentAnimator, m_BlendTree, parentBlendTree, currentParameter, newBlendValue);
}
else
{
// set the new threshold based on mousePosition
SerializedProperty child = m_Childs.GetArrayElementAtIndex(m_ReorderableList.index);
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
// get neighboring thresholds
SerializedProperty lastChild = (m_ReorderableList.index <= 0) ? child : m_Childs.GetArrayElementAtIndex(m_ReorderableList.index - 1);
SerializedProperty nextChild = (m_ReorderableList.index == m_Childs.arraySize - 1) ? child : m_Childs.GetArrayElementAtIndex(m_ReorderableList.index + 1);
SerializedProperty lastThreshold = lastChild.FindPropertyRelative("m_Threshold");
SerializedProperty nextThreshold = nextChild.FindPropertyRelative("m_Threshold");
// change threshold value
threshold.floatValue = newBlendValue;
// reorder if dragged beyond range
if (threshold.floatValue < lastThreshold.floatValue && m_ReorderableList.index != 0)
{
m_Childs.MoveArrayElement(m_ReorderableList.index, m_ReorderableList.index - 1);
m_ReorderableList.index -= 1;
}
if (threshold.floatValue > nextThreshold.floatValue && m_ReorderableList.index < m_Childs.arraySize - 1)
{
m_Childs.MoveArrayElement(m_ReorderableList.index, m_ReorderableList.index + 1);
m_ReorderableList.index += 1;
}
// snap to near thresholds
float snapThreshold = 3f * ((max - min) / area.width);
if (threshold.floatValue - lastThreshold.floatValue <= snapThreshold)
{
threshold.floatValue = lastThreshold.floatValue;
}
else if (nextThreshold.floatValue - threshold.floatValue <= snapThreshold)
{
threshold.floatValue = nextThreshold.floatValue;
}
SetMinMaxThresholds();
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl == sliderId)
{
evt.Use();
GUIUtility.hotControl = 0;
m_BlendValueManipulated = true;
}
break;
}
}
private void UpdateBlendVisualization()
{
Vector2[] points = GetActiveMotionPositions();
if (m_BlendTex == null)
{
m_BlendTex = new Texture2D(kVisResolution, kVisResolution, TextureFormat.RGBA32, false);
m_BlendTex.hideFlags = HideFlags.HideAndDontSave;
m_BlendTex.wrapMode = TextureWrapMode.Clamp;
}
while (m_WeightTexs.Count < points.Length)
{
Texture2D tex = new Texture2D(kVisResolution, kVisResolution, TextureFormat.RGBA32, false);
tex.wrapMode = TextureWrapMode.Clamp;
tex.hideFlags = HideFlags.HideAndDontSave;
m_WeightTexs.Add(tex);
}
while (m_WeightTexs.Count > points.Length)
{
DestroyImmediate(m_WeightTexs[m_WeightTexs.Count - 1]);
m_WeightTexs.RemoveAt(m_WeightTexs.Count - 1);
}
// Calculate min and max for all the points
if (GUIUtility.hotControl == 0)
m_BlendRect = Get2DBlendRect(GetMotionPositions());
m_VisBlendTree.Reset();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
Texture2D[] textures = m_WeightTexs.ToArray();
// While dragging, only update the weight texture that's being dragged.
if (GUIUtility.hotControl != 0 && !m_BlendValueManipulated)
{
int[] indices = GetMotionToActiveMotionIndices();
for (int i = 0; i < textures.Length; i++)
if (indices[m_ReorderableList.index] != i)
textures[i] = null;
}
UnityEditorInternal.BlendTreePreviewUtility.CalculateBlendTexture(m_VisBlendTree.animator, 0, m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).fullPathHash,
m_BlendTex, textures, m_BlendRect);
watch.Stop();
//Debug.Log ("CalculateBlendTexture took "+watch.ElapsedMilliseconds+" ms");
}
private Vector2[] GetMotionPositions()
{
int childCount = m_Childs.arraySize;
Vector2[] points = new Vector2[childCount];
for (int i = 0; i < childCount; i++)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty position = child.FindPropertyRelative("m_Position");
points[i] = position.vector2Value;
}
return points;
}
private Vector2[] GetActiveMotionPositions()
{
List<Vector2> points = new List<Vector2>();
int childCount = m_Childs.arraySize;
for (int i = 0; i < childCount; i++)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty motion = child.FindPropertyRelative("m_Motion");
if (motion.objectReferenceValue != null)
{
SerializedProperty position = child.FindPropertyRelative("m_Position");
points.Add(position.vector2Value);
}
}
return points.ToArray();
}
private int[] GetMotionToActiveMotionIndices()
{
int childCount = m_Childs.arraySize;
int[] indices = new int[childCount];
int activeMotion = 0;
for (int i = 0; i < childCount; i++)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty motion = child.FindPropertyRelative("m_Motion");
if (motion.objectReferenceValue == null)
indices[i] = -1;
else
{
indices[i] = activeMotion;
activeMotion++;
}
}
return indices;
}
private Rect Get2DBlendRect(Vector2[] points)
{
Vector2 center = Vector2.zero;
float maxDist = 0;
if (points.Length == 0)
{
return new Rect();
}
if (m_BlendType.intValue == (int)BlendTreeType.FreeformCartesian2D)
{
// Make min and max rect with center at the bounds center
Vector2 min = points[0];
Vector2 max = points[0];
for (int i = 1; i < points.Length; i++)
{
max.x = Mathf.Max(max.x, points[i].x);
max.y = Mathf.Max(max.y, points[i].y);
min.x = Mathf.Min(min.x, points[i].x);
min.y = Mathf.Min(min.y, points[i].y);
}
center = (min + max) * 0.5f;
maxDist = Mathf.Max(max.x - min.x, max.y - min.y) * 0.5f;
}
else
{
// Make min and max a rect with the origin in the center
for (int i = 0; i < points.Length; i++)
{
maxDist = Mathf.Max(maxDist, points[i].x);
maxDist = Mathf.Max(maxDist, -points[i].x);
maxDist = Mathf.Max(maxDist, points[i].y);
maxDist = Mathf.Max(maxDist, -points[i].y);
}
}
if (maxDist == 0)
maxDist = 1;
maxDist *= 1.35f;
return new Rect(center.x - maxDist, center.y - maxDist, maxDist * 2, maxDist * 2);
}
private Rect m_BlendRect;
private int m_SelectedPoint = -1;
private bool s_DraggingPoint = false;
private float ConvertFloat(float input, float fromMin, float fromMax, float toMin, float toMax)
{
float lerp = (input - fromMin) / (fromMax - fromMin);
return toMin * (1 - lerp) + toMax * lerp;
}
private void BlendGraph2D(Rect area)
{
if (m_VisBlendTree.controllerDirty)
{
UpdateBlendVisualization();
ValidatePositions();
}
// Get points array from child objects
Vector2[] points = GetMotionPositions();
int[] presences = GetMotionToActiveMotionIndices();
Vector2 min = new Vector2(m_BlendRect.xMin, m_BlendRect.yMin);
Vector2 max = new Vector2(m_BlendRect.xMax, m_BlendRect.yMax);
// Move points to GUI space
for (int i = 0; i < points.Length; i++)
{
points[i].x = ConvertFloat(points[i].x, min.x, max.x, area.xMin, area.xMax);
points[i].y = ConvertFloat(points[i].y, min.y, max.y, area.yMax, area.yMin);
}
// Get the input blend info
string currentParameterX = m_BlendTree.blendParameter;
string currentParameterY = m_BlendTree.blendParameterY;
float inputX = GetParameterValue(currentAnimator, m_BlendTree, currentParameterX);
float inputY = GetParameterValue(currentAnimator, m_BlendTree, currentParameterY);
// Get child weights
int activeChildCount = GetActiveMotionPositions().Length;
if (m_Weights == null || activeChildCount != m_Weights.Length)
m_Weights = new float[activeChildCount];
UnityEditorInternal.BlendTreePreviewUtility.CalculateRootBlendTreeChildWeights(m_VisBlendTree.animator, 0, m_VisBlendTree.animator.GetCurrentAnimatorStateInfo(0).fullPathHash, m_Weights, inputX, inputY);
// Move input into GUI space
inputX = area.x + Mathf.InverseLerp(min.x, max.x, inputX) * area.width;
inputY = area.y + (1 - Mathf.InverseLerp(min.y, max.y, inputY)) * area.height;
Rect inputRect = new Rect(inputX - 5, inputY - 5, 11, 11);
int drag2dId = GUIUtility.GetControlID(m_BlendAnimationID, FocusType.Passive);
Event evt = Event.current;
switch (evt.GetTypeForControl(drag2dId))
{
case EventType.Repaint:
GUI.color = styles.visBgColor;
GUI.DrawTexture(area, EditorGUIUtility.whiteTexture);
// Draw weight texture
if (m_BlendValueManipulated || m_ReorderableList.index >= presences.Length)
{
Color col = styles.visWeightColor;
col.a *= 0.75f;
GUI.color = col;
GUI.DrawTexture(area, m_BlendTex);
}
else if (presences[m_ReorderableList.index] >= 0)
{
GUI.color = styles.visWeightColor;
GUI.DrawTexture(area, m_WeightTexs[presences[m_ReorderableList.index]]);
}
GUI.color = Color.white;
// Draw the weight circles
if (!s_DraggingPoint)
{
for (int i = 0; i < points.Length; i++)
if (presences[i] >= 0)
DrawWeightShape(points[i], m_Weights[presences[i]], 0);
for (int i = 0; i < points.Length; i++)
if (presences[i] >= 0)
DrawWeightShape(points[i], m_Weights[presences[i]], 1);
}
// Draw the animation points
for (int i = 0; i < points.Length; i++)
{
Rect pointRect = new Rect(points[i].x - 6, points[i].y - 6, 13, 13);
bool drawSelected = (m_ReorderableList.index == i);
if (presences[i] < 0)
GUI.color = styles.visPointEmptyColor;
else
GUI.color = styles.visPointColor;
GUI.DrawTexture(pointRect, drawSelected ? styles.pointIconSelected : styles.pointIcon);
if (drawSelected)
{
GUI.color = styles.visPointOverlayColor;
GUI.DrawTexture(pointRect, styles.pointIconOverlay);
}
}
// Draw the input (sampler) point
if (!s_DraggingPoint)
{
GUI.color = styles.visSamplerColor;
GUI.DrawTexture(inputRect, styles.samplerIcon);
}
GUI.color = Color.white;
break;
case EventType.MouseDown:
if (inputRect.Contains(evt.mousePosition))
{
evt.Use();
GUIUtility.hotControl = drag2dId;
m_SelectedPoint = -1;
}
else if (area.Contains(evt.mousePosition))
{
m_BlendValueManipulated = true;
for (int i = 0; i < points.Length; i++)
{
Rect pointRect = new Rect(points[i].x - 4, points[i].y - 4, 9, 9);
if (pointRect.Contains(evt.mousePosition))
{
evt.Use();
GUIUtility.hotControl = drag2dId;
m_SelectedPoint = i;
m_ReorderableList.index = i;
m_BlendValueManipulated = false;
}
}
// Use in any case so we deselect point and get repaint.
evt.Use();
}
break;
case EventType.MouseDrag:
if (GUIUtility.hotControl != drag2dId)
break;
if (m_SelectedPoint == -1)
{
// Convert mouse position to point in blend space
Vector2 mousePosition;
mousePosition.x = ConvertFloat(evt.mousePosition.x, area.xMin, area.xMax, min.x, max.x);
mousePosition.y = ConvertFloat(evt.mousePosition.y, area.yMax, area.yMin, min.y, max.y);
// Set blend values
SetParameterValue(currentAnimator, m_BlendTree, parentBlendTree, currentParameterX, mousePosition.x);
SetParameterValue(currentAnimator, m_BlendTree, parentBlendTree, currentParameterY, mousePosition.y);
evt.Use();
}
else
{
for (int i = 0; i < points.Length; i++)
{
if (m_SelectedPoint == i)
{
// Convert mouse position to point in blend space
Vector2 mousePosition;
mousePosition.x = ConvertFloat(evt.mousePosition.x, area.xMin, area.xMax, min.x, max.x);
mousePosition.y = ConvertFloat(evt.mousePosition.y, area.yMax, area.yMin, min.y, max.y);
float minDiff = (max.x - min.x) / area.width;
mousePosition.x = MathUtils.RoundBasedOnMinimumDifference(mousePosition.x, minDiff);
mousePosition.y = MathUtils.RoundBasedOnMinimumDifference(mousePosition.y, minDiff);
mousePosition.x = Mathf.Clamp(mousePosition.x, -10000, 10000);
mousePosition.y = Mathf.Clamp(mousePosition.y, -10000, 10000);
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty position = child.FindPropertyRelative("m_Position");
position.vector2Value = mousePosition;
evt.Use();
s_DraggingPoint = true;
}
}
}
break;
case EventType.MouseUp:
if (GUIUtility.hotControl != drag2dId)
break;
evt.Use();
GUIUtility.hotControl = 0;
s_DraggingPoint = false;
break;
}
// Draw message
if (m_ReorderableList.index >= 0 && m_ReorderableList.index < presences.Length && presences[m_ReorderableList.index] < 0)
ShowHelp(area, EditorGUIUtility.TempContent("The selected child has no Motion assigned."));
else if (m_WarningMessage != null)
ShowHelp(area, EditorGUIUtility.TempContent(m_WarningMessage));
}
private void ShowHelp(Rect area, GUIContent content)
{
float height = EditorStyles.helpBox.CalcHeight(content, area.width);
GUI.Label(new Rect(area.x, area.y, area.width, height), content, EditorStyles.helpBox);
}
private void ValidatePositions()
{
m_WarningMessage = null;
Vector2[] points = GetMotionPositions();
// Check for duplicate positions (relevant for all blend types)
bool duplicatePositions = m_BlendRect.width == 0 || m_BlendRect.height == 0;
for (int i = 0; i < points.Length; i++)
{
for (int j = 0; j < i && !duplicatePositions; j++)
{
if (((points[i] - points[j]) / m_BlendRect.height).sqrMagnitude < 0.0001f)
{
duplicatePositions = true;
break;
}
}
}
if (duplicatePositions)
{
m_WarningMessage = "Two or more of the positions are too close to each other.";
return;
}
// Checks for individual blend types below
if (m_BlendType.intValue == (int)BlendTreeType.SimpleDirectional2D)
{
List<float> angles = points.Where(e => e != Vector2.zero).Select(e => Mathf.Atan2(e.y, e.x)).OrderBy(e => e).ToList();
float maxAngle = 0;
float minAngle = 180;
for (int i = 0; i < angles.Count; i++)
{
float angle = angles[(i + 1) % angles.Count] - angles[i];
if (i == angles.Count - 1)
angle += Mathf.PI * 2;
if (angle > maxAngle)
maxAngle = angle;
if (angle < minAngle)
minAngle = angle;
}
if (maxAngle * Mathf.Rad2Deg >= 180)
m_WarningMessage = "Simple Directional blend should have motions with directions less than 180 degrees apart.";
else if (minAngle * Mathf.Rad2Deg < 2)
m_WarningMessage = "Simple Directional blend should not have multiple motions in almost the same direction.";
}
else if (m_BlendType.intValue == (int)BlendTreeType.FreeformDirectional2D)
{
// Check if this blend type has a motion in the center.
bool hasCenter = false;
for (int i = 0; i < points.Length; i++)
{
if (points[i] == Vector2.zero)
{
hasCenter = true;
break;
}
}
if (!hasCenter)
m_WarningMessage = "Freeform Directional blend should have one motion at position (0,0) to avoid discontinuities.";
}
}
private int kNumCirclePoints = 20;
private void DrawWeightShape(Vector2 point, float weight, int pass)
{
if (weight <= 0)
return;
point.x = Mathf.Round(point.x);
point.y = Mathf.Round(point.y);
float radius = 20 * Mathf.Sqrt(weight);
// Calculate points in a circle
Vector3[] points = new Vector3[kNumCirclePoints + 2];
for (int i = 0; i < kNumCirclePoints; i++)
{
float v = (float)i / kNumCirclePoints;
points[i + 1] = new Vector3(point.x + 0.5f, point.y + 0.5f, 0) + new Vector3(Mathf.Sin(v * 2 * Mathf.PI), Mathf.Cos(v * 2 * Mathf.PI), 0) * radius;
}
// First and last point have to meet each other in a straight line; otherwise we'll get a gap
points[0] = points[kNumCirclePoints + 1] = (points[1] + points[kNumCirclePoints]) * 0.5f;
if (pass == 0)
{
// Draw disc
Handles.color = styles.visWeightShapeColor;
Handles.DrawSolidDisc(point + new Vector2(0.5f, 0.5f), -Vector3.forward, radius);
}
else
{
// Draw outline
Handles.color = styles.visWeightLineColor;
Handles.DrawAAPolyLine(points);
}
}
private void DrawAnimation(float val, float min, float max, bool selected, Rect area)
{
float top = area.y;
Rect leftRect = new Rect(min, top, val - min, area.height);
Rect rightRect = new Rect(val, top, max - val, area.height);
styles.triangleLeft.Draw(leftRect, selected, selected, false, false);
styles.triangleRight.Draw(rightRect, selected, selected, false, false);
area.height -= 1;
Color oldColor = Handles.color;
Color newColor = selected ? new Color(1f, 1f, 1f, 0.6f) : new Color(1f, 1f, 1f, 0.4f);
Handles.color = newColor;
if (selected)
Handles.DrawLine(new Vector3(val, top, 0), new Vector3(val, top + area.height, 0));
Vector3[] points = new Vector3[2] {new Vector3(min, top + area.height, 0f), new Vector3(val, top, 0f)};
Handles.DrawAAPolyLine(points);
points = new Vector3[2] {new Vector3(val, top, 0f), new Vector3(max, top + area.height, 0f)};
Handles.DrawAAPolyLine(points);
Handles.color = oldColor;
}
public void EndDragChild(UnityEditorInternal.ReorderableList list)
{
List<float> dragThresholds = new List<float>();
for (int i = 0; i < m_Childs.arraySize; i++)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
dragThresholds.Add(threshold.floatValue);
}
dragThresholds.Sort();
for (int i = 0; i < m_Childs.arraySize; i++)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(i);
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
threshold.floatValue = dragThresholds[i];
}
serializedObject.ApplyModifiedProperties();
}
private void DrawHeader(Rect headerRect)
{
headerRect.xMin += 14; // Ignore width used by drag-handles while calculating column widths.
headerRect.y++;
headerRect.height = 16;
Rect[] rects = GetRowRects(headerRect, m_BlendType.intValue);
int col = 0;
rects[col].xMin = rects[col].xMin - 14; // Make first column extend into space of drag-handles.
GUI.Label(rects[col], EditorGUIUtility.TempContent("Motion"), EditorStyles.label);
col++;
if (m_Childs.arraySize >= 1)
{
if (m_BlendType.intValue == (int)BlendTreeType.Simple1D)
{
GUI.Label(rects[col], EditorGUIUtility.TempContent("Threshold"), EditorStyles.label);
col++;
}
else if (m_BlendType.intValue == (int)BlendTreeType.Direct)
{
GUI.Label(rects[col], EditorGUIUtility.TempContent("Parameter"), EditorStyles.label);
col++;
}
else
{
GUI.Label(rects[col], EditorGUIUtility.TempContent("Pos X"), EditorStyles.label);
col++;
GUI.Label(rects[col], EditorGUIUtility.TempContent("Pos Y"), EditorStyles.label);
col++;
}
GUI.Label(rects[col], styles.speedIcon, styles.headerIcon);
col++;
GUI.Label(rects[col], styles.mirrorIcon, styles.headerIcon);
}
}
public void AddButton(Rect rect, UnityEditorInternal.ReorderableList list)
{
GenericMenu menu = new GenericMenu();
menu.AddItem(EditorGUIUtility.TrTextContent("Add Motion Field"), false, AddChildAnimation);
menu.AddItem(EditorGUIUtility.TempContent("New Blend Tree"), false, AddBlendTreeCallback);
menu.Popup(rect, 0);
}
public static bool DeleteBlendTreeDialog(string toDelete)
{
string title = "Delete selected Blend Tree asset?";
string subTitle = toDelete;
return EditorUtility.DisplayDialog(title, subTitle, "Delete", "Cancel");
}
public void RemoveButton(UnityEditorInternal.ReorderableList list)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(list.index);
SerializedProperty motion = child.FindPropertyRelative("m_Motion");
Motion actualMotion = motion.objectReferenceValue as Motion;
if (actualMotion == null || DeleteBlendTreeDialog(actualMotion.name))
{
m_Childs.DeleteArrayElementAtIndex(list.index);
if (list.index >= m_Childs.arraySize)
list.index = m_Childs.arraySize - 1;
SetMinMaxThresholds();
serializedObject.ApplyModifiedProperties();
// Layout has changed, bail out now.
EditorGUIUtility.ExitGUI();
}
}
private Rect[] GetRowRects(Rect r, int blendType)
{
int rowCount = blendType > (int)BlendTreeType.Simple1D && blendType < (int)BlendTreeType.Direct ? 2 : 1;
Rect[] rects = new Rect[3 + rowCount];
float remainingWidth = r.width;
float mirrorWidth = 16;
remainingWidth -= mirrorWidth;
remainingWidth -= 8 + 8 + 8 + (4 * (rowCount - 1));
float numberWidth = Mathf.FloorToInt(remainingWidth * 0.2f);
float motionWidth = remainingWidth - numberWidth * (rowCount + 1);
float x = r.x;
int col = 0;
rects[col] = new Rect(x, r.y, motionWidth, r.height);
x += motionWidth + 8;
col++;
for (int i = 0; i < rowCount; i++)
{
rects[col] = new Rect(x, r.y, numberWidth, r.height);
x += numberWidth + 4;
col++;
}
x += 4;
rects[col] = new Rect(x, r.y, numberWidth, r.height);
x += numberWidth + 8;
col++;
rects[col] = new Rect(x, r.y, mirrorWidth, r.height);
return rects;
}
public void DrawChild(Rect r, int index, bool isActive, bool isFocused)
{
SerializedProperty child = m_Childs.GetArrayElementAtIndex(index);
SerializedProperty motion = child.FindPropertyRelative("m_Motion");
r.y++;
r.height = EditorGUI.kSingleLineHeight;
Rect[] rects = GetRowRects(r, m_BlendType.intValue);
int col = 0;
// show a property field for the motion clip
EditorGUI.BeginChangeCheck();
Motion prevMotion = m_BlendTree.children[index].motion;
EditorGUI.PropertyField(rects[col], motion, GUIContent.none);
col++;
if (EditorGUI.EndChangeCheck())
{
// [case 1028113] Delete previous Motion only if it serialized in the same asset file
if (prevMotion is BlendTree && prevMotion != (motion.objectReferenceValue as Motion) && MecanimUtilities.AreSameAsset(m_BlendTree, prevMotion))
{
if (EditorUtility.DisplayDialog("Changing BlendTree will delete previous BlendTree", "You cannot undo this action.", "Delete", "Cancel"))
{
MecanimUtilities.DestroyBlendTreeRecursive(prevMotion as BlendTree);
}
else
{
motion.objectReferenceValue = prevMotion;
}
}
}
// use a delayed text field and force re-sort if value is manually changed
if (m_BlendType.intValue == (int)BlendTreeType.Simple1D)
{
// Threshold in 1D blending
SerializedProperty threshold = child.FindPropertyRelative("m_Threshold");
using (new EditorGUI.DisabledScope(m_UseAutomaticThresholds.boolValue))
{
float nr = threshold.floatValue;
EditorGUI.BeginChangeCheck();
nr = EditorGUI.DelayedFloatField(rects[col], "", nr, EditorStyles.textField);
col++;
if (EditorGUI.EndChangeCheck())
{
threshold.floatValue = nr;
serializedObject.ApplyModifiedProperties();
m_BlendTree.SortChildren();
SetMinMaxThresholds();
GUI.changed = true;
}
}
}
else if (m_BlendType.intValue == (int)BlendTreeType.Direct)
{
List<string> parameters = CollectParameters(currentController);
Animations.ChildMotion[] childs = m_BlendTree.children;
string directParam = childs[index].directBlendParameter;
EditorGUI.BeginChangeCheck();
directParam = EditorGUI.TextFieldDropDown(rects[col], directParam, parameters.ToArray());
col++;
if (EditorGUI.EndChangeCheck())
{
childs[index].directBlendParameter = directParam;
m_BlendTree.children = childs;
}
}
else
{
// Position in 2D blending
SerializedProperty position = child.FindPropertyRelative("m_Position");
Vector2 pos = position.vector2Value;
for (int i = 0; i < 2; i++)
{
EditorGUI.BeginChangeCheck();
float coord = EditorGUI.DelayedFloatField(rects[col], "", pos[i], EditorStyles.textField);
col++;
if (EditorGUI.EndChangeCheck())
{
pos[i] = Mathf.Clamp(coord, -10000, 10000);
position.vector2Value = pos;
serializedObject.ApplyModifiedProperties();
GUI.changed = true;
}
}
}
// If this is an animation, include the time scale.
if (motion.objectReferenceValue is AnimationClip)
{
SerializedProperty timeScale = child.FindPropertyRelative("m_TimeScale");
float timeScaleValue = timeScale.floatValue;
EditorGUI.BeginChangeCheck();
timeScaleValue = EditorGUI.DelayedFloatField(rects[col], "", timeScaleValue, EditorStyles.textField);
if (EditorGUI.EndChangeCheck())
{
timeScale.floatValue = timeScaleValue;
serializedObject.ApplyModifiedProperties();
GUI.changed = true;
}
}
else
{
// Otherwise show disabled dummy field with default value of 1.
using (new EditorGUI.DisabledScope(true))
{
EditorGUI.IntField(rects[col], 1);
}
}
col++;
// If this is a humanoid animation, include the mirror toggle.
if (motion.objectReferenceValue is AnimationClip && (motion.objectReferenceValue as AnimationClip).isHumanMotion)
{
SerializedProperty mirror = child.FindPropertyRelative("m_Mirror");
EditorGUI.PropertyField(rects[col], mirror, GUIContent.none);
SerializedProperty cycle = child.FindPropertyRelative("m_CycleOffset");
cycle.floatValue = mirror.boolValue ? 0.5f : 0.0f;
}
else
{
// Otherwise show disabled dummy toggle that's disabled.
using (new EditorGUI.DisabledScope(true))
{
EditorGUI.Toggle(rects[col], false);
}
}
}
private bool AllMotions()
{
bool allClips = true;
for (int i = 0; i < m_Childs.arraySize && allClips; i++)
{
SerializedProperty motion = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion");
allClips = motion.objectReferenceValue is AnimationClip;
}
return allClips;
}
private void AutoCompute()
{
if (m_BlendType.intValue == (int)BlendTreeType.Simple1D)
{
EditorGUILayout.PropertyField(m_UseAutomaticThresholds, EditorGUIUtility.TempContent("Automate Thresholds"));
m_ShowCompute.target = !m_UseAutomaticThresholds.boolValue;
}
else if (m_BlendType.intValue == (int)BlendTreeType.Direct)
{
m_ShowCompute.target = false;
}
else
{
m_ShowCompute.target = true;
}
m_ShowAdjust.target = AllMotions();
if (EditorGUILayout.BeginFadeGroup(m_ShowCompute.faded))
{
Rect controlRect = EditorGUILayout.GetControlRect();
GUIContent label = (ParameterCount == 1) ?
EditorGUIUtility.TempContent("Compute Thresholds") :
EditorGUIUtility.TempContent("Compute Positions");
controlRect = EditorGUI.PrefixLabel(controlRect, 0, label);
if (EditorGUI.DropdownButton(controlRect, EditorGUIUtility.TempContent("Select"), FocusType.Passive, EditorStyles.popup))
{
GenericMenu menu = new GenericMenu();
if (ParameterCount == 1)
{
AddComputeMenuItems(menu, string.Empty, ChildPropertyToCompute.Threshold);
}
else
{
menu.AddItem(EditorGUIUtility.TrTextContent("Velocity XZ"), false, ComputePositionsFromVelocity);
menu.AddItem(EditorGUIUtility.TrTextContent("Speed And Angular Speed"), false, ComputePositionsFromSpeedAndAngularSpeed);
AddComputeMenuItems(menu, "X Position From/", ChildPropertyToCompute.PositionX);
AddComputeMenuItems(menu, "Y Position From/", ChildPropertyToCompute.PositionY);
}
menu.DropDown(controlRect);
}
}
EditorGUILayout.EndFadeGroup();
if (EditorGUILayout.BeginFadeGroup(m_ShowAdjust.faded))
{
Rect controlRect = EditorGUILayout.GetControlRect();
controlRect = EditorGUI.PrefixLabel(controlRect, 0, EditorGUIUtility.TempContent("Adjust Time Scale"));
if (EditorGUI.DropdownButton(controlRect, EditorGUIUtility.TempContent("Select"), FocusType.Passive, EditorStyles.popup))
{
GenericMenu menu = new GenericMenu();
menu.AddItem(EditorGUIUtility.TrTextContent("Homogeneous Speed"), false, ComputeTimeScaleFromSpeed);
menu.AddItem(EditorGUIUtility.TrTextContent("Reset Time Scale"), false, ResetTimeScale);
menu.DropDown(controlRect);
}
}
EditorGUILayout.EndFadeGroup();
}
enum ChildPropertyToCompute
{
Threshold,
PositionX,
PositionY
}
delegate float GetFloatFromMotion(Motion motion, float mirrorMultiplier);
void AddComputeMenuItems(GenericMenu menu, string menuItemPrefix, ChildPropertyToCompute prop)
{
menu.AddItem(new GUIContent(menuItemPrefix + "Speed"), false, ComputeFromSpeed, prop);
menu.AddItem(new GUIContent(menuItemPrefix + "Velocity X"), false, ComputeFromVelocityX, prop);
menu.AddItem(new GUIContent(menuItemPrefix + "Velocity Y"), false, ComputeFromVelocityY, prop);
menu.AddItem(new GUIContent(menuItemPrefix + "Velocity Z"), false, ComputeFromVelocityZ, prop);
menu.AddItem(new GUIContent(menuItemPrefix + "Angular Speed (Rad)"), false, ComputeFromAngularSpeedRadians, prop);
menu.AddItem(new GUIContent(menuItemPrefix + "Angular Speed (Deg)"), false, ComputeFromAngularSpeedDegrees, prop);
}
private void ComputeFromSpeed(object obj)
{
ChildPropertyToCompute prop = (ChildPropertyToCompute)obj;
ComputeProperty((Motion m, float mirrorMultiplier) => m.apparentSpeed, prop);
}
private void ComputeFromVelocityX(object obj)
{
ChildPropertyToCompute prop = (ChildPropertyToCompute)obj;
ComputeProperty((Motion m, float mirrorMultiplier) => m.averageSpeed.x * mirrorMultiplier, prop);
}
private void ComputeFromVelocityY(object obj)
{
ChildPropertyToCompute prop = (ChildPropertyToCompute)obj;
ComputeProperty((Motion m, float mirrorMultiplier) => m.averageSpeed.y, prop);
}
private void ComputeFromVelocityZ(object obj)
{
ChildPropertyToCompute prop = (ChildPropertyToCompute)obj;
ComputeProperty((Motion m, float mirrorMultiplier) => m.averageSpeed.z, prop);
}
private void ComputeFromAngularSpeedDegrees(object obj)
{
ChildPropertyToCompute prop = (ChildPropertyToCompute)obj;
ComputeProperty((Motion m, float mirrorMultiplier) => m.averageAngularSpeed * 180.0f / Mathf.PI * mirrorMultiplier, prop);
}
private void ComputeFromAngularSpeedRadians(object obj)
{
ChildPropertyToCompute prop = (ChildPropertyToCompute)obj;
ComputeProperty((Motion m, float mirrorMultiplier) => m.averageAngularSpeed * mirrorMultiplier, prop);
}
private void ComputeProperty(GetFloatFromMotion func, ChildPropertyToCompute prop)
{
float mean = 0.0f;
float[] values = new float[m_Childs.arraySize];
m_UseAutomaticThresholds.boolValue = false;
for (int i = 0; i < m_Childs.arraySize; i++)
{
SerializedProperty motion = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion");
SerializedProperty mirror = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Mirror");
Motion motionObj = motion.objectReferenceValue as Motion;
if (motionObj != null)
{
float val = func(motionObj, mirror.boolValue ? -1 : 1);
values[i] = val;
mean += val;
if (prop == ChildPropertyToCompute.Threshold)
{
SerializedProperty threshold = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Threshold");
threshold.floatValue = val;
}
else
{
SerializedProperty position = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Position");
Vector2 pos = position.vector2Value;
if (prop == ChildPropertyToCompute.PositionX)
pos.x = val;
else
pos.y = val;
position.vector2Value = pos;
}
}
}
mean /= (float)m_Childs.arraySize;
float variance = 0.0f;
for (int i = 0; i < values.Length; i++)
{
variance += Mathf.Pow(values[i] - mean, 2.0f);
}
variance /= values.Length;
if (variance < Mathf.Epsilon)
{
Debug.LogWarning($"Can't distribute the motions of '{m_BlendTree.name}', they all have the same threshold value.");
m_SerializedObject.Update();
}
else
{
m_SerializedObject.ApplyModifiedProperties();
if (prop == ChildPropertyToCompute.Threshold)
{
SortByThreshold();
SetMinMaxThreshold();
}
}
}
private void ComputePositionsFromVelocity()
{
ComputeFromVelocityX(ChildPropertyToCompute.PositionX);
ComputeFromVelocityZ(ChildPropertyToCompute.PositionY);
}
private void ComputePositionsFromSpeedAndAngularSpeed()
{
ComputeFromAngularSpeedRadians(ChildPropertyToCompute.PositionX);
ComputeFromSpeed(ChildPropertyToCompute.PositionY);
}
private void ComputeTimeScaleFromSpeed()
{
float apparentSpeed = m_BlendTree.apparentSpeed;
for (int i = 0; i < m_Childs.arraySize; i++)
{
SerializedProperty motion = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion");
AnimationClip clip = motion.objectReferenceValue as AnimationClip;
if (clip != null)
{
if (!clip.legacy)
{
if (clip.apparentSpeed < Mathf.Epsilon)
{
Debug.LogWarning("Could not adjust time scale for " + clip.name + " because it has no speed");
}
else
{
SerializedProperty timeScale = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_TimeScale");
timeScale.floatValue = apparentSpeed / clip.apparentSpeed;
}
}
else
{
Debug.LogWarning("Could not adjust time scale for " + clip.name + " because it is not a muscle clip");
}
}
}
m_SerializedObject.ApplyModifiedProperties();
}
private void ResetTimeScale()
{
for (int i = 0; i < m_Childs.arraySize; i++)
{
SerializedProperty motion = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_Motion");
AnimationClip clip = motion.objectReferenceValue as AnimationClip;
if (clip != null && !clip.legacy)
{
SerializedProperty timeScale = m_Childs.GetArrayElementAtIndex(i).FindPropertyRelative("m_TimeScale");
timeScale.floatValue = 1;
}
}
m_SerializedObject.ApplyModifiedProperties();
}
private void SortByThreshold()
{
m_SerializedObject.Update();
for (int i = 0; i < m_Childs.arraySize; i++)
{
float minThreshold = Mathf.Infinity;
int minIndex = -1;
for (int j = i; j < m_Childs.arraySize; j++)
{
SerializedProperty testElement = m_Childs.GetArrayElementAtIndex(j);
float testThreshold = testElement.FindPropertyRelative("m_Threshold").floatValue;
if (testThreshold < minThreshold)
{
minThreshold = testThreshold;
minIndex = j;
}
}
if (minIndex != i)
m_Childs.MoveArrayElement(minIndex, i);
}
m_SerializedObject.ApplyModifiedProperties();
}
private void SetMinMaxThreshold()
{
m_SerializedObject.Update();
SerializedProperty minThreshold = m_Childs.GetArrayElementAtIndex(0).FindPropertyRelative("m_Threshold");
SerializedProperty maxThreshold = m_Childs.GetArrayElementAtIndex(m_Childs.arraySize - 1).FindPropertyRelative("m_Threshold");
m_MinThreshold.floatValue = Mathf.Min(minThreshold.floatValue, maxThreshold.floatValue);
m_MaxThreshold.floatValue = Mathf.Max(minThreshold.floatValue, maxThreshold.floatValue);
m_SerializedObject.ApplyModifiedProperties();
}
void AddChildAnimation()
{
m_BlendTree.AddChild(null);
int numChildren = m_BlendTree.children.Length;
if (currentController != null)
{
m_BlendTree.SetDirectBlendTreeParameter(numChildren - 1, currentController.GetDefaultBlendTreeParameter());
}
SetNewThresholdAndPosition(numChildren - 1);
m_ReorderableList.index = numChildren - 1;
}
void AddBlendTreeCallback()
{
BlendTree tree = m_BlendTree.CreateBlendTreeChild(0);
ChildMotion[] children = m_BlendTree.children;
int numChildren = children.Length;
if (currentController != null)
{
tree.blendParameter = m_BlendTree.blendParameter;
m_BlendTree.SetDirectBlendTreeParameter(numChildren - 1, currentController.GetDefaultBlendTreeParameter());
}
SetNewThresholdAndPosition(numChildren - 1);
m_ReorderableList.index = m_Childs.arraySize - 1;
}
void SetNewThresholdAndPosition(int index)
{
serializedObject.Update();
// Set new threshold
if (!m_UseAutomaticThresholds.boolValue)
{
float newThreshold = 0f;
if (m_Childs.arraySize >= 3 && index == m_Childs.arraySize - 1)
{
float threshold1 = m_Childs.GetArrayElementAtIndex(index - 2).FindPropertyRelative("m_Threshold").floatValue;
float threshold2 = m_Childs.GetArrayElementAtIndex(index - 1).FindPropertyRelative("m_Threshold").floatValue;
newThreshold = threshold2 + (threshold2 - threshold1);
}
else
{
if (m_Childs.arraySize == 1)
newThreshold = 0;
else
newThreshold = m_Childs.GetArrayElementAtIndex(m_Childs.arraySize - 1).FindPropertyRelative("m_Threshold").floatValue + 1;
}
SerializedProperty addedThreshold = m_Childs.GetArrayElementAtIndex(index).FindPropertyRelative("m_Threshold");
addedThreshold.floatValue = newThreshold;
SetMinMaxThresholds();
}
// Set new position
Vector2 newPosition = Vector2.zero;
if (m_Childs.arraySize >= 1)
{
Vector2 center = m_BlendRect.center;
Vector2[] points = GetMotionPositions();
float goodMinDist = m_BlendRect.width * 0.07f;
bool satisfied = false;
// Try to place new point along circle around center until successful
for (int iter = 0; iter < 24; iter++)
{
satisfied = true;
for (int i = 0; i < points.Length && satisfied; i++)
if (i != index && Vector2.Distance(points[i], newPosition) < goodMinDist)
satisfied = false;
if (satisfied)
break;
float radians = iter * 15 * Mathf.Deg2Rad;
newPosition = center + new Vector2(-Mathf.Cos(radians), Mathf.Sin(radians)) * 0.37f * m_BlendRect.width;
newPosition.x = MathUtils.RoundBasedOnMinimumDifference(newPosition.x, m_BlendRect.width * 0.005f);
newPosition.y = MathUtils.RoundBasedOnMinimumDifference(newPosition.y, m_BlendRect.width * 0.005f);
}
}
SerializedProperty addedPosition = m_Childs.GetArrayElementAtIndex(index).FindPropertyRelative("m_Position");
addedPosition.vector2Value = newPosition;
serializedObject.ApplyModifiedProperties();
}
public override bool HasPreviewGUI()
{
return true;
}
public override void OnPreviewSettings()
{
if (m_PreviewBlendTree != null)
m_PreviewBlendTree.OnPreviewSettings();
}
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
if (m_PreviewBlendTree != null)
m_PreviewBlendTree.OnInteractivePreviewGUI(r, background);
}
public void OnDisable()
{
if (m_PreviewBlendTree != null)
m_PreviewBlendTree.OnDisable();
if (m_VisBlendTree != null)
m_VisBlendTree.Reset();
}
public void OnDestroy()
{
if (m_VisBlendTree != null)
m_VisBlendTree.Destroy();
if (m_VisInstance != null)
DestroyImmediate(m_VisInstance);
for (int i = 0; i < m_WeightTexs.Count; i++)
DestroyImmediate(m_WeightTexs[i]);
if (m_BlendTex != null)
DestroyImmediate(m_BlendTex);
}
}
class VisualizationBlendTree
{
private AnimatorController m_Controller;
private AnimatorStateMachine m_StateMachine;
private AnimatorState m_State;
private BlendTree m_BlendTree;
private Animator m_Animator;
private bool m_ControllerIsDirty = false;
public Animator animator { get { return m_Animator; } }
public void Init(BlendTree blendTree, Animator animator)
{
m_BlendTree = blendTree;
m_Animator = animator;
m_Animator.logWarnings = false;
m_Animator.fireEvents = false;
m_Animator.enabled = false;
m_Animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
CreateStateMachine();
}
public bool controllerDirty
{
get
{
return m_ControllerIsDirty;
}
}
protected virtual void ControllerDirty()
{
m_ControllerIsDirty = true;
}
private void CreateParameters()
{
for (int i = 0; i < m_BlendTree.recursiveBlendParameterCount; i++)
m_Controller.AddParameter(m_BlendTree.GetRecursiveBlendParameter(i), AnimatorControllerParameterType.Float);
}
private void CreateStateMachine()
{
if (m_Controller == null)
{
m_Controller = new AnimatorController();
m_Controller.pushUndo = false;
m_Controller.AddLayer("viz");
m_StateMachine = m_Controller.layers[0].stateMachine;
m_StateMachine.pushUndo = false;
CreateParameters();
m_State = m_StateMachine.AddState("viz");
m_State.pushUndo = false;
m_State.motion = m_BlendTree;
m_State.iKOnFeet = false;
m_State.hideFlags = HideFlags.HideAndDontSave;
m_StateMachine.hideFlags = HideFlags.HideAndDontSave;
m_Controller.hideFlags = HideFlags.HideAndDontSave;
AnimatorController.SetAnimatorController(m_Animator, m_Controller);
m_Controller.OnAnimatorControllerDirty += ControllerDirty;
m_ControllerIsDirty = false;
}
}
private void ClearStateMachine()
{
if (m_Animator != null)
AnimatorController.SetAnimatorController(m_Animator, null);
if (m_Controller != null)
m_Controller.OnAnimatorControllerDirty -= ControllerDirty;
Object.DestroyImmediate(m_Controller);
Object.DestroyImmediate(m_State);
m_StateMachine = null;
m_Controller = null;
m_State = null;
}
public void Reset()
{
ClearStateMachine();
CreateStateMachine();
}
public void Destroy()
{
ClearStateMachine();
}
public void Update()
{
if (m_ControllerIsDirty)
Reset();
int count = m_BlendTree.recursiveBlendParameterCount;
if (m_Controller.parameters.Length < count)
return;
for (int i = 0; i < count; i++)
{
string blendParameter = m_BlendTree.GetRecursiveBlendParameter(i);
float value = BlendTreeInspector.GetParameterValue(animator, m_BlendTree, blendParameter);
animator.SetFloat(blendParameter, value);
}
animator.EvaluateController();
}
}
class PreviewBlendTree
{
private AnimatorController m_Controller;
private AvatarPreview m_AvatarPreview;
private AnimatorStateMachine m_StateMachine;
private AnimatorState m_State;
private BlendTree m_BlendTree;
private bool m_ControllerIsDirty = false;
protected virtual void ControllerDirty()
{
m_ControllerIsDirty = true;
}
bool m_PrevIKOnFeet;
public Animator PreviewAnimator { get { return m_AvatarPreview.Animator; } }
public void Init(BlendTree blendTree, Animator animator)
{
m_BlendTree = blendTree;
if (m_AvatarPreview == null)
{
m_AvatarPreview = new AvatarPreview(animator, m_BlendTree);
m_AvatarPreview.OnAvatarChangeFunc = OnPreviewAvatarChanged;
m_AvatarPreview.ResetPreviewFocus();
m_PrevIKOnFeet = m_AvatarPreview.IKOnFeet;
}
CreateStateMachine();
}
public void CreateParameters()
{
for (int i = 0; i < m_BlendTree.recursiveBlendParameterCount; i++)
{
m_Controller.AddParameter(m_BlendTree.GetRecursiveBlendParameter(i), AnimatorControllerParameterType.Float);
}
}
private void CreateStateMachine()
{
if (m_AvatarPreview != null && m_AvatarPreview.Animator != null)
{
if (m_Controller == null)
{
m_Controller = new AnimatorController();
m_Controller.pushUndo = false;
m_Controller.AddLayer("preview");
m_StateMachine = m_Controller.layers[0].stateMachine;
m_StateMachine.pushUndo = false;
CreateParameters();
m_State = m_StateMachine.AddState("preview");
m_State.pushUndo = false;
m_State.motion = m_BlendTree;
m_State.iKOnFeet = m_AvatarPreview.IKOnFeet;
m_State.hideFlags = HideFlags.HideAndDontSave;
m_Controller.hideFlags = HideFlags.HideAndDontSave;
m_StateMachine.hideFlags = HideFlags.HideAndDontSave;
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
m_Controller.OnAnimatorControllerDirty += ControllerDirty;
m_ControllerIsDirty = false;
}
if (AnimatorController.GetEffectiveAnimatorController(m_AvatarPreview.Animator) != m_Controller)
AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, m_Controller);
}
}
private void ClearStateMachine()
{
if (m_AvatarPreview != null && m_AvatarPreview.Animator != null) AnimatorController.SetAnimatorController(m_AvatarPreview.Animator, null);
if (m_Controller != null)
m_Controller.OnAnimatorControllerDirty -= ControllerDirty;
Object.DestroyImmediate(m_Controller);
Object.DestroyImmediate(m_State);
m_StateMachine = null;
m_Controller = null;
m_State = null;
}
private void OnPreviewAvatarChanged()
{
ResetStateMachine();
}
public void ResetStateMachine()
{
ClearStateMachine();
CreateStateMachine();
}
public void OnDisable()
{
ClearStateMachine();
if (m_AvatarPreview != null)
{
m_AvatarPreview.OnDisable();
m_AvatarPreview = null;
}
}
private void UpdateAvatarState()
{
if (Event.current.type != EventType.Repaint)
return;
if (m_AvatarPreview.PreviewObject == null || m_ControllerIsDirty)
{
m_AvatarPreview.ResetPreviewInstance();
if (m_AvatarPreview.PreviewObject)
ResetStateMachine();
}
if (m_AvatarPreview.Animator)
{
if (m_PrevIKOnFeet != m_AvatarPreview.IKOnFeet)
{
m_PrevIKOnFeet = m_AvatarPreview.IKOnFeet;
Vector3 prevPos = m_AvatarPreview.Animator.rootPosition;
Quaternion prevRotation = m_AvatarPreview.Animator.rootRotation;
ResetStateMachine();
m_AvatarPreview.Animator.Update(m_AvatarPreview.timeControl.currentTime);
m_AvatarPreview.Animator.Update(0); // forces deltaPos/Rot to 0,0,0
m_AvatarPreview.Animator.rootPosition = prevPos;
m_AvatarPreview.Animator.rootRotation = prevRotation;
}
if (m_AvatarPreview.Animator)
{
for (int i = 0; i < m_BlendTree.recursiveBlendParameterCount; i++)
{
string blendParameter = m_BlendTree.GetRecursiveBlendParameter(i);
float value = BlendTreeInspector.GetParameterValue(m_AvatarPreview.Animator, m_BlendTree, blendParameter);
m_AvatarPreview.Animator.SetFloat(blendParameter, value);
}
}
m_AvatarPreview.timeControl.loop = true;
float stateLength = 1.0f;
float stateTime = 0.0f;
if (m_AvatarPreview.Animator.layerCount > 0)
{
AnimatorStateInfo stateInfo = m_AvatarPreview.Animator.GetCurrentAnimatorStateInfo(0);
stateLength = stateInfo.length;
stateTime = stateInfo.normalizedTime;
}
m_AvatarPreview.timeControl.startTime = 0.0f;
m_AvatarPreview.timeControl.stopTime = stateLength;
m_AvatarPreview.timeControl.Update();
float deltaTime = m_AvatarPreview.timeControl.deltaTime;
if (!m_BlendTree.isLooping)
{
if (stateTime >= 1.0f)
{
deltaTime -= stateLength;
}
else if (stateTime < 0.0f)
{
deltaTime += stateLength;
}
}
m_AvatarPreview.Animator.Update(deltaTime);
}
}
public void TestForReset()
{
if ((m_State != null && m_AvatarPreview != null && m_State.iKOnFeet != m_AvatarPreview.IKOnFeet))
{
ResetStateMachine();
}
}
public void OnPreviewSettings()
{
m_AvatarPreview.DoPreviewSettings();
}
public void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
UpdateAvatarState();
m_AvatarPreview.DoAvatarPreview(r, background);
}
}
}
| UnityCsReference/Editor/Mono/Inspector/BlendTreeInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/BlendTreeInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 49538
} | 288 |
// 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.AddComponent
{
internal class ComponentDropdownItem : AdvancedDropdownItem
{
private string m_MenuPath;
private bool m_IsLegacy;
private string m_LocalizedName;
private string m_SearchableNameLocalized;
private string m_SearchableName;
internal override string displayName
{
get { return m_LocalizedName; }
}
public string searchableName
{
get
{
if (m_SearchableName == null)
return name;
return m_SearchableName;
}
set { m_SearchableName = value; }
}
public string searchableNameLocalized
{
get
{
if (m_SearchableNameLocalized == null)
return m_SearchableName;
return m_SearchableNameLocalized;
}
set { m_SearchableNameLocalized = value; }
}
public string localizedName
{
get { return m_LocalizedName ?? name; }
}
public string menuPath => m_MenuPath;
public ComponentDropdownItem(string name) : base(name)
{
}
public ComponentDropdownItem(string name, string localized) : base(name)
{
m_LocalizedName = localized;
m_SearchableName = name;
m_SearchableNameLocalized = localized;
}
public ComponentDropdownItem(string name, string localized, string menuPath, string command, bool isLegacy) : base(name)
{
m_LocalizedName = localized;
m_MenuPath = menuPath;
m_IsLegacy = isLegacy;
if (command.StartsWith("SCRIPT"))
{
var scriptId = int.Parse(command.Substring(6));
var obj = EditorUtility.InstanceIDToObject(scriptId);
var icon = AssetPreview.GetMiniThumbnail(obj);
base.name = name;
base.icon = icon;
}
else
{
var classId = int.Parse(command);
base.name = name;
base.icon = AssetPreview.GetMiniTypeThumbnailFromClassID(classId);
}
m_SearchableName = name;
m_SearchableNameLocalized = localized;
if (m_IsLegacy)
{
m_SearchableName += " (Legacy)";
}
}
public override int CompareTo(object o)
{
if (o is ComponentDropdownItem)
{
// legacy elements should always come after non legacy elements
var componentElement = (ComponentDropdownItem)o;
if (m_IsLegacy && !componentElement.m_IsLegacy)
return 1;
if (!m_IsLegacy && componentElement.m_IsLegacy)
return -1;
}
return base.CompareTo(o);
}
public override string ToString()
{
return m_MenuPath;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/AddComponent/ComponentDropdownItem.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/AddComponent/ComponentDropdownItem.cs",
"repo_id": "UnityCsReference",
"token_count": 1655
} | 289 |
// 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.Audio.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;
namespace UnityEditor
{
internal class GenericInspector : Editor
{
private enum OptimizedBlockState
{
CheckOptimizedBlock,
HasOptimizedBlock,
NoOptimizedBlock
}
private float m_LastHeight;
private Rect m_LastVisibleRect;
private OptimizedBlockState m_OptimizedBlockState = OptimizedBlockState.CheckOptimizedBlock;
static class Styles
{
public static string missingScriptMessage = L10n.Tr("The associated script can not be loaded.\nPlease fix any compile errors\nand assign a valid script.");
public static string missingSerializeReferenceInstanceMessage = L10n.Tr("This object contains SerializeReference types which are missing.\nFor more information see SerializationUtility.HasManagedReferencesWithMissingTypes.");
public static string missingScriptMessageForPrefabInstance = L10n.Tr("The associated script can not be loaded.\nPlease fix any compile errors\nand open Prefab Mode and assign a valid script to the Prefab Asset.");
}
internal static string GetMissingSerializeRefererenceMessageContainer()
{
return Styles.missingSerializeReferenceInstanceMessage;
}
internal override bool GetOptimizedGUIBlock(bool isDirty, bool isVisible, out float height)
{
height = -1;
// Don't use optimizedGUI for audio filters
var behaviour = target as MonoBehaviour;
if (behaviour != null && AudioUtil.HasAudioCallback(behaviour) && AudioUtil.GetCustomFilterChannelCount(behaviour) > 0)
return false;
if (ObjectIsMonoBehaviourOrScriptableObjectWithoutScript(target))
return false;
var scriptableObject = target as ScriptableObject;
if ((behaviour != null || scriptableObject != null) && SerializationUtility.HasManagedReferencesWithMissingTypes(target))
return false;
if (isDirty)
ResetOptimizedBlock();
if (!isVisible)
{
height = 0;
return true;
}
// Return cached result if any.
if (m_OptimizedBlockState != OptimizedBlockState.CheckOptimizedBlock)
{
if (m_OptimizedBlockState == OptimizedBlockState.NoOptimizedBlock)
return false;
height = m_LastHeight;
return true;
}
// Update serialized object representation
if (m_SerializedObject == null)
{
m_SerializedObject = new SerializedObject(targets, m_Context)
{
inspectorMode = inspectorMode,
inspectorDataMode = dataMode
};
}
else
{
m_SerializedObject.Update();
m_SerializedObject.inspectorMode = inspectorMode;
if (m_SerializedObject.inspectorDataMode != dataMode)
m_SerializedObject.inspectorDataMode = dataMode;
}
height = 0;
SerializedProperty property = m_SerializedObject.GetIterator();
bool childrenAreExpanded = true;
while (property.NextVisible(childrenAreExpanded))
{
var handler = ScriptAttributeUtility.GetHandler(property);
var hasPropertyDrawer = handler.propertyDrawer != null;
var propertyHeight = handler.GetHeight(property, null, hasPropertyDrawer || PropertyHandler.UseReorderabelListControl(property));
if (propertyHeight > 0)
height += propertyHeight + EditorGUI.kControlVerticalSpacing;
childrenAreExpanded = !hasPropertyDrawer && property.isExpanded && EditorGUI.HasVisibleChildFields(property);
}
m_LastHeight = height;
m_OptimizedBlockState = OptimizedBlockState.HasOptimizedBlock;
return true;
}
internal override bool OnOptimizedInspectorGUI(Rect contentRect)
{
m_SerializedObject.UpdateIfRequiredOrScript();
bool childrenAreExpanded = true;
bool wasEnabled = GUI.enabled;
var visibleRect = GUIClip.visibleRect;
var contentOffset = contentRect.y;
// In some specific cases (e.g. when the inspector field has a dropdown behavior - case 1335344) we need to
// apply the padding values so it behaves properly. By checking that xMin is zero when we do the assignments,
// we avoid applying the padding more than once (because this is called more than once in some cases and
// can lead to wrong indentation - case 1114055).
if (contentRect.xMin == 0)
{
contentRect.xMin = EditorStyles.kInspectorPaddingLeft;
contentRect.xMax -= EditorStyles.kInspectorPaddingRight;
}
if (Event.current.type != EventType.Repaint)
visibleRect = m_LastVisibleRect;
// Release keyboard focus before scrolling so that the virtual scrolling focus wrong control.
if (Event.current.type == EventType.ScrollWheel)
GUIUtility.keyboardControl = 0;
var behaviour = target as MonoBehaviour;
var property = m_SerializedObject.GetIterator();
bool isInspectorModeNormal = inspectorMode == InspectorMode.Normal;
bool isInPrefabInstance = PrefabUtility.GetPrefabInstanceHandle(behaviour) != null;
bool isMultiSelection = m_SerializedObject.targetObjectsCount > 1;
using (new LocalizationGroup(behaviour))
{
while (property.NextVisible(childrenAreExpanded))
{
if (GUI.isInsideList && property.depth <= EditorGUI.GetInsideListDepth())
EditorGUI.EndIsInsideList();
if (property.isArray)
EditorGUI.BeginIsInsideList(property.depth);
var handler = ScriptAttributeUtility.GetHandler(property);
var hasPropertyDrawer = handler.propertyDrawer != null;
childrenAreExpanded = !hasPropertyDrawer && property.isExpanded && EditorGUI.HasVisibleChildFields(property);
contentRect.height = handler.GetHeight(property, null, hasPropertyDrawer || PropertyHandler.UseReorderabelListControl(property));
if (contentRect.Overlaps(visibleRect))
{
EditorGUI.indentLevel = property.depth;
using (new EditorGUI.DisabledScope((isInspectorModeNormal || isInPrefabInstance || isMultiSelection) && string.Equals("m_Script", property.propertyPath, System.StringComparison.Ordinal)))
childrenAreExpanded &= handler.OnGUI(contentRect, property, GetPropertyLabel(property), PropertyHandler.UseReorderabelListControl(property), visibleRect);
}
if (contentRect.height > 0)
contentRect.y += contentRect.height + EditorGUI.kControlVerticalSpacing;
}
}
// Fix new height
if (Event.current.type == EventType.Repaint)
{
m_LastVisibleRect = visibleRect;
var newHeight = contentRect.y - contentOffset;
if (newHeight != m_LastHeight)
{
m_LastHeight = contentRect.y - contentOffset;
Repaint();
}
}
GUI.enabled = wasEnabled;
return m_SerializedObject.ApplyModifiedProperties();
}
GUIContent GetPropertyLabel(SerializedProperty property)
{
var isInspectorModeNormal = inspectorMode == InspectorMode.Normal;
if (isInspectorModeNormal)
return null;
return GUIContent.Temp(property.displayName, $"{property.tooltip}\n{property.propertyPath} ({property.propertyType})".Trim());
}
internal static bool IsAnyMonoBehaviourTargetPartOfPrefabInstance(Editor editor)
{
if ((editor.target is MonoBehaviour) == false)
return false;
foreach (var t in editor.targets)
{
var instanceID = t.GetInstanceID();
if (PrefabUtility.IsInstanceIDPartOfNonAssetPrefabInstance(instanceID))
return true;
}
return false;
}
public bool MissingMonoBehaviourGUI()
{
serializedObject.Update();
SerializedProperty scriptProperty = serializedObject.FindProperty("m_Script");
if (scriptProperty == null)
return false;
bool scriptLoaded = CheckIfScriptLoaded(scriptProperty);
bool oldGUIEnabled = GUI.enabled;
if (!scriptLoaded)
{
GUI.enabled = IsAnyMonoBehaviourTargetPartOfPrefabInstance(this) == false; // We don't support changing script as an override on Prefab Instances (case 1255454)
}
EditorGUILayout.PropertyField(scriptProperty);
if (!scriptLoaded)
{
GUI.enabled = true;
// if script is not loaded, this might also be because
// the asset is tied to an EditorClassIdentifier rather than a MonoScript
// (it happens when multiple types are defined in a C# script)
switch (ShowTypeFixup())
{
case ShowTypeFixupResult.CantFindCandidate:
ShowScriptNotLoadedWarning(IsAnyMonoBehaviourTargetPartOfPrefabInstance(this));
break;
case ShowTypeFixupResult.SelectedCandidate:
serializedObject.ApplyModifiedProperties();
EditorUtility.RequestScriptReload();
return true;
}
}
GUI.enabled = oldGUIEnabled;
if (serializedObject.ApplyModifiedProperties())
{
EditorUtility.ForceRebuildInspectors();
}
return true;
}
internal static bool MissingSerializeReference(Object unityTarget)
{
var monoBehaviour = unityTarget as MonoBehaviour;
var scriptableObject = unityTarget as ScriptableObject;
if ((monoBehaviour != null || scriptableObject != null) && SerializationUtility.HasManagedReferencesWithMissingTypes(unityTarget))
{
return true;
}
return false;
}
internal static bool ShowMissingSerializeReferenceWarningBoxIfRequired(Object unityTarget)
{
if (MissingSerializeReference(unityTarget))
{
EditorGUILayout.HelpBox(Styles.missingSerializeReferenceInstanceMessage, MessageType.Warning, true);
return true;
}
else
{
return false;
}
}
public bool ShowMissingSerializeReferenceWarningBoxIfRequired()
{
return ShowMissingSerializeReferenceWarningBoxIfRequired(target);
}
static GUIContent s_fixupTypeContent = new GUIContent("Fix underlying type");
enum ShowTypeFixupResult
{
CantFindCandidate,
DisplayedCandidates,
SelectedCandidate
}
private ShowTypeFixupResult ShowTypeFixup()
{
var originalClassIdentifier = serializedObject.FindProperty("m_EditorClassIdentifier");
if (originalClassIdentifier == null)
{
return ShowTypeFixupResult.CantFindCandidate;
}
var assemblySepartor = originalClassIdentifier.stringValue?.IndexOf("::");
if (assemblySepartor == null || assemblySepartor == -1)
{
return ShowTypeFixupResult.CantFindCandidate;
}
var withoutAssembly = originalClassIdentifier.stringValue.Substring(assemblySepartor.Value + 2);
var potentialMatches = TypeCache.GetTypesDerivedFrom<ScriptableObject>().Where(c => c.FullName == withoutAssembly)
.Concat(TypeCache.GetTypesDerivedFrom<MonoBehaviour>().Where(c => c.FullName == withoutAssembly))
.Select(c => $"{c.Assembly.GetName().Name}::{c.FullName}")
.Where(c => c != originalClassIdentifier.stringValue)
.ToList();
if (potentialMatches.Count == 0)
{
return ShowTypeFixupResult.CantFindCandidate;
}
var buttons = new string[potentialMatches.Count + 1];
buttons[0] = "-";
for (int i = 0; i < potentialMatches.Count; i++)
{
buttons[i + 1] = potentialMatches[i];
}
EditorGUILayout.HelpBox("It seems that the underlying type has been moved in a different assembly. Please select the correct object type.", MessageType.Warning);
EditorGUI.BeginChangeCheck();
var value = EditorGUILayout.Popup(s_fixupTypeContent, 0, buttons);
if (EditorGUI.EndChangeCheck())
{
originalClassIdentifier.stringValue = buttons[value];
return ShowTypeFixupResult.SelectedCandidate;
}
return ShowTypeFixupResult.DisplayedCandidates;
}
private static bool CheckIfScriptLoaded(SerializedProperty scriptProperty)
{
MonoScript targetScript = scriptProperty?.objectReferenceValue as MonoScript;
return targetScript != null && targetScript.GetScriptTypeWasJustCreatedFromComponentMenu();
}
private static void ShowScriptNotLoadedWarning(bool missingScriptIsOnPrefabInstance)
{
var message = missingScriptIsOnPrefabInstance ? Styles.missingScriptMessageForPrefabInstance : Styles.missingScriptMessage;
EditorGUILayout.HelpBox(message, MessageType.Warning, true);
}
internal static void ShowScriptNotLoadedWarning(SerializedProperty scriptProperty, bool isPartOfPrefabInstance)
{
bool scriptLoaded = CheckIfScriptLoaded(scriptProperty);
if (!scriptLoaded)
{
ShowScriptNotLoadedWarning(isPartOfPrefabInstance);
}
}
private void ResetOptimizedBlock(OptimizedBlockState resetState = OptimizedBlockState.CheckOptimizedBlock)
{
m_LastHeight = -1;
m_OptimizedBlockState = resetState;
}
internal void OnDisableINTERNAL()
{
ResetOptimizedBlock();
CleanupPropertyEditor();
propertyHandlerCache.Dispose();
if (m_DummyPreview != null && m_DummyPreview is not Editor)
m_DummyPreview.Cleanup();
}
internal static bool ObjectIsMonoBehaviourOrScriptableObjectWithoutScript(Object obj)
{
if (obj)
{
// When script is present the type will be a derived class instead
return obj.GetType() == typeof(MonoBehaviour) || obj.GetType() == typeof(ScriptableObject);
}
return obj is MonoBehaviour || obj is ScriptableObject;
}
public override void OnInspectorGUI()
{
if (ObjectIsMonoBehaviourOrScriptableObjectWithoutScript(target))
{
if (MissingMonoBehaviourGUI())
return;
}
else
{
ShowMissingSerializeReferenceWarningBoxIfRequired();
}
base.OnInspectorGUI();
}
public override VisualElement CreateInspectorGUI()
{
if (serializedObject == null)
return null;
var root = new VisualElement();
if (MissingSerializeReference(target))
{
root.Add(new HelpBox(GetMissingSerializeRefererenceMessageContainer(), HelpBoxMessageType.Warning));
}
UIElements.InspectorElement.FillDefaultInspector(root, serializedObject, this);
if (target is MonoBehaviour behaviour && behaviour != null && AudioUtil.HasAudioCallback(behaviour))
{
root.Add(new OnAudioFilterReadLevelMeter(behaviour));
}
return root;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/GenericInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/GenericInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 7635
} | 290 |
// 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.Reflection;
using System.Text.RegularExpressions;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal class ScriptAttributeUtility
{
readonly struct CustomPropertyDrawerContainer
{
public readonly Type drawerType;
public readonly Type[] supportedRenderPipelineTypes;
public readonly bool editorForChildClasses;
public CustomPropertyDrawerContainer(Type drawerType, Type[] supportedRenderPipelineTypes, bool editorForChildClasses)
{
this.drawerType = drawerType;
this.supportedRenderPipelineTypes = supportedRenderPipelineTypes;
this.editorForChildClasses = editorForChildClasses;
}
}
// Internal API members
internal static Stack<PropertyDrawer> s_DrawerStack = new Stack<PropertyDrawer>();
private static Dictionary<string, List<PropertyAttribute>> s_BuiltinAttributes = null;
static Dictionary<Type, List<FieldInfo>> s_AutoLoadProperties;
private static PropertyHandler s_SharedNullHandler = new PropertyHandler();
private static PropertyHandler s_NextHandler = new PropertyHandler();
private static PropertyHandlerCache s_GlobalCache = new PropertyHandlerCache();
private static PropertyHandlerCache s_CurrentCache = null;
static readonly Lazy<Dictionary<Type, CustomPropertyDrawerContainer[]>> k_DrawerTypeForType = new(BuildDrawerTypeForTypeDictionary);
static readonly Dictionary<Type, Type> k_DrawerStaticTypesCache = new();
static readonly Dictionary<Type, Type[]> k_SupportedRenderPipelinesForSerializedObject = new();
static readonly Comparer<CustomPropertyDrawerContainer> k_RenderPipelineTypeComparer
= Comparer<CustomPropertyDrawerContainer>.Create((c1, c2)
=>
{
var firstRenderPipelineByFullName1 = c1.supportedRenderPipelineTypes?.FirstOrDefaultSorted();
var firstRenderPipelineByFullName2 = c2.supportedRenderPipelineTypes?.FirstOrDefaultSorted();
return string.Compare(firstRenderPipelineByFullName1?.FullName, firstRenderPipelineByFullName2?.FullName, StringComparison.Ordinal);
});
static Type[] s_CurrentRenderPipelineAssetTypeArray;
static Type[] currentRenderPipelineAssetTypeArray
{
get
{
if (s_CurrentRenderPipelineAssetTypeArray != null && s_CurrentRenderPipelineAssetTypeArray[0] == GraphicsSettings.currentRenderPipelineAssetType)
return s_CurrentRenderPipelineAssetTypeArray;
s_CurrentRenderPipelineAssetTypeArray = new[] { GraphicsSettings.currentRenderPipelineAssetType };
return s_CurrentRenderPipelineAssetTypeArray;
}
}
static void ResetCachedTypesAndAsset()
{
k_DrawerStaticTypesCache.Clear();
ClearGlobalCache();
}
internal static PropertyHandlerCache propertyHandlerCache
{
get => s_CurrentCache ?? s_GlobalCache;
set => s_CurrentCache = value;
}
internal static void ClearGlobalCache()
{
s_GlobalCache.Clear();
}
private static void PopulateBuiltinAttributes()
{
s_BuiltinAttributes = new Dictionary<string, List<PropertyAttribute>>();
AddBuiltinAttribute("TextMesh", "m_Text", new MultilineAttribute());
// Example: Make Orthographic Size in Camera component be in range between 0 and 1000
//AddBuiltinAttribute ("Camera", "m_OrthographicSize", new RangeAttribute (0, 1000));
}
private static void AddBuiltinAttribute(string componentTypeName, string propertyPath, PropertyAttribute attr)
{
string key = componentTypeName + "_" + propertyPath;
if (!s_BuiltinAttributes.ContainsKey(key))
s_BuiltinAttributes.Add(key, new List<PropertyAttribute>());
s_BuiltinAttributes[key].Add(attr);
}
private static List<PropertyAttribute> GetBuiltinAttributes(SerializedProperty property)
{
if (property.serializedObject.targetObject == null)
return null;
Type t = property.serializedObject.targetObject.GetType();
string attrKey = t.Name + "_" + property.propertyPath;
List<PropertyAttribute> attr = null;
s_BuiltinAttributes.TryGetValue(attrKey, out attr);
return attr;
}
// Build a dictionary when k_DrawerTypeForType is first accessed
static Dictionary<Type, CustomPropertyDrawerContainer[]> BuildDrawerTypeForTypeDictionary()
{
RenderPipelineManager.activeRenderPipelineDisposed += ResetCachedTypesAndAsset;
RenderPipelineManager.activeRenderPipelineCreated += ResetCachedTypesAndAsset;
var tempDictionary = new Dictionary<Type, List<CustomPropertyDrawerContainer>>();
foreach (var drawerType in TypeCache.GetTypesDerivedFrom<GUIDrawer>())
{
//Debug.Log("Drawer: " + type);
var customPropertyDrawers = drawerType.GetCustomAttributes<CustomPropertyDrawer>(true);
var supportedOnRenderPipelineAttribute = drawerType.GetCustomAttribute<SupportedOnRenderPipelineAttribute>();
foreach (CustomPropertyDrawer drawer in customPropertyDrawers)
{
var propertyType = drawer.m_Type;
if (!tempDictionary.ContainsKey(propertyType))
tempDictionary.Add(propertyType, new List<CustomPropertyDrawerContainer>());
tempDictionary[propertyType].AddSorted(new CustomPropertyDrawerContainer(drawerType, supportedOnRenderPipelineAttribute?.renderPipelineTypes, drawer.m_UseForChildren),
k_RenderPipelineTypeComparer);
}
}
var dictionaryWithArrays = new Dictionary<Type, CustomPropertyDrawerContainer[]>();
foreach (var kvp in tempDictionary)
dictionaryWithArrays.Add(kvp.Key, kvp.Value.ToArray());
return dictionaryWithArrays;
}
/// <summary>
/// We build our CustomPropertyDrawerContainer cache the first time we access it.
/// It used solely to have a quick access to drawer types and their information.
/// We have a separate cache to map Type -> Drawer. It will work with managed references too as we map real type to the drawers.
/// This cache resets each type we create or dispose a Render Pipeline as SupportedOn can exist on some drawers.
/// </summary>
/// <param name="propertyType">Find a drawer for provided Type</param>
/// <param name="renderPipelineAssetTypes">This can be either GraphicsSettings.currentRenderPipelineAssetType or type from SupportedOnRenderPipeline attribute for serializedObject</param>
/// <param name="isPropertyTypeAManagedReference">Specify if it's known that we deal with ManagedReference property</param>
/// <returns></returns>
internal static Type GetDrawerTypeForType(Type propertyType, Type[] renderPipelineAssetTypes, bool isPropertyTypeAManagedReference = false)
{
//We map specific types to drawers and it will work with managed references too.
if (k_DrawerStaticTypesCache.TryGetValue(propertyType, out var drawerTypeForType))
return drawerTypeForType;
var currentRenderPipelineAssetType = GraphicsSettings.currentRenderPipelineAssetType;
Type[] allInterfaces = null;
bool[] checkedInterfaces = null;
for (var inspectedType = propertyType; inspectedType != null; inspectedType = inspectedType.BaseType)
{
//In the first case we don't need to check for some properties as we know that we deal not with a Base class
//We check only if we have direct drawer and prepare to check interfaces in the next step if they exist
var requestedPropertyType = inspectedType == propertyType;
//Check for class drawers. For generics it would be 2 checks. One for generic type and one for generic definition.
//For example, for A <bool> we will check first for A<bool> and then for A<T>.
if (TryGetDrawerTypeForTypeFromCache(requestedPropertyType, renderPipelineAssetTypes, isPropertyTypeAManagedReference, inspectedType, currentRenderPipelineAssetType, out var drawerType))
{
k_DrawerStaticTypesCache.Add(propertyType, drawerType);
return drawerType;
}
if (requestedPropertyType)
{
//Gather all interfaces for requested property type
allInterfaces = inspectedType.GetInterfaces();
checkedInterfaces = new bool[allInterfaces.Length];
// Calculate inheritance level for each interface
var interfaceLevels = new Dictionary<Type, int>();
foreach (var interfaceType in allInterfaces)
CalculateInheritanceLevel(interfaceType, 0, interfaceLevels);
// Sort interfaces by inheritance level and then by name
Array.Sort(allInterfaces, (x, y) =>
{
var levelComparison = interfaceLevels[x].CompareTo(interfaceLevels[y]);
return levelComparison != 0 ? levelComparison : string.CompareOrdinal(x.Name, y.Name);
});
}
else if (allInterfaces.Length != 0)
{
// Get all interfaces for the current inspected type
var baseTypeInterfaces = inspectedType.GetInterfaces();
for (int i = 0; i < allInterfaces.Length; i++)
{
// Skipped already checked interfaces
if (checkedInterfaces[i])
continue;
// Exclude interfaces that are implemented by the base type
var interfaceType = allInterfaces[i];
if (baseTypeInterfaces.ContainsByEquals(interfaceType))
continue;
// Check if there's an appropriate drawer for the interface
checkedInterfaces[i] = true;
if (TryGetDrawerTypeForTypeFromCache(requestedPropertyType, renderPipelineAssetTypes, isPropertyTypeAManagedReference, interfaceType, currentRenderPipelineAssetType, out drawerType))
{
k_DrawerStaticTypesCache.Add(propertyType, drawerType);
return drawerType;
}
}
}
}
return null;
}
static int CalculateInheritanceLevel(Type interfaceType, int currentLevel, Dictionary<Type, int> processedInterfaces)
{
// Get parent interfaces
var parentInterfaces = interfaceType.GetInterfaces();
// Base case: if there are no parent interfaces, return current inheritance level
if (parentInterfaces.Length == 0)
return AddOrReplaceInterfaceLevel(currentLevel);
// Recursive case: return the minimum inheritance level minus 1 of the parent interfaces
var minParentLevel = int.MaxValue;
for (var i = 0; i < parentInterfaces.Length; i++)
{
var parentLevel = CalculateInheritanceLevel(parentInterfaces[i], currentLevel + 1, processedInterfaces);
if (parentLevel < minParentLevel)
minParentLevel = parentLevel;
}
return AddOrReplaceInterfaceLevel(minParentLevel - 1);
//Local method just to simplify code
int AddOrReplaceInterfaceLevel(int newLevel)
{
// Check if the interface has already been processed and update its inheritance level if necessary
if (processedInterfaces.TryGetValue(interfaceType, out var level))
{
// If the interface has already been processed and the new inheritance level is greater than the current one, update it
if (level >= newLevel)
return level;
processedInterfaces[interfaceType] = newLevel;
return newLevel;
}
processedInterfaces.Add(interfaceType, newLevel);
return newLevel;
}
}
static bool TryGetDrawerTypeForTypeFromCache(bool requestedPropertyType, Type[] renderPipelineAssetTypes, bool isPropertyTypeIsManagedReference, Type currentType, Type currentRenderPipelineAssetType,
out Type drawerType)
{
drawerType = null;
// check for exact type
if (TryExtractDrawerTypeForTypeFromCache(requestedPropertyType, renderPipelineAssetTypes, isPropertyTypeIsManagedReference, currentType, currentRenderPipelineAssetType, out drawerType))
return true;
// check for base generic versions of the drawers
if (!currentType.IsGenericType)
return false;
var genericDefinition = currentType.GetGenericTypeDefinition();
return TryExtractDrawerTypeForTypeFromCache(requestedPropertyType, renderPipelineAssetTypes, isPropertyTypeIsManagedReference, genericDefinition, currentRenderPipelineAssetType, out drawerType);
}
static bool TryExtractDrawerTypeForTypeFromCache(bool requestedPropertyType, Type[] renderPipelineAssetTypes, bool isPropertyTypeIsManagedReference, Type currentType, Type currentRenderPipelineAssetType,
out Type drawerType)
{
drawerType = null;
// Extract drawers for the current type from the cache
if (!k_DrawerTypeForType.Value.TryGetValue(currentType, out var drawerTypes))
return false;
// Check if there's an appropriate drawer for the current type and render pipeline. This is where we check for SupportedOnRenderPipelineAttribute
var result = TryFindDrawers(renderPipelineAssetTypes, drawerTypes, currentRenderPipelineAssetType, out var customPropertyDrawerContainer);
if (!IsAppropriateDrawerFound())
return false;
drawerType = customPropertyDrawerContainer.drawerType;
return true;
//Extracted just to simplify a condition
bool IsAppropriateDrawerFound()
{
if (!result)
return false;
//When we check for requested property type we don't need to check for editorForChildClasses and managed reference type
if (requestedPropertyType)
return true;
// Check for drawers with editorForChildClasses set to true and special case for managed references.
// The custom property drawers for those are defined with 'useForChildren=false'
// (otherwise the dynamic type is not taking into account in the custom property
// drawer resolution) so even if 's_DrawerTypeForType' is built (based on static types)
// we have to check base types for custom property drawers manually.
// Managed references with no drawers should properly try to fallback
return (customPropertyDrawerContainer.editorForChildClasses || isPropertyTypeIsManagedReference);
}
}
static bool TryFindDrawers(Type[] renderPipelineAssetTypes, CustomPropertyDrawerContainer[] drawerTypes, Type currentRenderPipelineAssetType,
out CustomPropertyDrawerContainer customPropertyDrawerContainer)
{
CustomPropertyDrawerContainer? supportedOnRenderPipelineDrawer = null;
CustomPropertyDrawerContainer? supportedByBaseRenderPipelineDrawer = null;
CustomPropertyDrawerContainer? regularDrawer = null;
for (var i = 0; i < drawerTypes.Length; i++)
{
var drawerContainer = drawerTypes[i];
if (drawerContainer.supportedRenderPipelineTypes == null)
{
regularDrawer ??= drawerContainer;
continue;
}
if (renderPipelineAssetTypes == null)
continue;
for (int j = 0; j < renderPipelineAssetTypes.Length; j++)
{
var renderPipelineAssetType = renderPipelineAssetTypes[j];
var supportedMode = SupportedOnRenderPipelineAttribute.GetSupportedMode(drawerContainer.supportedRenderPipelineTypes, renderPipelineAssetType);
switch (supportedMode)
{
case SupportedOnRenderPipelineAttribute.SupportedMode.Supported:
if (supportedOnRenderPipelineDrawer == null || renderPipelineAssetType == currentRenderPipelineAssetType)
supportedOnRenderPipelineDrawer = drawerContainer;
break;
case SupportedOnRenderPipelineAttribute.SupportedMode.SupportedByBaseClass:
supportedByBaseRenderPipelineDrawer ??= drawerContainer;
break;
}
}
}
if (supportedOnRenderPipelineDrawer.HasValue)
{
customPropertyDrawerContainer = supportedOnRenderPipelineDrawer.Value;
return true;
}
if (supportedByBaseRenderPipelineDrawer.HasValue)
{
customPropertyDrawerContainer = supportedByBaseRenderPipelineDrawer.Value;
return true;
}
customPropertyDrawerContainer = regularDrawer ?? default;
return regularDrawer.HasValue;
}
/// <summary>
/// Does the same thing as 'GetDrawerTypeForType' (with the same side effect of building the cache)
/// but also plays well with Managed References. If the property that is used as a reference for the drawer
/// query is of a managed reference type, the class parents are also looked up as fallbacks.
/// </summary>
/// <param name="property"></param>
/// <param name="type"></param>
/// <returns>The custom property drawer type or 'null' if not found.</returns>
internal static Type GetDrawerTypeForPropertyAndType(SerializedProperty property, Type type)
{
//Try to gather SupportedOn from Serialized Object and rely on this instead of GraphicsSettings.currentRenderPipelineAssetType if exist
var serializedObject = property.serializedObject;
var serializedObjectType = serializedObject.targetObject.GetType();
if (!k_SupportedRenderPipelinesForSerializedObject.TryGetValue(serializedObjectType, out var supportedOnRenderPipelineTypes))
{
var supportedOn = serializedObjectType.GetCustomAttribute<SupportedOnRenderPipelineAttribute>();
supportedOnRenderPipelineTypes = supportedOn?.renderPipelineTypes;
k_SupportedRenderPipelinesForSerializedObject.Add(serializedObjectType, supportedOnRenderPipelineTypes);
}
//Choose to use SupportedOn from SO if exist or current RenderPipelineAsset.
//If our SO has SupportedOn it will indicate to our system that this SO used specifically with defined Render Pipeline Asset types
var renderPipelineAssetTypes = supportedOnRenderPipelineTypes ?? (GraphicsSettings.isScriptableRenderPipelineEnabled ? currentRenderPipelineAssetTypeArray : null);
return GetDrawerTypeForType(type, renderPipelineAssetTypes, property.propertyType == SerializedPropertyType.ManagedReference);
}
private static List<PropertyAttribute> GetFieldAttributes(FieldInfo field)
{
if (field == null)
return null;
var attrs = field.GetCustomAttributes<PropertyAttribute>(true);
Comparer<PropertyAttribute> comparer = null;
List<PropertyAttribute> propertyAttributeList = null;
foreach (PropertyAttribute attribute in attrs)
{
propertyAttributeList ??= new List<PropertyAttribute>();
comparer ??= Comparer<PropertyAttribute>.Create((p1, p2) => p1.order.CompareTo(p2.order));
propertyAttributeList.AddSorted(attribute, comparer);
}
return propertyAttributeList;
}
/// <summary>
/// Returns the field info and field type for the property. The types are based on the
/// static field definition.
/// </summary>
/// <param name="property"></param>
/// <param name="type"></param>
/// <returns></returns>
internal static FieldInfo GetFieldInfoAndStaticTypeFromProperty(SerializedProperty property, out Type type)
{
var classType = GetScriptTypeFromProperty(property);
if (classType == null)
{
type = null;
return null;
}
var fieldPath = property.propertyPath;
if (property.isReferencingAManagedReferenceField)
{
// When the field we are trying to access is a dynamic instance, things are a bit more tricky
// since we cannot "statically" (looking only at the parent class field types) know the actual
// "classType" of the parent class.
// The issue also is that at this point our only view on the object is the very limited SerializedProperty.
// So we have to:
// 1. try to get the FQN from for the current managed type from the serialized data,
// 2. get the path *in the current managed instance* of the field we are pointing to,
// 3. foward that to 'GetFieldInfoFromPropertyPath' as if it was a regular field,
var objectTypename = property.GetFullyQualifiedTypenameForCurrentTypeTreeInternal();
GetTypeFromManagedReferenceFullTypeName(objectTypename, out classType);
fieldPath = property.GetPropertyPathInCurrentManagedTypeTreeInternal();
}
if (classType == null)
{
type = null;
return null;
}
return GetFieldInfoFromPropertyPath(classType, fieldPath, out type);
}
/// <summary>
/// Returns the field info and type for the property. Contrary to GetFieldInfoAndStaticTypeFromProperty,
/// when confronted with a managed reference the dynamic instance type is returned.
/// </summary>
/// <param name="property"></param>
/// <param name="type"></param>
/// <returns></returns>
internal static FieldInfo GetFieldInfoFromProperty(SerializedProperty property, out Type type)
{
var fieldInfo = GetFieldInfoAndStaticTypeFromProperty(property, out type);
if (fieldInfo == null)
return null;
// Managed references are a special case, we need to override the static type
// returned by 'GetFieldInfoFromPropertyPath' for custom property handler matching
// by the dynamic type of the instance.
if (property.propertyType == SerializedPropertyType.ManagedReference)
{
// Try to get a Type instance for the managed reference
if (GetTypeFromManagedReferenceFullTypeName(property.managedReferenceFullTypename, out var managedReferenceInstanceType))
{
type = managedReferenceInstanceType;
}
// We keep the fallback to the field type returned by 'GetFieldInfoFromPropertyPath'.
}
return fieldInfo;
}
/// <summary>
/// Create a Type instance from the managed reference full type name description.
/// The expected format for the typename string is the one returned by SerializedProperty.managedReferenceFullTypename.
/// </summary>
/// <param name="managedReferenceFullTypename"></param>
/// <param name="managedReferenceInstanceType"></param>
/// <returns></returns>
internal static bool GetTypeFromManagedReferenceFullTypeName(string managedReferenceFullTypename, out Type managedReferenceInstanceType)
{
managedReferenceInstanceType = null;
var splitIndex = managedReferenceFullTypename.IndexOf(' ');
if (splitIndex > 0)
{
var assemblyPart = managedReferenceFullTypename.Substring(0, splitIndex);
var nsClassnamePart = managedReferenceFullTypename.Substring(splitIndex);
managedReferenceInstanceType = Type.GetType($"{nsClassnamePart}, {assemblyPart}");
}
return managedReferenceInstanceType != null;
}
private static Type GetScriptTypeFromProperty(SerializedProperty property)
{
if (property.serializedObject.targetObject != null)
return property.serializedObject.targetObject.GetType();
// Fallback in case the targetObject has been destroyed but the property is still valid.
SerializedProperty scriptProp = property.serializedObject.FindProperty("m_Script");
if (scriptProp == null)
return null;
MonoScript script = scriptProp.objectReferenceValue as MonoScript;
if (script == null)
return null;
return script.GetClass();
}
struct Cache : IEquatable<Cache>
{
Type host;
string path;
public Cache(Type host, string path)
{
this.host = host;
this.path = path;
}
public bool Equals(Cache other)
{
return Equals(host, other.host) && string.Equals(path, other.path);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Cache cache && Equals(cache);
}
public override int GetHashCode()
{
unchecked
{
return ((host != null ? host.GetHashCode() : 0) * 397) ^ (path != null ? path.GetHashCode() : 0);
}
}
}
class FieldInfoCache
{
public FieldInfo fieldInfo;
public Type type;
}
static Dictionary<Cache, FieldInfoCache> s_FieldInfoFromPropertyPathCache = new Dictionary<Cache, FieldInfoCache>();
private static FieldInfo GetFieldInfoFromPropertyPath(Type host, string path, out Type type)
{
Cache cache = new Cache(host, path);
if (s_FieldInfoFromPropertyPathCache.TryGetValue(cache, out var fieldInfoCache))
{
type = fieldInfoCache?.type;
return fieldInfoCache?.fieldInfo;
}
const string arrayData = @"\.Array\.data\[[0-9]+\]";
// we are looking for array element only when the path ends with Array.data[x]
var lookingForArrayElement = Regex.IsMatch(path, arrayData + "$");
// remove any Array.data[x] from the path because it is prevents cache searching.
path = Regex.Replace(path, arrayData, ".___ArrayElement___");
FieldInfo fieldInfo = null;
type = host;
string[] parts = path.Split('.');
for (int i = 0; i < parts.Length; i++)
{
string member = parts[i];
// GetField on class A will not find private fields in base classes to A,
// so we have to iterate through the base classes and look there too.
// Private fields are relevant because they can still be shown in the Inspector,
// and that applies to private fields in base classes too.
FieldInfo foundField = null;
for (Type currentType = type; foundField == null && currentType != null; currentType = currentType.BaseType)
foundField = currentType.GetField(member, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (foundField == null)
{
type = null;
s_FieldInfoFromPropertyPathCache.Add(cache, null);
return null;
}
fieldInfo = foundField;
type = fieldInfo.FieldType;
// we want to get the element type if we are looking for Array.data[x]
if (i < parts.Length - 1 && parts[i + 1] == "___ArrayElement___" && type.IsArrayOrList())
{
i++; // skip the "___ArrayElement___" part
type = type.GetArrayOrListElementType();
}
}
// we want to get the element type if we are looking for Array.data[x]
if (lookingForArrayElement && type != null && type.IsArrayOrList())
type = type.GetArrayOrListElementType();
fieldInfoCache = new FieldInfoCache
{
type = type,
fieldInfo = fieldInfo
};
s_FieldInfoFromPropertyPathCache.Add(cache, fieldInfoCache);
return fieldInfo;
}
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static PropertyHandler GetHandler(SerializedProperty property)
{
if (property == null)
return s_SharedNullHandler;
// Don't use custom drawers in debug mode
if (property.serializedObject.inspectorMode != InspectorMode.Normal)
return s_SharedNullHandler;
// If the drawer is cached, use the cached drawer
PropertyHandler handler = propertyHandlerCache.GetHandler(property);
if (handler != null)
return handler;
Type propertyType = null;
List<PropertyAttribute> attributes = null;
FieldInfo field = null;
// Determine if SerializedObject target is a script or a builtin type
Object target = property.serializedObject.targetObject;
if (NativeClassExtensionUtilities.ExtendsANativeType(target))
{
// For scripts, use reflection to get FieldInfo for the member the property represents
field = GetFieldInfoFromProperty(property, out propertyType);
// Use reflection to see if this member has an attribute
attributes = GetFieldAttributes(field);
}
else
{
// For builtin types, look if we hardcoded an attribute for this property
// First initialize the hardcoded properties if not already done
if (s_BuiltinAttributes == null)
PopulateBuiltinAttributes();
attributes = GetBuiltinAttributes(property);
}
handler = s_NextHandler;
if (attributes != null)
{
for (int i = 0; i < attributes.Count; i++)
handler.HandleAttribute(property, attributes[i], field, propertyType);
}
// Field has no CustomPropertyDrawer attribute with matching drawer so look for default drawer for field type
if (!handler.hasPropertyDrawer && propertyType != null)
handler.HandleDrawnType(property, propertyType, propertyType, field, null);
if (handler.empty)
{
propertyHandlerCache.SetHandler(property, s_SharedNullHandler);
handler = s_SharedNullHandler;
}
else
{
propertyHandlerCache.SetHandler(property, handler);
s_NextHandler = new PropertyHandler();
}
return handler;
}
internal static bool CanUseSameHandler(SerializedProperty p1, SerializedProperty p2)
{
return PropertyHandlerCache.CanUseSameHandler(p1, p2);
}
internal static List<FieldInfo> GetAutoLoadProperties(Type type)
{
if (s_AutoLoadProperties == null)
s_AutoLoadProperties = new Dictionary<Type, List<FieldInfo>>();
if (!s_AutoLoadProperties.TryGetValue(type, out var list))
{
list = new List<FieldInfo>();
foreach (var field in type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance))
{
if (field.FieldType == typeof(SerializedProperty) && field.IsDefined(typeof(CachePropertyAttribute), false))
list.Add(field);
}
s_AutoLoadProperties.Add(type, list);
}
return list;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/Core/ScriptAttributeGUI/ScriptAttributeUtility.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/Core/ScriptAttributeGUI/ScriptAttributeUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 14358
} | 291 |
// 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 UnityEditorInternal;
using UnityEngine;
using UnityEditor.Hardware;
using UnityEngine.Rendering;
using UnityEngine.Assertions;
namespace UnityEditor
{
[CustomEditor(typeof(EditorSettings))]
internal class EditorSettingsInspector : ProjectSettingsBaseEditor
{
class Content
{
public static GUIContent unityRemote = EditorGUIUtility.TrTextContent("Unity Remote");
public static GUIContent device = EditorGUIUtility.TrTextContent("Device");
public static GUIContent compression = EditorGUIUtility.TrTextContent("Compression");
public static GUIContent resolution = EditorGUIUtility.TrTextContent("Resolution");
public static GUIContent joystickSource = EditorGUIUtility.TrTextContent("Joystick Source");
public static GUIContent mode = EditorGUIUtility.TrTextContent("Mode");
public static GUIContent parallelImport = EditorGUIUtility.TrTextContent("Parallel Import", "During an asset database refresh some asset imports can be performed in parallel in sub processes.");
public static GUIContent parallelImportLearnMore = EditorGUIUtility.TrTextContent("Learn more...", "During an asset database refresh some asset imports can be performed in parallel in sub processes.");
public static GUIContent desiredImportWorkerCountOverride = EditorGUIUtility.TrTextContent("Override Desired Worker Count", "Override the desired worker count specified in the preferences.");
public static GUIContent desiredImportWorkerCount = EditorGUIUtility.TrTextContent("Desired Import Worker Count", "The desired number of import worker processes to use for importing. The actual number of worker processes on the system can be both lower or higher that this, but the system will seek towards this number when importing.");
public static GUIContent standbyImportWorkerCount = EditorGUIUtility.TrTextContent("Standby Import Worker Count", "The number of import worker processes to keep around in standby and ready for importing. The actual number of worker processes on the system can be both lower or higher that this, but the system will seek towards this number when worker processes are idle.");
public static GUIContent idleWorkerShutdownDelay = EditorGUIUtility.TrTextContent("Idle Import Worker Shutdown Delay", "When an importer worker has been idle for this amount of seconds in will be shutdown unless it would take the worker count below the standby worker count setting.");
public static GUIContent cacheServer = EditorGUIUtility.TrTextContent("Cache Server (project specific)");
public static GUIContent assetPipeline = EditorGUIUtility.TrTextContent("Asset Pipeline");
public static GUIContent artifactGarbageCollection = EditorGUIUtility.TrTextContent("Remove unused Artifacts on Restart", "By default, when you start the Editor, Unity removes unused artifact files in the Library folder, and removes their entries in the asset database. This is a form of \"garbage collection\". This setting allows you to turn off the asset database garbage collection, so that previous artifact revisions which are no longer used are still preserved after restarting the Editor. This is useful if you need to debug unexpected import results.");
public static GUIContent cacheServerIPLabel = EditorGUIUtility.TrTextContent("IP address");
public static GUIContent cacheServerNamespacePrefixLabel = EditorGUIUtility.TrTextContent("Namespace prefix", "The namespace used for looking up and storing values on the cache server");
public static GUIContent cacheServerEnableDownloadLabel = EditorGUIUtility.TrTextContent("Download", "Enables downloads from the cache server.");
public static GUIContent cacheServerEnableUploadLabel = EditorGUIUtility.TrTextContent("Upload", "Enables uploads to the cache server.");
public static GUIContent cacheServerEnableTlsLabel = EditorGUIUtility.TrTextContent("TLS/SSL", "Enabled encryption on the cache server connection.");
public static GUIContent cacheServerEnableAuthLabel = EditorGUIUtility.TrTextContent("Authentication (using Unity ID)", "Enable authentication for cache server using Unity ID. Also forces TLS/SSL encryption.");
public static GUIContent cacheServerAuthUserLabel = EditorGUIUtility.TrTextContent("User");
public static GUIContent cacheServerAuthPasswordLabel = EditorGUIUtility.TrTextContent("Password");
public static GUIContent cacheServerValidationLabel = EditorGUIUtility.TrTextContent("Content Validation");
public static GUIContent cacheServerDownloadBatchSizeLabel = EditorGUIUtility.TrTextContent("Download Batch Size");
public static readonly GUIContent cacheServerLearnMore = new GUIContent("Learn more...", "Go to cacheserver documentation.");
public static GUIContent assetSerialization = EditorGUIUtility.TrTextContent("Asset Serialization");
public static GUIContent textSerializeMappingsOnOneLine = EditorGUIUtility.TrTextContent("Reduce version control noise", "Forces Unity to write references and similar YAML structures on one line, which reduces version control noise.");
public static GUIContent defaultBehaviorMode = EditorGUIUtility.TrTextContent("Default Behaviour Mode");
public static GUIContent buildPipelineHeader = EditorGUIUtility.TrTextContent("Build Pipeline");
public static GUIContent ucbpEnableAssetBundles = EditorGUIUtility.TrTextContent("Multi-Process AssetBundle Building", "Enable experimental improvements to the AssetBundle Build Pipeline aimed at reducing build times with multi-process importing and providing more efficient incremental content building");
public static readonly GUIContent ucbpLearnMore = new GUIContent("Learn more...", "Review official Unity documentation for important considerations around these experimental improvements.");
public static GUIContent graphics = EditorGUIUtility.TrTextContent("Graphics");
public static GUIContent showLightmapResolutionOverlay = EditorGUIUtility.TrTextContent("Show Lightmap Resolution Overlay");
public static GUIContent useLegacyProbeSampleCount = EditorGUIUtility.TrTextContent("Use legacy Light Probe sample counts", "Uses fixed Light Probe sample counts for baking with the Progressive Lightmapper. The sample counts are: 64 direct samples, 2048 indirect samples and 2048 environment samples.");
public static GUIContent enableCookiesInLightmapper = EditorGUIUtility.TrTextContent("Enable baked cookies support", "Determines whether cookies should be evaluated by the Progressive Lightmapper during Global Illumination calculations. Introduced in version 2020.1. ");
public static GUIContent spritePacker = EditorGUIUtility.TrTextContent("Sprite Atlas");
public static readonly GUIContent spriteMaxCacheSize = EditorGUIUtility.TrTextContent("Max SpriteAtlas Cache Size (GB)", "The size of the Sprite Atlas Cache folder will be kept below this maximum value when possible. Change requires Editor restart.");
public static GUIContent cSharpProjectGeneration = EditorGUIUtility.TrTextContent("C# Project Generation");
public static GUIContent additionalExtensionsToInclude = EditorGUIUtility.TrTextContent("Additional extensions to include");
public static GUIContent rootNamespace = EditorGUIUtility.TrTextContent("Root namespace");
public static GUIContent textureCompressors = EditorGUIUtility.TrTextContent("Texture Compressors");
public static GUIContent bc7Compressor = EditorGUIUtility.TrTextContent("BC7 Compressor", "Compressor to use for BC7 format texture compression");
public static GUIContent etcCompressor = EditorGUIUtility.TrTextContent("ETC Compressor", "Compressors to use for ETC/ETC2/EAC format texture compression");
public static GUIContent fast = EditorGUIUtility.TrTextContent("Fast");
public static GUIContent normal = EditorGUIUtility.TrTextContent("Normal");
public static GUIContent best = EditorGUIUtility.TrTextContent("Best");
public static GUIContent lineEndingForNewScripts = EditorGUIUtility.TrTextContent("Line Endings For New Scripts");
public static GUIContent streamingSettings = EditorGUIUtility.TrTextContent("Streaming Settings");
public static GUIContent enablePlayModeTextureStreaming = EditorGUIUtility.TrTextContent("Enable Texture Streaming In Play Mode", "Texture Streaming must be enabled in Quality Settings for mipmap streaming to function in Play Mode. This reduces GPU memory by streaming mips in and out as needed.");
public static GUIContent enableEditModeTextureStreaming = EditorGUIUtility.TrTextContent("Enable Texture Streaming In Edit Mode", "Texture Streaming must be enabled in Quality Settings for mipmap streaming to function in Edit Mode. This reduces GPU memory by streaming mips in and out as needed.");
public static GUIContent enableEditorAsyncCPUTextureLoading = EditorGUIUtility.TrTextContent("Load texture data on demand", "While in Editor, load CPU side texture data for streaming textures from disk asynchronously on demand (will avoid some stalls and reduce CPU memory usage). Change requires Editor restart.");
public static GUIContent shaderCompilation = EditorGUIUtility.TrTextContent("Shader Compilation");
public static GUIContent asyncShaderCompilation = EditorGUIUtility.TrTextContent("Asynchronous Shader Compilation", "Enables async shader compilation in Game and Scene view. Async compilation for custom editor tools can be achieved via script API and is not affected by this option.");
public static GUIContent prefabMode = EditorGUIUtility.TrTextContent("Prefab Mode");
public static GUIContent prefabModeAllowAutoSave = EditorGUIUtility.TrTextContent("Allow Auto Save", "When enabled, an Auto Save toggle is displayed in Prefab Mode which you can turn on or off. This is the default. When disabled, there is no Auto Save in Prefab Mode in this project and the toggle is not displayed.");
public static GUIContent prefabModeEditingEnvironments = EditorGUIUtility.TrTextContent("Editing Environments");
public static GUIContent prefabModeRegularEnvironment = EditorGUIUtility.TrTextContent("Regular Environment");
public static GUIContent prefabModeUIEnvironment = EditorGUIUtility.TrTextContent("UI Environment");
public static readonly GUIContent enterPlayModeSettings = EditorGUIUtility.TrTextContent("Enter Play Mode Settings");
public static readonly GUIContent enterPlayModeOptionsEnabled = EditorGUIUtility.TrTextContent("Enter Play Mode Options", "Enables options when Entering Play Mode");
public static readonly GUIContent enterPlayModeOptionsEnableDomainReload = EditorGUIUtility.TrTextContent("Reload Domain", "Enables Domain Reload when Entering Play Mode. Domain reload reinitializes game completely making loading behavior very close to the Player");
public static readonly GUIContent enterPlayModeOptionsEnableSceneReload = EditorGUIUtility.TrTextContent("Reload Scene", "Enables Scene Reload when Entering Play Mode. Scene reload makes loading behavior and performance characteristics very close to the Player");
public static readonly GUIContent numberingScheme = EditorGUIUtility.TrTextContent("Numbering Scheme");
public static readonly GUIContent inspectorSettings = EditorGUIUtility.TrTextContent("Inspector");
public static readonly GUIContent inspectorUseIMGUIDefaultInspector = EditorGUIUtility.TrTextContent("Use IMGUI Default Inspector", "Revert to using IMGUI to generate Default Inspectors where no custom Inspector/Editor was defined.");
public static readonly GUIContent[] numberingSchemeNames =
{
EditorGUIUtility.TrTextContent("Prefab (1)", "Number in parentheses"),
EditorGUIUtility.TrTextContent("Prefab.1", "Number after dot"),
EditorGUIUtility.TrTextContent("Prefab_1", "Number after underscore")
};
public static readonly int[] numberingSchemeValues =
{
(int)EditorSettings.NamingScheme.SpaceParenthesis,
(int)EditorSettings.NamingScheme.Dot,
(int)EditorSettings.NamingScheme.Underscore
};
public static readonly GUIContent numberingHierarchyScheme = EditorGUIUtility.TrTextContent("Game Object Naming");
public static readonly GUIContent numberingHierarchyDigits = EditorGUIUtility.TrTextContent("Game Object Digits");
public static readonly GUIContent numberingProjectSpace = EditorGUIUtility.TrTextContent("Space Before Number in Asset Names");
public static GUIContent referencedClipsExactNaming = EditorGUIUtility.TrTextContent("Exactly Match Referenced Clip Names", "Controls how referenced clips are matched with models that are animated in Legacy mode. If turned on, the model name and the referenced clip names must exactly match. If turned off, only the start of the model name needs to match the referenced clip name. Also controls the behavior of the \"Update referenced clips\" button for models that are animated in Humanoid mode. See the documentation for EditorSettings.referencedClipsExactNaming for more details.");
}
internal struct PopupElement
{
public readonly string id;
public readonly GUIContent content;
public PopupElement(string content)
{
this.id = content;
this.content = new GUIContent(content);
}
public PopupElement(string id, string content)
{
this.id = id;
this.content = new GUIContent(content);
}
}
private PopupElement[] serializationPopupList =
{
new PopupElement("Mixed"),
new PopupElement("Force Binary"),
new PopupElement("Force Text"),
};
private PopupElement[] behaviorPopupList =
{
new PopupElement("3D"),
new PopupElement("2D"),
};
private PopupElement[] spritePackerPopupList =
{
new PopupElement("Disabled"),
new PopupElement("Sprite Atlas V1 - Enabled For Builds"),
new PopupElement("Sprite Atlas V1 - Always Enabled"),
new PopupElement("Sprite Atlas V2 - Enabled"),
new PopupElement("Sprite Atlas V2 - Enabled for Builds"),
};
private static readonly int spritePackDeprecatedEnums = 2;
private PopupElement[] lineEndingsPopupList =
{
new PopupElement("OS Native"),
new PopupElement("Unix"),
new PopupElement("Windows"),
};
private PopupElement[] remoteDevicePopupList;
private DevDevice[] remoteDeviceList;
private PopupElement[] remoteCompressionList =
{
new PopupElement("JPEG"),
new PopupElement("PNG"),
};
private PopupElement[] remoteResolutionList =
{
new PopupElement("Downsize"),
new PopupElement("Normal"),
};
private PopupElement[] remoteJoystickSourceList =
{
new PopupElement("Remote"),
new PopupElement("Local"),
};
private PopupElement[] cacheServerModePopupList =
{
new PopupElement("Use global settings (stored in preferences)"),
new PopupElement("Enabled"),
new PopupElement("Disabled"),
};
private PopupElement[] refreshImportModePopupList =
{
new PopupElement("In process"),
new PopupElement("Out of process by queue"),
};
private PopupElement[] cacheServerAuthMode =
{
new PopupElement("Basic")
};
private GUIContent[] cacheServerValidationPopupList =
{
EditorGUIUtility.TrTextContent("Disabled", "Content hashes are not calculated for uploaded artifacts and are not validated for downloaded artifacts."),
EditorGUIUtility.TrTextContent("Upload Only", "Content hashes are calculated for uploaded artifacts and sent to the Accelerator. Content hashes are not validated for downloaded artifacts." ),
EditorGUIUtility.TrTextContent("Enabled", "Content hashes are calculated for uploaded artifacts and sent to the Accelerator. Content hashes, if provided by the Accelerator, are validated for downloaded artifacts."),
EditorGUIUtility.TrTextContent("Required", "Content hashes are calculated for uploaded artifacts and sent to the Accelerator. Content hashes are required and validated for downloaded artifacts."),
};
private GUIContent[] bc7TextureCompressorOptions =
{
EditorGUIUtility.TrTextContent("Default", "Use default BC7 compressor (currently bc7e)"),
EditorGUIUtility.TrTextContent("ISPC (legacy)", "Use Intel ISPCTextureCompressor (legacy pre-2021.2 behavior)"),
EditorGUIUtility.TrTextContent("bc7e", "Use Binomial bc7e compressor"),
};
private PopupElement[] etcTextureCompressorPopupList =
{
new PopupElement("Legacy"),
new PopupElement("Default"),
new PopupElement("Custom"),
};
private PopupElement[] etcTextureFastCompressorPopupList =
{
new PopupElement("etcpak"),
new PopupElement("ETCPACK Fast"),
};
private PopupElement[] etcTextureNormalCompressorPopupList =
{
new PopupElement("etcpak"),
new PopupElement("ETCPACK Fast"),
new PopupElement("Etc2Comp Fast"),
new PopupElement("Etc2Comp Best"),
};
private PopupElement[] etcTextureBestCompressorPopupList =
{
new PopupElement("Etc2Comp Fast"),
new PopupElement("Etc2Comp Best"),
new PopupElement("ETCPACK Best"),
};
SerializedProperty m_EnableTextureStreamingInPlayMode;
SerializedProperty m_EnableTextureStreamingInEditMode;
SerializedProperty m_EnableEditorAsyncCPUTextureLoading;
SerializedProperty m_GameObjectNamingDigits;
SerializedProperty m_GameObjectNamingScheme;
SerializedProperty m_AssetNamingUsesSpace;
SerializedProperty m_AsyncShaderCompilation;
SerializedProperty m_DefaultBehaviorMode;
SerializedProperty m_SerializationMode;
SerializedProperty m_SerializeInlineMappingsOnOneLine;
SerializedProperty m_PrefabRegularEnvironment;
SerializedProperty m_PrefabUIEnvironment;
SerializedProperty m_PrefabModeAllowAutoSave;
SerializedProperty m_UseLegacyProbeSampleCount;
SerializedProperty m_DisableCookiesInLightmapper;
SerializedProperty m_SpritePackerMode;
SerializedProperty m_SpritePackerCacheSize;
SerializedProperty m_Bc7TextureCompressor;
SerializedProperty m_EtcTextureCompressorBehavior;
SerializedProperty m_EtcTextureFastCompressor;
SerializedProperty m_EtcTextureNormalCompressor;
SerializedProperty m_EtcTextureBestCompressor;
SerializedProperty m_LineEndingsForNewScripts;
SerializedProperty m_EnterPlayModeOptionsEnabled;
SerializedProperty m_EnterPlayModeOptions;
SerializedProperty m_ProjectGenerationIncludedExtensions;
SerializedProperty m_ProjectGenerationRootNamespace;
SerializedProperty m_CacheServerValidationMode;
SerializedProperty m_InspectorUseIMGUIDefaultInspector;
bool m_IsGlobalSettings;
const string kRefreshImportModeKeyArgs = "-refreshImportMode";
const string kStandbyWorkerCountKeyArgs = "-standbyWorkerCount";
const string kIdleWorkerShutdownDelayKeyArgs = "-idleWorkerShutdownDelay";
const string kDesiredImportWorkerCountKeyArgs = "-desiredWorkerCount";
private const string kCacheServerDownloadBatchSizeCmdArg = "-cacheServerDownloadBatchSize";
enum CacheServerConnectionState { Unknown, Success, Failure }
private CacheServerConnectionState m_CacheServerConnectionState;
public void OnEnable()
{
DevDeviceList.Changed += OnDeviceListChanged;
BuildRemoteDeviceList();
m_EnableTextureStreamingInPlayMode = serializedObject.FindProperty("m_EnableTextureStreamingInPlayMode");
m_EnableTextureStreamingInEditMode = serializedObject.FindProperty("m_EnableTextureStreamingInEditMode");
m_EnableEditorAsyncCPUTextureLoading = serializedObject.FindProperty("m_EnableEditorAsyncCPUTextureLoading");
m_GameObjectNamingDigits = serializedObject.FindProperty("m_GameObjectNamingDigits");
m_GameObjectNamingScheme = serializedObject.FindProperty("m_GameObjectNamingScheme");
m_AssetNamingUsesSpace = serializedObject.FindProperty("m_AssetNamingUsesSpace");
m_AsyncShaderCompilation = serializedObject.FindProperty("m_AsyncShaderCompilation");
m_DefaultBehaviorMode = serializedObject.FindProperty("m_DefaultBehaviorMode");
Assert.IsNotNull(m_DefaultBehaviorMode);
m_SerializationMode = serializedObject.FindProperty("m_SerializationMode");
Assert.IsNotNull(m_SerializationMode);
m_SerializeInlineMappingsOnOneLine = serializedObject.FindProperty("m_SerializeInlineMappingsOnOneLine");
Assert.IsNotNull(m_SerializeInlineMappingsOnOneLine);
m_PrefabRegularEnvironment = serializedObject.FindProperty("m_PrefabRegularEnvironment");
Assert.IsNotNull(m_PrefabRegularEnvironment);
m_PrefabUIEnvironment = serializedObject.FindProperty("m_PrefabUIEnvironment");
Assert.IsNotNull(m_PrefabUIEnvironment);
m_PrefabModeAllowAutoSave = serializedObject.FindProperty("m_PrefabModeAllowAutoSave");
Assert.IsNotNull(m_PrefabModeAllowAutoSave);
m_UseLegacyProbeSampleCount = serializedObject.FindProperty("m_UseLegacyProbeSampleCount");
Assert.IsNotNull(m_UseLegacyProbeSampleCount);
m_DisableCookiesInLightmapper = serializedObject.FindProperty("m_DisableCookiesInLightmapper");
Assert.IsNotNull(m_DisableCookiesInLightmapper);
m_SpritePackerMode = serializedObject.FindProperty("m_SpritePackerMode");
Assert.IsNotNull(m_SpritePackerMode);
m_SpritePackerCacheSize = serializedObject.FindProperty("m_SpritePackerCacheSize");
Assert.IsNotNull(m_SpritePackerCacheSize);
m_Bc7TextureCompressor = serializedObject.FindProperty("m_Bc7TextureCompressor");
Assert.IsNotNull(m_Bc7TextureCompressor);
m_EtcTextureCompressorBehavior = serializedObject.FindProperty("m_EtcTextureCompressorBehavior");
Assert.IsNotNull(m_EtcTextureCompressorBehavior);
m_EtcTextureFastCompressor = serializedObject.FindProperty("m_EtcTextureFastCompressor");
Assert.IsNotNull(m_EtcTextureFastCompressor);
m_EtcTextureNormalCompressor = serializedObject.FindProperty("m_EtcTextureNormalCompressor");
Assert.IsNotNull(m_EtcTextureNormalCompressor);
m_EtcTextureBestCompressor = serializedObject.FindProperty("m_EtcTextureBestCompressor");
Assert.IsNotNull(m_EtcTextureBestCompressor);
m_LineEndingsForNewScripts = serializedObject.FindProperty("m_LineEndingsForNewScripts");
Assert.IsNotNull(m_LineEndingsForNewScripts);
m_EnterPlayModeOptionsEnabled = serializedObject.FindProperty("m_EnterPlayModeOptionsEnabled");
Assert.IsNotNull(m_EnterPlayModeOptionsEnabled);
m_EnterPlayModeOptions = serializedObject.FindProperty("m_EnterPlayModeOptions");
Assert.IsNotNull(m_EnterPlayModeOptions);
m_ProjectGenerationIncludedExtensions = serializedObject.FindProperty("m_ProjectGenerationIncludedExtensions");
Assert.IsNotNull(m_ProjectGenerationIncludedExtensions);
m_ProjectGenerationRootNamespace = serializedObject.FindProperty("m_ProjectGenerationRootNamespace");
Assert.IsNotNull(m_ProjectGenerationRootNamespace);
m_CacheServerValidationMode = serializedObject.FindProperty("m_CacheServerValidationMode");
Assert.IsNotNull(m_ProjectGenerationRootNamespace);
m_CacheServerConnectionState = CacheServerConnectionState.Unknown;
m_InspectorUseIMGUIDefaultInspector = serializedObject.FindProperty("m_InspectorUseIMGUIDefaultInspector");
Assert.IsNotNull(m_InspectorUseIMGUIDefaultInspector);
m_IsGlobalSettings = EditorSettings.GetEditorSettings() == target;
}
public void OnDisable()
{
DevDeviceList.Changed -= OnDeviceListChanged;
AssetDatabase.RefreshSettings();
}
void OnDeviceListChanged()
{
BuildRemoteDeviceList();
}
void BuildRemoteDeviceList()
{
var devices = new List<DevDevice>();
var popupList = new List<PopupElement>();
devices.Add(DevDevice.none);
popupList.Add(new PopupElement("None"));
// TODO: move Android stuff to editor extension
devices.Add(new DevDevice("Any Android Device", "Any Android Device",
"virtual", "Android", DevDeviceState.Connected,
DevDeviceFeatures.RemoteConnection));
popupList.Add(new PopupElement("Any Android Device"));
foreach (var device in DevDeviceList.GetDevices())
{
bool supportsRemote = (device.features & DevDeviceFeatures.RemoteConnection) != 0;
if (!device.isConnected || !supportsRemote)
continue;
devices.Add(device);
popupList.Add(new PopupElement(device.name));
}
remoteDeviceList = devices.ToArray();
remoteDevicePopupList = popupList.ToArray();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
// GUI.enabled hack because we don't want some controls to be disabled if the EditorSettings.asset is locked
// since some of the controls are not dependent on the Editor Settings asset. Unfortunately, this assumes
// that the editor will only be disabled because of version control locking which may change in the future.
var editorEnabled = GUI.enabled;
// Remove Settings are taken from preferences and NOT from the EditorSettings Asset.
// Only show them when editing the "global" settings
if (m_IsGlobalSettings)
ShowUnityRemoteGUI(editorEnabled);
GUILayout.Space(10);
GUI.enabled = true;
GUILayout.Label(Content.assetSerialization, EditorStyles.boldLabel);
GUI.enabled = editorEnabled;
int index = m_SerializationMode.intValue;
CreatePopupMenu("Mode", serializationPopupList, index, SetAssetSerializationMode);
if (m_SerializationMode.intValue != (int)SerializationMode.ForceBinary)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_SerializeInlineMappingsOnOneLine, Content.textSerializeMappingsOnOneLine);
if (EditorGUI.EndChangeCheck() && m_IsGlobalSettings)
{
EditorSettings.serializeInlineMappingsOnOneLine = m_SerializeInlineMappingsOnOneLine.boolValue;
}
}
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUI.enabled = true;
GUILayout.Label(Content.buildPipelineHeader, EditorStyles.boldLabel);
GUI.enabled = editorEnabled;
if (GUILayout.Button(Content.ucbpLearnMore, EditorStyles.linkLabel))
{
var help = Help.FindHelpNamed("Build-MultiProcess");
Application.OpenURL(help);
}
GUILayout.EndHorizontal();
EditorGUI.BeginChangeCheck();
bool parallelAssetBundleBuilding = EditorBuildSettings.UseParallelAssetBundleBuilding;
parallelAssetBundleBuilding = EditorGUILayout.Toggle(Content.ucbpEnableAssetBundles, parallelAssetBundleBuilding);
if (EditorGUI.EndChangeCheck())
EditorBuildSettings.UseParallelAssetBundleBuilding = parallelAssetBundleBuilding;
if(parallelAssetBundleBuilding)
EditorGUILayout.HelpBox("Please review official documentation before building any content with these experimental improvements enabled. These improvements apply only to AssetBundles built with BuildPipeline.BuildAssetBundles() and do not apply to AssetBundles built with Scriptable Build Pipeline or Addressables.", MessageType.Info);
GUILayout.Space(10);
GUI.enabled = true;
GUILayout.Label(Content.defaultBehaviorMode, EditorStyles.boldLabel);
GUI.enabled = editorEnabled;
index = Mathf.Clamp(m_DefaultBehaviorMode.intValue, 0, behaviorPopupList.Length - 1);
CreatePopupMenu(Content.mode.text, behaviorPopupList, index, SetDefaultBehaviorMode);
DoAssetPipelineSettings();
// CacheServer is part asset and preferences. Only show UI in case of Global Settings editing.
if (m_IsGlobalSettings)
{
var wasEnabled = GUI.enabled;
GUI.enabled = true;
DoCacheServerSettings();
GUI.enabled = wasEnabled;
}
GUILayout.Space(10);
GUI.enabled = true;
GUILayout.Label(Content.prefabMode, EditorStyles.boldLabel);
GUI.enabled = editorEnabled;
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_PrefabModeAllowAutoSave, Content.prefabModeAllowAutoSave);
if (EditorGUI.EndChangeCheck() && m_IsGlobalSettings)
{
EditorSettings.prefabModeAllowAutoSave = m_PrefabModeAllowAutoSave.boolValue;
}
}
GUILayout.Label(Content.prefabModeEditingEnvironments, EditorStyles.label);
EditorGUI.indentLevel++;
{
EditorGUI.BeginChangeCheck();
var scene = m_PrefabRegularEnvironment.objectReferenceValue as SceneAsset;
scene = (SceneAsset)EditorGUILayout.ObjectField(Content.prefabModeRegularEnvironment, scene, typeof(SceneAsset), false);
if (EditorGUI.EndChangeCheck())
{
m_PrefabRegularEnvironment.objectReferenceValue = scene;
if (m_IsGlobalSettings)
{
EditorSettings.prefabRegularEnvironment = scene;
}
}
}
{
EditorGUI.BeginChangeCheck();
var scene = m_PrefabUIEnvironment.objectReferenceValue as SceneAsset;
scene = (SceneAsset)EditorGUILayout.ObjectField(Content.prefabModeUIEnvironment, scene, typeof(SceneAsset), false);
if (EditorGUI.EndChangeCheck())
{
m_PrefabUIEnvironment.objectReferenceValue = scene;
if (m_IsGlobalSettings)
{
EditorSettings.prefabUIEnvironment = scene;
}
}
}
EditorGUI.indentLevel--;
GUILayout.Space(10);
GUI.enabled = true;
GUILayout.Label(Content.graphics, EditorStyles.boldLabel);
GUI.enabled = editorEnabled;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_UseLegacyProbeSampleCount, Content.useLegacyProbeSampleCount);
if (EditorGUI.EndChangeCheck())
{
if (m_IsGlobalSettings)
EditorSettings.useLegacyProbeSampleCount = m_UseLegacyProbeSampleCount.boolValue;
EditorApplication.RequestRepaintAllViews();
}
var rect = EditorGUILayout.GetControlRect();
EditorGUI.BeginProperty(rect, Content.enableCookiesInLightmapper, m_DisableCookiesInLightmapper);
EditorGUI.BeginChangeCheck();
bool enableCookiesInLightmapperValue = !m_DisableCookiesInLightmapper.boolValue;
enableCookiesInLightmapperValue = EditorGUI.Toggle(rect, Content.enableCookiesInLightmapper, enableCookiesInLightmapperValue);
if (EditorGUI.EndChangeCheck())
{
m_DisableCookiesInLightmapper.boolValue = !enableCookiesInLightmapperValue;
if (m_IsGlobalSettings)
EditorSettings.enableCookiesInLightmapper = enableCookiesInLightmapperValue;
EditorApplication.RequestRepaintAllViews();
}
EditorGUI.EndProperty();
GUILayout.Space(10);
GUI.enabled = true;
GUILayout.Label(Content.spritePacker, EditorStyles.boldLabel);
GUI.enabled = editorEnabled;
// Legacy Packer has been deprecated.
index = Mathf.Clamp(m_SpritePackerMode.intValue - spritePackDeprecatedEnums, 0, spritePackerPopupList.Length - 1);
CreatePopupMenu(Content.mode.text, spritePackerPopupList, index, SetSpritePackerMode);
if (EditorSettings.spritePackerMode != SpritePackerMode.SpriteAtlasV2 && EditorSettings.spritePackerMode != SpritePackerMode.SpriteAtlasV2Build && EditorSettings.spritePackerMode != SpritePackerMode.Disabled)
EditorGUILayout.IntSlider(m_SpritePackerCacheSize, 1, 200, Content.spriteMaxCacheSize);
DoProjectGenerationSettings();
var compressorsChanged = DoTextureCompressorSettings();
DoLineEndingsSettings();
DoStreamingSettings();
DoShaderCompilationSettings();
DoEnterPlayModeSettings();
DoNumberingSchemeSettings();
DoEnterInspectorSettings();
serializedObject.ApplyModifiedProperties();
if (compressorsChanged)
AssetDatabase.Refresh(); // note: needs to be done after ApplyModifiedProperties call
}
private void DoProjectGenerationSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.cSharpProjectGeneration, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_ProjectGenerationIncludedExtensions, Content.additionalExtensionsToInclude);
if (EditorGUI.EndChangeCheck() && m_IsGlobalSettings)
{
EditorSettings.Internal_ProjectGenerationUserExtensions = m_ProjectGenerationIncludedExtensions.stringValue;
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_ProjectGenerationRootNamespace, Content.rootNamespace);
if (EditorGUI.EndChangeCheck() && m_IsGlobalSettings)
{
EditorSettings.projectGenerationRootNamespace = m_ProjectGenerationRootNamespace.stringValue;
}
}
private bool DoTextureCompressorSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.textureCompressors, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
// BC7
EditorGUILayout.Popup(m_Bc7TextureCompressor, bc7TextureCompressorOptions, Content.bc7Compressor);
// ETC
int index = Mathf.Clamp(m_IsGlobalSettings ? EditorSettings.etcTextureCompressorBehavior : m_EtcTextureCompressorBehavior.intValue, 0, etcTextureCompressorPopupList.Length - 1);
CreatePopupMenu(Content.etcCompressor.text, etcTextureCompressorPopupList, index, SetEtcTextureCompressorBehavior);
EditorGUI.indentLevel++;
EditorGUI.BeginDisabledGroup(index < 2);
index = Mathf.Clamp(m_IsGlobalSettings ? EditorSettings.etcTextureFastCompressor : m_EtcTextureFastCompressor.intValue, 0, etcTextureFastCompressorPopupList.Length - 1);
CreatePopupMenu(Content.fast.text, etcTextureFastCompressorPopupList, index, SetEtcTextureFastCompressor);
index = Mathf.Clamp(m_IsGlobalSettings ? EditorSettings.etcTextureNormalCompressor : m_EtcTextureNormalCompressor.intValue, 0, etcTextureNormalCompressorPopupList.Length - 1);
CreatePopupMenu(Content.normal.text, etcTextureNormalCompressorPopupList, index, SetEtcTextureNormalCompressor);
index = Mathf.Clamp(m_IsGlobalSettings ? EditorSettings.etcTextureBestCompressor : m_EtcTextureBestCompressor.intValue, 0, etcTextureBestCompressorPopupList.Length - 1);
CreatePopupMenu(Content.best.text, etcTextureBestCompressorPopupList, index, SetEtcTextureBestCompressor);
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel--;
return EditorGUI.EndChangeCheck();
}
private void DoAssetPipelineSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.assetPipeline, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
bool enableArtifactGarbageCollection = EditorUserSettings.artifactGarbageCollection;
enableArtifactGarbageCollection = EditorGUILayout.Toggle(Content.artifactGarbageCollection, enableArtifactGarbageCollection);
if (EditorGUI.EndChangeCheck())
EditorUserSettings.artifactGarbageCollection = enableArtifactGarbageCollection;
var overrideMode = GetCommandLineOverride(kRefreshImportModeKeyArgs);
if (overrideMode != null)
{
EditorGUILayout.HelpBox($"Refresh Import mode forced to {overrideMode} via command line argument. To use the mode specified here please restart Unity without the -refreshImportMode command line argument.", MessageType.Info, true);
}
using (new EditorGUI.DisabledScope(overrideMode != null))
{
GUILayout.BeginHorizontal();
var refreshMode = EditorSettings.refreshImportMode;
var parallelImportEnabledOld = refreshMode == AssetDatabase.RefreshImportMode.OutOfProcessPerQueue;
var parallelImportEnabledNew = EditorGUILayout.Toggle(Content.parallelImport, parallelImportEnabledOld);
if (parallelImportEnabledOld != parallelImportEnabledNew)
EditorSettings.refreshImportMode = parallelImportEnabledNew ? AssetDatabase.RefreshImportMode.OutOfProcessPerQueue : AssetDatabase.RefreshImportMode.InProcess;
if (GUILayout.Button(Content.parallelImportLearnMore, EditorStyles.linkLabel))
{
// Known issue with Docs redirect - versioned pages might not open offline docs
var help = Help.FindHelpNamed("ParallelImport");
Help.BrowseURL(help);
}
GUILayout.EndHorizontal();
}
var overrideDesiredCount = GetCommandLineOverride(kDesiredImportWorkerCountKeyArgs);
if (overrideDesiredCount != null)
{
EditorGUILayout.HelpBox($"Desired import worker count forced to {overrideDesiredCount} via command line argument. To use the worker count specified here please restart Unity without the -desiredWorkerCount command line argument.", MessageType.Info, true);
}
// This min/max worker count is enforced here and in EditorUserSettings.cpp
// Please keep them in sync.
const int minWorkerCount = 1;
const int maxWorkerCount = 128;
using (new EditorGUI.DisabledScope(overrideDesiredCount != null))
{
var oldCount = EditorUserSettings.desiredImportWorkerCount;
int newCount = EditorGUILayout.IntField(Content.desiredImportWorkerCount, oldCount);
newCount = Mathf.Clamp(newCount, minWorkerCount, maxWorkerCount);
if (oldCount != newCount)
EditorUserSettings.desiredImportWorkerCount = newCount;
}
var overrideStandbyCount = GetCommandLineOverride(kStandbyWorkerCountKeyArgs);
if (overrideStandbyCount != null)
{
EditorGUILayout.HelpBox($"Standby import worker count forced to {overrideStandbyCount} via command line argument. To use the standby worker count specified here please restart Unity without the -standbyWorkerCount command line argument.", MessageType.Info, true);
}
using (new EditorGUI.DisabledScope(overrideStandbyCount != null))
{
var oldCount = EditorUserSettings.standbyImportWorkerCount;
var newCount = EditorGUILayout.IntField(Content.standbyImportWorkerCount, oldCount);
int desiredWorkerCount = EditorUserSettings.desiredImportWorkerCount;
newCount = Mathf.Clamp(newCount, 0, desiredWorkerCount);
if (oldCount != newCount)
{
EditorUserSettings.standbyImportWorkerCount = newCount;
}
}
var overridekIdleWorkerShutdownDelay = GetCommandLineOverride(kIdleWorkerShutdownDelayKeyArgs);
if (overridekIdleWorkerShutdownDelay != null)
{
EditorGUILayout.HelpBox($"Idle import worker shutdown delay forced to {overridekIdleWorkerShutdownDelay} ms. via command line argument. To use the settings specified here please restart Unity without the -idleWorkerShutdownDelay command line argument.", MessageType.Info, true);
}
using (new EditorGUI.DisabledScope(overridekIdleWorkerShutdownDelay != null))
{
var oldSeconds = EditorUserSettings.idleImportWorkerShutdownDelayMilliseconds / 1000.0f;
var newSeconds = EditorGUILayout.FloatField(Content.idleWorkerShutdownDelay, oldSeconds);
newSeconds = Mathf.Max(0, newSeconds);
if (oldSeconds != newSeconds)
{
EditorUserSettings.idleImportWorkerShutdownDelayMilliseconds = (int)(newSeconds * 1000.0f);
}
}
EditorGUI.BeginChangeCheck();
bool referencedClipsExactNaming = EditorSettings.referencedClipsExactNaming;
referencedClipsExactNaming = EditorGUILayout.Toggle(Content.referencedClipsExactNaming, referencedClipsExactNaming);
if (EditorGUI.EndChangeCheck())
{
if (EditorUtility.DisplayDialog(
"Warning: Long Import Times",
"Changing this setting might result in several models being re-imported",
$"Proceed",
"Cancel"))
{
EditorSettings.referencedClipsExactNaming = referencedClipsExactNaming;
AssetDatabase.Refresh();
}
}
}
private void DoCacheServerSettings()
{
Assert.IsTrue(m_IsGlobalSettings);
GUILayout.Space(10);
GUILayout.BeginHorizontal();
GUILayout.Label(Content.cacheServer, EditorStyles.boldLabel);
if (GUILayout.Button(Content.cacheServerLearnMore, EditorStyles.linkLabel))
{
// Known issue with Docs redirect - versioned pages might not open offline docs
var help = Help.FindHelpNamed("UnityAccelerator");
Help.BrowseURL(help);
}
GUILayout.EndHorizontal();
int index = Mathf.Clamp((int)EditorSettings.cacheServerMode, 0, cacheServerModePopupList.Length - 1);
CreatePopupMenu(Content.mode.text, cacheServerModePopupList, index, SetCacheServerMode);
if (index != (int)CacheServerMode.Disabled)
{
bool isCacheServerEnabled = true;
if (index == (int)CacheServerMode.AsPreferences)
{
isCacheServerEnabled = false;
if (AssetPipelinePreferences.IsCacheServerEnabled)
{
var cacheServerIP = AssetPipelinePreferences.CacheServerAddress;
cacheServerIP = string.IsNullOrEmpty(cacheServerIP) ? "Not set in preferences" : cacheServerIP;
EditorGUILayout.HelpBox(cacheServerIP, MessageType.None, false);
}
else
{
EditorGUILayout.HelpBox("Disabled", MessageType.None, false);
}
}
if (isCacheServerEnabled)
{
var oldEndpoint = EditorSettings.cacheServerEndpoint;
var newEndpoint = EditorGUILayout.TextField(Content.cacheServerIPLabel, oldEndpoint);
if (newEndpoint != oldEndpoint)
{
EditorSettings.cacheServerEndpoint = newEndpoint;
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Check Connection", GUILayout.Width(150)))
{
var address = EditorSettings.cacheServerEndpoint.Split(':');
var ip = address[0];
UInt16 port = 0; // If 0, will use the default set port
if (address.Length == 2)
port = Convert.ToUInt16(address[1]);
bool canConnect = AssetDatabase.CanConnectToCacheServer(ip, port);
bool isConnected = AssetDatabase.IsConnectedToCacheServer();
if (canConnect)
m_CacheServerConnectionState = CacheServerConnectionState.Success;
else
m_CacheServerConnectionState = CacheServerConnectionState.Failure;
//We have to check if we're out of sync. here.
//If we can connect, but we're not connected, we need to update some UI
//If we CANNOT connect, but we are connected, we are out of sync. too and
//need to update some UI.
//Calling RefreshSettings here fixes that, and this check encapsulates the
//above 2 conditions.
if (canConnect != isConnected)
AssetDatabase.RefreshSettings();
}
GUILayout.Space(25);
switch (m_CacheServerConnectionState)
{
case CacheServerConnectionState.Success:
EditorGUILayout.HelpBox("Connection successful.", MessageType.Info, true);
break;
case CacheServerConnectionState.Failure:
EditorGUILayout.HelpBox("Connection failed.", MessageType.Warning, true);
break;
case CacheServerConnectionState.Unknown:
GUILayout.Space(44);
break;
}
EditorGUILayout.EndHorizontal();
var oldPrefix = EditorSettings.cacheServerNamespacePrefix;
var newPrefix = EditorGUILayout.TextField(Content.cacheServerNamespacePrefixLabel, oldPrefix);
if (newPrefix != oldPrefix)
{
EditorSettings.cacheServerNamespacePrefix = newPrefix;
}
EditorGUI.BeginChangeCheck();
bool enableDownload = EditorSettings.cacheServerEnableDownload;
enableDownload = EditorGUILayout.Toggle(Content.cacheServerEnableDownloadLabel, enableDownload);
if (EditorGUI.EndChangeCheck())
EditorSettings.cacheServerEnableDownload = enableDownload;
EditorGUI.BeginChangeCheck();
bool enableUpload = EditorSettings.cacheServerEnableUpload;
enableUpload = EditorGUILayout.Toggle(Content.cacheServerEnableUploadLabel, enableUpload);
if (EditorGUI.EndChangeCheck())
EditorSettings.cacheServerEnableUpload = enableUpload;
bool enableAuth = EditorSettings.cacheServerEnableAuth;
using (new EditorGUI.DisabledScope(enableAuth))
{
EditorGUI.BeginChangeCheck();
bool enableTls = EditorSettings.cacheServerEnableTls;
enableTls = EditorGUILayout.Toggle(Content.cacheServerEnableTlsLabel, enableTls);
if (EditorGUI.EndChangeCheck())
EditorSettings.cacheServerEnableTls = enableTls;
}
EditorGUI.BeginChangeCheck();
enableAuth = EditorGUILayout.Toggle(Content.cacheServerEnableAuthLabel, enableAuth);
if (EditorGUI.EndChangeCheck())
{
EditorSettings.cacheServerEnableAuth = enableAuth;
if (enableAuth)
{
EditorSettings.cacheServerEnableTls = true;
}
}
int validationIndex = Mathf.Clamp((int)EditorSettings.cacheServerValidationMode, 0, cacheServerValidationPopupList.Length - 1);
EditorGUILayout.Popup(m_CacheServerValidationMode, cacheServerValidationPopupList, Content.cacheServerValidationLabel);
var cacheServerDownloadBatchSizeOverride = GetCommandLineOverride(kCacheServerDownloadBatchSizeCmdArg);
if (cacheServerDownloadBatchSizeOverride != null)
EditorGUILayout.HelpBox($"Forced via command line argument. To use the setting, please restart Unity without the {kCacheServerDownloadBatchSizeCmdArg} command line argument.", MessageType.Info, true);
using (new EditorGUI.DisabledScope(cacheServerDownloadBatchSizeOverride != null))
{
var oldDownloadBatchSize = cacheServerDownloadBatchSizeOverride != null ? Int32.Parse(cacheServerDownloadBatchSizeOverride) : EditorSettings.cacheServerDownloadBatchSize;
var newDownloadBatchSize = EditorGUILayout.IntField(Content.cacheServerDownloadBatchSizeLabel, oldDownloadBatchSize);
newDownloadBatchSize = Mathf.Max(0, newDownloadBatchSize);
if (newDownloadBatchSize != oldDownloadBatchSize)
EditorSettings.cacheServerDownloadBatchSize = newDownloadBatchSize;
}
}
}
}
private static string GetCommandLineOverride(string key)
{
string address = null;
var argv = Environment.GetCommandLineArgs();
var index = Array.IndexOf(argv, key);
if (index >= 0 && argv.Length > index + 1)
address = argv[index + 1];
return address;
}
private void DoLineEndingsSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.lineEndingForNewScripts, EditorStyles.boldLabel);
int index = m_LineEndingsForNewScripts.intValue;
CreatePopupMenu(Content.mode.text, lineEndingsPopupList, index, SetLineEndingsForNewScripts);
}
private void DoStreamingSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.streamingSettings, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_EnableTextureStreamingInPlayMode, Content.enablePlayModeTextureStreaming);
EditorGUILayout.PropertyField(m_EnableTextureStreamingInEditMode, Content.enableEditModeTextureStreaming);
EditorGUILayout.PropertyField(m_EnableEditorAsyncCPUTextureLoading, Content.enableEditorAsyncCPUTextureLoading);
}
EditorSettings.NamingScheme m_PrevGoNamingScheme;
int m_PrevGoNamingDigits = -1;
string m_GoNamingHelpText;
static string GetNewName(string name, List<string> names)
{
var newName = ObjectNames.GetUniqueName(names.ToArray(), name);
names.Add(newName);
return newName;
}
void DoNumberingSchemeSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.numberingScheme, EditorStyles.boldLabel);
EditorGUILayout.IntPopup(m_GameObjectNamingScheme, Content.numberingSchemeNames, Content.numberingSchemeValues, Content.numberingHierarchyScheme);
EditorGUILayout.IntSlider(m_GameObjectNamingDigits, 1, 5, Content.numberingHierarchyDigits);
if (m_PrevGoNamingDigits != EditorSettings.gameObjectNamingDigits ||
m_PrevGoNamingScheme != EditorSettings.gameObjectNamingScheme ||
m_GoNamingHelpText == null)
{
var names = new List<string>();
var n1 = "Clap";
var n2 = "High5";
m_GoNamingHelpText = $"Instances of prefab '{n1}' will become '{GetNewName(n1, names)}', '{GetNewName(n1, names)}', '{GetNewName(n1, names)}'\nInstances of prefab '{n2}' will become '{GetNewName(n2, names)}', '{GetNewName(n2, names)}', '{GetNewName(n2, names)}'";
m_PrevGoNamingDigits = EditorSettings.gameObjectNamingDigits;
m_PrevGoNamingScheme = EditorSettings.gameObjectNamingScheme;
}
EditorGUILayout.HelpBox(m_GoNamingHelpText, MessageType.Info, true);
EditorGUILayout.PropertyField(m_AssetNamingUsesSpace, Content.numberingProjectSpace);
}
private void DoShaderCompilationSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.shaderCompilation, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_AsyncShaderCompilation, Content.asyncShaderCompilation);
}
private void DoEnterPlayModeSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.enterPlayModeSettings, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_EnterPlayModeOptionsEnabled, Content.enterPlayModeOptionsEnabled);
if (EditorGUI.EndChangeCheck() && m_IsGlobalSettings)
EditorSettings.enterPlayModeOptionsEnabled = m_EnterPlayModeOptionsEnabled.boolValue;
EditorGUI.indentLevel++;
using (new EditorGUI.DisabledScope(!m_EnterPlayModeOptionsEnabled.boolValue))
{
EnterPlayModeOptions options = (EnterPlayModeOptions)m_EnterPlayModeOptions.intValue;
options = ToggleEnterPlayModeOptions(options, EnterPlayModeOptions.DisableDomainReload, Content.enterPlayModeOptionsEnableDomainReload);
options = ToggleEnterPlayModeOptions(options, EnterPlayModeOptions.DisableSceneReload, Content.enterPlayModeOptionsEnableSceneReload);
if (m_EnterPlayModeOptions.intValue != (int)options)
{
m_EnterPlayModeOptions.intValue = (int)options;
if (m_IsGlobalSettings)
EditorSettings.enterPlayModeOptions = options;
}
}
EditorGUI.indentLevel--;
}
private void DoEnterInspectorSettings()
{
GUILayout.Space(10);
GUILayout.Label(Content.inspectorSettings, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_InspectorUseIMGUIDefaultInspector, Content.inspectorUseIMGUIDefaultInspector);
if (EditorGUI.EndChangeCheck() && m_IsGlobalSettings)
{
EditorSettings.inspectorUseIMGUIDefaultInspector = m_InspectorUseIMGUIDefaultInspector.boolValue;
PropertyEditor.ClearAndRebuildAll();
}
}
static int GetIndexById(DevDevice[] elements, string id, int defaultIndex)
{
for (int i = 0; i < elements.Length; i++)
if (elements[i].id == id)
return i;
return defaultIndex;
}
static int GetIndexById(PopupElement[] elements, string id, int defaultIndex)
{
for (int i = 0; i < elements.Length; i++)
if (elements[i].id == id)
return i;
return defaultIndex;
}
private void ShowUnityRemoteGUI(bool editorEnabled)
{
// This is a global Settings persisted in preferences
Assert.IsTrue(m_IsGlobalSettings);
GUI.enabled = true;
GUILayout.Label(Content.unityRemote, EditorStyles.boldLabel);
GUI.enabled = editorEnabled;
// Find selected device index
string id = EditorSettings.unityRemoteDevice;
// We assume first device to be "None", and default to it, hence 0
int index = GetIndexById(remoteDeviceList, id, 0);
var content = new GUIContent(remoteDevicePopupList[index].content);
var popupRect = GUILayoutUtility.GetRect(content, EditorStyles.popup);
popupRect = EditorGUI.PrefixLabel(popupRect, 0, Content.device);
if (EditorGUI.DropdownButton(popupRect, content, FocusType.Passive, EditorStyles.popup))
DoPopup(popupRect, remoteDevicePopupList, index, SetUnityRemoteDevice);
int compression = GetIndexById(remoteCompressionList, EditorSettings.unityRemoteCompression, 0);
content = new GUIContent(remoteCompressionList[compression].content);
popupRect = GUILayoutUtility.GetRect(content, EditorStyles.popup);
popupRect = EditorGUI.PrefixLabel(popupRect, 0, Content.compression);
if (EditorGUI.DropdownButton(popupRect, content, FocusType.Passive, EditorStyles.popup))
DoPopup(popupRect, remoteCompressionList, compression, SetUnityRemoteCompression);
int resolution = GetIndexById(remoteResolutionList, EditorSettings.unityRemoteResolution, 0);
content = new GUIContent(remoteResolutionList[resolution].content);
popupRect = GUILayoutUtility.GetRect(content, EditorStyles.popup);
popupRect = EditorGUI.PrefixLabel(popupRect, 0, Content.resolution);
if (EditorGUI.DropdownButton(popupRect, content, FocusType.Passive, EditorStyles.popup))
DoPopup(popupRect, remoteResolutionList, resolution, SetUnityRemoteResolution);
int joystickSource = GetIndexById(remoteJoystickSourceList, EditorSettings.unityRemoteJoystickSource, 0);
content = new GUIContent(remoteJoystickSourceList[joystickSource].content);
popupRect = GUILayoutUtility.GetRect(content, EditorStyles.popup);
popupRect = EditorGUI.PrefixLabel(popupRect, 0, Content.joystickSource);
if (EditorGUI.DropdownButton(popupRect, content, FocusType.Passive, EditorStyles.popup))
DoPopup(popupRect, remoteJoystickSourceList, joystickSource, SetUnityRemoteJoystickSource);
}
private void CreatePopupMenu(string title, PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
{
CreatePopupMenu(serializedObject, new GUIContent(title), elements[selectedIndex].content, elements, selectedIndex, func);
}
internal static void CreatePopupMenu(SerializedObject obj, GUIContent titleContent, GUIContent content, PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
{
var popupRect = GUILayoutUtility.GetRect(content, EditorStyles.popup);
popupRect = EditorGUI.PrefixLabel(popupRect, 0, titleContent);
if (EditorGUI.DropdownButton(popupRect, content, FocusType.Passive, EditorStyles.popup))
{
DoPopup(popupRect, elements, selectedIndex, data =>
{
func(data);
obj?.ApplyModifiedProperties();
});
}
}
internal static void DoPopup(Rect popupRect, PopupElement[] elements, int selectedIndex, GenericMenu.MenuFunction2 func)
{
GenericMenu menu = new GenericMenu();
for (int i = 0; i < elements.Length; i++)
{
var element = elements[i];
menu.AddItem(element.content, i == selectedIndex, func, i);
}
menu.DropDown(popupRect);
}
private void SetAssetSerializationMode(object data)
{
int popupIndex = (int)data;
if (m_SerializationMode.intValue == popupIndex) return;
if (!EditorUtility.DisplayDialog("Change Asset Serialization Mode?",
"Changing the serialization method for assets may force a reimport of some or all assets immediately in the project.\n\nAre you sure you wish to change the asset serialization mode?",
"Yes", "No")) return;
m_SerializationMode.intValue = popupIndex;
if (m_IsGlobalSettings)
EditorSettings.serializationMode = (SerializationMode)popupIndex;
}
private void SetUnityRemoteDevice(object data)
{
EditorSettings.unityRemoteDevice = remoteDeviceList[(int)data].id;
}
private void SetUnityRemoteCompression(object data)
{
EditorSettings.unityRemoteCompression = remoteCompressionList[(int)data].id;
}
private void SetUnityRemoteResolution(object data)
{
EditorSettings.unityRemoteResolution = remoteResolutionList[(int)data].id;
}
private void SetUnityRemoteJoystickSource(object data)
{
EditorSettings.unityRemoteJoystickSource = remoteJoystickSourceList[(int)data].id;
}
private void SetDefaultBehaviorMode(object data)
{
int popupIndex = (int)data;
m_DefaultBehaviorMode.intValue = popupIndex;
if (m_IsGlobalSettings)
{
EditorSettings.defaultBehaviorMode = (EditorBehaviorMode)popupIndex;
}
}
private void SetSpritePackerMode(object data)
{
int popupIndex = (int)data;
// Legacy Packer has been obsoleted (1 & 2). Disabled (0) is still valid.
popupIndex = (popupIndex != 0) ? (popupIndex + spritePackDeprecatedEnums) : 0;
m_SpritePackerMode.intValue = popupIndex;
if (m_IsGlobalSettings)
{
EditorSettings.spritePackerMode = (SpritePackerMode)popupIndex;
if (popupIndex >= (int)SpritePackerMode.SpriteAtlasV2)
{
UnityEditor.U2D.SpriteAtlasImporter.MigrateAllSpriteAtlases();
}
}
}
private void SetRefreshImportMode(object data)
{
EditorSettings.refreshImportMode = (AssetDatabase.RefreshImportMode)data;
}
private void SetCacheServerMode(object data)
{
EditorSettings.cacheServerMode = (CacheServerMode)data;
}
private void SetCacheServerAuthMode(object data)
{
EditorUserSettings.SetConfigValue("cacheServerAuthMode", $"{(int)data}");
}
private void SetCacheServerValidationMode(object data)
{
EditorSettings.cacheServerValidationMode = (CacheServerValidationMode)data;
}
private void SetEtcTextureCompressorBehavior(object data)
{
int newValue = (int)data;
if (m_IsGlobalSettings)
{
if (EditorSettings.etcTextureCompressorBehavior == newValue)
return;
EditorSettings.etcTextureCompressorBehavior = newValue;
if (newValue == 0)
EditorSettings.SetEtcTextureCompressorLegacyBehavior();
else
EditorSettings.SetEtcTextureCompressorDefaultBehavior();
}
else
{
m_EtcTextureCompressorBehavior.intValue = newValue;
}
}
private void SetEtcTextureFastCompressor(object data)
{
if (m_IsGlobalSettings)
EditorSettings.etcTextureFastCompressor = (int)data;
else
m_EtcTextureFastCompressor.intValue = (int)data;
}
private void SetEtcTextureNormalCompressor(object data)
{
if (m_IsGlobalSettings)
EditorSettings.etcTextureNormalCompressor = (int)data;
else
m_EtcTextureNormalCompressor.intValue = (int)data;
}
private void SetEtcTextureBestCompressor(object data)
{
if (m_IsGlobalSettings)
EditorSettings.etcTextureBestCompressor = (int)data;
else
m_EtcTextureBestCompressor.intValue = (int)data;
}
private void SetLineEndingsForNewScripts(object data)
{
int popupIndex = (int)data;
m_LineEndingsForNewScripts.intValue = popupIndex;
if (m_IsGlobalSettings)
EditorSettings.lineEndingsForNewScripts = (LineEndingsMode)popupIndex;
}
private EnterPlayModeOptions ToggleEnterPlayModeOptions(EnterPlayModeOptions options, EnterPlayModeOptions flag, GUIContent content)
{
bool isSet = ((options & flag) == flag);
isSet = EditorGUILayout.Toggle(content, !isSet);
if (isSet)
{
options &= ~flag;
}
else
{
options |= flag;
}
return options;
}
[SettingsProvider]
internal static SettingsProvider CreateProjectSettingsProvider()
{
var provider = AssetSettingsProvider.CreateProviderFromAssetPath(
"Project/Editor", "ProjectSettings/EditorSettings.asset",
SettingsProvider.GetSearchKeywordsFromGUIContentProperties<Content>());
return provider;
}
}
}
| UnityCsReference/Editor/Mono/Inspector/EditorSettingsInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/EditorSettingsInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 27703
} | 292 |
// 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 UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Linq;
using Object = UnityEngine.Object;
namespace UnityEditor
{
internal class LabelGUI
{
HashSet<Object> m_CurrentAssetsSet;
PopupList.InputData m_AssetLabels;
string m_ChangedLabel;
bool m_CurrentChanged = false;
bool m_ChangeWasAdd = false;
bool m_IgnoreNextAssetLabelsChangedCall = false;
static Action<Object> s_AssetLabelsForObjectChangedDelegates;
private static int s_MaxShownLabels = 10;
public void OnEnable()
{
s_AssetLabelsForObjectChangedDelegates += AssetLabelsChangedForObject;
EditorApplication.projectChanged += InvalidateLabels;
}
public void OnDisable()
{
s_AssetLabelsForObjectChangedDelegates -= AssetLabelsChangedForObject;
EditorApplication.projectChanged -= InvalidateLabels;
SaveLabels();
}
public void OnLostFocus()
{
SaveLabels();
}
public void InvalidateLabels()
{
m_AssetLabels = null;
m_CurrentAssetsSet = null;
}
public void AssetLabelsChangedForObject(Object asset)
{
if (!m_IgnoreNextAssetLabelsChangedCall && m_CurrentAssetsSet != null && m_CurrentAssetsSet.Contains(asset))
{
InvalidateLabels(); // someone else changed the labels for one of our selected assets, so invalidate cache
}
m_IgnoreNextAssetLabelsChangedCall = false;
}
public void SaveLabels()
{
if (m_CurrentChanged && m_AssetLabels != null && m_CurrentAssetsSet != null)
{
bool anyLabelsWereChanged = false;
foreach (var currentAsset in m_CurrentAssetsSet)
{
bool currentAssetWasChanged = false; // when multi-editing, some assets might e.g. already have the label that was added to all
string[] currentLabels = AssetDatabase.GetLabels(currentAsset);
List<string> currentLabelList = currentLabels.ToList<string>();
if (m_ChangeWasAdd)
{
if (!currentLabelList.Contains(m_ChangedLabel))
{
currentLabelList.Add(m_ChangedLabel);
currentAssetWasChanged = true;
}
}
else
{
if (currentLabelList.Contains(m_ChangedLabel))
{
currentLabelList.Remove(m_ChangedLabel);
currentAssetWasChanged = true;
}
}
if (currentAssetWasChanged)
{
AssetDatabase.SetLabels(currentAsset, currentLabelList.ToArray());
if (s_AssetLabelsForObjectChangedDelegates != null)
{
m_IgnoreNextAssetLabelsChangedCall = true;
s_AssetLabelsForObjectChangedDelegates(currentAsset);
}
anyLabelsWereChanged = true;
}
}
if (anyLabelsWereChanged)
EditorApplication.Internal_CallAssetLabelsHaveChanged();
m_CurrentChanged = false;
}
}
public void AssetLabelListCallback(PopupList.ListElement element)
{
m_ChangedLabel = element.text;
element.selected = !element.selected;
m_ChangeWasAdd = element.selected;
element.partiallySelected = false;
m_CurrentChanged = true;
SaveLabels();
InspectorWindow.RepaintAllInspectors();
}
public void InitLabelCache(Object[] assets)
{
HashSet<Object> newAssetSet = new HashSet<Object>(assets);
// Init only if new asset
if (m_CurrentAssetsSet == null || !m_CurrentAssetsSet.SetEquals(newAssetSet))
{
List<string> all;
List<string> partial;
GetLabelsForAssets(assets, out all, out partial);
m_AssetLabels = new PopupList.InputData
{
m_CloseOnSelection = false,
m_AllowCustom = true,
m_OnSelectCallback = AssetLabelListCallback,
m_MaxCount = 15,
m_SortAlphabetically = true
};
Dictionary<string, float> allLabels = AssetDatabase.GetAllLabels();
foreach (var pair in allLabels)
{
PopupList.ListElement element = m_AssetLabels.NewOrMatchingElement(pair.Key);
if (element.filterScore < pair.Value)
{
element.filterScore = pair.Value;
}
element.selected = all.Any(label => string.Equals(label, pair.Key, StringComparison.OrdinalIgnoreCase));
element.partiallySelected = partial.Any(label => string.Equals(label, pair.Key, StringComparison.OrdinalIgnoreCase));
}
}
m_CurrentAssetsSet = newAssetSet;
m_CurrentChanged = false;
}
public void OnLabelGUI(Object[] assets)
{
InitLabelCache(assets);
// For the label list as a whole
// The previous layouting means we've already lost a pixel to the left and couple at the top, so it is an attempt at horizontal padding: 3, verical padding: 5
// (the rounded sides of labels makes this look like the horizontal and vertical padding is the same)
float leftPadding = 1.0f;
float rightPadding = 2.0f;
float topPadding = 3.0f;
float bottomPadding = 5.0f;
GUIStyle labelButton = EditorStyles.assetLabelIcon;
float buttonWidth = labelButton.margin.left + labelButton.fixedWidth + rightPadding;
// Assumes we are already in a vertical layout
GUILayout.Space(topPadding);
// Create a rect to test how wide the label list can be
Rect widthProbeRect = GUILayoutUtility.GetRect(0, 10240, 0, 0);
widthProbeRect.width -= buttonWidth; // reserve some width for the button
EditorGUILayout.BeginHorizontal();
// Left padding
GUILayoutUtility.GetRect(leftPadding, leftPadding, 0, 0);
// Draw labels (fully selected)
DrawLabelList(false, widthProbeRect.xMax);
// Draw labels (partially selected)
DrawLabelList(true, widthProbeRect.xMax);
GUILayout.FlexibleSpace();
Rect r = GUILayoutUtility.GetRect(labelButton.fixedWidth, labelButton.fixedWidth, labelButton.fixedHeight + bottomPadding, labelButton.fixedHeight + bottomPadding);
r.x = widthProbeRect.xMax + labelButton.margin.left;
if (EditorGUI.DropdownButton(r, GUIContent.none, FocusType.Passive, labelButton))
{
PopupWindow.Show(r, new PopupList(m_AssetLabels));
}
EditorGUILayout.EndHorizontal();
}
private void DrawLabelList(bool partiallySelected, float xMax)
{
GUIStyle labelStyle = partiallySelected ? EditorStyles.assetLabelPartial : EditorStyles.assetLabel;
Event evt = Event.current;
foreach (GUIContent content in (from i in m_AssetLabels.m_ListElements where (partiallySelected ? i.partiallySelected : i.selected) orderby i.text.ToLower() select i.m_Content).Take(s_MaxShownLabels))
{
Rect rt = GUILayoutUtility.GetRect(content, labelStyle);
if (Event.current.type == EventType.Repaint && rt.xMax >= xMax)
break;
GUI.Label(rt, content, labelStyle);
if (rt.xMax <= xMax && evt.type == EventType.MouseDown && rt.Contains(evt.mousePosition) && evt.button == 0 && GUI.enabled)
{
evt.Use();
rt.x = xMax;
PopupWindow.Show(rt, new PopupList(m_AssetLabels, content.text));
}
}
}
private void GetLabelsForAssets(Object[] assets, out List<string> all, out List<string> partial)
{
all = new List<string>();
partial = new List<string>();
Dictionary<string, int> labelAssetCount = new Dictionary<string, int>();
foreach (Object asset in assets)
{
string[] currentLabels = AssetDatabase.GetLabels(asset);
foreach (string label in currentLabels)
{
labelAssetCount[label] = labelAssetCount.ContainsKey(label) ? labelAssetCount[label] + 1 : 1;
}
}
foreach (KeyValuePair<string, int> entry in labelAssetCount)
{
var list = (entry.Value == assets.Length) ? all : partial;
list.Add(entry.Key);
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/LabelGUI.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/LabelGUI.cs",
"repo_id": "UnityCsReference",
"token_count": 4708
} | 293 |
// 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.Rendering;
using System;
using System.Collections.Generic;
namespace UnityEditor
{
public partial class MaterialEditor
{
public const int kMiniTextureFieldLabelIndentLevel = 2;
const float kSpaceBetweenFlexibleAreaAndField = 5f;
const float kQueuePopupWidth = 100f;
const float kCustomQueuePopupWidth = kQueuePopupWidth + 15f;
private bool isPrefabAsset
{
get
{
if (m_SerializedObject == null || m_SerializedObject.targetObject == null)
return false;
return PrefabUtility.IsPartOfPrefabAsset(m_SerializedObject.targetObject);
}
}
// Field for editing render queue value, with an automatically calculated rect
public void RenderQueueField()
{
Rect r = GetControlRectForSingleLine();
RenderQueueField(r);
}
// Field for editing render queue value, with an explicit rect
public void RenderQueueField(Rect r)
{
BeginProperty(r, MaterialSerializedProperty.CustomRenderQueue, targets);
var mat = targets[0] as Material;
int curRawQueue = mat.rawRenderQueue;
int curDisplayQueue = mat.renderQueue; // this gets final queue value used for rendering, taking shader's queue into account
// Figure out if we're using one of common queues, or a custom one
GUIContent[] queueNames = null;
int[] queueValues = null;
float labelWidth;
// If we use queue value that is not available, lets switch to the custom one
bool useCustomQueue = Array.IndexOf(Styles.queueValues, curRawQueue) < 0;
if (useCustomQueue)
{
// It is a big chance that we already have this custom queue value available
bool updateNewCustomQueueValue = Array.IndexOf(Styles.customQueueNames, curRawQueue) < 0;
if (updateNewCustomQueueValue)
{
int targetQueueIndex = CalculateClosestQueueIndexToValue(curRawQueue);
string targetQueueName = Styles.queueNames[targetQueueIndex].text;
int targetQueueValueOverflow = curRawQueue - Styles.queueValues[targetQueueIndex];
string newQueueName = string.Format(
targetQueueValueOverflow > 0 ? "{0}+{1}" : "{0}{1}",
targetQueueName,
targetQueueValueOverflow);
Styles.customQueueNames[Styles.kCustomQueueIndex].text = newQueueName;
Styles.customQueueValues[Styles.kCustomQueueIndex] = curRawQueue;
}
queueNames = Styles.customQueueNames;
queueValues = Styles.customQueueValues;
labelWidth = kCustomQueuePopupWidth;
}
else
{
queueNames = Styles.queueNames;
queueValues = Styles.queueValues;
labelWidth = kQueuePopupWidth;
}
// We want the custom queue number field to line up with thumbnails & other value fields
// (on the right side), and common queues popup to be on the left of that.
float oldLabelWidth = EditorGUIUtility.labelWidth;
float oldFieldWidth = EditorGUIUtility.fieldWidth;
SetDefaultGUIWidths();
EditorGUIUtility.labelWidth -= labelWidth;
Rect popupRect = r;
popupRect.width -= EditorGUIUtility.fieldWidth + 2;
Rect numberRect = r;
numberRect.xMin = numberRect.xMax - EditorGUIUtility.fieldWidth;
numberRect.height = EditorGUI.kSingleLineHeight;
// Queues popup
int curPopupValue = curRawQueue;
int newPopupValue = EditorGUI.IntPopup(popupRect, Styles.queueLabel, curRawQueue, queueNames, queueValues);
// Custom queue field
int newDisplayQueue = EditorGUI.DelayedIntField(numberRect, curDisplayQueue);
// If popup or custom field changed, set the new queue
if (curPopupValue != newPopupValue || curDisplayQueue != newDisplayQueue)
{
RegisterPropertyChangeUndo("Render Queue");
// Take the value from the number field,
int newQueue = newDisplayQueue;
// But if it's the popup that was changed
if (newPopupValue != curPopupValue)
newQueue = newPopupValue;
newQueue = Mathf.Clamp(newQueue, -1, 5000); // clamp to valid queue ranges
// Change the material queues
foreach (var m in targets)
{
((Material)m).renderQueue = newQueue;
}
}
EditorGUIUtility.labelWidth = oldLabelWidth;
EditorGUIUtility.fieldWidth = oldFieldWidth;
EndProperty();
}
public bool EnableInstancingField()
{
if (!ShaderUtil.HasInstancing(m_Shader))
return false;
Rect r = GetControlRectForSingleLine();
EnableInstancingField(r);
return true;
}
public void EnableInstancingField(Rect r)
{
BeginProperty(r, MaterialSerializedProperty.EnableInstancingVariants, targets);
using (var scope = new EditorGUI.ChangeCheckScope())
{
bool enableInstancing = EditorGUI.Toggle(r, Styles.enableInstancingLabel, (targets[0] as Material).enableInstancing);
if (scope.changed)
{
foreach (Material material in targets)
material.enableInstancing = enableInstancing;
}
}
EndProperty();
}
public bool IsInstancingEnabled()
{
return ShaderUtil.HasInstancing(m_Shader) && (targets[0] as Material).enableInstancing;
}
public bool DoubleSidedGIField()
{
Rect r = GetControlRectForSingleLine();
BeginProperty(r, MaterialSerializedProperty.DoubleSidedGI, targets);
EditorGUI.BeginChangeCheck();
bool doubleSidedGI = EditorGUI.Toggle(r, Styles.doubleSidedGILabel, (targets[0] as Material).doubleSidedGI);
if (EditorGUI.EndChangeCheck())
{
foreach (Material material in targets)
material.doubleSidedGI = doubleSidedGI;
}
EndProperty();
return true;
}
private int CalculateClosestQueueIndexToValue(int requestedValue)
{
int bestCloseByDiff = int.MaxValue;
int result = 1;
for (int i = 1; i < Styles.queueValues.Length; i++)
{
int queueValue = Styles.queueValues[i];
int closeByDiff = Mathf.Abs(queueValue - requestedValue);
if (closeByDiff < bestCloseByDiff)
{
result = i;
bestCloseByDiff = closeByDiff;
}
}
return result;
}
public Rect TexturePropertySingleLine(GUIContent label, MaterialProperty textureProp)
{
return TexturePropertySingleLine(label, textureProp, null, null);
}
public Rect TexturePropertySingleLine(GUIContent label, MaterialProperty textureProp, MaterialProperty extraProperty1)
{
return TexturePropertySingleLine(label, textureProp, extraProperty1, null);
}
// Mini texture slot, with two extra controls on the same line (allocates rect in GUILayout)
// Have up to 3 controls on one line
public Rect TexturePropertySingleLine(GUIContent label, MaterialProperty textureProp, MaterialProperty extraProperty1, MaterialProperty extraProperty2)
{
Rect r = GetControlRectForSingleLine();
bool hasExtraProp = !(extraProperty1 == null && extraProperty2 == null);
if (hasExtraProp) BeginProperty(r, textureProp);
if (extraProperty1 != null) BeginProperty(r, extraProperty1);
if (extraProperty2 != null) BeginProperty(r, extraProperty2);
TexturePropertyMiniThumbnail(r, textureProp, label.text, label.tooltip);
// No extra properties: early out
if (!hasExtraProp)
return r;
// Temporarily reset the indent level as it was already used earlier to compute the positions of the layout items. See issue 946082.
int oldIndentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
// One extra property
if (extraProperty1 == null || extraProperty2 == null)
{
var prop = extraProperty1 ?? extraProperty2;
ExtraPropertyAfterTexture(GetRectAfterLabelWidth(r), prop, false);
}
else // Two extra properties
{
if (extraProperty1.type == MaterialProperty.PropType.Color)
{
ExtraPropertyAfterTexture(GetFlexibleRectBetweenFieldAndRightEdge(r), extraProperty2);
ExtraPropertyAfterTexture(GetLeftAlignedFieldRect(r), extraProperty1);
}
else
{
ExtraPropertyAfterTexture(GetRightAlignedFieldRect(r), extraProperty2);
ExtraPropertyAfterTexture(GetFlexibleRectBetweenLabelAndField(r), extraProperty1);
}
}
// Restore the indent level
EditorGUI.indentLevel = oldIndentLevel;
if (extraProperty2 != null) EndProperty();
if (extraProperty1 != null) EndProperty();
if (hasExtraProp) EndProperty();
return r;
}
[Obsolete("Use TexturePropertyWithHDRColor(GUIContent label, MaterialProperty textureProp, MaterialProperty colorProperty, bool showAlpha)")]
public Rect TexturePropertyWithHDRColor(
GUIContent label, MaterialProperty textureProp, MaterialProperty colorProperty, ColorPickerHDRConfig hdrConfig, bool showAlpha
)
{
return TexturePropertyWithHDRColor(label, textureProp, colorProperty, showAlpha);
}
public Rect TexturePropertyWithHDRColor(GUIContent label, MaterialProperty textureProp, MaterialProperty colorProperty, bool showAlpha)
{
Rect r = GetControlRectForSingleLine();
bool isColorProperty = colorProperty.type == MaterialProperty.PropType.Color;
if (isColorProperty)
{
BeginProperty(r, textureProp);
BeginProperty(r, colorProperty);
}
TexturePropertyMiniThumbnail(r, textureProp, label.text, label.tooltip);
if (!isColorProperty)
{
Debug.LogError("Assuming MaterialProperty.PropType.Color (was " + colorProperty.type + ")");
return r;
}
// Temporarily reset the indent level. See issue 946082.
int oldIndentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
BeginAnimatedCheck(r, colorProperty);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = colorProperty.hasMixedValue;
Color newValue = EditorGUI.ColorField(GetRectAfterLabelWidth(r), GUIContent.none, colorProperty.colorValue, true, showAlpha, true);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
colorProperty.colorValue = newValue;
EndAnimatedCheck();
// Restore the indent level
EditorGUI.indentLevel = oldIndentLevel;
if (isColorProperty)
{
EndProperty();
EndProperty();
}
return r;
}
public Rect TexturePropertyTwoLines(GUIContent label, MaterialProperty textureProp, MaterialProperty extraProperty1, GUIContent label2, MaterialProperty extraProperty2)
{
// If not using the second extra property then use the single line version as
// the first extra property is always inlined with the the texture slot
if (extraProperty2 == null)
{
return TexturePropertySingleLine(label, textureProp, extraProperty1);
}
Rect r = GetControlRectForSingleLine();
BeginProperty(r, textureProp);
BeginProperty(r, extraProperty1);
TexturePropertyMiniThumbnail(r, textureProp, label.text, label.tooltip);
// Temporarily reset the indent level. See issue 946082.
int oldIndentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
// First extra control on the same line as the texture
Rect r1 = GetRectAfterLabelWidth(r);
if (extraProperty1.type == MaterialProperty.PropType.Color)
r1 = GetLeftAlignedFieldRect(r);
ExtraPropertyAfterTexture(r1, extraProperty1);
EndProperty();
EndProperty();
// New line for extraProperty2
Rect r2 = GetControlRectForSingleLine();
ShaderProperty(r2, extraProperty2, label2.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
// Restore the indent level
EditorGUI.indentLevel = oldIndentLevel;
// Return total rect
r.height += r2.height;
return r;
}
Rect GetControlRectForSingleLine()
{
const float extraSpacing = 2f; // The shader properties needs a little more vertical spacing due to the mini texture field (looks cramped without)
return EditorGUILayout.GetControlRect(true, EditorGUI.kSingleLineHeight + extraSpacing, EditorStyles.layerMaskField);
}
void ExtraPropertyAfterTexture(Rect r, MaterialProperty property, bool adjustLabelWidth = true)
{
if (adjustLabelWidth && (property.type == MaterialProperty.PropType.Float || property.type == MaterialProperty.PropType.Color) && r.width > EditorGUIUtility.fieldWidth)
{
// We want color fields and float fields to have same width as EditorGUIUtility.fieldWidth
// so controls aligns vertically.
// This also makes us able to have a draggable area in front of the float fields. We therefore ensures
// the property has a label (here we use a whitespace) and adjust label width.
float oldLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = r.width - EditorGUIUtility.fieldWidth;
ShaderProperty(r, property, " ");
EditorGUIUtility.labelWidth = oldLabelWidth;
return;
}
ShaderProperty(r, property, string.Empty);
}
static public Rect GetRightAlignedFieldRect(Rect r)
{
return new Rect(r.xMax - EditorGUIUtility.fieldWidth, r.y, EditorGUIUtility.fieldWidth, EditorGUIUtility.singleLineHeight);
}
static public Rect GetLeftAlignedFieldRect(Rect r)
{
return new Rect(r.x + EditorGUIUtility.labelWidth, r.y, EditorGUIUtility.fieldWidth, EditorGUIUtility.singleLineHeight);
}
static public Rect GetFlexibleRectBetweenLabelAndField(Rect r)
{
return new Rect(r.x + EditorGUIUtility.labelWidth, r.y, r.width - EditorGUIUtility.labelWidth - EditorGUIUtility.fieldWidth - kSpaceBetweenFlexibleAreaAndField, EditorGUIUtility.singleLineHeight);
}
static public Rect GetFlexibleRectBetweenFieldAndRightEdge(Rect r)
{
Rect r2 = GetRectAfterLabelWidth(r);
r2.xMin += EditorGUIUtility.fieldWidth + kSpaceBetweenFlexibleAreaAndField;
return r2;
}
static public Rect GetRectAfterLabelWidth(Rect r)
{
return new Rect(r.x + EditorGUIUtility.labelWidth, r.y, r.width - EditorGUIUtility.labelWidth, EditorGUIUtility.singleLineHeight);
}
static internal System.Type GetTextureTypeFromDimension(TextureDimension dim)
{
switch (dim)
{
case TextureDimension.Tex2D: return typeof(Texture); // common use case is RenderTextures too, so return base class
case TextureDimension.Cube: return typeof(Cubemap);
case TextureDimension.Tex3D: return typeof(Texture3D);
case TextureDimension.Tex2DArray: return typeof(Texture2DArray);
case TextureDimension.CubeArray: return typeof(CubemapArray);
case TextureDimension.Any: return typeof(Texture);
default: return null; // Unknown, None etc.
}
}
}
} // namespace UnityEditor
| UnityCsReference/Editor/Mono/Inspector/MaterialEditorGUIHelpers.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/MaterialEditorGUIHelpers.cs",
"repo_id": "UnityCsReference",
"token_count": 7529
} | 294 |
// 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.Expressions;
using System.Reflection;
using UnityEditor.IMGUI.Controls;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor
{
internal class UniformBoxBoundsHandle : SphereBoundsHandle
{
internal UniformBoxBoundsHandle() : base() {}
protected override void DrawWireframe()
{
Handles.DrawWireCube(center, GetSize());
}
}
[CustomEditor(typeof(ParticleSystemForceField))]
[CanEditMultipleObjects]
internal class ParticleSystemForceFieldInspector : Editor
{
private static readonly SphereBoundsHandle s_SphereBoundsHandle = new SphereBoundsHandle();
private static readonly UniformBoxBoundsHandle s_BoxBoundsHandle = new UniformBoxBoundsHandle();
private static PrefColor s_GizmoColor = new PrefColor("Particle System/Force Field Gizmos", 148f / 255f, 229f / 255f, 1f, 0.9f);
private static readonly Color s_GizmoFocusTint = new Color(0.7f, 0.7f, 0.7f, 1.0f);
private static PropertyInfo s_StartRangeProperty = typeof(ParticleSystemForceField).GetProperty("startRange");
private static PropertyInfo s_EndRangeProperty = typeof(ParticleSystemForceField).GetProperty("endRange");
private static PropertyInfo s_GravityFocusProperty = typeof(ParticleSystemForceField).GetProperty("gravityFocus");
private static PropertyInfo s_LengthProperty = typeof(ParticleSystemForceField).GetProperty("length");
private static readonly string s_UndoString = L10n.Tr("Modify {0}");
private SerializedProperty m_Shape;
private SerializedProperty m_StartRange;
private SerializedProperty m_EndRange;
private SerializedProperty m_Length;
private SerializedProperty m_DirectionX;
private SerializedProperty m_DirectionY;
private SerializedProperty m_DirectionZ;
private SerializedProperty m_Gravity;
private SerializedProperty m_GravityFocus;
private SerializedProperty m_RotationSpeed;
private SerializedProperty m_RotationAttraction;
private SerializedProperty m_RotationRandomness;
private SerializedProperty m_Drag;
private SerializedProperty m_MultiplyDragByParticleSize;
private SerializedProperty m_MultiplyDragByParticleVelocity;
private SerializedProperty m_VectorField;
private SerializedProperty m_VectorFieldSpeed;
private SerializedProperty m_VectorFieldAttraction;
MinMaxCurvePropertyDrawer m_DirectionDrawerX;
MinMaxCurvePropertyDrawer m_DirectionDrawerY;
MinMaxCurvePropertyDrawer m_DirectionDrawerZ;
MinMaxCurvePropertyDrawer m_GravityDrawer;
MinMaxCurvePropertyDrawer m_RotationSpeedDrawer;
MinMaxCurvePropertyDrawer m_RotationAttractionDrawer;
MinMaxCurvePropertyDrawer m_DragDrawer;
MinMaxCurvePropertyDrawer m_VectorFieldSpeedDrawer;
MinMaxCurvePropertyDrawer m_VectorFieldAttractionDrawer;
private class Styles
{
public static GUIContent shape = EditorGUIUtility.TrTextContent("Shape", "The bounding shape that forces are applied inside.");
public static GUIContent startRange = EditorGUIUtility.TrTextContent("Start Range", "The inner extent of the bounding shape.");
public static GUIContent endRange = EditorGUIUtility.TrTextContent("End Range", "The outer extent of the bounding shape.");
public static GUIContent length = EditorGUIUtility.TrTextContent("Length", "The length of the cylinder.");
public static GUIContent directionX = EditorGUIUtility.TrTextContent("X", "The force to apply along the X axis.");
public static GUIContent directionY = EditorGUIUtility.TrTextContent("Y", "The force to apply along the Y axis.");
public static GUIContent directionZ = EditorGUIUtility.TrTextContent("Z", "The force to apply along the Z axis.");
public static GUIContent gravity = EditorGUIUtility.TrTextContent("Strength", "The strength of the gravity effect.");
public static GUIContent gravityFocus = EditorGUIUtility.TrTextContent("Focus", "Choose a band within the volume that particles will be attracted towards.");
public static GUIContent rotationSpeed = EditorGUIUtility.TrTextContent("Speed", "The speed at which particles are propelled around the vortex.");
public static GUIContent rotationAttraction = EditorGUIUtility.TrTextContent("Attraction", "Controls how strongly particles are dragged into the vortex motion.");
public static GUIContent rotationRandomness = EditorGUIUtility.TrTextContent("Randomness", "Propel particles around random axes of the shape.");
public static GUIContent drag = EditorGUIUtility.TrTextContent("Strength", "The strength of the drag effect.");
public static GUIContent multiplyDragByParticleSize = EditorGUIUtility.TrTextContent("Multiply by Size", "Adjust the drag based on the size of the particles.");
public static GUIContent multiplyDragByParticleVelocity = EditorGUIUtility.TrTextContent("Multiply by Velocity", "Adjust the drag based on the velocity of the particles.");
public static GUIContent vectorField = EditorGUIUtility.TrTextContent("Volume Texture", "The texture used for the vector field.");
public static GUIContent vectorFieldSpeed = EditorGUIUtility.TrTextContent("Speed", "The speed multiplier applied to particles traveling through the vector field.");
public static GUIContent vectorFieldAttraction = EditorGUIUtility.TrTextContent("Attraction", "Controls how strongly particles are dragged into the vector field motion.");
public static GUIContent[] shapeOptions =
{
EditorGUIUtility.TrTextContent("Sphere"),
EditorGUIUtility.TrTextContent("Hemisphere"),
EditorGUIUtility.TrTextContent("Cylinder"),
EditorGUIUtility.TrTextContent("Box")
};
public static GUIContent shapeHeading = EditorGUIUtility.TrTextContent("Shape");
public static GUIContent directionHeading = EditorGUIUtility.TrTextContent("Direction");
public static GUIContent gravityHeading = EditorGUIUtility.TrTextContent("Gravity");
public static GUIContent rotationHeading = EditorGUIUtility.TrTextContent("Rotation");
public static GUIContent dragHeading = EditorGUIUtility.TrTextContent("Drag");
public static GUIContent vectorFieldHeading = EditorGUIUtility.TrTextContent("Vector Field");
}
void OnEnable()
{
m_Shape = serializedObject.FindProperty("m_Parameters.m_Shape");
m_StartRange = serializedObject.FindProperty("m_Parameters.m_StartRange");
m_EndRange = serializedObject.FindProperty("m_Parameters.m_EndRange");
m_Length = serializedObject.FindProperty("m_Parameters.m_Length");
m_DirectionX = serializedObject.FindProperty("m_Parameters.m_DirectionCurveX");
m_DirectionY = serializedObject.FindProperty("m_Parameters.m_DirectionCurveY");
m_DirectionZ = serializedObject.FindProperty("m_Parameters.m_DirectionCurveZ");
m_Gravity = serializedObject.FindProperty("m_Parameters.m_GravityCurve");
m_GravityFocus = serializedObject.FindProperty("m_Parameters.m_GravityFocus");
m_RotationSpeed = serializedObject.FindProperty("m_Parameters.m_RotationSpeedCurve");
m_RotationAttraction = serializedObject.FindProperty("m_Parameters.m_RotationAttractionCurve");
m_RotationRandomness = serializedObject.FindProperty("m_Parameters.m_RotationRandomness");
m_Drag = serializedObject.FindProperty("m_Parameters.m_DragCurve");
m_MultiplyDragByParticleSize = serializedObject.FindProperty("m_Parameters.m_MultiplyDragByParticleSize");
m_MultiplyDragByParticleVelocity = serializedObject.FindProperty("m_Parameters.m_MultiplyDragByParticleVelocity");
m_VectorField = serializedObject.FindProperty("m_Parameters.m_VectorField");
m_VectorFieldSpeed = serializedObject.FindProperty("m_Parameters.m_VectorFieldSpeedCurve");
m_VectorFieldAttraction = serializedObject.FindProperty("m_Parameters.m_VectorFieldAttractionCurve");
m_DirectionDrawerX = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_DirectionDrawerY = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_DirectionDrawerZ = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_GravityDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_RotationSpeedDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_RotationAttractionDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_DragDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_VectorFieldSpeedDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
m_VectorFieldAttractionDrawer = new MinMaxCurvePropertyDrawer() { isNativeProperty = true, xAxisLabel = "distance" };
}
static void DrawMinMaxCurveField(SerializedProperty property, MinMaxCurvePropertyDrawer drawer, GUIContent label)
{
var rect = EditorGUILayout.GetControlRect(false, drawer.GetPropertyHeight(property, label));
EditorGUI.BeginProperty(rect, label, property);
drawer.OnGUI(rect, property, label);
EditorGUI.EndProperty();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUILayout.Label(Styles.shapeHeading, EditorStyles.boldLabel);
EditorGUI.showMixedValue = m_Shape.hasMultipleDifferentValues;
var shapeRect = EditorGUILayout.GetControlRect(true);
EditorGUI.Popup(shapeRect, m_Shape, Styles.shapeOptions, Styles.shape);
EditorGUILayout.PropertyField(m_StartRange, Styles.startRange);
EditorGUILayout.PropertyField(m_EndRange, Styles.endRange);
if (m_Shape.intValue == (int)ParticleSystemForceFieldShape.Cylinder)
EditorGUILayout.PropertyField(m_Length, Styles.length);
EditorGUILayout.Space();
GUILayout.Label(Styles.directionHeading, EditorStyles.boldLabel);
DrawMinMaxCurveField(m_DirectionX, m_DirectionDrawerX, Styles.directionX);
DrawMinMaxCurveField(m_DirectionY, m_DirectionDrawerY, Styles.directionY);
DrawMinMaxCurveField(m_DirectionZ, m_DirectionDrawerZ, Styles.directionZ);
EditorGUILayout.Space();
EditorGUILayout.Space();
GUILayout.Label(Styles.gravityHeading, EditorStyles.boldLabel);
DrawMinMaxCurveField(m_Gravity, m_GravityDrawer, Styles.gravity);
EditorGUILayout.PropertyField(m_GravityFocus, Styles.gravityFocus);
EditorGUILayout.Space();
GUILayout.Label(Styles.rotationHeading, EditorStyles.boldLabel);
DrawMinMaxCurveField(m_RotationSpeed, m_RotationSpeedDrawer, Styles.rotationSpeed);
DrawMinMaxCurveField(m_RotationAttraction, m_RotationAttractionDrawer, Styles.rotationAttraction);
EditorGUILayout.PropertyField(m_RotationRandomness, Styles.rotationRandomness);
EditorGUILayout.Space();
GUILayout.Label(Styles.dragHeading, EditorStyles.boldLabel);
DrawMinMaxCurveField(m_Drag, m_DragDrawer, Styles.drag);
EditorGUILayout.PropertyField(m_MultiplyDragByParticleSize, Styles.multiplyDragByParticleSize);
EditorGUILayout.PropertyField(m_MultiplyDragByParticleVelocity, Styles.multiplyDragByParticleVelocity);
EditorGUILayout.Space();
GUILayout.Label(Styles.vectorFieldHeading, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_VectorField, Styles.vectorField);
DrawMinMaxCurveField(m_VectorFieldSpeed, m_VectorFieldSpeedDrawer, Styles.vectorFieldSpeed);
DrawMinMaxCurveField(m_VectorFieldAttraction, m_VectorFieldAttractionDrawer, Styles.vectorFieldAttraction);
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
}
void OnSceneGUI()
{
if (!target)
return;
EditorGUI.BeginChangeCheck();
ParticleSystemForceField ff = (ParticleSystemForceField)target;
DrawHandle(ff);
if (EditorGUI.EndChangeCheck())
Repaint();
}
public static void DrawHandle(ParticleSystemForceField ff)
{
using (new Handles.DrawingScope(s_GizmoColor, ff.transform.localToWorldMatrix))
{
ParticleSystemForceFieldShape forceShape = ff.shape;
if (forceShape == ParticleSystemForceFieldShape.Sphere)
{
DrawSphere(s_EndRangeProperty, ff);
if (ff.startRange > 0.0f)
DrawSphere(s_StartRangeProperty, ff);
if (ff.gravityFocus > 0.0f)
{
using (new Handles.DrawingScope(s_GizmoColor * s_GizmoFocusTint))
DrawSphere(s_GravityFocusProperty, ff, ff.endRange);
}
}
else if (forceShape == ParticleSystemForceFieldShape.Hemisphere)
{
DrawHemisphere(s_EndRangeProperty, ff);
if (ff.startRange > 0.0f)
DrawHemisphere(s_StartRangeProperty, ff);
if (ff.gravityFocus > 0.0f)
{
using (new Handles.DrawingScope(s_GizmoColor * s_GizmoFocusTint))
DrawHemisphere(s_GravityFocusProperty, ff, ff.endRange);
}
}
else if (forceShape == ParticleSystemForceFieldShape.Cylinder)
{
DrawCylinder(s_EndRangeProperty, s_LengthProperty, ff);
if (ff.startRange > 0.0f)
DrawCylinder(s_StartRangeProperty, s_LengthProperty, ff);
if (ff.gravityFocus > 0.0f)
{
using (new Handles.DrawingScope(s_GizmoColor * s_GizmoFocusTint))
DrawCylinder(s_GravityFocusProperty, s_LengthProperty, ff, ff.endRange);
}
}
else if (forceShape == ParticleSystemForceFieldShape.Box)
{
DrawBox(s_EndRangeProperty, ff);
if (ff.startRange > 0.0f)
DrawBox(s_StartRangeProperty, ff);
if (ff.gravityFocus > 0.0f)
{
using (new Handles.DrawingScope(s_GizmoColor * s_GizmoFocusTint))
DrawBox(s_GravityFocusProperty, ff, ff.endRange);
}
}
}
}
private static void DrawSphere(PropertyInfo radiusProp, ParticleSystemForceField target, float multiplyByRadius = 1.0f)
{
s_SphereBoundsHandle.axes = PrimitiveBoundsHandle.Axes.All;
s_SphereBoundsHandle.center = Vector3.zero;
s_SphereBoundsHandle.radius = (float)radiusProp.GetValue(target, null) * multiplyByRadius;
EditorGUI.BeginChangeCheck();
s_SphereBoundsHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name)));
radiusProp.SetValue(target, s_SphereBoundsHandle.radius / multiplyByRadius, null);
}
}
private static void DrawHemisphere(PropertyInfo radiusProp, ParticleSystemForceField target, float multiplyByRadius = 1.0f)
{
EditorGUI.BeginChangeCheck();
float oldRadius = (float)radiusProp.GetValue(target, null) * multiplyByRadius;
float newRadius = Handles.DoSimpleRadiusHandle(Quaternion.Euler(-90, 0, 0), Vector3.zero, oldRadius, true);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name)));
radiusProp.SetValue(target, newRadius / multiplyByRadius, null);
}
}
private static void DrawCylinder(PropertyInfo radiusProp, PropertyInfo lengthProp, ParticleSystemForceField target, float multiplyByRadius = 1.0f)
{
float lengthHalf = (float)lengthProp.GetValue(target, null) * 0.5f;
// Circle at each end
for (int i = 0; i < 2; i++)
{
s_SphereBoundsHandle.axes = PrimitiveBoundsHandle.Axes.X | PrimitiveBoundsHandle.Axes.Z;
s_SphereBoundsHandle.center = new Vector3(0.0f, (i > 0) ? -lengthHalf : lengthHalf, 0.0f);
s_SphereBoundsHandle.radius = (float)radiusProp.GetValue(target, null) * multiplyByRadius;
EditorGUI.BeginChangeCheck();
s_SphereBoundsHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name)));
radiusProp.SetValue(target, s_SphereBoundsHandle.radius / multiplyByRadius, null);
}
}
// Handle at each end for controlling the length
EditorGUI.BeginChangeCheck();
lengthHalf = Handles.SizeSlider(Vector3.zero, Vector3.up, lengthHalf);
lengthHalf = Handles.SizeSlider(Vector3.zero, -Vector3.up, lengthHalf);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name)));
lengthProp.SetValue(target, Mathf.Max(0.0f, lengthHalf * 2.0f), null);
}
// Connecting lines
float lineRadius = (float)radiusProp.GetValue(target, null) * multiplyByRadius;
Handles.DrawLine(new Vector3(lineRadius, lengthHalf, 0.0f), new Vector3(lineRadius, -lengthHalf, 0.0f));
Handles.DrawLine(new Vector3(-lineRadius, lengthHalf, 0.0f), new Vector3(-lineRadius, -lengthHalf, 0.0f));
Handles.DrawLine(new Vector3(0.0f, lengthHalf, lineRadius), new Vector3(0.0f, -lengthHalf, lineRadius));
Handles.DrawLine(new Vector3(0.0f, lengthHalf, -lineRadius), new Vector3(0.0f, -lengthHalf, -lineRadius));
}
private static void DrawBox(PropertyInfo extentProp, ParticleSystemForceField target, float multiplyByRadius = 1.0f)
{
s_BoxBoundsHandle.axes = PrimitiveBoundsHandle.Axes.All;
s_BoxBoundsHandle.center = Vector3.zero;
s_BoxBoundsHandle.radius = (float)extentProp.GetValue(target, null) * multiplyByRadius;
EditorGUI.BeginChangeCheck();
s_BoxBoundsHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, string.Format(s_UndoString, ObjectNames.NicifyVariableName(target.GetType().Name)));
extentProp.SetValue(target, s_BoxBoundsHandle.radius / multiplyByRadius, null);
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/ParticleSystemForceFieldInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/ParticleSystemForceFieldInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 8342
} | 295 |
// 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 System.IO;
using System.Linq;
using UnityEditor.AnimatedValues;
using UnityEditor.IMGUI.Controls;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEditor.SceneManagement;
namespace UnityEditor
{
[CustomEditor(typeof(ReflectionProbe))]
[CanEditMultipleObjects]
internal class ReflectionProbeEditor : Editor
{
static ReflectionProbeEditor s_LastInteractedEditor;
static HashSet<ReflectionProbe> s_CurrentlyEditedProbes = new HashSet<ReflectionProbe>();
SerializedProperty m_Mode;
SerializedProperty m_RefreshMode;
SerializedProperty m_TimeSlicingMode;
SerializedProperty m_Resolution;
SerializedProperty m_ShadowDistance;
SerializedProperty m_Importance;
SerializedProperty m_BoxSize;
SerializedProperty m_BoxOffset;
SerializedProperty m_CullingMask;
SerializedProperty m_ClearFlags;
SerializedProperty m_BackgroundColor;
SerializedProperty m_HDR;
SerializedProperty m_BoxProjection;
SerializedProperty m_IntensityMultiplier;
SerializedProperty m_BlendDistance;
SerializedProperty m_CustomBakedTexture;
SerializedProperty m_RenderDynamicObjects;
SerializedProperty m_UseOcclusionCulling;
SerializedProperty[] m_NearAndFarProperties;
private static Mesh s_SphereMesh;
private Material m_ReflectiveMaterial;
private Matrix4x4 m_OldLocalSpace = Matrix4x4.identity;
private float m_MipLevelPreview = 0.0F;
private BoxBoundsHandle m_BoundsHandle = new BoxBoundsHandle();
private Hashtable m_CachedGizmoMaterials = new Hashtable();
public static void GetResolutionArray(ref int[] resolutionList, ref GUIContent[] resolutionStringList)
{
if (Styles.reflectionResolutionValuesArray == null && Styles.reflectionResolutionTextArray == null)
{
int cubemapResolution = Mathf.Max(1, ReflectionProbe.minBakedCubemapResolution);
List<int> envReflectionResolutionValues = new List<int>();
List<GUIContent> envReflectionResolutionText = new List<GUIContent>();
do
{
envReflectionResolutionValues.Add(cubemapResolution);
envReflectionResolutionText.Add(new GUIContent(cubemapResolution.ToString()));
cubemapResolution *= 2;
}
while (cubemapResolution <= ReflectionProbe.maxBakedCubemapResolution);
Styles.reflectionResolutionValuesArray = envReflectionResolutionValues.ToArray();
Styles.reflectionResolutionTextArray = envReflectionResolutionText.ToArray();
}
resolutionList = Styles.reflectionResolutionValuesArray;
resolutionStringList = Styles.reflectionResolutionTextArray;
}
static internal class Styles
{
static Styles()
{
richTextMiniLabel.richText = true;
}
public static GUIStyle richTextMiniLabel = new GUIStyle(EditorStyles.miniLabel);
public static GUIContent bakeButtonText = EditorGUIUtility.TrTextContent("Bake");
public static string[] bakeCustomOptionText = { "Bake as new Cubemap..." };
public static string[] bakeButtonsText = { "Bake All Reflection Probes" };
public static GUIContent bakeCustomButtonText = EditorGUIUtility.TrTextContent("Bake", "Bakes Reflection Probe's cubemap, overwriting the existing cubemap texture asset (if any).");
public static GUIContent runtimeSettingsHeader = EditorGUIUtility.TrTextContent("Runtime Settings", "These settings determine this Probe's priority, blending, intensity, and zone of effect and works in conjunction with the cubemap of this probe when it is rendered.");
public static GUIContent backgroundColorText = EditorGUIUtility.TrTextContent("Background Color", "Camera clears the screen to this color before rendering.");
public static GUIContent clearFlagsText = EditorGUIUtility.TrTextContent("Clear Flags", "Specify how to fill empty areas of the cubemap.");
public static GUIContent intensityText = EditorGUIUtility.TrTextContent("Intensity", "The intensity modifier the Editor applies to this probe's texture in its shader.");
public static GUIContent resolutionText = EditorGUIUtility.TrTextContent("Resolution", "The resolution of the cubemap.");
public static GUIContent captureCubemapHeader = EditorGUIUtility.TrTextContent("Cubemap Capture Settings", "Settings that determine how to render this probe's cubemap.");
public static GUIContent boxProjectionText = EditorGUIUtility.TrTextContent("Box Projection", "When enabled, Unity assumes that the reflected light is originating from the inside of the probe's box, rather than from infinitely far away. This is useful for box-shaped indoor environments.");
public static GUIContent blendDistanceText = EditorGUIUtility.TrTextContent("Blend Distance", "Area around the probe where it is blended with other probes. Only used in deferred probes.");
public static GUIContent sizeText = EditorGUIUtility.TrTextContent("Box Size", "The size of the box in which the reflections will be applied to objects. The value is not affected by the Transform of the Game Object.");
public static GUIContent centerText = EditorGUIUtility.TrTextContent("Box Offset", "The center of the box in which the reflections will be applied to objects. The value is relative to the position of the Game Object.");
public static GUIContent customCubemapText = EditorGUIUtility.TrTextContent("Cubemap", "Sets a custom cubemap for this probe.");
public static GUIContent importanceText = EditorGUIUtility.TrTextContent("Importance", "When reflection probes overlap, Unity uses Importance to determine which probe should take priority.");
public static GUIContent renderDynamicObjects = EditorGUIUtility.TrTextContent("Dynamic Objects", "If enabled dynamic objects are also rendered into the cubemap");
public static GUIContent timeSlicing = EditorGUIUtility.TrTextContent("Time Slicing", "If enabled this probe will update over several frames, to help reduce the impact on the frame rate");
public static GUIContent refreshMode = EditorGUIUtility.TrTextContent("Refresh Mode", "Controls how this probe refreshes in the Player");
public static GUIContent useOcclusionCulling = EditorGUIUtility.TrTextContent("Occlusion Culling", "If this property is enabled, geometries which are blocked from the probe's line of sight are skipped during rendering.");
public static GUIContent hdrText = EditorGUIUtility.TrTextContent("HDR", "Enable High Dynamic Range rendering.");
public static GUIContent shadowDistanceText = EditorGUIUtility.TrTextContent("Shadow Distance", "Maximum distance at which Unity renders shadows associated with this probe.");
public static GUIContent cullingMaskText = EditorGUIUtility.TrTextContent("Culling Mask", "Allows objects on specified layers to be included or excluded in the reflection.");
public static GUIContent typeText = EditorGUIUtility.TrTextContent("Type", "Specify the lighting setup for this probe: Baked, Custom, or Realtime.");
public static GUIContent[] reflectionProbeMode = { EditorGUIUtility.TrTextContent("Baked"), EditorGUIUtility.TrTextContent("Custom"), EditorGUIUtility.TrTextContent("Realtime") };
public static int[] reflectionProbeModeValues = { (int)ReflectionProbeMode.Baked, (int)ReflectionProbeMode.Custom, (int)ReflectionProbeMode.Realtime };
public static int[] reflectionResolutionValuesArray = null;
public static GUIContent[] reflectionResolutionTextArray = null;
public static GUIContent[] clearFlags =
{
EditorGUIUtility.TrTextContent("Skybox"),
EditorGUIUtility.TrTextContent("Solid Color")
};
public static int[] clearFlagsValues = { 1, 2 }; // taken from Camera.h
private static GUIContent customPrivitiveBoundsHandleEditModeButton = new GUIContent(
EditorGUIUtility.IconContent("EditCollider").image,
EditorGUIUtility.TrTextContent("Adjust the probe's zone of effect. Holding Alt or Shift and click the control handle to pin the center or scale the volume uniformly.").text
);
public static GUIContent[] toolContents =
{
customPrivitiveBoundsHandleEditModeButton,
EditorGUIUtility.TrIconContent("MoveTool", "Move the selected objects.")
};
public static EditMode.SceneViewEditMode[] sceneViewEditModes = new[]
{
EditMode.SceneViewEditMode.ReflectionProbeBox,
EditMode.SceneViewEditMode.ReflectionProbeOrigin
};
public static string baseSceneEditingToolText = "<color=grey>Probe Scene Editing Mode:</color> ";
public static GUIContent[] toolNames =
{
new GUIContent(baseSceneEditingToolText + "Box Projection Bounds", ""),
new GUIContent(baseSceneEditingToolText + "Probe Origin", "")
};
} // end of class Styles
// Should match reflection probe gizmo color in GizmoDrawers.cpp!
internal static Color kGizmoReflectionProbe = new Color(0xFF / 255f, 0xE5 / 255f, 0x94 / 255f, 0x80 / 255f);
internal static Color kGizmoReflectionProbeDisabled = new Color(0x99 / 255f, 0x89 / 255f, 0x59 / 255f, 0x60 / 255f);
internal static Color kGizmoHandleReflectionProbe = new Color(0xFF / 255f, 0xE5 / 255f, 0xAA / 255f, 0xFF / 255f);
private SavedBool m_ShowRuntimeSettings;
private SavedBool m_ShowCubemapCaptureSettings;
readonly AnimBool m_ShowProbeModeRealtimeOptions = new AnimBool(); // p.mode == ReflectionProbeMode.Realtime; Will be brought back in 5.1
readonly AnimBool m_ShowProbeModeCustomOptions = new AnimBool();
readonly AnimBool m_ShowBoxOptions = new AnimBool();
private TextureInspector m_CubemapEditor = null;
static bool IsReflectionProbeEditMode(EditMode.SceneViewEditMode editMode)
{
return editMode == EditMode.SceneViewEditMode.ReflectionProbeBox ||
editMode == EditMode.SceneViewEditMode.ReflectionProbeOrigin;
}
bool sceneViewEditing
{
get { return IsReflectionProbeEditMode(EditMode.editMode) && EditMode.IsOwner(this); }
}
public void OnEnable()
{
m_Mode = serializedObject.FindProperty("m_Mode");
m_RefreshMode = serializedObject.FindProperty("m_RefreshMode");
m_TimeSlicingMode = serializedObject.FindProperty("m_TimeSlicingMode");
m_Resolution = serializedObject.FindProperty("m_Resolution");
m_NearAndFarProperties = new[] { serializedObject.FindProperty("m_NearClip"), serializedObject.FindProperty("m_FarClip") };
m_ShadowDistance = serializedObject.FindProperty("m_ShadowDistance");
m_Importance = serializedObject.FindProperty("m_Importance");
m_BoxSize = serializedObject.FindProperty("m_BoxSize");
m_BoxOffset = serializedObject.FindProperty("m_BoxOffset");
m_CullingMask = serializedObject.FindProperty("m_CullingMask");
m_ClearFlags = serializedObject.FindProperty("m_ClearFlags");
m_BackgroundColor = serializedObject.FindProperty("m_BackGroundColor");
m_HDR = serializedObject.FindProperty("m_HDR");
m_BoxProjection = serializedObject.FindProperty("m_BoxProjection");
m_IntensityMultiplier = serializedObject.FindProperty("m_IntensityMultiplier");
m_BlendDistance = serializedObject.FindProperty("m_BlendDistance");
m_CustomBakedTexture = serializedObject.FindProperty("m_CustomBakedTexture");
m_RenderDynamicObjects = serializedObject.FindProperty("m_RenderDynamicObjects");
m_UseOcclusionCulling = serializedObject.FindProperty("m_UseOcclusionCulling");
ReflectionProbe p = target as ReflectionProbe;
m_ShowProbeModeRealtimeOptions.valueChanged.AddListener(Repaint);
m_ShowProbeModeCustomOptions.valueChanged.AddListener(Repaint);
m_ShowBoxOptions.valueChanged.AddListener(Repaint);
m_ShowProbeModeRealtimeOptions.value = p.mode == ReflectionProbeMode.Realtime;
m_ShowProbeModeCustomOptions.value = p.mode == ReflectionProbeMode.Custom;
m_ShowBoxOptions.value = true;
m_BoundsHandle.handleColor = kGizmoHandleReflectionProbe;
m_BoundsHandle.wireframeColor = Color.clear;
m_ShowRuntimeSettings = new SavedBool("ReflectionProbeEditor.ShowRuntimeSettings", true);
m_ShowCubemapCaptureSettings = new SavedBool("ReflectionProbeEditor.ShowCubemapCaptureSettings", true);
UpdateOldLocalSpace();
SceneView.beforeSceneGui += OnPreSceneGUICallback;
for (int i = 0; i < targets.Length; ++i)
{
s_CurrentlyEditedProbes.Add((ReflectionProbe)targets[i]);
}
}
public void OnDisable()
{
SceneView.beforeSceneGui -= OnPreSceneGUICallback;
DestroyImmediate(m_ReflectiveMaterial);
DestroyImmediate(m_CubemapEditor);
foreach (Material mat in m_CachedGizmoMaterials.Values)
DestroyImmediate(mat);
m_CachedGizmoMaterials.Clear();
for (int i = 0; i < targets.Length; ++i)
{
s_CurrentlyEditedProbes.Remove((ReflectionProbe)targets[i]);
}
}
private bool IsCollidingWithOtherProbes(string targetPath, ReflectionProbe targetProbe, out ReflectionProbe collidingProbe)
{
ReflectionProbe[] probes = FindObjectsByType<ReflectionProbe>(FindObjectsSortMode.InstanceID).ToArray();
collidingProbe = null;
foreach (var probe in probes)
{
if (probe == targetProbe || probe.customBakedTexture == null)
continue;
string path = AssetDatabase.GetAssetPath(probe.customBakedTexture);
if (path == targetPath)
{
collidingProbe = probe;
return true;
}
}
return false;
}
private void BakeCustomReflectionProbe(ReflectionProbe probe, bool usePreviousAssetPath)
{
string path = "";
if (usePreviousAssetPath)
path = AssetDatabase.GetAssetPath(probe.customBakedTexture);
string targetExtension = probe.hdr ? "exr" : "png";
if (string.IsNullOrEmpty(path) || Path.GetExtension(path) != "." + targetExtension)
{
// We use the path of the active scene as the target path
string targetPath = FileUtil.GetPathWithoutExtension(SceneManager.GetActiveScene().path);
if (string.IsNullOrEmpty(targetPath))
targetPath = "Assets";
else if (Directory.Exists(targetPath) == false)
Directory.CreateDirectory(targetPath);
string fileName = probe.name + (probe.hdr ? "-reflectionHDR" : "-reflection") + "." + targetExtension;
fileName = Path.GetFileNameWithoutExtension(AssetDatabase.GenerateUniqueAssetPath(Path.Combine(targetPath, fileName)));
path = EditorUtility.SaveFilePanelInProject("Save reflection probe's cubemap.", fileName, targetExtension, "", targetPath);
if (string.IsNullOrEmpty(path))
return;
ReflectionProbe collidingProbe;
if (IsCollidingWithOtherProbes(path, probe, out collidingProbe))
{
if (!EditorUtility.DisplayDialog("Cubemap is used by other reflection probe",
string.Format("'{0}' path is used by the game object '{1}', do you really want to overwrite it?",
path, collidingProbe.name), "Yes", "No"))
{
return;
}
}
}
EditorUtility.DisplayProgressBar("Reflection Probes", "Baking " + path, 0.5f);
if (!Lightmapping.BakeReflectionProbe(probe, path))
Debug.LogError("Failed to bake reflection probe to " + path);
EditorUtility.ClearProgressBar();
}
private void OnBakeCustomButton(object data)
{
int mode = (int)data;
ReflectionProbe p = target as ReflectionProbe;
if (mode == 0)
BakeCustomReflectionProbe(p, false);
}
private void OnBakeButton(object data)
{
int mode = (int)data;
if (mode == 0)
Lightmapping.BakeAllReflectionProbesSnapshots();
}
ReflectionProbe reflectionProbeTarget
{
get { return (ReflectionProbe)target; }
}
void DoBakeButton()
{
if (reflectionProbeTarget.mode == ReflectionProbeMode.Realtime)
{
EditorGUILayout.HelpBox("Baking of this reflection probe should be initiated from the scripting API because the type is 'Realtime'", MessageType.Info);
if (!QualitySettings.realtimeReflectionProbes)
EditorGUILayout.HelpBox("Realtime reflection probes are disabled in Quality Settings", MessageType.Warning);
return;
}
GUILayout.BeginHorizontal();
switch (reflectionProbeMode)
{
case ReflectionProbeMode.Custom:
if (EditorGUI.LargeSplitButtonWithDropdownList(Styles.bakeCustomButtonText, Styles.bakeCustomOptionText, OnBakeCustomButton))
{
BakeCustomReflectionProbe(reflectionProbeTarget, true);
GUIUtility.ExitGUI();
}
break;
case ReflectionProbeMode.Baked:
using (new EditorGUI.DisabledScope(!reflectionProbeTarget.enabled))
{
// Bake button in non-continous mode
if (EditorGUI.LargeSplitButtonWithDropdownList(Styles.bakeButtonText, Styles.bakeButtonsText, OnBakeButton))
{
Lightmapping.BakeReflectionProbeSnapshot(reflectionProbeTarget);
GUIUtility.ExitGUI();
}
}
break;
case ReflectionProbeMode.Realtime:
// Not showing bake button in realtime
break;
}
GUILayout.EndHorizontal();
}
void DoToolbar()
{
// Show the master tool selector
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUI.changed = false;
var oldEditMode = EditMode.editMode;
EditorGUI.BeginChangeCheck();
EditMode.DoInspectorToolbar(Styles.sceneViewEditModes, Styles.toolContents, this);
if (EditorGUI.EndChangeCheck())
s_LastInteractedEditor = this;
if (oldEditMode != EditMode.editMode)
{
switch (EditMode.editMode)
{
case EditMode.SceneViewEditMode.ReflectionProbeOrigin:
UpdateOldLocalSpace();
break;
}
if (Toolbar.get != null)
Toolbar.get.Repaint();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
// Info box for tools
GUILayout.BeginVertical(EditorStyles.helpBox);
string helpText = Styles.baseSceneEditingToolText;
if (sceneViewEditing)
{
int index = ArrayUtility.IndexOf(Styles.sceneViewEditModes, EditMode.editMode);
if (index >= 0)
helpText = Styles.toolNames[index].text;
}
GUILayout.Label(helpText, Styles.richTextMiniLabel);
GUILayout.EndVertical();
EditorGUILayout.Space();
}
ReflectionProbeMode reflectionProbeMode
{
get { return reflectionProbeTarget.mode; }
}
public override void OnInspectorGUI()
{
serializedObject.Update();
if (targets.Length == 1)
DoToolbar();
m_ShowProbeModeRealtimeOptions.target = reflectionProbeMode == ReflectionProbeMode.Realtime;
m_ShowProbeModeCustomOptions.target = reflectionProbeMode == ReflectionProbeMode.Custom;
// Bake/custom/realtime type
EditorGUILayout.IntPopup(m_Mode, Styles.reflectionProbeMode, Styles.reflectionProbeModeValues, Styles.typeText);
// We cannot show multiple different type controls
if (!m_Mode.hasMultipleDifferentValues)
{
EditorGUI.indentLevel++;
{
// Custom cubemap UI (Bake button and manual cubemap assignment)
if (EditorGUILayout.BeginFadeGroup(m_ShowProbeModeCustomOptions.faded))
{
EditorGUILayout.PropertyField(m_RenderDynamicObjects, Styles.renderDynamicObjects);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = m_CustomBakedTexture.hasMultipleDifferentValues;
var newCubemap = EditorGUILayout.ObjectField(Styles.customCubemapText, m_CustomBakedTexture.objectReferenceValue, typeof(Texture), false);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
m_CustomBakedTexture.objectReferenceValue = newCubemap;
}
EditorGUILayout.EndFadeGroup();
// Realtime UI
if (EditorGUILayout.BeginFadeGroup(m_ShowProbeModeRealtimeOptions.faded))
{
EditorGUILayout.PropertyField(m_RefreshMode, Styles.refreshMode);
EditorGUILayout.PropertyField(m_TimeSlicingMode, Styles.timeSlicing);
EditorGUILayout.Space();
}
EditorGUILayout.EndFadeGroup();
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
m_ShowRuntimeSettings.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_ShowRuntimeSettings.value, Styles.runtimeSettingsHeader);
if (m_ShowRuntimeSettings.value)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_Importance, Styles.importanceText);
EditorGUILayout.PropertyField(m_IntensityMultiplier, Styles.intensityText);
// Only take graphic Tier settings into account when built-in render pipeline is active.
if (GraphicsSettings.currentRenderPipeline == null && Rendering.EditorGraphicsSettings.GetCurrentTierSettings().reflectionProbeBoxProjection == false)
{
using (new EditorGUI.DisabledScope(true))
{
EditorGUILayout.Toggle(Styles.boxProjectionText, false);
}
}
else
{
EditorGUILayout.PropertyField(m_BoxProjection, Styles.boxProjectionText);
}
bool isDeferredRenderingPath = SceneView.IsUsingDeferredRenderingPath();
bool isDeferredReflections = isDeferredRenderingPath && (UnityEngine.Rendering.GraphicsSettings.GetShaderMode(BuiltinShaderType.DeferredReflections) != BuiltinShaderMode.Disabled);
using (new EditorGUI.DisabledScope(!isDeferredReflections && !SupportedRenderingFeatures.active.reflectionProbesBlendDistance))
{
EditorGUILayout.PropertyField(m_BlendDistance, Styles.blendDistanceText);
}
// Bounds editing (box projection bounds + the bounds that objects use to check if they should be affected by this reflection probe)
if (EditorGUILayout.BeginFadeGroup(m_ShowBoxOptions.faded))
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_BoxSize, Styles.sizeText);
EditorGUILayout.PropertyField(m_BoxOffset, Styles.centerText);
if (EditorGUI.EndChangeCheck())
{
Vector3 center = m_BoxOffset.vector3Value;
Vector3 size = m_BoxSize.vector3Value;
if (ValidateAABB(ref center, ref size))
{
m_BoxOffset.vector3Value = center;
m_BoxSize.vector3Value = size;
}
}
}
EditorGUILayout.EndFadeGroup();
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
m_ShowCubemapCaptureSettings.value = EditorGUILayout.BeginFoldoutHeaderGroup(m_ShowCubemapCaptureSettings.value, Styles.captureCubemapHeader);
if (m_ShowCubemapCaptureSettings.value)
{
EditorGUI.indentLevel++;
int[] reflectionResolutionValuesArray = null;
GUIContent[] reflectionResolutionTextArray = null;
GetResolutionArray(ref reflectionResolutionValuesArray, ref reflectionResolutionTextArray);
EditorGUILayout.IntPopup(m_Resolution, reflectionResolutionTextArray, reflectionResolutionValuesArray, Styles.resolutionText, GUILayout.MinWidth(40));
EditorGUILayout.PropertyField(m_HDR, Styles.hdrText);
EditorGUILayout.PropertyField(m_ShadowDistance, Styles.shadowDistanceText);
EditorGUILayout.IntPopup(m_ClearFlags, Styles.clearFlags, Styles.clearFlagsValues, Styles.clearFlagsText);
EditorGUILayout.PropertyField(m_BackgroundColor, Styles.backgroundColorText);
EditorGUILayout.PropertyField(m_CullingMask, Styles.cullingMaskText);
EditorGUILayout.PropertyField(m_UseOcclusionCulling, Styles.useOcclusionCulling);
EditorGUILayout.PropertiesField(EditorGUI.s_ClipingPlanesLabel, m_NearAndFarProperties, EditorGUI.s_NearAndFarLabels, EditorGUI.kNearFarLabelsWidth);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space();
if (targets.Length == 1)
{
ReflectionProbe probe = (ReflectionProbe)target;
if (probe.mode == ReflectionProbeMode.Custom && probe.customBakedTexture != null)
{
Cubemap cubemap = probe.customBakedTexture as Cubemap;
if (cubemap && cubemap.mipmapCount == 1)
EditorGUILayout.HelpBox("No mipmaps in the cubemap, Smoothness value in Standard shader will be ignored.", MessageType.Warning);
}
}
DoBakeButton();
EditorGUILayout.Space();
serializedObject.ApplyModifiedProperties();
}
internal override Bounds GetWorldBoundsOfTarget(Object targetObject)
{
return ((ReflectionProbe)targetObject).bounds;
}
bool ValidPreviewSetup()
{
ReflectionProbe p = (ReflectionProbe)target;
return (p != null && p.texture != null);
}
void CreateTextureInspector(Texture texture, ref Editor previousEditor)
{
switch (texture)
{
case Cubemap _:
Editor.CreateCachedEditor(texture, typeof(CubemapInspector), ref previousEditor);
break;
case CustomRenderTexture _:
Editor.CreateCachedEditor(texture, typeof(CustomRenderTextureEditor), ref previousEditor);
break;
case RenderTexture _:
Editor.CreateCachedEditor(texture, typeof(RenderTextureEditor), ref previousEditor);
break;
default:
Editor.CreateCachedEditor(texture, typeof(TextureInspector), ref previousEditor);
break;
}
}
public override bool HasPreviewGUI()
{
if (targets.Length > 1)
return false; // We only handle one preview for reflection probes
// Ensure valid cube map editor (if possible)
if (ValidPreviewSetup())
{
Editor editor = m_CubemapEditor;
CreateTextureInspector(((ReflectionProbe)target).texture, ref editor);
m_CubemapEditor = editor as TextureInspector;
}
// If having one probe selected we always want preview (to prevent preview window from popping)
return true;
}
public override void OnPreviewSettings()
{
if (!ValidPreviewSetup())
return;
m_CubemapEditor.mipLevel = m_MipLevelPreview;
EditorGUI.BeginChangeCheck();
m_CubemapEditor.OnPreviewSettings();
// Need to repaint, because mipmap value changes affect reflection probe preview in the scene
if (EditorGUI.EndChangeCheck())
{
EditorApplication.SetSceneRepaintDirty();
m_MipLevelPreview = m_CubemapEditor.mipLevel;
}
}
public override void OnPreviewGUI(Rect position, GUIStyle style)
{
// Fix for case 939947 where we didn't get the Layout event if the texture was null when changing color
if (!ValidPreviewSetup() && Event.current.type != EventType.ExecuteCommand)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
Color prevColor = GUI.color;
GUI.color = new Color(1, 1, 1, 0.5f);
GUILayout.Label("Reflection Probe not baked/ready yet");
GUI.color = prevColor;
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
return;
}
ReflectionProbe p = target as ReflectionProbe;
if (p != null && p.texture != null && targets.Length == 1)
{
Editor editor = m_CubemapEditor;
CreateTextureInspector(p.texture, ref editor);
m_CubemapEditor = editor as TextureInspector;
}
if (m_CubemapEditor != null)
{
m_CubemapEditor.SetCubemapIntensity(GetProbeIntensity((ReflectionProbe)target));
m_CubemapEditor.OnPreviewGUI(position, style);
}
}
private static Mesh sphereMesh
{
get { return s_SphereMesh ?? (s_SphereMesh = Resources.GetBuiltinResource(typeof(Mesh), "New-Sphere.fbx") as Mesh); }
}
private Material reflectiveMaterial
{
get
{
if (m_ReflectiveMaterial == null)
{
m_ReflectiveMaterial = (Material)Instantiate(EditorGUIUtility.Load("Previews/PreviewCubemapMaterial.mat"));
m_ReflectiveMaterial.hideFlags = HideFlags.HideAndDontSave;
}
return m_ReflectiveMaterial;
}
}
private float GetProbeIntensity(ReflectionProbe p)
{
if (p == null || p.texture == null)
return 1.0f;
float intensity = p.intensity;
if (TextureUtil.GetTextureColorSpaceString(p.texture) == "Linear")
intensity = Mathf.LinearToGammaSpace(intensity);
return intensity;
}
// Draw Reflection probe preview sphere
private void OnPreSceneGUICallback(SceneView sceneView)
{
if (Event.current.type != EventType.Repaint)
return;
foreach (var t in targets)
{
ReflectionProbe p = (ReflectionProbe)t;
if (!reflectiveMaterial)
return;
if (StageUtility.IsGizmoCulledBySceneCullingMasksOrFocusedScene(p.gameObject, Camera.current))
return;
Matrix4x4 m = new Matrix4x4();
// @TODO: use MaterialPropertyBlock instead - once it actually works!
// Tried to use MaterialPropertyBlock in 5.4.0b2, but would get incorrectly set parameters when using with Graphics.DrawMesh
if (!m_CachedGizmoMaterials.ContainsKey(p))
m_CachedGizmoMaterials.Add(p, Instantiate(reflectiveMaterial));
Material mat = m_CachedGizmoMaterials[p] as Material;
if (!mat)
return;
{
// Get mip level
float mipLevel = 0.0F;
TextureInspector cubemapEditor = m_CubemapEditor;
if (cubemapEditor)
mipLevel = cubemapEditor.GetMipLevelForRendering();
mat.SetTexture("_MainTex", p.texture);
mat.SetMatrix("_CubemapRotation", Matrix4x4.identity);
mat.SetFloat("_Mip", mipLevel);
mat.SetFloat("_Alpha", 0.0f);
mat.SetFloat("_Intensity", GetProbeIntensity(p));
mat.SetVector("_MainTex_HDR", p.textureHDRDecodeValues);
if (PlayerSettings.colorSpace == ColorSpace.Linear)
{
mat.SetInt("_ColorspaceIsGamma", 0);
}
else
{
mat.SetInt("_ColorspaceIsGamma", 1);
}
// draw a preview sphere that scales with overall GO scale, but always uniformly
var scale = p.transform.lossyScale.magnitude * 0.5f;
m.SetTRS(p.transform.position, Quaternion.identity, new Vector3(scale, scale, scale));
Graphics.DrawMesh(sphereMesh, m, mat, 0, SceneView.currentDrawingSceneView.camera, 0);
}
}
}
// Ensures that probe's AABB encapsulates probe's position
// Returns true, if center or size was modified
private bool ValidateAABB(ref Vector3 center, ref Vector3 size)
{
ReflectionProbe p = (ReflectionProbe)target;
Matrix4x4 localSpace = GetLocalSpace(p);
Vector3 localTransformPosition = localSpace.inverse.MultiplyPoint3x4(p.transform.position);
Bounds b = new Bounds(center, size);
if (b.Contains(localTransformPosition)) return false;
b.Encapsulate(localTransformPosition);
center = b.center;
size = b.size;
return true;
}
[DrawGizmo(GizmoType.Active)]
static void RenderBoxGizmo(ReflectionProbe reflectionProbe, GizmoType gizmoType)
{
if (s_LastInteractedEditor == null)
return;
if (s_LastInteractedEditor.sceneViewEditing && EditMode.editMode == EditMode.SceneViewEditMode.ReflectionProbeBox)
{
Color oldColor = Gizmos.color;
Gizmos.color = kGizmoReflectionProbe;
Gizmos.matrix = GetLocalSpace(reflectionProbe);
Gizmos.DrawCube(reflectionProbe.center, -1f * reflectionProbe.size);
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = oldColor;
}
}
[DrawGizmo(GizmoType.Selected)]
static void RenderBoxOutline(ReflectionProbe reflectionProbe, GizmoType gizmoType)
{
if (!s_CurrentlyEditedProbes.Contains(reflectionProbe))
return;
Color oldColor = Gizmos.color;
Gizmos.color = reflectionProbe.isActiveAndEnabled ? kGizmoReflectionProbe : kGizmoReflectionProbeDisabled;
Gizmos.matrix = GetLocalSpace(reflectionProbe);
Gizmos.DrawWireCube(reflectionProbe.center, reflectionProbe.size);
Gizmos.matrix = Matrix4x4.identity;
Gizmos.color = oldColor;
}
public static bool IsSceneGUIEnabled()
{
return IsReflectionProbeEditMode(EditMode.editMode);
}
public void OnSceneGUI()
{
if (!sceneViewEditing)
return;
switch (EditMode.editMode)
{
case EditMode.SceneViewEditMode.ReflectionProbeBox:
DoBoxEditing();
break;
case EditMode.SceneViewEditMode.ReflectionProbeOrigin:
DoOriginEditing();
break;
}
}
void UpdateOldLocalSpace()
{
m_OldLocalSpace = GetLocalSpace((ReflectionProbe)target);
}
void DoOriginEditing()
{
ReflectionProbe p = (ReflectionProbe)target;
Vector3 transformPosition = p.transform.position;
Vector3 size = p.size;
EditorGUI.BeginChangeCheck();
Vector3 newPostion = Handles.PositionHandle(transformPosition, GetLocalSpaceRotation(p));
bool changed = EditorGUI.EndChangeCheck();
if (changed || m_OldLocalSpace != GetLocalSpace((ReflectionProbe)target))
{
Vector3 localNewPosition = m_OldLocalSpace.inverse.MultiplyPoint3x4(newPostion);
Bounds b = new Bounds(p.center, size);
localNewPosition = b.ClosestPoint(localNewPosition);
Undo.RecordObject(p.transform, "Modified Reflection Probe Origin");
p.transform.position = m_OldLocalSpace.MultiplyPoint3x4(localNewPosition);
Undo.RecordObject(p, "Modified Reflection Probe Origin");
p.center = GetLocalSpace(p).inverse.MultiplyPoint3x4(m_OldLocalSpace.MultiplyPoint3x4(p.center));
EditorUtility.SetDirty(target);
UpdateOldLocalSpace();
}
}
static Matrix4x4 GetLocalSpace(ReflectionProbe probe)
{
Vector3 t = probe.transform.position;
return Matrix4x4.TRS(t, GetLocalSpaceRotation(probe), Vector3.one);
}
static Quaternion GetLocalSpaceRotation(ReflectionProbe probe)
{
bool supportsRotation = (SupportedRenderingFeatures.active.reflectionProbeModes & SupportedRenderingFeatures.ReflectionProbeModes.Rotation) != 0;
if (supportsRotation)
return probe.transform.rotation;
else
return Quaternion.identity;
}
void DoBoxEditing()
{
// Drawing of the probe box is done from GizmoDrawers.cpp,
// here we only want to show the box editing handles when needed.
ReflectionProbe p = (ReflectionProbe)target;
using (new Handles.DrawingScope(GetLocalSpace(p)))
{
m_BoundsHandle.center = p.center;
m_BoundsHandle.size = p.size;
EditorGUI.BeginChangeCheck();
m_BoundsHandle.DrawHandle();
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(p, "Modified Reflection Probe AABB");
Vector3 center = m_BoundsHandle.center;
Vector3 size = m_BoundsHandle.size;
ValidateAABB(ref center, ref size);
p.center = center;
p.size = size;
EditorUtility.SetDirty(target);
}
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/ReflectionProbeEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/ReflectionProbeEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 18686
} | 296 |
// 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 System.Collections.Generic;
using System.Globalization;
using UnityEditor.Rendering;
using Object = UnityEngine.Object;
using UnityEngine.Rendering;
namespace UnityEditor
{
[CustomEditor(typeof(Shader))]
internal class ShaderInspector : Editor
{
private static readonly string[] kPropertyTypes =
{
"Color: ",
"Vector: ",
"Float: ",
"Range: ",
"Texture: "
};
private static readonly string[] kTextureTypes =
{
"No Texture?: ",
"Any texture: ",
"2D: ",
"3D: ",
"Cube: ",
"2DArray: ",
"CubeArray: "
};
private const float kSpace = 5f;
const float kValueFieldWidth = 200.0f;
const float kArrayValuePopupBtnWidth = 25.0f;
private static bool s_KeywordsUnfolded = false;
private static bool s_PropertiesUnfolded = true;
internal class Styles
{
public static Texture2D errorIcon = EditorGUIUtility.LoadIcon("console.erroricon.sml");
public static Texture2D warningIcon = EditorGUIUtility.LoadIcon("console.warnicon.sml");
public static GUIContent togglePreprocess = EditorGUIUtility.TrTextContent("Preprocess only", "Show preprocessor output instead of compiled shader code");
public static GUIContent toggleStripLineDirective = EditorGUIUtility.TrTextContent("Strip #line directives", "Strip #line directives from preprocessor output");
public static GUIContent showSurface = EditorGUIUtility.TrTextContent("Show generated code", "Show generated code of a surface shader");
public static GUIContent showFF = EditorGUIUtility.TrTextContent("Show generated code", "Show generated code of a fixed function shader");
public static GUIContent showCurrent = EditorGUIUtility.TrTextContent("Compile and show code \u007C \u25BE"); // vertical bar & dropdow arrow - due to lacking editor style of "mini button with a dropdown"
public static GUIContent overridableKeywords = EditorGUIUtility.TrTextContent("Overridable", "Shader keywords overridable by global shader keyword state");
public static GUIContent notOverridableKeywords = EditorGUIUtility.TrTextContent("Not overridable", "Shader keywords not overridable by global shader keyword state");
public static GUIStyle messageStyle = "CN StatusInfo";
public static GUIStyle evenBackground = "CN EntryBackEven";
public static GUIContent no = EditorGUIUtility.TrTextContent("no");
public static GUIContent builtinShader = EditorGUIUtility.TrTextContent("Built-in shader");
public static readonly GUIContent arrayValuePopupButton = EditorGUIUtility.TrTextContent("...");
}
static readonly int kErrorViewHash = "ShaderErrorView".GetHashCode();
private static bool s_PreprocessOnly = false;
private static bool s_StripLineDirectives = true;
Vector2 m_ScrollPosition = Vector2.zero;
private Material m_SrpCompatibilityCheckMaterial = null;
public Material srpCompatibilityCheckMaterial
{
get
{
if (m_SrpCompatibilityCheckMaterial == null)
{
m_SrpCompatibilityCheckMaterial = new Material(target as Shader);
}
return m_SrpCompatibilityCheckMaterial;
}
}
public virtual void OnEnable()
{
var s = target as Shader;
if (s != null)
ShaderUtil.FetchCachedMessages(s);
}
public virtual void OnDisable()
{
if (m_SrpCompatibilityCheckMaterial != null)
{
GameObject.DestroyImmediate(m_SrpCompatibilityCheckMaterial);
}
}
private static string GetPropertyType(Shader s, int index)
{
var type = s.GetPropertyType(index);
if (type == ShaderPropertyType.Texture)
{
return kTextureTypes[(int)s.GetPropertyTextureDimension(index)];
}
return kPropertyTypes[(int)type];
}
public override void OnInspectorGUI()
{
var s = target as Shader;
if (s == null)
return;
GUI.enabled = true;
EditorGUI.indentLevel = 0;
ShowShaderCodeArea(s);
if (s.isSupported)
{
EditorGUILayout.LabelField("Cast shadows", (ShaderUtil.HasShadowCasterPass(s)) ? "yes" : "no");
EditorGUILayout.LabelField("Render queue", ShaderUtil.GetRenderQueue(s).ToString(CultureInfo.InvariantCulture));
EditorGUILayout.LabelField("LOD", ShaderUtil.GetLOD(s).ToString(CultureInfo.InvariantCulture));
EditorGUILayout.LabelField("Ignore projector", ShaderUtil.DoesIgnoreProjector(s) ? "yes" : "no");
string disableBatchingString;
switch (s.disableBatching)
{
case DisableBatchingType.False:
disableBatchingString = "no";
break;
case DisableBatchingType.True:
disableBatchingString = "yes";
break;
case DisableBatchingType.WhenLODFading:
disableBatchingString = "when LOD fading is on";
break;
default:
disableBatchingString = "unknown";
break;
}
EditorGUILayout.LabelField("Disable batching", disableBatchingString);
ShowKeywords(s);
// If any SRP is active, then display the SRP Batcher compatibility status
if (GraphicsSettings.currentRenderPipeline != null)
{
// NOTE: Force the shader compilation to ensure GetSRPBatcherCompatibilityCode will be up to date
srpCompatibilityCheckMaterial.SetPass(0);
int subShader = ShaderUtil.GetShaderActiveSubshaderIndex(s);
int SRPErrCode = ShaderUtil.GetSRPBatcherCompatibilityCode(s, subShader);
string result = (0 == SRPErrCode) ? "compatible" : "not compatible";
EditorGUILayout.LabelField("SRP Batcher", result);
if (SRPErrCode != 0)
{
EditorGUILayout.HelpBox(ShaderUtil.GetSRPBatcherCompatibilityIssueReason(s, subShader, SRPErrCode), MessageType.Info);
}
}
ShowShaderProperties(s);
}
}
private void ShowKeywords(Shader s)
{
EditorGUILayout.BeginVertical();
s_KeywordsUnfolded = EditorGUILayout.Foldout(s_KeywordsUnfolded, "Keywords");
if (s_KeywordsUnfolded)
{
var keywords = s.keywordSpace.keywords;
var overridable = new List<LocalKeyword>();
var nonOverridable = new List<LocalKeyword>();
foreach (var k in keywords)
{
if (k.isOverridable)
overridable.Add(k);
else
nonOverridable.Add(k);
}
overridable.Sort((x, y) => string.CompareOrdinal(x.name, y.name));
nonOverridable.Sort((x, y) => string.CompareOrdinal(x.name, y.name));
EditorGUILayout.LabelField(Styles.overridableKeywords, EditorStyles.boldLabel);
foreach (var k in overridable)
EditorGUILayout.LabelField(k.name);
EditorGUILayout.LabelField(Styles.notOverridableKeywords, EditorStyles.boldLabel);
foreach (var k in nonOverridable)
EditorGUILayout.LabelField(k.name);
}
EditorGUILayout.EndVertical();
}
private void ShowShaderCodeArea(Shader s)
{
ShowSurfaceShaderButton(s);
ShowFixedFunctionShaderButton(s);
ShowCompiledCodeButton(s);
ShowShaderErrors(s);
}
private static void ShowShaderProperties(Shader s)
{
GUILayout.Space(kSpace);
s_PropertiesUnfolded = EditorGUILayout.Foldout(s_PropertiesUnfolded, "Properties");
if (s_PropertiesUnfolded)
{
int n = s.GetPropertyCount();
for (int i = 0; i < n; ++i)
{
string pname = s.GetPropertyName(i);
string pdesc = s.GetPropertyDescription(i) + " (" + s.GetPropertyType(i) + ")";
EditorGUILayout.LabelField(pname, pdesc);
}
}
}
// shared by compute shader inspector too
internal static void ShaderErrorListUI(Object shader, ShaderMessage[] messages, ref Vector2 scrollPosition)
{
int n = messages.Length;
int errorCount = 0;
int warningCount = 0;
for (int i = 0; i < n; ++i)
{
ShaderCompilerMessageSeverity severity = messages[i].severity;
if (severity == ShaderCompilerMessageSeverity.Warning)
warningCount++;
else if (severity == ShaderCompilerMessageSeverity.Error)
errorCount++;
}
GUILayout.Space(kSpace);
GUILayout.Label(string.Format("({0}) Error{1} and ({2}) Warning{3}:", errorCount, (errorCount != 1) ? "s" : "", warningCount, (warningCount != 1) ? "s" : ""), EditorStyles.boldLabel);
int errorListID = GUIUtility.GetControlID(kErrorViewHash, FocusType.Passive);
float height = Mathf.Min(n * 20f + 40f, 150f);
scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUISkin.current.box, GUILayout.MinHeight(height));
EditorGUIUtility.SetIconSize(new Vector2(16.0f, 16.0f));
float lineHeight = Styles.messageStyle.CalcHeight(EditorGUIUtility.TempContent(Styles.errorIcon), 100);
Event e = Event.current;
for (int i = 0; i < n; ++i)
{
Rect r = EditorGUILayout.GetControlRect(false, lineHeight);
string err = messages[i].message;
string plat = messages[i].platform.ToString();
bool warn = messages[i].severity != ShaderCompilerMessageSeverity.Error;
string fileName = FileUtil.GetLastPathNameComponent(messages[i].file);
int line = messages[i].line;
// Double click opens shader file at error line
if (e.type == EventType.MouseDown && e.button == 0 && r.Contains(e.mousePosition))
{
GUIUtility.keyboardControl = errorListID;
if (e.clickCount == 2)
{
string filePath = messages[i].file;
Object asset = string.IsNullOrEmpty(filePath) ? null : AssetDatabase.LoadMainAssetAtPath(filePath);
// if we don't have an asset and the filePath is an absolute path, it's an error in a system
// cginc - open that instead
if (asset == null && System.IO.Path.IsPathRooted(filePath))
ShaderUtil.OpenSystemShaderIncludeError(filePath, line);
else
AssetDatabase.OpenAsset(asset ?? shader, line);
GUIUtility.ExitGUI();
}
e.Use();
}
// Context menu, "Copy"
if (e.type == EventType.ContextClick && r.Contains(e.mousePosition))
{
e.Use();
var menu = new GenericMenu();
// need to copy current value to be used in delegate
// (C# closures close over variables, not their values)
var errorIndex = i;
menu.AddItem(EditorGUIUtility.TrTextContent("Copy error text"), false, delegate {
string errMsg = messages[errorIndex].message;
if (!string.IsNullOrEmpty(messages[errorIndex].messageDetails))
{
errMsg += '\n';
errMsg += messages[errorIndex].messageDetails;
}
EditorGUIUtility.systemCopyBuffer = errMsg;
});
menu.ShowAsContext();
}
// background
if (e.type == EventType.Repaint)
{
if ((i & 1) == 0)
{
GUIStyle st = Styles.evenBackground;
st.Draw(r, false, false, false, false);
}
}
// error location on the right side
Rect locRect = r;
locRect.xMin = locRect.xMax;
if (line > 0)
{
GUIContent gc;
if (string.IsNullOrEmpty(fileName))
gc = EditorGUIUtility.TempContent(line.ToString(CultureInfo.InvariantCulture));
else
gc = EditorGUIUtility.TempContent(fileName + ":" + line.ToString(CultureInfo.InvariantCulture));
// calculate size so we can right-align it
Vector2 size = EditorStyles.miniLabel.CalcSize(gc);
locRect.xMin -= size.x;
GUI.Label(locRect, gc, EditorStyles.miniLabel);
locRect.xMin -= 2;
// ensure some minimum width so that platform field next will line up
if (locRect.width < 30)
locRect.xMin = locRect.xMax - 30;
}
// platform to the left of it
Rect platRect = locRect;
platRect.width = 0;
if (plat.Length > 0)
{
GUIContent gc = EditorGUIUtility.TempContent(plat);
// calculate size so we can right-align it
Vector2 size = EditorStyles.miniLabel.CalcSize(gc);
platRect.xMin -= size.x;
// draw platform in dimmer color; it's often not very important information
Color oldColor = GUI.contentColor;
GUI.contentColor = new Color(1, 1, 1, 0.5f);
GUI.Label(platRect, gc, EditorStyles.miniLabel);
GUI.contentColor = oldColor;
platRect.xMin -= 2;
}
// error message
Rect msgRect = r;
msgRect.xMax = platRect.xMin;
GUI.Label(msgRect, EditorGUIUtility.TempContent(err, warn ? Styles.warningIcon : Styles.errorIcon), Styles.messageStyle);
}
EditorGUIUtility.SetIconSize(Vector2.zero);
GUILayout.EndScrollView();
}
ShaderMessage[] m_ShaderMessages;
private void ShowShaderErrors(Shader s)
{
if (Event.current.type == EventType.Layout)
{
int n = ShaderUtil.GetShaderMessageCount(s);
m_ShaderMessages = null;
if (n >= 1)
{
m_ShaderMessages = ShaderUtil.GetShaderMessages(s);
}
}
if (m_ShaderMessages == null)
return;
ShaderErrorListUI(s, m_ShaderMessages, ref m_ScrollPosition);
}
// Compiled shader code button+dropdown
private void ShowCompiledCodeButton(Shader s)
{
EditorGUILayout.BeginVertical();
ShaderImporter importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(s.GetInstanceID())) as ShaderImporter;
s_PreprocessOnly = EditorGUILayout.Toggle(Styles.togglePreprocess, s_PreprocessOnly);
if (s_PreprocessOnly)
s_StripLineDirectives = EditorGUILayout.Toggle(Styles.toggleStripLineDirective, s_StripLineDirectives);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Compiled code", EditorStyles.miniButton);
var hasCode = ShaderUtil.HasShaderSnippets(s) || ShaderUtil.HasSurfaceShaders(s) || ShaderUtil.HasFixedFunctionShaders(s);
if (hasCode)
{
// button with a drop-down part on the right
var modeContent = Styles.showCurrent;
var modeRect = GUILayoutUtility.GetRect(modeContent, EditorStyles.miniButton, GUILayout.ExpandWidth(false));
var modeDropRect = new Rect(modeRect.xMax - 16, modeRect.y, 16, modeRect.height);
if (EditorGUI.DropdownButton(modeDropRect, GUIContent.none, FocusType.Passive, GUIStyle.none))
{
Rect rect = GUILayoutUtility.topLevel.GetLast();
PopupWindow.Show(rect, new ShaderInspectorPlatformsPopup(s));
GUIUtility.ExitGUI();
}
if (GUI.Button(modeRect, modeContent, EditorStyles.miniButton))
{
ShaderUtil.OpenCompiledShader(s, ShaderInspectorPlatformsPopup.currentMode, ShaderInspectorPlatformsPopup.currentPlatformMask, ShaderInspectorPlatformsPopup.currentVariantStripping == 0, s_PreprocessOnly, s_StripLineDirectives);
GUIUtility.ExitGUI();
}
}
else
{
// Note: PrefixLabel is sometimes buggy if followed by a non-control (like Label).
// We just want to show a label here, but have to pretend it's a button so it is treated like
// a control.
GUILayout.Button("none (precompiled shader)", GUI.skin.label);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
}
// "show surface shader" button
private static void ShowSurfaceShaderButton(Shader s)
{
var hasSurface = ShaderUtil.HasSurfaceShaders(s);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Surface shader", EditorStyles.miniButton);
if (hasSurface)
{
// check if this is a built-in shader (has no importer);
// we can't show generated code in that case
var builtinShader = (AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(s)) == null);
if (!builtinShader)
{
if (GUILayout.Button(Styles.showSurface, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
ShaderUtil.OpenParsedSurfaceShader(s);
GUIUtility.ExitGUI();
}
}
else
{
// See comment below why this is a button.
GUILayout.Button(Styles.builtinShader, GUI.skin.label);
}
}
else
{
// Note: PrefixLabel is sometimes buggy if followed by a non-control (like Label).
// We just want to show a label here, but have to pretend it's a button so it is treated like
// a control.
GUILayout.Button(Styles.no, GUI.skin.label);
}
EditorGUILayout.EndHorizontal();
}
// "show fixed function shader" button
private static void ShowFixedFunctionShaderButton(Shader s)
{
var hasFF = ShaderUtil.HasFixedFunctionShaders(s);
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Fixed function", EditorStyles.miniButton);
if (hasFF)
{
// check if this is a built-in shader (has no importer);
// we can't show generated code in that case
var builtinShader = (AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(s)) == null);
if (!builtinShader)
{
if (GUILayout.Button(Styles.showFF, EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
ShaderUtil.OpenGeneratedFixedFunctionShader(s);
GUIUtility.ExitGUI();
}
}
else
{
// See comment below why this is a button.
GUILayout.Button(Styles.builtinShader, GUI.skin.label);
}
}
else
{
// Note: PrefixLabel is sometimes buggy if followed by a non-control (like Label).
// We just want to show a label here, but have to pretend it's a button so it is treated like
// a control.
GUILayout.Button(Styles.no, GUI.skin.label);
}
EditorGUILayout.EndHorizontal();
}
}
// Popup window to select which platforms to compile a shader for.
internal class ShaderInspectorPlatformsPopup : PopupWindowContent
{
private class Styles
{
static public readonly GUIStyle menuItem = "MenuItem";
static public readonly GUIStyle separator = "sv_iconselector_sep";
}
static internal readonly string[] s_PlatformModes =
{
"Current graphics device",
"Current build platform",
"All platforms",
"Custom:"
};
private static string[] s_ShaderPlatformNames;
private static int[] s_ShaderPlatformIndices;
const float kFrameWidth = 1f;
const float kSeparatorHeight = 6;
private readonly Shader m_Shader;
private ulong totalVariants;
private ulong variantsWithUsage;
public static int currentMode
{
get
{
if (s_CurrentMode < 0)
s_CurrentMode = EditorPrefs.GetInt("ShaderInspectorPlatformMode", 1);
return s_CurrentMode;
}
set
{
s_CurrentMode = value;
EditorPrefs.SetInt("ShaderInspectorPlatformMode", value);
}
}
static int s_CurrentMode = -1;
public static int currentPlatformMask
{
get
{
if (s_CurrentPlatformMask < 0)
{
int defaultMask = (1 << Enum.GetNames(typeof(Rendering.ShaderCompilerPlatform)).Length - 1);
s_CurrentPlatformMask = EditorPrefs.GetInt("ShaderInspectorPlatformMask", defaultMask);
}
return s_CurrentPlatformMask;
}
set
{
s_CurrentPlatformMask = value;
EditorPrefs.SetInt("ShaderInspectorPlatformMask", value);
}
}
static int s_CurrentPlatformMask = -1;
public static int currentVariantStripping
{
get
{
if (s_CurrentVariantStripping < 0)
s_CurrentVariantStripping = EditorPrefs.GetInt("ShaderInspectorVariantStripping", 1);
return s_CurrentVariantStripping;
}
set
{
s_CurrentVariantStripping = value;
EditorPrefs.SetInt("ShaderInspectorVariantStripping", value);
}
}
static int s_CurrentVariantStripping = -1;
public ShaderInspectorPlatformsPopup(Shader shader)
{
m_Shader = shader;
InitializeShaderPlatforms();
totalVariants = 0;
variantsWithUsage = 0;
}
static void InitializeShaderPlatforms()
{
if (s_ShaderPlatformNames != null)
return;
int platformMask = ShaderUtil.GetAvailableShaderCompilerPlatforms();
var names = new List<string>();
var indices = new List<int>();
for (int i = 0; i < 32; ++i)
{
if ((platformMask & (1 << i)) == 0)
continue;
names.Add(((Rendering.ShaderCompilerPlatform)i).ToString());
indices.Add(i);
}
s_ShaderPlatformNames = names.ToArray();
s_ShaderPlatformIndices = indices.ToArray();
currentPlatformMask &= platformMask;
}
public override Vector2 GetWindowSize()
{
var rowCount = s_PlatformModes.Length + s_ShaderPlatformNames.Length + 2;
var windowHeight = rowCount * EditorGUI.kSingleLineHeight + kSeparatorHeight * 3;
windowHeight += 2 * kFrameWidth;
var windowSize = new Vector2(210, windowHeight);
return windowSize;
}
public override void OnGUI(Rect rect)
{
if (m_Shader == null)
return;
// We do not use the layout event
if (Event.current.type == EventType.Layout)
return;
Draw(editorWindow, rect.width);
// Use mouse move so we get hover state correctly in the menu item rows
if (Event.current.type == EventType.MouseMove)
Event.current.Use();
// Escape closes the window
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape)
{
editorWindow.Close();
GUIUtility.ExitGUI();
}
}
private void DrawSeparator(ref Rect rect)
{
GUI.Label(new Rect(rect.x + 5, rect.y + 3, rect.width - 10, 3), GUIContent.none, Styles.separator);
rect.y += kSeparatorHeight;
}
private void Draw(EditorWindow caller, float listElementWidth)
{
var drawPos = new Rect(0, 0, listElementWidth, EditorGUI.kSingleLineHeight);
// Generic platform modes
for (var i = 0; i < s_PlatformModes.Length; ++i)
{
DoOneMode(drawPos, i);
drawPos.y += EditorGUI.kSingleLineHeight;
}
// Custom platform settings
Color oldColor = GUI.color;
if (currentMode != 3) // darker color when "Custom" is not selected
GUI.color *= new Color(1, 1, 1, 0.7f);
drawPos.xMin += 16.0f;
for (var i = 0; i < s_ShaderPlatformNames.Length; ++i)
{
DoCustomPlatformBit(drawPos, i);
drawPos.y += EditorGUI.kSingleLineHeight;
}
GUI.color = oldColor;
drawPos.xMin -= 16.0f;
DrawSeparator(ref drawPos);
DoShaderVariants(caller, ref drawPos);
}
void DoOneMode(Rect rect, int index)
{
EditorGUI.BeginChangeCheck();
GUI.Toggle(rect, currentMode == index, EditorGUIUtility.TempContent(s_PlatformModes[index]), Styles.menuItem);
if (EditorGUI.EndChangeCheck())
currentMode = index;
}
void DoCustomPlatformBit(Rect rect, int index)
{
EditorGUI.BeginChangeCheck();
int maskBit = 1 << s_ShaderPlatformIndices[index];
bool on = (currentPlatformMask & maskBit) != 0;
on = GUI.Toggle(rect, on, EditorGUIUtility.TempContent(s_ShaderPlatformNames[index]), Styles.menuItem);
if (EditorGUI.EndChangeCheck())
{
if (on)
currentPlatformMask |= maskBit;
else
currentPlatformMask &= ~maskBit;
currentMode = 3; // custom
}
}
static string FormatCount(ulong count)
{
if (count > 1000 * 1000 * 1000)
return ((double)count / 1000000000.0).ToString("f2", CultureInfo.InvariantCulture.NumberFormat) + "B";
if (count > 1000 * 1000)
return ((double)count / 1000000.0).ToString("f2", CultureInfo.InvariantCulture.NumberFormat) + "M";
if (count > 1000)
return ((double)count / 1000.0).ToString("f2", CultureInfo.InvariantCulture.NumberFormat) + "K";
return count.ToString();
}
void DoShaderVariants(EditorWindow caller, ref Rect drawPos)
{
// setting for whether shader variants should be stripped
EditorGUI.BeginChangeCheck();
bool strip = GUI.Toggle(drawPos, currentVariantStripping == 1, EditorGUIUtility.TempContent("Skip unused shader_features"), Styles.menuItem);
drawPos.y += EditorGUI.kSingleLineHeight;
if (EditorGUI.EndChangeCheck())
currentVariantStripping = strip ? 1 : 0;
// display included variant count, and a button to show list of them
drawPos.y += kSeparatorHeight;
ulong variantCount = 0;
if (strip)
{
if (variantsWithUsage == 0)
variantsWithUsage = ShaderUtil.GetVariantCount(m_Shader, true);
variantCount = variantsWithUsage;
}
else
{
if (totalVariants == 0)
totalVariants = ShaderUtil.GetVariantCount(m_Shader, false);
variantCount = totalVariants;
}
var variantText = FormatCount(variantCount) +
(strip ?
" variants included" :
" variants total");
Rect buttonRect = drawPos;
buttonRect.x += Styles.menuItem.padding.left;
buttonRect.width -= Styles.menuItem.padding.left + 4;
GUI.Label(buttonRect, variantText);
buttonRect.xMin = buttonRect.xMax - 40;
if (GUI.Button(buttonRect, "Show", EditorStyles.miniButtonMid))
{
ShaderUtil.OpenShaderCombinations(m_Shader, strip);
caller.Close();
GUIUtility.ExitGUI();
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/ShaderInspector.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/ShaderInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 15478
} | 297 |
// 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
{
// Version for editors not derived from AssetImporterEditor
internal abstract class TabbedEditor : Editor
{
protected System.Type[] m_SubEditorTypes = null;
protected string[] m_SubEditorNames = null;
private int m_ActiveEditorIndex = 0;
private Editor m_ActiveEditor;
public Editor activeEditor { get { return m_ActiveEditor; } }
internal virtual void OnEnable()
{
m_ActiveEditorIndex = EditorPrefs.GetInt(GetType().Name + "ActiveEditorIndex", 0);
if (m_ActiveEditor == null)
m_ActiveEditor = CreateEditor(targets, m_SubEditorTypes[m_ActiveEditorIndex]);
}
void OnDestroy()
{
DestroyImmediate(activeEditor);
}
public override void OnInspectorGUI()
{
using (new GUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
using (var check = new EditorGUI.ChangeCheckScope())
{
m_ActiveEditorIndex = GUILayout.Toolbar(m_ActiveEditorIndex, m_SubEditorNames, "LargeButton", GUI.ToolbarButtonSize.FitToContents);
if (check.changed)
{
EditorPrefs.SetInt(GetType().Name + "ActiveEditorIndex", m_ActiveEditorIndex);
var oldEditor = activeEditor;
m_ActiveEditor = null;
DestroyImmediate(oldEditor);
m_ActiveEditor = CreateEditor(targets, m_SubEditorTypes[m_ActiveEditorIndex]);
}
}
GUILayout.FlexibleSpace();
}
activeEditor.OnInspectorGUI();
}
public override void OnPreviewSettings()
{
activeEditor.OnPreviewSettings();
}
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
activeEditor.OnInteractivePreviewGUI(r, background);
}
public override bool HasPreviewGUI()
{
return activeEditor.HasPreviewGUI();
}
}
}
| UnityCsReference/Editor/Mono/Inspector/TabbedEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/TabbedEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 1084
} | 298 |
// 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.Reflection;
using System.Text;
using UnityEngine;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.Events;
using Object = UnityEngine.Object;
using UnityEngine.Pool;
using UnityEngine.UIElements;
namespace UnityEditorInternal
{
[CustomPropertyDrawer(typeof(UnityEventBase), true)]
public class UnityEventDrawer : PropertyDrawer
{
internal struct PropertyData
{
public SerializedProperty mode;
public SerializedProperty arguments;
public SerializedProperty callState;
public SerializedProperty listenerTarget;
public SerializedProperty methodName;
public SerializedProperty objectArgument;
}
protected class State
{
internal ReorderableList m_ReorderableList;
public int lastSelectedIndex;
}
private const string kNoFunctionString = "No Function";
//Persistent Listener Paths
internal const string kInstancePath = "m_Target";
internal const string kInstanceTypePath = "m_TargetAssemblyTypeName";
internal const string kCallStatePath = "m_CallState";
internal const string kArgumentsPath = "m_Arguments";
internal const string kModePath = "m_Mode";
internal const string kMethodNamePath = "m_MethodName";
internal const string kCallsPath = "m_PersistentCalls.m_Calls";
//ArgumentCache paths
internal const string kFloatArgument = "m_FloatArgument";
internal const string kIntArgument = "m_IntArgument";
internal const string kObjectArgument = "m_ObjectArgument";
internal const string kStringArgument = "m_StringArgument";
internal const string kBoolArgument = "m_BoolArgument";
internal const string kObjectArgumentAssemblyTypeName = "m_ObjectArgumentAssemblyTypeName";
//property path splits and separators
private const string kDotString = ".";
private const string kArrayDataString = "Array.data[";
private static readonly char[] kDotSeparator = { '.' };
private static readonly char[] kClosingSquareBraceSeparator = { ']' };
// uss names
internal const string kUssClassName = "unity-event";
internal const string kLeftColumnClassName = kUssClassName + "__left-column";
internal const string kRightColumnClassName = kUssClassName + "__right-column";
internal const string kContainerClassName = kUssClassName + "__container";
internal const string kHeaderClassName = "unity-list-view__header";
internal const string kListViewScrollViewClassName = kUssClassName + "__list-view-scroll-view";
internal const string kListViewItemClassName = kUssClassName + "__list-view-item";
string m_Text;
UnityEventBase m_DummyEvent;
SerializedProperty m_Prop;
SerializedProperty m_ListenersArray;
const int kExtraSpacing = 9;
//State:
ReorderableList m_ReorderableList;
int m_LastSelectedIndex;
Dictionary<string, State> m_States = new Dictionary<string, State>();
static string GetEventParams(UnityEventBase evt)
{
var methodInfo = evt.FindMethod("Invoke", evt.GetType(), PersistentListenerMode.EventDefined, null);
var sb = new StringBuilder();
sb.Append(" (");
var types = methodInfo.GetParameters().Select(x => x.ParameterType).ToArray();
for (int i = 0; i < types.Length; i++)
{
sb.Append(types[i].Name);
if (i < types.Length - 1)
{
sb.Append(", ");
}
}
sb.Append(")");
return sb.ToString();
}
private State GetState(SerializedProperty prop)
{
State state;
string key = prop.propertyPath;
m_States.TryGetValue(key, out state);
// ensure the cached SerializedProperty is synchronized (case 974069)
if (state == null || state.m_ReorderableList.serializedProperty.serializedObject != prop.serializedObject)
{
if (state == null)
state = new State();
SerializedProperty listenersArray = prop.FindPropertyRelative(kCallsPath);
state.m_ReorderableList =
new ReorderableList(prop.serializedObject, listenersArray, true, true, true, true)
{
drawHeaderCallback = DrawEventHeader,
drawElementCallback = DrawEvent,
onSelectCallback = OnSelectEvent,
onReorderCallback = OnReorderEvent,
onAddCallback = OnAddEvent,
onRemoveCallback = OnRemoveEvent
};
SetupReorderableList(state.m_ReorderableList);
m_States[key] = state;
}
return state;
}
private State RestoreState(SerializedProperty property)
{
State state = GetState(property);
m_ListenersArray = state.m_ReorderableList.serializedProperty;
m_ReorderableList = state.m_ReorderableList;
m_LastSelectedIndex = state.lastSelectedIndex;
m_ReorderableList.index = m_LastSelectedIndex;
return state;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
m_Prop = property;
m_Text = label.text;
State state = RestoreState(property);
OnGUI(position);
state.lastSelectedIndex = m_LastSelectedIndex;
}
private ListView CreateListView(SerializedProperty property)
{
var listView = new ListView
{
showAddRemoveFooter = true,
reorderMode = ListViewReorderMode.Animated,
showBorder = true,
showFoldoutHeader = false,
showBoundCollectionSize = false,
showAlternatingRowBackgrounds = AlternatingRowBackground.None,
fixedItemHeight = GetElementHeight()
};
var propertyRelative = property.FindPropertyRelative(kCallsPath);
listView.bindingPath = propertyRelative.propertyPath;
listView.makeItem += () => new UnityEventItem();
listView.bindItem += (VisualElement element, int i) =>
{
if (i >= propertyRelative.arraySize)
{
return;
}
var pListener = propertyRelative.GetArrayElementAtIndex(i);
var arguments = pListener.FindPropertyRelative(kArgumentsPath);
var listenerTarget = pListener.FindPropertyRelative(kInstancePath);
var propertyData = new PropertyData()
{
mode = pListener.FindPropertyRelative(kModePath),
arguments = arguments,
callState = pListener.FindPropertyRelative(kCallStatePath),
listenerTarget = listenerTarget,
methodName = pListener.FindPropertyRelative(kMethodNamePath),
objectArgument = arguments.FindPropertyRelative(kObjectArgument)
};
Func<GenericMenu> createMenuCallback = () =>
{
var genericMenu = BuildPopupList(listenerTarget.objectReferenceValue, m_DummyEvent, pListener);
return genericMenu;
};
Func<string, string> formatSelectedValueCallback = (value) =>
{
return GetFunctionDropdownText(pListener);
};
Func<SerializedProperty> getArgumentCallback = () =>
{
return GetArgument(pListener);
};
var eventItem = element as UnityEventItem;
eventItem.BindFields(propertyData, createMenuCallback, formatSelectedValueCallback, getArgumentCallback);
};
listView.itemsAdded += indices =>
{
foreach (var i in indices)
{
var pListener = propertyRelative.GetArrayElementAtIndex(i);
var callState = pListener.FindPropertyRelative(kCallStatePath);
// SERIAL-124
// Objects added to an array via SerializedObject do not have their default values set.
// Therefore we need to set the initial values here to fix UUM-27561
callState.enumValueIndex = (int)UnityEventCallState.RuntimeOnly;
callState.serializedObject.ApplyModifiedPropertiesWithoutUndo();
}
};
return listView;
}
private SerializedProperty GetArgument(SerializedProperty pListener)
{
var listenerTarget = pListener.FindPropertyRelative(kInstancePath);
var methodName = pListener.FindPropertyRelative(kMethodNamePath);
var mode = pListener.FindPropertyRelative(kModePath);
var arguments = pListener.FindPropertyRelative(kArgumentsPath);
SerializedProperty argument;
var modeEnum = GetMode(mode);
//only allow argument if we have a valid target / method
if (listenerTarget.objectReferenceValue == null || string.IsNullOrEmpty(methodName.stringValue))
modeEnum = PersistentListenerMode.Void;
switch (modeEnum)
{
case PersistentListenerMode.Float:
argument = arguments.FindPropertyRelative(kFloatArgument);
break;
case PersistentListenerMode.Int:
argument = arguments.FindPropertyRelative(kIntArgument);
break;
case PersistentListenerMode.Object:
argument = arguments.FindPropertyRelative(kObjectArgument);
break;
case PersistentListenerMode.String:
argument = arguments.FindPropertyRelative(kStringArgument);
break;
case PersistentListenerMode.Bool:
argument = arguments.FindPropertyRelative(kBoolArgument);
break;
default:
argument = arguments.FindPropertyRelative(kIntArgument);
break;
}
return argument;
}
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
m_Prop = property;
m_Text = preferredLabel;
m_DummyEvent = GetDummyEvent(m_Prop);
var listViewContainer = new VisualElement();
listViewContainer.AddToClassList(kContainerClassName);
var header = new Label();
header.text = GetHeaderText();
header.tooltip = property.tooltip;
BindingsStyleHelpers.RegisterRightClickMenu(header, property);
header.AddToClassList(kHeaderClassName);
var listView = CreateListView(property);
listView.scrollView.AddToClassList(kListViewScrollViewClassName);
listViewContainer.Add(header);
listViewContainer.Add(listView);
return listViewContainer;
}
private float GetElementHeight()
{
return EditorGUI.kSingleLineHeight * 2 + EditorGUI.kControlVerticalSpacing + kExtraSpacing;
}
private string GetHeaderText()
{
return (string.IsNullOrEmpty(m_Text) ? "Event" : m_Text) + GetEventParams(m_DummyEvent);
}
private string GetFunctionDropdownText(SerializedProperty pListener)
{
var listenerTarget = pListener.FindPropertyRelative(kInstancePath);
var methodName = pListener.FindPropertyRelative(kMethodNamePath);
var mode = pListener.FindPropertyRelative(kModePath);
var arguments = pListener.FindPropertyRelative(kArgumentsPath);
var desiredArgTypeName = arguments.FindPropertyRelative(kObjectArgumentAssemblyTypeName).stringValue;
var desiredType = typeof(Object);
if (!string.IsNullOrEmpty(desiredArgTypeName))
desiredType = Type.GetType(desiredArgTypeName, false) ?? typeof(Object);
var buttonLabel = new StringBuilder();
if (listenerTarget.objectReferenceValue == null || string.IsNullOrEmpty(methodName.stringValue))
{
buttonLabel.Append(kNoFunctionString);
}
else if (!IsPersistantListenerValid(m_DummyEvent, methodName.stringValue, listenerTarget.objectReferenceValue, GetMode(mode), desiredType))
{
var instanceString = "UnknownComponent";
var instance = listenerTarget.objectReferenceValue;
if (instance != null)
instanceString = instance.GetType().Name;
buttonLabel.Append(string.Format("<Missing {0}.{1}>", instanceString, methodName.stringValue));
}
else
{
buttonLabel.Append(listenerTarget.objectReferenceValue.GetType().Name);
if (!string.IsNullOrEmpty(methodName.stringValue))
{
buttonLabel.Append(".");
if (methodName.stringValue.StartsWith("set_"))
buttonLabel.Append(methodName.stringValue.Substring(4));
else
buttonLabel.Append(methodName.stringValue);
}
}
return buttonLabel.ToString();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
//TODO: Also we need to have a constructor or initializer called for this property Drawer, before OnGUI or GetPropertyHeight
//otherwise, we get Restore the State twice, once here and again in OnGUI. Maybe we should only do it here?
RestoreState(property);
float height = 0f;
if (m_ReorderableList != null)
{
height = m_ReorderableList.GetHeight();
}
return height;
}
public void OnGUI(Rect position)
{
if (m_ListenersArray == null || !m_ListenersArray.isArray)
return;
m_DummyEvent = GetDummyEvent(m_Prop);
if (m_DummyEvent == null)
return;
if (m_ReorderableList != null)
{
var oldIdentLevel = EditorGUI.indentLevel;
position = EditorGUI.IndentedRect(position);
EditorGUI.indentLevel = 0;
m_ReorderableList.DoList(position);
EditorGUI.indentLevel = oldIdentLevel;
}
}
protected virtual void SetupReorderableList(ReorderableList list)
{
// Two standard lines with standard spacing between and extra spacing below to better separate items visually.
list.elementHeight = GetElementHeight();
}
protected virtual void DrawEventHeader(Rect headerRect)
{
headerRect.height = EditorGUI.kSingleLineHeight;
string text = GetHeaderText();
GUI.Label(headerRect, text);
}
static PersistentListenerMode GetMode(SerializedProperty mode)
{
return (PersistentListenerMode)mode.enumValueIndex;
}
protected virtual void DrawEvent(Rect rect, int index, bool isActive, bool isFocused)
{
var pListener = m_ListenersArray.GetArrayElementAtIndex(index);
rect.y++;
Rect[] subRects = GetRowRects(rect);
Rect enabledRect = subRects[0];
Rect goRect = subRects[1];
Rect functionRect = subRects[2];
Rect argRect = subRects[3];
// find the current event target...
var callState = pListener.FindPropertyRelative(kCallStatePath);
var mode = pListener.FindPropertyRelative(kModePath);
var arguments = pListener.FindPropertyRelative(kArgumentsPath);
var listenerTarget = pListener.FindPropertyRelative(kInstancePath);
var methodName = pListener.FindPropertyRelative(kMethodNamePath);
Color c = GUI.backgroundColor;
GUI.backgroundColor = Color.white;
EditorGUI.PropertyField(enabledRect, callState, GUIContent.none);
EditorGUI.BeginChangeCheck();
{
GUI.Box(goRect, GUIContent.none);
EditorGUI.PropertyField(goRect, listenerTarget, GUIContent.none);
if (EditorGUI.EndChangeCheck())
methodName.stringValue = null;
}
SerializedProperty argument = GetArgument(pListener);
var modeEnum = GetMode(mode);
//only allow argument if we have a valid target / method
if (listenerTarget.objectReferenceValue == null || string.IsNullOrEmpty(methodName.stringValue))
modeEnum = PersistentListenerMode.Void;
var desiredArgTypeName = arguments.FindPropertyRelative(kObjectArgumentAssemblyTypeName).stringValue;
var desiredType = typeof(Object);
if (!string.IsNullOrEmpty(desiredArgTypeName))
desiredType = Type.GetType(desiredArgTypeName, false) ?? typeof(Object);
if (modeEnum == PersistentListenerMode.Object)
{
EditorGUI.BeginChangeCheck();
var result = EditorGUI.ObjectField(argRect, GUIContent.none, argument.objectReferenceValue, desiredType, true);
if (EditorGUI.EndChangeCheck())
argument.objectReferenceValue = result;
}
else if (modeEnum != PersistentListenerMode.Void && modeEnum != PersistentListenerMode.EventDefined)
EditorGUI.PropertyField(argRect, argument, GUIContent.none);
using (new EditorGUI.DisabledScope(listenerTarget.objectReferenceValue == null))
{
EditorGUI.BeginProperty(functionRect, GUIContent.none, methodName);
{
GUIContent buttonContent;
if (EditorGUI.showMixedValue)
{
buttonContent = EditorGUI.mixedValueContent;
}
else
{
var buttonLabel = GetFunctionDropdownText(pListener);
buttonContent = GUIContent.Temp(buttonLabel.ToString());
}
if (EditorGUI.DropdownButton(functionRect, buttonContent, FocusType.Passive, EditorStyles.popup))
BuildPopupList(listenerTarget.objectReferenceValue, m_DummyEvent, pListener).DropDown(functionRect);
}
EditorGUI.EndProperty();
}
GUI.backgroundColor = c;
}
Rect[] GetRowRects(Rect rect)
{
Rect[] rects = new Rect[4];
rect.height = EditorGUI.kSingleLineHeight;
rect.y += 2;
Rect enabledRect = rect;
enabledRect.width *= 0.3f;
Rect goRect = enabledRect;
goRect.y += EditorGUIUtility.singleLineHeight + EditorGUI.kControlVerticalSpacing;
Rect functionRect = rect;
functionRect.xMin = goRect.xMax + EditorGUI.kSpacing;
Rect argRect = functionRect;
argRect.y += EditorGUIUtility.singleLineHeight + EditorGUI.kControlVerticalSpacing;
rects[0] = enabledRect;
rects[1] = goRect;
rects[2] = functionRect;
rects[3] = argRect;
return rects;
}
protected virtual void OnRemoveEvent(ReorderableList list)
{
ReorderableList.defaultBehaviours.DoRemoveButton(list);
m_LastSelectedIndex = list.index;
}
protected virtual void OnAddEvent(ReorderableList list)
{
if (m_ListenersArray.hasMultipleDifferentValues)
{
//When increasing a multi-selection array using Serialized Property
//Data can be overwritten if there is mixed values.
//The Serialization system applies the Serialized data of one object, to all other objects in the selection.
//We handle this case here, by creating a SerializedObject for each object.
//Case 639025.
foreach (var targetObject in m_ListenersArray.serializedObject.targetObjects)
{
using (var temSerialziedObject = new SerializedObject(targetObject))
{
var listenerArrayProperty = temSerialziedObject.FindProperty(m_ListenersArray.propertyPath);
listenerArrayProperty.arraySize += 1;
temSerialziedObject.ApplyModifiedProperties();
}
}
m_ListenersArray.serializedObject.SetIsDifferentCacheDirty();
m_ListenersArray.serializedObject.Update();
list.index = list.serializedProperty.arraySize - 1;
}
else
{
ReorderableList.defaultBehaviours.DoAddButton(list);
}
m_LastSelectedIndex = list.index;
var pListener = m_ListenersArray.GetArrayElementAtIndex(list.index);
var callState = pListener.FindPropertyRelative(kCallStatePath);
var listenerTarget = pListener.FindPropertyRelative(kInstancePath);
var methodName = pListener.FindPropertyRelative(kMethodNamePath);
var mode = pListener.FindPropertyRelative(kModePath);
var arguments = pListener.FindPropertyRelative(kArgumentsPath);
callState.enumValueIndex = (int)UnityEventCallState.RuntimeOnly;
listenerTarget.objectReferenceValue = null;
methodName.stringValue = null;
mode.enumValueIndex = (int)PersistentListenerMode.Void;
arguments.FindPropertyRelative(kFloatArgument).floatValue = 0;
arguments.FindPropertyRelative(kIntArgument).intValue = 0;
arguments.FindPropertyRelative(kObjectArgument).objectReferenceValue = null;
arguments.FindPropertyRelative(kStringArgument).stringValue = null;
arguments.FindPropertyRelative(kObjectArgumentAssemblyTypeName).stringValue = null;
}
protected virtual void OnSelectEvent(ReorderableList list)
{
m_LastSelectedIndex = list.index;
}
protected virtual void OnReorderEvent(ReorderableList list)
{
m_LastSelectedIndex = list.index;
}
internal static UnityEventBase GetDummyEvent(SerializedProperty prop)
{
//Use the SerializedProperty path to iterate through the fields of the inspected targetObject
Object tgtobj = prop.serializedObject.targetObject;
if (tgtobj == null)
return new UnityEvent();
ScriptAttributeUtility.GetFieldInfoAndStaticTypeFromProperty(prop, out var propType);
if (propType.IsSubclassOf(typeof(UnityEventBase)))
return Activator.CreateInstance(propType) as UnityEventBase;
return new UnityEvent();
}
struct ValidMethodMap
{
public Object target;
public MethodInfo methodInfo;
public PersistentListenerMode mode;
}
static IEnumerable<ValidMethodMap> CalculateMethodMap(Object target, Type[] t, bool allowSubclasses)
{
var validMethods = new List<ValidMethodMap>();
if (target == null || t == null)
return validMethods;
// find the methods on the behaviour that match the signature
Type componentType = target.GetType();
var componentMethods = componentType.GetMethods().Where(x => !x.IsSpecialName).ToList();
var wantedProperties = componentType.GetProperties().AsEnumerable();
wantedProperties = wantedProperties.Where(x => x.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length == 0 && x.GetSetMethod() != null);
componentMethods.AddRange(wantedProperties.Select(x => x.GetSetMethod()));
foreach (var componentMethod in componentMethods)
{
//Debug.Log ("Method: " + componentMethod);
// if the argument length is not the same, no match
var componentParamaters = componentMethod.GetParameters();
if (componentParamaters.Length != t.Length)
continue;
// Don't show obsolete methods.
if (componentMethod.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0)
continue;
if (componentMethod.ReturnType != typeof(void))
continue;
// if the argument types do not match, no match
bool paramatersMatch = true;
for (int i = 0; i < t.Length; i++)
{
if (!componentParamaters[i].ParameterType.IsAssignableFrom(t[i]))
paramatersMatch = false;
if (allowSubclasses && t[i].IsAssignableFrom(componentParamaters[i].ParameterType))
paramatersMatch = true;
}
// valid method
if (paramatersMatch)
{
var vmm = new ValidMethodMap
{
target = target,
methodInfo = componentMethod
};
validMethods.Add(vmm);
}
}
return validMethods;
}
public static bool IsPersistantListenerValid(UnityEventBase dummyEvent, string methodName, Object uObject, PersistentListenerMode modeEnum, Type argumentType)
{
if (uObject == null || string.IsNullOrEmpty(methodName))
return false;
return dummyEvent.FindMethod(methodName, uObject.GetType(), modeEnum, argumentType) != null;
}
internal static GenericMenu BuildPopupList(Object target, UnityEventBase dummyEvent, SerializedProperty listener)
{
//special case for components... we want all the game objects targets there!
var targetToUse = target;
if (targetToUse is Component)
targetToUse = (target as Component).gameObject;
// find the current event target...
var methodName = listener.FindPropertyRelative(kMethodNamePath);
var menu = new GenericMenu();
menu.AddItem(new GUIContent(kNoFunctionString),
string.IsNullOrEmpty(methodName.stringValue),
ClearEventFunction,
new UnityEventFunction(listener, null, null, PersistentListenerMode.EventDefined));
if (targetToUse == null)
return menu;
menu.AddSeparator("");
// figure out the signature of this delegate...
// The property at this stage points to the 'container' and has the field name
Type delegateType = dummyEvent.GetType();
// check out the signature of invoke as this is the callback!
MethodInfo delegateMethod = delegateType.GetMethod("Invoke");
var delegateArgumentsTypes = delegateMethod.GetParameters().Select(x => x.ParameterType).ToArray();
var duplicateNames = DictionaryPool<string, int>.Get();
var duplicateFullNames = DictionaryPool<string, int>.Get();
GeneratePopUpForType(menu, targetToUse, targetToUse.GetType().Name, listener, delegateArgumentsTypes);
duplicateNames[targetToUse.GetType().Name] = 0;
if (targetToUse is GameObject)
{
Component[] comps = (targetToUse as GameObject).GetComponents<Component>();
// Collect all the names and record how many times the same name is used.
foreach (Component comp in comps)
{
if (comp == null)
continue;
var duplicateIndex = 0;
if (duplicateNames.TryGetValue(comp.GetType().Name, out duplicateIndex))
duplicateIndex++;
duplicateNames[comp.GetType().Name] = duplicateIndex;
}
foreach (Component comp in comps)
{
if (comp == null)
continue;
var compType = comp.GetType();
string targetName = compType.Name;
int duplicateIndex = 0;
// Is this name used multiple times? If so then use the full name plus an index if there are also duplicates of this. (case 1309997)
if (duplicateNames[compType.Name] > 0)
{
if (duplicateFullNames.TryGetValue(compType.FullName, out duplicateIndex))
targetName = $"{compType.FullName} ({duplicateIndex})";
else
targetName = compType.FullName;
}
GeneratePopUpForType(menu, comp, targetName, listener, delegateArgumentsTypes);
duplicateFullNames[compType.FullName] = duplicateIndex + 1;
}
DictionaryPool<string, int>.Release(duplicateNames);
DictionaryPool<string, int>.Release(duplicateFullNames);
}
return menu;
}
private static void GeneratePopUpForType(GenericMenu menu, Object target, string targetName, SerializedProperty listener, Type[] delegateArgumentsTypes)
{
var methods = new List<ValidMethodMap>();
bool didAddDynamic = false;
// skip 'void' event defined on the GUI as we have a void prebuilt type!
if (delegateArgumentsTypes.Length != 0)
{
GetMethodsForTargetAndMode(target, delegateArgumentsTypes, methods, PersistentListenerMode.EventDefined);
if (methods.Count > 0)
{
menu.AddDisabledItem(new GUIContent(targetName + "/Dynamic " + string.Join(", ", delegateArgumentsTypes.Select(e => GetTypeName(e)).ToArray())));
AddMethodsToMenu(menu, listener, methods, targetName);
didAddDynamic = true;
}
}
methods.Clear();
GetMethodsForTargetAndMode(target, new[] {typeof(float)}, methods, PersistentListenerMode.Float);
GetMethodsForTargetAndMode(target, new[] {typeof(int)}, methods, PersistentListenerMode.Int);
GetMethodsForTargetAndMode(target, new[] {typeof(string)}, methods, PersistentListenerMode.String);
GetMethodsForTargetAndMode(target, new[] {typeof(bool)}, methods, PersistentListenerMode.Bool);
GetMethodsForTargetAndMode(target, new[] {typeof(Object)}, methods, PersistentListenerMode.Object);
GetMethodsForTargetAndMode(target, new Type[] {}, methods, PersistentListenerMode.Void);
if (methods.Count > 0)
{
if (didAddDynamic)
// AddSeperator doesn't seem to work for sub-menus, so we have to use this workaround instead of a proper separator for now.
menu.AddItem(new GUIContent(targetName + "/ "), false, null);
if (delegateArgumentsTypes.Length != 0)
menu.AddDisabledItem(new GUIContent(targetName + "/Static Parameters"));
AddMethodsToMenu(menu, listener, methods, targetName);
}
}
private static void AddMethodsToMenu(GenericMenu menu, SerializedProperty listener, List<ValidMethodMap> methods, string targetName)
{
// Note: sorting by a bool in OrderBy doesn't seem to work for some reason, so using numbers explicitly.
IEnumerable<ValidMethodMap> orderedMethods = methods.OrderBy(e => e.methodInfo.Name.StartsWith("set_") ? 0 : 1).ThenBy(e => e.methodInfo.Name);
foreach (var validMethod in orderedMethods)
AddFunctionsForScript(menu, listener, validMethod, targetName);
}
private static void GetMethodsForTargetAndMode(Object target, Type[] delegateArgumentsTypes, List<ValidMethodMap> methods, PersistentListenerMode mode)
{
IEnumerable<ValidMethodMap> newMethods = CalculateMethodMap(target, delegateArgumentsTypes, mode == PersistentListenerMode.Object);
foreach (var m in newMethods)
{
var method = m;
method.mode = mode;
methods.Add(method);
}
}
static void AddFunctionsForScript(GenericMenu menu, SerializedProperty listener, ValidMethodMap method, string targetName)
{
PersistentListenerMode mode = method.mode;
// find the current event target...
var listenerTarget = listener.FindPropertyRelative(kInstancePath).objectReferenceValue;
var methodName = listener.FindPropertyRelative(kMethodNamePath).stringValue;
var setMode = GetMode(listener.FindPropertyRelative(kModePath));
var typeName = listener.FindPropertyRelative(kArgumentsPath).FindPropertyRelative(kObjectArgumentAssemblyTypeName);
var args = new StringBuilder();
var count = method.methodInfo.GetParameters().Length;
for (int index = 0; index < count; index++)
{
var methodArg = method.methodInfo.GetParameters()[index];
args.Append(string.Format("{0}", GetTypeName(methodArg.ParameterType)));
if (index < count - 1)
args.Append(", ");
}
var isCurrentlySet = listenerTarget == method.target
&& methodName == method.methodInfo.Name
&& mode == setMode;
if (isCurrentlySet && mode == PersistentListenerMode.Object && method.methodInfo.GetParameters().Length == 1)
{
isCurrentlySet &= (method.methodInfo.GetParameters()[0].ParameterType.AssemblyQualifiedName == typeName.stringValue);
}
string path = GetFormattedMethodName(targetName, method.methodInfo.Name, args.ToString(), mode == PersistentListenerMode.EventDefined);
menu.AddItem(new GUIContent(path),
isCurrentlySet,
SetEventFunction,
new UnityEventFunction(listener, method.target, method.methodInfo, mode));
}
private static string GetTypeName(Type t)
{
if (t == typeof(int))
return "int";
if (t == typeof(float))
return "float";
if (t == typeof(string))
return "string";
if (t == typeof(bool))
return "bool";
return t.Name;
}
static string GetFormattedMethodName(string targetName, string methodName, string args, bool dynamic)
{
if (dynamic)
{
if (methodName.StartsWith("set_"))
return string.Format("{0}/{1}", targetName, methodName.Substring(4));
else
return string.Format("{0}/{1}", targetName, methodName);
}
else
{
if (methodName.StartsWith("set_"))
return string.Format("{0}/{2} {1}", targetName, methodName.Substring(4), args);
else
return string.Format("{0}/{1} ({2})", targetName, methodName, args);
}
}
static void SetEventFunction(object source)
{
((UnityEventFunction)source).Assign();
}
static void ClearEventFunction(object source)
{
((UnityEventFunction)source).Clear();
}
struct UnityEventFunction
{
readonly SerializedProperty m_Listener;
readonly Object m_Target;
readonly MethodInfo m_Method;
readonly PersistentListenerMode m_Mode;
public UnityEventFunction(SerializedProperty listener, Object target, MethodInfo method, PersistentListenerMode mode)
{
m_Listener = listener;
m_Target = target;
m_Method = method;
m_Mode = mode;
}
public void Assign()
{
// find the current event target...
var listenerTarget = m_Listener.FindPropertyRelative(kInstancePath);
var listenerTargetType = m_Listener.FindPropertyRelative(kInstanceTypePath);
var methodName = m_Listener.FindPropertyRelative(kMethodNamePath);
var mode = m_Listener.FindPropertyRelative(kModePath);
var arguments = m_Listener.FindPropertyRelative(kArgumentsPath);
listenerTarget.objectReferenceValue = m_Target;
listenerTargetType.stringValue = m_Method.DeclaringType.AssemblyQualifiedName;
methodName.stringValue = m_Method.Name;
mode.enumValueIndex = (int)m_Mode;
if (m_Mode == PersistentListenerMode.Object)
{
var fullArgumentType = arguments.FindPropertyRelative(kObjectArgumentAssemblyTypeName);
var argParams = m_Method.GetParameters();
if (argParams.Length == 1 && typeof(Object).IsAssignableFrom(argParams[0].ParameterType))
fullArgumentType.stringValue = argParams[0].ParameterType.AssemblyQualifiedName;
else
fullArgumentType.stringValue = typeof(Object).AssemblyQualifiedName;
}
ValidateObjectParamater(arguments, m_Mode);
m_Listener.m_SerializedObject.ApplyModifiedProperties();
}
private void ValidateObjectParamater(SerializedProperty arguments, PersistentListenerMode mode)
{
var fullArgumentType = arguments.FindPropertyRelative(kObjectArgumentAssemblyTypeName);
var argument = arguments.FindPropertyRelative(kObjectArgument);
var argumentObj = argument.objectReferenceValue;
if (mode != PersistentListenerMode.Object)
{
fullArgumentType.stringValue = typeof(Object).AssemblyQualifiedName;
argument.objectReferenceValue = null;
return;
}
if (argumentObj == null)
return;
Type t = Type.GetType(fullArgumentType.stringValue, false);
if (!typeof(Object).IsAssignableFrom(t) || !t.IsInstanceOfType(argumentObj))
argument.objectReferenceValue = null;
}
public void Clear()
{
// find the current event target...
var methodName = m_Listener.FindPropertyRelative(kMethodNamePath);
methodName.stringValue = null;
var mode = m_Listener.FindPropertyRelative(kModePath);
mode.enumValueIndex = (int)PersistentListenerMode.Void;
m_Listener.m_SerializedObject.ApplyModifiedProperties();
}
}
}
}
| UnityCsReference/Editor/Mono/Inspector/UnityEventDrawer.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Inspector/UnityEventDrawer.cs",
"repo_id": "UnityCsReference",
"token_count": 18348
} | 299 |
// 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.Assertions;
namespace UnityEditor
{
[NativeType(Header = "Editor/Src/InteractionContext.h")]
internal partial class InteractionContext
{
[Flags]
public enum Flags
{
DisableNone = 0,
DisableUndo = 1,
DisableDialogs = 2,
DisableUndoAndDialogs = DisableUndo | DisableDialogs,
}
internal IntPtr m_NativePtr;
public InteractionContext(Flags flags) : this (Internal_Create((int)flags))
{
}
private InteractionContext(IntPtr nativePtr)
{
m_NativePtr = nativePtr;
}
~InteractionContext()
{
Internal_Destroy(m_NativePtr);
}
public extern bool IsUndoEnabled();
public extern bool WasAnyUndoOperationRegisteredSinceCreation();
public extern bool AreDialogsEnabled();
public extern bool HasUnusedDialogResponses();
public extern bool IsCurrentDialogResponse(string dialogTitle);
public extern string GetCurrentDialogResponse();
public extern string GetCurrentDialogResponseAndAvance();
public extern void AppendDialogResponse(string dialogTitle, string dialogResponse);
public extern string GetErrors();
[FreeFunction("CreateInteractionContext", IsThreadSafe = false)]
private static extern IntPtr Internal_Create(int flags);
[FreeFunction("DestroyInteractionContext")]
private static extern void Internal_Destroy(IntPtr m_NativePtr);
public static InteractionContext UserAction = new InteractionContext(Flags.DisableNone);
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(InteractionContext context) => context.m_NativePtr;
public static InteractionContext ConvertToManaged(IntPtr ptr) => new InteractionContext(ptr);
}
}
internal class GlobalInteractionContext : InteractionContext, IDisposable
{
public GlobalInteractionContext(InteractionContext.Flags flags)
: base(flags)
{
Assert.IsNull(GetGlobalInteractionContext());
SetGlobalInteractionContext(this);
}
public void Dispose()
{
try
{
Assert.IsFalse(HasUnusedDialogResponses());
if (!IsUndoEnabled())
{
Assert.IsFalse(WasAnyUndoOperationRegisteredSinceCreation(), "InteractionContext has unused dialog responses");
}
}
finally
{
ClearGlobalInteractionContext();
}
}
[FreeFunction("SetGlobalInteractionContext")]
private static extern void SetGlobalInteractionContext(InteractionContext interactionContext);
[FreeFunction("GetGlobalInteractionContext")]
private static extern InteractionContext GetGlobalInteractionContext();
[FreeFunction("ClearGlobalInteractionContext")]
private static extern void ClearGlobalInteractionContext();
new internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(GlobalInteractionContext context) => context.m_NativePtr;
}
}
}
| UnityCsReference/Editor/Mono/InteractionContext.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/InteractionContext.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1379
} | 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;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Scripting;
namespace UnityEditor
{
// The MenuItem attribute allows you to add menu items to the main menu and inspector context menus.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
[RequiredByNativeCode]
public sealed class MenuItem : Attribute
{
private static readonly string[] kMenuItemSeparators = {"/"};
// Creates a menu item and invokes the static function following it, when the menu item is selected.
public MenuItem(string itemName) : this(itemName, false) {}
// Creates a menu item and invokes the static function following it, when the menu item is selected.
public MenuItem(string itemName, bool isValidateFunction) : this(itemName, isValidateFunction, itemName.StartsWith("GameObject/Create Other") ? 10 : 1000) {}
// The special treatment of "GameObject/Other" is to ensure that legacy scripts that don't set a priority don't create a
// "Create Other" menu at the very bottom of the GameObject menu (thus preventing the items from being propagated to the
// scene hierarchy dropdown and context menu).
// Creates a menu item and invokes the static function following it, when the menu item is selected.
public MenuItem(string itemName, bool isValidateFunction, int priority) : this(itemName, isValidateFunction, priority, false) {}
// Creates a menu item and invokes the static function following it, when the menu item is selected.
internal MenuItem(string itemName, bool isValidateFunction, int priority, bool internalMenu) : this(itemName, isValidateFunction, priority, internalMenu, new string[] { "default" }) {}
// Creates a menu item and invokes the static function following it, when the menu item is selected.
internal MenuItem(string itemName, bool isValidateFunction, int priority, bool internalMenu, string[] editorModes)
{
itemName = NormalizeMenuItemName(itemName);
if (internalMenu)
menuItem = "internal:" + itemName;
else
menuItem = itemName;
validate = isValidateFunction;
this.priority = priority;
this.editorModes = editorModes;
secondaryPriority = float.MaxValue;
}
private static string NormalizeMenuItemName(string rawName)
{
return string.Join(kMenuItemSeparators[0], rawName.Split(kMenuItemSeparators, StringSplitOptions.None).Select(token => token.Trim()).ToArray());
}
public string menuItem;
public bool validate;
public int priority;
public float secondaryPriority; // transition period until UW-65 lands.
public string[] editorModes;
}
[RequiredByNativeCode(GenerateProxy = true)]
[StructLayout(LayoutKind.Sequential)]
class MenuItemScriptCommand : IMenuItem
{
public string name;
public int priority;
public float secondaryPriority;
public MethodInfo execute;
public MethodInfo validate;
public Delegate commandExecute;
public Delegate commandValidate;
public bool @checked;
public string shortcut;
public string Name => name;
public int Priority => priority;
public float SecondaryPriority => secondaryPriority;
internal bool IsNotValid => validate != null && execute == null;
public static MenuItemScriptCommand Initialize(string menuName, MenuItem menuItemAttribute, MethodInfo methodInfo)
{
if (!menuItemAttribute.validate)
return InitializeFromExecute(menuName, menuItemAttribute.priority, menuItemAttribute.secondaryPriority, methodInfo);
else
return InitializeFromValidate(menuName, methodInfo);
}
private static MenuItemScriptCommand InitializeFromValidate(string menuName, MethodInfo validate)
{
return new MenuItemScriptCommand()
{
name = menuName,
validate = validate
};
}
private static MenuItemScriptCommand InitializeFromExecute(string menuName, int priority, float secondaryPriority, MethodInfo execute)
{
return new MenuItemScriptCommand()
{
name = menuName,
priority = priority,
secondaryPriority = secondaryPriority,
execute = execute
};
}
internal static MenuItemScriptCommand InitializeFromCommand(string fullMenuName, int priority, string commandId, string validateCommandId)
{
var menuItem = new MenuItemScriptCommand()
{
name = fullMenuName,
priority = priority,
commandExecute = new Action(() => CommandService.Execute(commandId, CommandHint.Menu))
};
if (!string.IsNullOrEmpty(validateCommandId))
menuItem.commandValidate = new Func<bool>(() => (bool)CommandService.Execute(commandId, CommandHint.Menu | CommandHint.Validate));
return menuItem;
}
internal void Update(MenuItem menuItemAttribute, MethodInfo methodInfo)
{
if (!menuItemAttribute.validate)
{
if (execute != null)
{
if (!(name == "GameObject/3D Object/Mirror" || name == "GameObject/Light/Planar Reflection Probe")) //TODO: remove when HDRP removes the duplicate menus
Debug.LogWarning($"Cannot add menu item '{name}' for method '{methodInfo.DeclaringType}.{methodInfo.Name}' because a menu item with the same name already exists.");
return;
}
priority = menuItemAttribute.priority;
secondaryPriority = menuItemAttribute.secondaryPriority;
execute = methodInfo;
}
else
{
if (validate != null)
{
Debug.LogWarning($"Cannot add validate method '{methodInfo.DeclaringType}.{methodInfo.Name}' for menu item '{name}' because a menu item with the same name already has a validate method.");
return;
}
validate = methodInfo;
}
}
}
[RequiredByNativeCode(GenerateProxy = true)]
[StructLayout(LayoutKind.Sequential)]
class MenuItemOrderingNative : IMenuItem
{
public int position = -1;
public int parentPosition = -1;
public float secondaryPriority;
public string currentModeFullMenuName; // name of the menu to show
public string defaultModeFullMenuName; // name to find the default menu
public bool addChildren; // if true then native should add all children menu
public string[] childrenToExclude; // exclude those menu (path) when adding children
public string[] childrenToNotExclude; // if excluding, those menu (path) will not be excluded
public MenuItemOrderingNative()
{
defaultModeFullMenuName = string.Empty;
}
public MenuItemOrderingNative(string currentModeFullMenuName, string defaultModeFullMenuName, int position, int parentPosition, float secondaryPriority, bool addChildren = false)
{
this.position = position;
this.parentPosition = parentPosition;
this.secondaryPriority = secondaryPriority;
this.currentModeFullMenuName = currentModeFullMenuName;
this.defaultModeFullMenuName = defaultModeFullMenuName;
this.addChildren = addChildren;
}
public string Name => defaultModeFullMenuName;
public int Priority => position;
public float SecondaryPriority => secondaryPriority;
}
interface IMenuItem
{
string Name { get; }
int Priority { get; }
float SecondaryPriority { get; }
}
}
| UnityCsReference/Editor/Mono/MenuItem.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/MenuItem.cs",
"repo_id": "UnityCsReference",
"token_count": 3176
} | 301 |
// 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.IO;
using System.Linq;
using System.Reflection;
using Mono.Cecil;
using Mono.Cecil.Cil;
using UnityEngine;
namespace UnityEditor
{
internal class MonoCecilHelper : IMonoCecilHelper
{
private static SequencePoint GetMethodFirstSequencePoint(MethodDefinition methodDefinition)
{
if (methodDefinition == null)
{
Debug.Log("MethodDefinition cannot be null. Check if any method was found by name in its declaring type TypeDefinition.");
return null;
}
if (!methodDefinition.HasBody || !methodDefinition.Body.Instructions.Any() || methodDefinition.DebugInformation == null)
{
Debug.Log(string.Concat("To get SequencePoints MethodDefinition for ", methodDefinition.Name, " must have MethodBody, DebugInformation and Instructions."));
return null;
}
if (!methodDefinition.DebugInformation.HasSequencePoints)
{
// If we don't have any sequence points for this method, it could be that
// the method is delegating its implementation to a state machine method (e.g using yield).
// The state machine method will contain the debug info, not this method.
// In that case, the debug information of the state machine method (e.g MoveNext)
// will contain a StateMachineKickOffMethod that will link backward to the
// this original method that was containing the yield.
// That's the method we are looking for to extract correct sequence points after.
foreach (var nestedType in methodDefinition.DeclaringType.NestedTypes)
{
foreach (var method in nestedType.Methods)
{
if (method.DebugInformation != null && method.DebugInformation.StateMachineKickOffMethod == methodDefinition && method.HasBody && method.Body.Instructions.Count > 0)
{
methodDefinition = method;
goto foundKickOffMethod;
}
}
}
Debug.Log(string.Concat("No SequencePoints for MethodDefinition for ", methodDefinition.Name));
return null;
}
foundKickOffMethod:
foreach (var instruction in methodDefinition.Body.Instructions)
{
// An instruction might be attached to a hidden sequence point (or no seq point at all)
// so we need to skip them as they don't have any debug line info.
var sequencePoint = methodDefinition.DebugInformation.GetSequencePoint(instruction);
if (sequencePoint != null && !sequencePoint.IsHidden)
{
return sequencePoint;
}
}
return null;
}
private static AssemblyDefinition ReadAssembly(string assemblyPath)
{
using var assemblyResolver = new DefaultAssemblyResolver();
assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(assemblyPath));
var readerParameters = new ReaderParameters
{
ReadSymbols = true,
SymbolReaderProvider = new DefaultSymbolReaderProvider(false),
AssemblyResolver = assemblyResolver,
ReadingMode = ReadingMode.Deferred
};
try
{
return AssemblyDefinition.ReadAssembly(assemblyPath, readerParameters);
}
catch (Exception exception)
{
Debug.Log(exception.Message);
return null;
}
}
public IFileOpenInfo TryGetCecilFileOpenInfo(Type type, MethodInfo methodInfo)
{
var assemblyPath = type.Assembly.Location;
// Get the sequence point directly from the method token (to avoid scanning all types/methods)
using var assemblyDefinition = ReadAssembly(assemblyPath);
var methodDefinition = assemblyDefinition.MainModule.LookupToken(methodInfo.MetadataToken) as MethodDefinition;
var sequencePoint = GetMethodFirstSequencePoint(methodDefinition);
var fileOpenInfo = new FileOpenInfo();
if (sequencePoint != null) // Can be null in case of yield return in target method
{
fileOpenInfo.LineNumber = sequencePoint.StartLine;
fileOpenInfo.FilePath = sequencePoint.Document.Url;
}
return fileOpenInfo;
}
}
}
| UnityCsReference/Editor/Mono/MonoCecil/MonoCecilHelper.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/MonoCecil/MonoCecilHelper.cs",
"repo_id": "UnityCsReference",
"token_count": 2071
} | 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.Collections.Generic;
namespace UnityEditor.Overlays
{
public interface ICreateHorizontalToolbar
{
OverlayToolbar CreateHorizontalToolbarContent();
}
public interface ICreateVerticalToolbar
{
OverlayToolbar CreateVerticalToolbarContent();
}
public interface ICreateToolbar
{
public IEnumerable<string> toolbarElements { get; }
}
}
| UnityCsReference/Editor/Mono/Overlays/ICreateToolbar.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Overlays/ICreateToolbar.cs",
"repo_id": "UnityCsReference",
"token_count": 192
} | 303 |
// 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.Overlays
{
class OverlayPopup : VisualElement
{
// FocusOutEvent.originalMousePosition is not valid, so we keep track of where the mouse is when clicking.
bool m_CursorIsOverPopup;
public bool containsCursor => m_CursorIsOverPopup;
const string k_OutsideToolbar = "overlay-popup--outside-toolbar";
const string k_FromHorizontal = "overlay-popup--from-horizontal";
const string k_FromVertical = "overlay-popup--from-vertical";
const string k_Clamped = "overlay-popup--clamped";
public Overlay overlay { get; private set; }
OverlayPopup(Overlay overlay)
{
name = "overlay-popup";
this.overlay = overlay;
Overlay.treeAsset.CloneTree(this);
this.Q(Overlay.k_CollapsedContent)?.RemoveFromHierarchy();
this.Q(null, Overlay.k_Header)?.RemoveFromHierarchy();
focusable = true;
pickingMode = PickingMode.Position;
AddToClassList(Overlay.ussClassName);
style.position = Position.Absolute;
var root = this.Q("overlay-content");
root.renderHints = RenderHints.ClipWithScissors;
root.Add(overlay.GetSimpleHeader());
root.Add(overlay.CreatePanelContent());
RegisterCallback<MouseEnterEvent>(evt => m_CursorIsOverPopup = true);
RegisterCallback<MouseLeaveEvent>(evt => m_CursorIsOverPopup = false);
}
public static OverlayPopup CreateUnderOverlay(Overlay overlay)
{
var popup = new OverlayPopup(overlay);
popup.RegisterCallback<GeometryChangedEvent>(evt =>
{
var proposed = overlay.collapsedButtonRect;
proposed.size = evt.newRect.size;
if (overlay.layout == Layout.HorizontalToolbar)
popup.EnableInClassList(k_FromHorizontal, true);
else if (overlay.layout == Layout.VerticalToolbar)
popup.EnableInClassList(k_FromVertical, true);
if (!overlay.isInToolbar)
popup.EnableInClassList(k_OutsideToolbar, true);
var overlayWorldBound = overlay.rootVisualElement.worldBound;
var placement = OverlayCanvas.ClampRectToBounds(overlay.canvas.windowRoot.worldBound, proposed);
popup.HandleGeometryChangedEvent(overlay.canvas, placement, overlayWorldBound);
});
return popup;
}
public static OverlayPopup CreateAtPosition(OverlayCanvas canvas, Overlay overlay, Vector2 position)
{
var popup = new OverlayPopup(overlay);
popup.RegisterCallback<GeometryChangedEvent>(evt =>
{
//Use mouse position to set the popup to the right coordinates
var proposed = new Rect(position, evt.newRect.size);
var overlayWorldBound = new Rect(position, Vector2.zero);
var placement = OverlayCanvas.ClampRectToBounds(canvas.windowRoot.worldBound, proposed);
if (!Mathf.Approximately(proposed.position.x, placement.position.x))
popup.EnableInClassList(k_Clamped, true);
popup.HandleGeometryChangedEvent(canvas, placement, overlayWorldBound);
});
return popup;
}
public static OverlayPopup CreateAtCanvasCenter(OverlayCanvas canvas, Overlay overlay)
{
var popup = new OverlayPopup(overlay);
popup.RegisterCallback<GeometryChangedEvent>(evt =>
{
var size = evt.newRect.size;
var parentRect = canvas.rootVisualElement.rect;
var middle = parentRect.size / 2f;
var position = middle - size / 2f;
var placement = OverlayCanvas.ClampRectToBounds(canvas.windowRoot.worldBound, new Rect(position, size));
popup.Place(placement);
});
return popup;
}
void HandleGeometryChangedEvent(OverlayCanvas canvas, Rect placement, Rect overlayWorldBound)
{
var canvasWorld = canvas.rootVisualElement.worldBound;
var rightPlacement = overlayWorldBound.x + overlayWorldBound.width;
var rightSideSpace = canvasWorld.xMax - rightPlacement;
var xAdjusted = placement.position.x;
if (rightSideSpace >= placement.width)
{
xAdjusted = rightPlacement;
}
else
{
var leftSideSpace = placement.x - canvas.rootVisualElement.worldBound.x;
if (leftSideSpace >= placement.width)
{
xAdjusted = overlayWorldBound.x - placement.width;
}
else // If neither side has enough space, show the popup on the widest one
{
if (rightSideSpace > leftSideSpace)
xAdjusted = overlayWorldBound.x + overlayWorldBound.width;
else
xAdjusted = overlayWorldBound.x - placement.width;
placement.width = canvasWorld.xMax - xAdjusted;
}
}
var yAdjusted = placement.position.y;
var bottomSpace = canvasWorld.yMax - yAdjusted;
if (bottomSpace < placement.height)
{
var upPlacement = overlayWorldBound.y + overlayWorldBound.height;
var upSpace = upPlacement - canvasWorld.y;
if (upSpace >= placement.height)
{
yAdjusted = upPlacement - placement.height;
}
else // If neither side has enough space, show the popup on the widest one
{
// Try to show the popup as clamped if possible
EnableInClassList(k_Clamped, true);
if (bottomSpace <= upSpace)
{
var oldY = yAdjusted;
yAdjusted = canvasWorld.yMin;
placement.height = oldY - yAdjusted;
}
else
{
placement.height = canvasWorld.yMax - yAdjusted;
}
}
}
placement.position = new Vector2(xAdjusted, yAdjusted) - canvasWorld.position;
Place(placement);
}
void Place(Rect placement)
{
style.maxHeight = placement.height;
style.maxWidth = placement.width;
transform.position = placement.position;
}
}
}
| UnityCsReference/Editor/Mono/Overlays/OverlayPopup.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Overlays/OverlayPopup.cs",
"repo_id": "UnityCsReference",
"token_count": 3303
} | 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.Text;
using System.Globalization;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Profiling;
using UnityEngine.Experimental.Rendering;
using UnityEditor;
using UnityEditor.Rendering;
using UnityEditor.AnimatedValues;
namespace UnityEditorInternal.FrameDebuggerInternal
{
internal class FrameDebuggerEventDetailsView
{
// Render target view options
[NonSerialized] private int m_RTIndex;
[NonSerialized] private int m_MeshIndex = 0;
[NonSerialized] private int m_RTIndexLastSet = 0;
[NonSerialized] private int m_RTSelectedChannel;
[NonSerialized] private float m_RTBlackLevel;
[NonSerialized] private float m_RTWhiteLevel = 1.0f;
[NonSerialized] private float m_RTBlackMinLevel;
[NonSerialized] private float m_RTWhiteMaxLevel = 1.0f;
// Private
private int m_SelectedColorChannel = 0;
private Vector2 m_ScrollViewVector = Vector2.zero;
private Vector4 m_SelectedMask = Vector4.one;
private AnimBool[] m_FoldoutAnimators = null;
private MeshPreview m_Preview;
private CachedEventDisplayData m_CachedEventData = null;
private FrameDebuggerWindow m_FrameDebugger = null;
private Lazy<FrameDebuggerEventData> m_CurEventData = new Lazy<FrameDebuggerEventData>(() => new FrameDebuggerEventData());
private RenderTexture m_RenderTargetRenderTextureCopy = null;
// Constants / Readonly
private const int k_NumberGUISections = 11;
private readonly string[] k_foldoutKeys = new string[]{
"FrameDebuggerFoldout0",
"FrameDebuggerFoldout1",
"FrameDebuggerFoldout2",
"FrameDebuggerFoldout3",
"FrameDebuggerFoldout4",
"FrameDebuggerFoldout5",
"FrameDebuggerFoldout6",
"FrameDebuggerFoldout7",
"FrameDebuggerFoldout8",
"FrameDebuggerFoldout9",
"FrameDebuggerFoldout10",
};
// Properties
private FrameDebuggerEvent curEvent { get; set; }
private FrameDebuggerEventData curEventData => m_CurEventData.Value;
private int curEventIndex => FrameDebuggerUtility.limit - 1;
// Internal functions
internal FrameDebuggerEventDetailsView(FrameDebuggerWindow frameDebugger)
{
m_FrameDebugger = frameDebugger;
}
internal void Reset()
{
m_RTSelectedChannel = 0;
m_SelectedColorChannel = 0;
m_RTIndex = 0;
m_RTBlackLevel = 0.0f;
m_RTBlackMinLevel = 0.0f;
m_RTWhiteLevel = 1.0f;
m_RTWhiteMaxLevel = 1.0f;
}
internal void OnNewFrameEventSelected()
{
m_MeshIndex = 0;
m_Preview?.Dispose();
m_Preview = null;
}
internal void OnDisable()
{
if (m_CachedEventData != null)
m_CachedEventData.OnDisable();
// Release the texture...
FrameDebuggerHelper.ReleaseTemporaryTexture(ref m_RenderTargetRenderTextureCopy);
m_Preview?.Dispose();
m_Preview = null;
Reset();
}
internal void DrawEventDetails(Rect rect, FrameDebuggerEvent[] descs, bool isDebuggingEditor)
{
// Early out if the frame is not valid
if (!FrameDebuggerHelper.IsAValidFrame(curEventIndex, descs.Length))
return;
// Making sure we only initialize once. We do that in the Layout event, which is called before repaint
if (Event.current.type == EventType.Layout)
Initialize(curEventIndex, descs);
if (m_CachedEventData == null)
return;
// Make sure the window is scrollable...
GUILayout.BeginArea(rect);
m_ScrollViewVector = EditorGUILayout.BeginScrollView(m_ScrollViewVector);
// Toolbar
Profiler.BeginSample("DrawToolbar");
DrawRenderTargetToolbar();
Profiler.EndSample();
// Title
Profiler.BeginSample("DrawTitle");
GUILayout.BeginHorizontal(FrameDebuggerStyles.EventDetails.s_TitleHorizontalStyle);
EditorGUILayout.LabelField(m_CachedEventData.m_Title, FrameDebuggerStyles.EventDetails.s_TitleStyle);
GUILayout.EndHorizontal();
if (Event.current.type == EventType.ContextClick)
ShaderPropertyCopyValueMenu(GUILayoutUtility.GetLastRect(), FrameDebuggerStyles.EventDetails.s_CopyEventText, () => m_CachedEventData.copyString);
Profiler.EndSample();
// Output & Mesh
// We disable Output and Mesh for Compute and Ray Tracing events
bool shouldDrawOutput = !m_CachedEventData.m_IsComputeEvent && !m_CachedEventData.m_IsRayTracingEvent;
Profiler.BeginSample("DrawOutputAndMesh");
DrawOutputFoldout(rect, shouldDrawOutput, isDebuggingEditor);
Profiler.EndSample();
// Event Details
Profiler.BeginSample("DrawDetails");
DrawDetails(rect);
Profiler.EndSample();
Profiler.BeginSample("DrawMeshFoldout");
bool shouldDrawMesh = shouldDrawOutput && !FrameDebugger.IsRemoteEnabled();
DrawMeshFoldout(rect, shouldDrawMesh, isDebuggingEditor);
Profiler.EndSample();
ShaderPropertyCollection[] shaderProperties = m_CachedEventData.m_ShaderProperties;
if (shaderProperties != null && shaderProperties.Length > 0)
{
// Shader keywords & properties...
Profiler.BeginSample("DrawKeywords");
DrawShaderData(ShaderPropertyType.Keyword, 2, FrameDebuggerStyles.EventDetails.s_FoldoutKeywordsText, m_CachedEventData.m_Keywords);
Profiler.EndSample();
Profiler.BeginSample("DrawTextureProperties");
DrawShaderData(ShaderPropertyType.Texture, 3, FrameDebuggerStyles.EventDetails.s_FoldoutTexturesText, m_CachedEventData.m_Textures);
Profiler.EndSample();
Profiler.BeginSample("DrawIntProperties");
DrawShaderData(ShaderPropertyType.Int, 4, FrameDebuggerStyles.EventDetails.s_FoldoutIntsText, m_CachedEventData.m_Ints);
Profiler.EndSample();
Profiler.BeginSample("DrawFloatProperties");
DrawShaderData(ShaderPropertyType.Float, 5, FrameDebuggerStyles.EventDetails.s_FoldoutFloatsText, m_CachedEventData.m_Floats);
Profiler.EndSample();
Profiler.BeginSample("DrawVectorProperties");
DrawShaderData(ShaderPropertyType.Vector, 6, FrameDebuggerStyles.EventDetails.s_FoldoutVectorsText, m_CachedEventData.m_Vectors);
Profiler.EndSample();
Profiler.BeginSample("DrawMatrixProperties");
DrawShaderData(ShaderPropertyType.Matrix, 7, FrameDebuggerStyles.EventDetails.s_FoldoutMatricesText, m_CachedEventData.m_Matrices);
Profiler.EndSample();
Profiler.BeginSample("DrawBufferProperties");
DrawShaderData(ShaderPropertyType.Buffer, 8, FrameDebuggerStyles.EventDetails.s_FoldoutBuffersText, m_CachedEventData.m_Buffers);
Profiler.EndSample();
Profiler.BeginSample("DrawConstantBufferProperties");
DrawShaderData(ShaderPropertyType.CBuffer, 9, FrameDebuggerStyles.EventDetails.s_FoldoutCBufferText, m_CachedEventData.m_CBuffers);
Profiler.EndSample();
}
EditorGUILayout.EndScrollView();
GUILayout.EndArea();
}
///////////////////////////////////////////////
// PRIVATE
///////////////////////////////////////////////
private void Initialize(int curEventIndex, FrameDebuggerEvent[] descs)
{
Profiler.BeginSample("Initialize");
uint eventDataHash = FrameDebuggerUtility.eventDataHash;
bool isReceivingFrameEventData = FrameDebugger.IsRemoteEnabled() && FrameDebuggerUtility.receivingRemoteFrameEventData;
bool isFrameEventDataValid = curEventIndex == curEventData.m_FrameEventIndex;
if (!isFrameEventDataValid
|| m_CachedEventData == null
|| !m_CachedEventData.m_IsValid
|| m_CachedEventData.m_Index != curEventIndex
|| (eventDataHash != 0 && (eventDataHash != m_CachedEventData.m_Hash))
)
{
if (m_CachedEventData == null)
m_CachedEventData = new CachedEventDisplayData();
// Release the texture...
FrameDebuggerHelper.ReleaseTemporaryTexture(ref m_RenderTargetRenderTextureCopy);
isFrameEventDataValid = FrameDebuggerUtility.GetFrameEventData(curEventIndex, curEventData);
m_CachedEventData.m_IsValid = false;
}
// event type and draw call info
curEvent = descs[curEventIndex];
FrameEventType eventType = curEvent.m_Type;
// Rebuild strings...
if (isFrameEventDataValid)
{
if (!m_CachedEventData.m_IsValid || m_CachedEventData.m_Index != curEventIndex || m_CachedEventData.m_Type != eventType)
{
m_CachedEventData.m_Hash = eventDataHash;
m_CachedEventData.Initialize(curEvent, curEventData);
}
}
if (m_FoldoutAnimators == null || m_FoldoutAnimators.Length == 0)
{
m_FoldoutAnimators = new AnimBool[k_NumberGUISections];
for (int i = 0; i < m_FoldoutAnimators.Length; i++)
{
bool val = EditorPrefs.HasKey(k_foldoutKeys[i]) ? EditorPrefs.GetBool(k_foldoutKeys[i]) : false;
m_FoldoutAnimators[i] = new AnimBool(val);
}
}
Profiler.EndSample();
}
private void DrawRenderTargetToolbar()
{
if (m_CachedEventData.m_IsRayTracingEvent)
return;
bool isBackBuffer = curEventData.m_RenderTargetIsBackBuffer;
bool isDepthOnlyRT = GraphicsFormatUtility.IsDepthFormat((GraphicsFormat)curEventData.m_RenderTargetFormat);
bool isClearAction = (int)curEvent.m_Type <= 7;
bool hasShowableDepth = (curEventData.m_RenderTargetHasDepthTexture != 0);
bool hasStencil = (curEventData.m_RenderTargetHasStencilBits != 0);
int showableRTCount = curEventData.m_RenderTargetCount;
if (hasShowableDepth)
showableRTCount++;
GUILayout.BeginHorizontal(FrameDebuggerStyles.EventToolbar.s_HorizontalStyle);
// MRT to show
EditorGUI.BeginChangeCheck();
GUI.enabled = showableRTCount > 1;
var rtNames = new GUIContent[showableRTCount + (hasStencil ? 1 : 0)];
for (var i = 0; i < showableRTCount; ++i)
rtNames[i] = FrameDebuggerStyles.EventToolbar.s_MRTLabels[i];
if (hasShowableDepth)
rtNames[curEventData.m_RenderTargetCount] = FrameDebuggerStyles.EventToolbar.s_DepthLabel;
if (hasStencil)
rtNames[rtNames.Length - 1] = FrameDebuggerStyles.EventToolbar.s_StencilLabel;
// Render Target Selection
// --------------------------------
// The UI Dropdown and FrameDebugger use different
// indices so we need to convert between the two:
// Dropdown Frame Debugger
// Depth | Penultimate item | -1
// Stencil | Last item | -2
// If we showed depth/stencil before then try to keep showing depth/stencil
// otherwise try to keep showing color
if (m_RTIndexLastSet == -1)
m_RTIndex = hasShowableDepth ? showableRTCount - 1 : 0;
else if (m_RTIndexLastSet == -2)
m_RTIndex = hasStencil ? showableRTCount : 0;
else if (m_RTIndex > curEventData.m_RenderTargetCount)
m_RTIndex = 0;
m_RTIndex = EditorGUILayout.Popup(m_RTIndex, rtNames, FrameDebuggerStyles.EventToolbar.s_PopupLeftStyle, GUILayout.Width(70));
int rtIndexToSet = m_RTIndex;
if (hasShowableDepth && rtIndexToSet == (showableRTCount - 1))
rtIndexToSet = -1;
if (hasStencil && rtIndexToSet == showableRTCount)
rtIndexToSet = showableRTCount > 1 ? -2 : -1;
// --------------------------------
bool isForcingRTSelection = isBackBuffer || isDepthOnlyRT;
GUI.enabled = !isForcingRTSelection;
// color channels
EditorGUILayout.Space(5f);
GUILayout.Label(FrameDebuggerStyles.EventToolbar.s_ChannelHeader, FrameDebuggerStyles.EventToolbar.s_ChannelHeaderStyle);
EditorGUILayout.Space(5f);
int channelToDisplay = 0;
bool forceUpdate = false;
bool shouldDisableChannelButtons = isDepthOnlyRT || isClearAction || isBackBuffer;
UInt32 componentCount = GraphicsFormatUtility.GetComponentCount((GraphicsFormat)curEventData.m_RenderTargetFormat);
GUILayout.BeginHorizontal();
{
GUI.enabled = !shouldDisableChannelButtons && m_SelectedColorChannel != 0;
if (GUILayout.Button(FrameDebuggerStyles.EventToolbar.s_ChannelAll, FrameDebuggerStyles.EventToolbar.s_ChannelAllStyle)) { m_RTSelectedChannel = 0; }
GUI.enabled = !shouldDisableChannelButtons && componentCount > 0 && m_SelectedColorChannel != 1;
if (GUILayout.Button(FrameDebuggerStyles.EventToolbar.s_ChannelR, FrameDebuggerStyles.EventToolbar.s_ChannelStyle)) { m_RTSelectedChannel = 1; }
GUI.enabled = !shouldDisableChannelButtons && componentCount > 1 && m_SelectedColorChannel != 2;
if (GUILayout.Button(FrameDebuggerStyles.EventToolbar.s_ChannelG, FrameDebuggerStyles.EventToolbar.s_ChannelStyle)) { m_RTSelectedChannel = 2; }
GUI.enabled = !shouldDisableChannelButtons && componentCount > 2 && m_SelectedColorChannel != 3;
if (GUILayout.Button(FrameDebuggerStyles.EventToolbar.s_ChannelB, FrameDebuggerStyles.EventToolbar.s_ChannelStyle)) { m_RTSelectedChannel = 3; }
GUI.enabled = !shouldDisableChannelButtons && componentCount > 3 && m_SelectedColorChannel != 4;
if (GUILayout.Button(FrameDebuggerStyles.EventToolbar.s_ChannelA, FrameDebuggerStyles.EventToolbar.s_ChannelAStyle)) { m_RTSelectedChannel = 4; }
// Force the channel to be "All" when:
// * Showing the back buffer
// * Showing Shadows/Depth/Clear
// * Channel index is higher then the number available channels
bool shouldForceAll = isBackBuffer || (m_RTSelectedChannel != 0 && (shouldDisableChannelButtons || m_RTSelectedChannel < 4 && componentCount < m_RTSelectedChannel));
channelToDisplay = shouldForceAll ? 0 : m_RTSelectedChannel;
if (channelToDisplay != m_SelectedColorChannel)
{
forceUpdate = true;
m_SelectedColorChannel = channelToDisplay;
}
GUI.enabled = true;
}
GUILayout.EndHorizontal();
GUI.enabled = !isBackBuffer;
// levels
GUILayout.BeginHorizontal(FrameDebuggerStyles.EventToolbar.s_LevelsHorizontalStyle);
GUILayout.Label(FrameDebuggerStyles.EventToolbar.s_LevelsHeader);
float blackMinLevel = EditorGUILayout.DelayedFloatField(m_RTBlackMinLevel, GUILayout.MaxWidth(40.0f));
float blackLevel = m_RTBlackLevel;
float whiteLevel = m_RTWhiteLevel;
EditorGUILayout.MinMaxSlider(ref blackLevel, ref whiteLevel, m_RTBlackMinLevel, m_RTWhiteMaxLevel, GUILayout.MaxWidth(200.0f));
float whiteMaxLevel = EditorGUILayout.DelayedFloatField(m_RTWhiteMaxLevel, GUILayout.MaxWidth(40.0f));
if (blackMinLevel < whiteMaxLevel && whiteMaxLevel > blackMinLevel)
{
m_RTBlackMinLevel = blackMinLevel;
m_RTWhiteMaxLevel = whiteMaxLevel;
m_RTBlackLevel = Mathf.Clamp(blackLevel, m_RTBlackMinLevel, whiteLevel);
m_RTWhiteLevel = Mathf.Clamp(whiteLevel, blackLevel, m_RTWhiteMaxLevel);
}
if (EditorGUI.EndChangeCheck()
|| (!isForcingRTSelection && (rtIndexToSet != m_RTIndexLastSet))
|| forceUpdate)
{
m_SelectedMask = Vector4.zero;
switch (channelToDisplay)
{
case 1: m_SelectedMask.x = 1f; break;
case 2: m_SelectedMask.y = 1f; break;
case 3: m_SelectedMask.z = 1f; break;
case 4: m_SelectedMask.w = 1f; break;
case 5: m_SelectedMask = Vector4.zero; break;
default: m_SelectedMask = Vector4.one; break;
}
FrameDebuggerUtility.SetRenderTargetDisplayOptions(rtIndexToSet, m_SelectedMask, m_RTBlackLevel, m_RTWhiteLevel);
m_FrameDebugger.RepaintAllNeededThings();
m_RTIndexLastSet = rtIndexToSet;
FrameDebuggerHelper.ReleaseTemporaryTexture(ref m_RenderTargetRenderTextureCopy);
}
else if (m_RTIndexLastSet == -2 && showableRTCount <= 1)
{
m_RTIndexLastSet = -1;
FrameDebuggerUtility.SetRenderTargetDisplayOptions(-1, m_SelectedMask, m_RTBlackLevel, m_RTWhiteLevel);
}
GUILayout.EndHorizontal();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUI.enabled = true;
}
private void DrawOutputFoldout(Rect rect, bool shouldDrawOutput, bool isDebuggingEditor)
{
if (BeginFoldoutBox(0, shouldDrawOutput, FrameDebuggerStyles.EventDetails.s_FoldoutOutputText, out float fadePercent, null))
{
if (shouldDrawOutput)
{
EditorGUILayout.BeginVertical();
{
float viewportWidth = rect.width - 30f;
float viewportHeightFaded = FrameDebuggerStyles.EventDetails.k_MaxViewportHeight * fadePercent;
float renderTargetWidth = m_CachedEventData.m_RenderTargetWidth;
float renderTargetHeight = m_CachedEventData.m_RenderTargetHeight;
float scaledRenderTargetWidth = renderTargetWidth;
float scaledRenderTargetHeight = renderTargetHeight;
if (scaledRenderTargetWidth > viewportWidth)
{
float scale = viewportWidth / scaledRenderTargetWidth;
scaledRenderTargetWidth *= scale;
scaledRenderTargetHeight *= scale;
}
if (scaledRenderTargetHeight > FrameDebuggerStyles.EventDetails.k_MaxViewportHeight)
{
float scale = FrameDebuggerStyles.EventDetails.k_MaxViewportHeight / scaledRenderTargetHeight;
scaledRenderTargetWidth *= scale;
scaledRenderTargetHeight = FrameDebuggerStyles.EventDetails.k_MaxViewportHeight;
}
DrawTargetTexture(rect, viewportWidth, viewportHeightFaded, renderTargetWidth, renderTargetHeight, scaledRenderTargetWidth, scaledRenderTargetHeight, fadePercent, isDebuggingEditor);
}
GUILayout.EndVertical();
}
}
EndFoldoutBox();
}
private void DrawTargetTexture(Rect rect, float viewportWidth, float viewportHeight, float renderTargetWidth, float renderTargetHeight, float scaledRenderTargetWidth, float scaledRenderTargetHeight, float fadePercent, bool isDebuggingEditor)
{
EditorGUILayout.BeginHorizontal(FrameDebuggerStyles.EventDetails.s_RenderTargetMeshBackgroundStyle);
Rect previewRect = GUILayoutUtility.GetRect(viewportWidth, viewportHeight);
// Early out if the texture is so small it can not be drawn...
int scaledTexWidthInt = (int) scaledRenderTargetWidth;
int scaledTexHeightInt = (int) scaledRenderTargetHeight;
if (scaledTexWidthInt <= 0 || scaledTexHeightInt <= 0)
{
EditorGUILayout.EndHorizontal();
return;
}
// We insert a dummy Draw Texture call when not repainting.
if (Event.current.type != EventType.Repaint)
{
GUI.DrawTexture(Rect.zero, null, ScaleMode.ScaleAndCrop, false, (scaledRenderTargetWidth / scaledRenderTargetHeight));
EditorGUILayout.EndHorizontal();
return;
}
float yPos = previewRect.y;
if (viewportHeight > scaledRenderTargetHeight)
yPos += (viewportHeight - scaledRenderTargetHeight) * 0.5f;
float xPos = 10f + Mathf.Max(viewportWidth * 0.5f - scaledRenderTargetWidth * 0.5f, 0f);
// This is a weird one. When opening/closing the foldout, the image
// shifts a tiny bit to the right. This magic code prevents that.
if (fadePercent < 1f)
xPos -= 7f;
Rect textureRect = new Rect(xPos, yPos, scaledRenderTargetWidth, scaledRenderTargetHeight);
if (m_RenderTargetRenderTextureCopy)
{
GUI.DrawTexture(textureRect, m_RenderTargetRenderTextureCopy, ScaleMode.ScaleAndCrop, false, (scaledRenderTargetWidth / scaledRenderTargetHeight));
}
else if (m_CachedEventData.m_RenderTargetRenderTexture && previewRect.height > 1.0f)
{
GraphicsFormat targetTextureFormat = m_CachedEventData.m_RenderTargetFormat;
uint componentCount = GraphicsFormatUtility.GetComponentCount(targetTextureFormat);
// On some devices the backbuffer gives the None Graphics Format. To prevent us
// displaying a black & white texture we force the channels to the selected mask.
bool shouldForceSelectedMask = targetTextureFormat == GraphicsFormat.None && m_CachedEventData.m_RenderTargetIsBackBuffer;
Vector4 channels = (!m_CachedEventData.m_RenderTargetIsDepthOnlyRT && (componentCount > 1 || shouldForceSelectedMask)) ? m_SelectedMask : new Vector4(1, 0, 0, 0);
bool linearColorSpace = QualitySettings.activeColorSpace == ColorSpace.Linear;
bool textureSRGB = GraphicsFormatUtility.IsSRGBFormat(targetTextureFormat);
bool undoOutputSRGB = (isDebuggingEditor && (!linearColorSpace || textureSRGB)) ? false : true;
bool shouldYFlip = m_CachedEventData.m_RenderTargetIsBackBuffer && isDebuggingEditor;
Vector4 levels = new Vector4(m_RTBlackLevel, m_RTWhiteLevel, 0f, 0f);
// Get a temporary texture...
int renderTargetWidthInt = (int)renderTargetWidth;
int renderTargetHeightInt = (int)renderTargetHeight;
m_RenderTargetRenderTextureCopy = RenderTexture.GetTemporary(renderTargetWidthInt, renderTargetHeightInt);
// Blit with the settings from the toolbar...
FrameDebuggerHelper.BlitToRenderTexture(
ref m_CachedEventData.m_RenderTargetRenderTexture,
ref m_RenderTargetRenderTextureCopy,
renderTargetWidthInt,
renderTargetHeightInt,
channels,
levels,
shouldYFlip,
undoOutputSRGB
);
// Draw the texture to the screen...
GUI.DrawTexture(textureRect, m_RenderTargetRenderTextureCopy, ScaleMode.ScaleAndCrop, false, (scaledRenderTargetWidth / scaledRenderTargetHeight));
}
EditorGUILayout.EndHorizontal();
}
private void DrawMeshFoldout(Rect rect, bool shouldDrawMesh, bool isDebuggingEditor)
{
// Not supported on remote players so we change the foldout header to show that.
GUIContent header;
bool shouldDraw;
if (FrameDebugger.IsRemoteEnabled())
{
shouldDraw = false;
header = FrameDebuggerStyles.EventDetails.s_FoldoutMeshNotSupportedText;
}
else
{
shouldDraw = shouldDrawMesh && m_CachedEventData.m_Meshes != null && m_CachedEventData.m_Meshes.Length > 0;
header = FrameDebuggerStyles.EventDetails.s_FoldoutMeshText;
}
if (BeginFoldoutBox(10, shouldDraw, header, out float fadePercent, null) && shouldDraw)
{
// Safety checks as things can get go wrong when switching between editor and remote...
m_MeshIndex = Mathf.Min(m_MeshIndex, m_CachedEventData.m_Meshes.Length - 1);
for (int i = 0; i < m_CachedEventData.m_Meshes.Length; i++)
{
if (m_CachedEventData.m_Meshes[i] == null)
{
EndFoldoutBox();
return;
}
}
// Draw the Mesh Preview
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
{
float viewportWidth = rect.width - 30f;
float viewportHeightFaded = FrameDebuggerStyles.EventDetails.k_MaxViewportHeight * fadePercent;
float renderTargetWidth = m_CachedEventData.m_RenderTargetWidth;
float renderTargetHeight = m_CachedEventData.m_RenderTargetHeight;
float scaledRenderTargetWidth = renderTargetWidth;
float scaledRenderTargetHeight = renderTargetHeight;
if (scaledRenderTargetWidth > viewportWidth)
{
float scale = viewportWidth / scaledRenderTargetWidth;
scaledRenderTargetWidth *= scale;
scaledRenderTargetHeight *= scale;
}
if (scaledRenderTargetHeight > FrameDebuggerStyles.EventDetails.k_MaxViewportHeight)
{
float scale = FrameDebuggerStyles.EventDetails.k_MaxViewportHeight / scaledRenderTargetHeight;
scaledRenderTargetWidth *= scale;
scaledRenderTargetHeight = FrameDebuggerStyles.EventDetails.k_MaxViewportHeight;
}
DrawEventMesh(viewportWidth, viewportHeightFaded, scaledRenderTargetWidth);
}
GUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
// Draw the list of meshes to select from...
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(FrameDebuggerStyles.EventDetails.s_FoldoutMeshText, FrameDebuggerStyles.EventDetails.s_MonoLabelStyle);
EditorGUILayout.EndHorizontal();
bool clicked = false;
GUIStyle style;
for (int i = 0; i < m_CachedEventData.m_Meshes.Length; i++)
{
if (m_CachedEventData.m_Meshes[i] == null)
continue;
style = (i == m_MeshIndex) ? FrameDebuggerStyles.EventDetails.s_MonoLabelBoldPaddingStyle : FrameDebuggerStyles.EventDetails.s_MonoLabelStylePadding;
// Draw...
EditorGUILayout.BeginHorizontal();
// Mesh Name to select for the preview...
clicked = GUILayout.Button(m_CachedEventData.m_Meshes[i].name, style);
// Object Field to ping the object in the Project View
GUI.enabled = false;
EditorGUILayout.ObjectField(m_CachedEventData.m_Meshes[i], typeof(Mesh), true, GUILayout.Width(FrameDebuggerStyles.EventDetails.k_ShaderObjectFieldWidth));
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
// Update the mesh index if the label was clicked...
if (clicked)
m_MeshIndex = Mathf.Min(i, m_CachedEventData.m_Meshes.Length - 1);
}
if (m_Preview != null && m_CachedEventData.m_Meshes[m_MeshIndex] != null)
m_Preview.mesh = m_CachedEventData.m_Meshes[m_MeshIndex];
}
EndFoldoutBox();
}
private void DrawEventMesh(float viewportWidth, float viewportHeight, float texWidth)
{
if (viewportHeight - FrameDebuggerStyles.EventDetails.k_MeshBottomToolbarHeight < 1.0f)
return;
if (m_CachedEventData.m_Meshes == null || m_CachedEventData.m_Meshes.Length == 0 || m_CachedEventData.m_Meshes[m_MeshIndex] == null)
{
DrawEventMeshBackground(viewportWidth, viewportHeight);
return;
}
if (m_Preview == null)
m_Preview = new MeshPreview(m_CachedEventData.m_Meshes[m_MeshIndex]);
else if (m_Preview.mesh == null)
m_Preview.mesh = m_CachedEventData.m_Meshes[m_MeshIndex];
// We need this rect called here to push the control buttons below the Mesh...
Rect previewRect = GUILayoutUtility.GetRect(viewportWidth - 100, viewportHeight - FrameDebuggerStyles.EventDetails.k_MeshBottomToolbarHeight, GUILayout.ExpandHeight(false));
// Rectangle for the buttons...
Rect rect = EditorGUILayout.BeginHorizontal(GUIContent.none, EditorStyles.toolbar, GUILayout.Height(FrameDebuggerStyles.EventDetails.k_MeshBottomToolbarHeight));
{
GUILayout.FlexibleSpace();
m_Preview.OnPreviewSettings();
}
EditorGUILayout.EndHorizontal();
var evt = Event.current;
if (FrameDebuggerHelper.IsHoveringRect(previewRect) || evt.type != EventType.ScrollWheel)
{
m_Preview?.OnPreviewGUI(previewRect, EditorStyles.helpBox);
}
}
private void DrawEventMeshBackground(float viewportWidth, float viewportHeight)
{
EditorGUILayout.BeginHorizontal(FrameDebuggerStyles.EventDetails.s_RenderTargetMeshBackgroundStyle, GUILayout.Width(viewportWidth));
GUILayoutUtility.GetRect(viewportWidth, viewportHeight);
EditorGUILayout.EndHorizontal();
}
private void DrawDetails(Rect rect)
{
bool isFoldoutOpen = BeginFoldoutBox(1, true, FrameDebuggerStyles.EventDetails.s_FoldoutEventDetailsText, out float fadePercent, () => m_CachedEventData.detailsCopyString);
if (!isFoldoutOpen)
{
EndFoldoutBox();
return;
}
GUIStyle style = FrameDebuggerStyles.EventDetails.s_MonoLabelStyle;
// Size, Color Actions, Blending, Z, Stencil...
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(m_CachedEventData.details, style, GUILayout.MinWidth(m_CachedEventData.m_DetailsGUIWidth), GUILayout.MinHeight(m_CachedEventData.m_DetailsGUIHeight));
EditorGUILayout.EndHorizontal();
// Shader
if (m_CachedEventData.m_ShouldDisplayRealAndOriginalShaders)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(FrameDebuggerStyles.EventDetails.s_RealShaderText, style, GUILayout.Width(FrameDebuggerStyles.EventDetails.k_ShaderLabelWidth));
if (m_CachedEventData.m_RealShader == null)
EditorGUILayout.LabelField(m_CachedEventData.m_RealShaderName, style);
else
{
GUI.enabled = false;
EditorGUILayout.ObjectField(m_CachedEventData.m_RealShader, typeof(Shader), true, GUILayout.Width(FrameDebuggerStyles.EventDetails.k_ShaderObjectFieldWidth));
GUI.enabled = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(FrameDebuggerStyles.EventDetails.s_OriginalShaderText, GUILayout.Width(FrameDebuggerStyles.EventDetails.k_ShaderLabelWidth));
if (m_CachedEventData.m_OriginalShader == null)
EditorGUILayout.LabelField(m_CachedEventData.m_OriginalShaderName, style);
else
{
GUI.enabled = false;
EditorGUILayout.ObjectField(m_CachedEventData.m_OriginalShader, typeof(Shader), true, GUILayout.Width(FrameDebuggerStyles.EventDetails.k_ShaderObjectFieldWidth));
GUI.enabled = true;
}
EditorGUILayout.EndHorizontal();
}
EndFoldoutBox();
}
private void DrawShaderData(ShaderPropertyType propType, int foldoutIndex, GUIContent foldoutText, ShaderPropertyCollection shaderProperties)
{
ShaderPropertyDisplayInfo[] propertyDisplayInfo = shaderProperties.m_Data;
// We disable and hide keywords and shader properties for clear and resolve events or when we don't have any data.
bool shouldDisplayProperties = !m_CachedEventData.m_IsClearEvent && !m_CachedEventData.m_IsResolveEvent;
bool shouldDraw = shouldDisplayProperties && propertyDisplayInfo != null && propertyDisplayInfo.Length > 0;
bool isFoldoutOpen = BeginFoldoutBox(foldoutIndex, shouldDraw, foldoutText, out float fadePercent, () => shaderProperties.copyString);
if (!shouldDraw || !isFoldoutOpen)
{
EndFoldoutBox();
return;
}
GUILayout.BeginVertical(FrameDebuggerStyles.EventDetails.s_PropertiesBottomMarginStyle);
GUILayout.BeginHorizontal(FrameDebuggerStyles.EventDetails.s_PropertiesLeftMarginStyle);
GUILayout.Label(shaderProperties.m_Header, FrameDebuggerStyles.EventDetails.s_MonoLabelBoldStyle);
GUILayout.EndHorizontal();
for (int i = 0; i < propertyDisplayInfo.Length; i++)
{
ShaderPropertyDisplayInfo data = propertyDisplayInfo[i];
if (!data.m_IsArray)
{
Texture textureToDisplay = data.m_TextureCopy != null ? data.m_TextureCopy as Texture : data.m_Texture;
if (textureToDisplay == null)
{
GUILayout.BeginHorizontal(FrameDebuggerStyles.EventDetails.s_PropertiesLeftMarginStyle);
GUILayout.Label(data.m_PropertyString, FrameDebuggerStyles.EventDetails.s_MonoLabelNoWrapStyle);
}
else
{
GUILayout.BeginHorizontal();
// Texture Preview..
// for 2D textures, we want to display them directly as a preview (this will make render textures display their contents) but
// for cube maps and other non-2D types DrawPreview does not do anything useful right now, so get their asset type icon at least
bool isTex2D = textureToDisplay.dimension == TextureDimension.Tex2D;
Texture previewTexture = isTex2D ? textureToDisplay : AssetPreview.GetMiniThumbnail(textureToDisplay);
Rect previewRect = GUILayoutUtility.GetRect(10, 10, FrameDebuggerStyles.EventDetails.s_TextureButtonStyle);
previewRect.width = 10;
previewRect.height = 10;
previewRect.x += 4f;
previewRect.y += 6f;
GUI.DrawTexture(previewRect, previewTexture, ScaleMode.StretchToFill, false);
GUILayout.Label(data.m_PropertyString, FrameDebuggerStyles.EventDetails.s_MonoLabelNoWrapStyle);
if (FrameDebuggerHelper.IsCurrentEventMouseDown() && FrameDebuggerHelper.IsClickingRect(previewRect))
{
PopupWindowWithoutFocus.Show(
previewRect,
new ObjectPreviewPopup(textureToDisplay),
new[] { PopupLocation.Left, PopupLocation.Below, PopupLocation.Right }
);
}
}
GUILayout.EndHorizontal();
}
else
{
GUILayout.BeginVertical(FrameDebuggerStyles.EventDetails.s_PropertiesLeftMarginStyle);
data.m_IsFoldoutOpen = EditorGUILayout.Foldout(data.m_IsFoldoutOpen, data.m_FoldoutString, FrameDebuggerStyles.EventDetails.s_ArrayFoldoutStyle);
if (data.m_IsFoldoutOpen)
GUILayout.Label(data.m_PropertyString, data.m_ArrayGUIStyle);
GUILayout.EndVertical();
}
propertyDisplayInfo[i] = data;
if (Event.current.type == EventType.ContextClick)
ShaderPropertyCopyValueMenu(GUILayoutUtility.GetLastRect(), FrameDebuggerStyles.EventDetails.s_CopyPropertyText, () => data.copyString);
}
GUILayout.EndVertical();
EndFoldoutBox();
}
private bool BeginFoldoutBox(int foldoutIndex, bool hasData, GUIContent header, out float fadePercent, Func<string> copyStringAction = null)
{
GUI.enabled = hasData;
EditorGUILayout.BeginVertical(FrameDebuggerStyles.EventDetails.s_FoldoutCategoryBoxStyle);
Rect r = GUILayoutUtility.GetRect(2, 21);
EditorGUI.BeginChangeCheck();
bool expanded = EditorGUI.FoldoutTitlebar(r, header, m_FoldoutAnimators[foldoutIndex].target, true, EditorStyles.inspectorTitlebarFlat, EditorStyles.inspectorTitlebarText);
if (EditorGUI.EndChangeCheck())
{
bool newState = !m_FoldoutAnimators[foldoutIndex].target;
EditorPrefs.SetBool(k_foldoutKeys[foldoutIndex], newState);
// If Shift is being held down, we change the state for all of them...
if (Event.current.shift || Event.current.alt)
for (int i = m_FoldoutAnimators.Length - 1; i >= 0; i--)
m_FoldoutAnimators[i].target = newState;
else
m_FoldoutAnimators[foldoutIndex].target = newState;
}
if (Event.current.type == EventType.ContextClick)
if (copyStringAction != null && FrameDebuggerStyles.EventDetails.s_FoldoutCopyText[foldoutIndex] != null && copyStringAction != null)
ShaderPropertyCopyValueMenu(r, FrameDebuggerStyles.EventDetails.s_FoldoutCopyText[foldoutIndex], copyStringAction);
GUI.enabled = true;
EditorGUI.indentLevel++;
fadePercent = m_FoldoutAnimators[foldoutIndex].faded;
return EditorGUILayout.BeginFadeGroup(m_FoldoutAnimators[foldoutIndex].faded);
}
private void EndFoldoutBox()
{
EditorGUILayout.EndFadeGroup();
EditorGUI.indentLevel--;
EditorGUILayout.EndVertical();
}
private void ShaderPropertyCopyValueMenu(Rect valueRect, GUIContent menuText, Func<string> textToCopy)
{
Profiler.BeginSample("ShaderPropertyCopyValueMenu");
var e = Event.current;
// Copy function
if (valueRect.Contains(e.mousePosition))
{
e.Use();
GenericMenu menu = new GenericMenu();
menu.AddItem(menuText, false, delegate {
if (textToCopy != null)
EditorGUIUtility.systemCopyBuffer = textToCopy();
});
menu.ShowAsContext();
}
Profiler.EndSample();
}
}
}
| UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerEventDetailsView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PerformanceTools/FrameDebuggerEventDetailsView.cs",
"repo_id": "UnityCsReference",
"token_count": 19363
} | 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.Playables;
namespace UnityEditor.Playables
{
public static class PlayableOutputEditorExtensions
{
public static string GetEditorName<U>(this U output) where U : struct, IPlayableOutput
{
return output.GetHandle().GetEditorName();
}
}
}
| UnityCsReference/Editor/Mono/Playables/PlayableOutputEditorExtensions.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Playables/PlayableOutputEditorExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 159
} | 306 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor
{
public partial class PlayerSettings : UnityEngine.Object
{
public partial class SplashScreen
{
public enum AnimationMode
{
Static = 0,
Dolly = 1,
Custom = 2
}
public enum DrawMode
{
UnityLogoBelow = 0,
AllSequential = 1
}
public enum UnityLogoStyle
{
DarkOnLight = 0,
LightOnDark = 1
}
}
}
}
| UnityCsReference/Editor/Mono/PlayerSettingsSplashScreen.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PlayerSettingsSplashScreen.cs",
"repo_id": "UnityCsReference",
"token_count": 384
} | 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 Object = UnityEngine.Object;
using System;
using UnityEngine.Bindings;
namespace UnityEditor
{
[NativeHeader("Editor/Src/AssetPipeline/PrefabImporter.h")]
[ExcludeFromPreset]
[HelpURL("https://docs.unity3d.com/2023.2/Documentation/Manual/Prefabs.html")]
internal class PrefabImporter : AssetImporter
{
}
}
| UnityCsReference/Editor/Mono/Prefabs/PrefabImporter.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Prefabs/PrefabImporter.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 177
} | 308 |
// 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;
namespace UnityEditor
{
[AssetFileNameExtension("colors")]
[ExcludeFromPreset]
class ColorPresetLibrary : PresetLibrary
{
[SerializeField]
List<ColorPreset> m_Presets = new List<ColorPreset>();
Texture2D m_ColorSwatch;
Texture2D m_ColorSwatchTriangular;
Texture2D m_MiniColorSwatchTriangular;
Texture2D m_CheckerBoard;
public const int kSwatchSize = 14;
public const int kMiniSwatchSize = 8;
void OnDestroy()
{
if (m_ColorSwatch != null)
DestroyImmediate(m_ColorSwatch);
if (m_ColorSwatchTriangular != null)
DestroyImmediate(m_ColorSwatchTriangular);
if (m_MiniColorSwatchTriangular != null)
DestroyImmediate(m_MiniColorSwatchTriangular);
if (m_CheckerBoard != null)
DestroyImmediate(m_CheckerBoard);
}
public override int Count()
{
return m_Presets.Count;
}
public override object GetPreset(int index)
{
return m_Presets[index].color;
}
public override void Add(object presetObject, string presetName)
{
Color color = (Color)presetObject;
m_Presets.Add(new ColorPreset(color, presetName));
}
public override void Replace(int index, object newPresetObject)
{
Color color = (Color)newPresetObject;
m_Presets[index].color = color;
}
public override void Remove(int index)
{
m_Presets.RemoveAt(index);
}
public override void Move(int index, int destIndex, bool insertAfterDestIndex)
{
PresetLibraryHelpers.MoveListItem(m_Presets, index, destIndex, insertAfterDestIndex);
}
public override void Draw(Rect rect, int index)
{
DrawInternal(rect, m_Presets[index].color);
}
public override void Draw(Rect rect, object presetObject)
{
DrawInternal(rect, (Color)presetObject);
}
private void Init()
{
if (m_ColorSwatch == null)
m_ColorSwatch = CreateColorSwatchWithBorder(kSwatchSize, kSwatchSize, false);
if (m_ColorSwatchTriangular == null)
m_ColorSwatchTriangular = CreateColorSwatchWithBorder(kSwatchSize, kSwatchSize, true);
if (m_MiniColorSwatchTriangular == null)
m_MiniColorSwatchTriangular = CreateColorSwatchWithBorder(kMiniSwatchSize, kMiniSwatchSize, true);
if (m_CheckerBoard == null)
m_CheckerBoard = GradientEditor.CreateCheckerTexture(2, 2, 3, new Color(0.8f, 0.8f, 0.8f), new Color(0.5f, 0.5f, 0.5f));
}
private void DrawInternal(Rect rect, Color preset)
{
Init();
bool isHDR = preset.maxColorComponent > 1f;
// Normalize color if HDR to give some color hint (otherwise it likely is just white)
if (isHDR)
preset = preset.RGBMultiplied(1f / preset.maxColorComponent);
Color orgColor = GUI.color;
if ((int)rect.height == kSwatchSize)
{
if (preset.a > 0.97f)
RenderSolidSwatch(rect, preset);
else
RenderSwatchWithAlpha(rect, preset, m_ColorSwatchTriangular);
if (isHDR)
GUI.Label(rect, "h");
}
else
{
// The Add preset button swatch
RenderSwatchWithAlpha(rect, preset, m_MiniColorSwatchTriangular);
}
GUI.color = orgColor;
}
private void RenderSolidSwatch(Rect rect, Color preset)
{
GUI.color = preset;
GUI.DrawTexture(rect, m_ColorSwatch);
}
private void RenderSwatchWithAlpha(Rect rect, Color preset, Texture2D swatchTexture)
{
Rect r2 = new Rect(rect.x + 1, rect.y + 1, rect.width - 2, rect.height - 2);
// Background checkers
GUI.color = Color.white;
Rect texCoordsRect = new Rect(0, 0, r2.width / m_CheckerBoard.width, r2.height / m_CheckerBoard.height);
GUI.DrawTextureWithTexCoords(r2, m_CheckerBoard, texCoordsRect, false);
// Alpha color
GUI.color = preset;
GUI.DrawTexture(rect, EditorGUIUtility.whiteTexture);
// Solid color in half triangle
GUI.color = new Color(preset.r, preset.g, preset.b, 1f);
GUI.DrawTexture(rect, swatchTexture);
}
public override string GetName(int index)
{
return m_Presets[index].name;
}
public override void SetName(int index, string presetName)
{
m_Presets[index].name = presetName;
}
public void CreateDebugColors()
{
for (int i = 0; i < 2000; ++i)
m_Presets.Add(new ColorPreset(new Color(Random.Range(0.2f, 1f), Random.Range(0.2f, 1f), Random.Range(0.2f, 1f), 1f), "Preset Color " + i));
}
private static Texture2D CreateColorSwatchWithBorder(int width, int height, bool triangular)
{
Texture2D texture = new Texture2D(width, height, TextureFormat.RGBA32, false);
texture.hideFlags = HideFlags.HideAndDontSave;
Color[] pixels = new Color[width * height];
Color transparent = new Color(1, 1, 1, 0f);
if (triangular)
{
for (int i = 0; i < height; i++)
for (int j = 0; j < width; j++)
{
if (i < width - j)
pixels[j + i * width] = Color.white;
else
pixels[j + i * width] = transparent;
}
}
else
{
for (int i = 0; i < height * width; i++)
pixels[i] = Color.white;
}
// first row
for (int i = 0; i < width; i++)
pixels[i] = Color.black;
// last row
for (int i = 0; i < width; i++)
pixels[(height - 1) * width + i] = Color.black;
// first col
for (int i = 0; i < height; i++)
pixels[i * width] = Color.black;
// last col
for (int i = 0; i < height; i++)
pixels[i * width + width - 1] = Color.black;
texture.SetPixels(pixels);
texture.Apply();
return texture;
}
[System.Serializable]
class ColorPreset
{
[SerializeField]
string m_Name;
[SerializeField]
Color m_Color;
public ColorPreset(Color preset, string presetName)
{
color = preset;
name = presetName;
}
public ColorPreset(Color preset, Color preset2, string presetName)
{
color = preset;
name = presetName;
}
public Color color
{
get { return m_Color; }
set { m_Color = value; }
}
public string name
{
get { return m_Name; }
set { m_Name = value; }
}
}
}
}
| UnityCsReference/Editor/Mono/PresetLibraries/ColorPresetLibrary.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/PresetLibraries/ColorPresetLibrary.cs",
"repo_id": "UnityCsReference",
"token_count": 3920
} | 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 System.Collections.Generic;
using System.Linq;
using UnityEditor.Experimental;
using UnityEngine.Assertions;
namespace UnityEditor
{
internal partial class FilteredHierarchy
{
public class FilterResult
{
public int instanceID;
public string name;
public bool hasChildren;
public int colorCode;
public bool isMainRepresentation;
public bool hasFullPreviewImage;
public IconDrawStyle iconDrawStyle;
public bool isFolder;
public HierarchyType type;
public Texture2D icon
{
get
{
if (m_Icon == null)
{
if (type == HierarchyType.Assets)
{
// Note: Do not set m_Icon as GetCachedIcon uses its own cache that is cleared on reaching a max limit.
// This is because when having e.g very large projects (1000s of textures with unique icons) we do not want all icons loaded
// at the same time so don't keep a reference in m_Icon here
string path = instanceID == 0 ? null : AssetDatabase.GetAssetPath(instanceID);
if (path != null)
// Finding icon based on only file extension fails in several ways, and a different approach have to be found.
// Using InternalEditorUtility.FindIconForFile first in revision f25945218bb6 / 29b23dbe4b5c introduced several regressions.
// - Doesn't support custom user-assigned icons for monoscripts.
// - Doesn't support open/closed folder icon destinction.
// - The change only affected Two-Column mode in Project View and not One-Column mode, adding inconsistency.
// - Doesn't support showing different icons for different prefab types, such as prefab variants.
// Support for specific file types based on file extensiom have to be supported inside AssetDatabase.GetCachedIcon
// itself to work correctly and universally. for e.g. uxml files from within GetCachedIcon without relying on FindIconForFile.
return AssetDatabase.GetCachedIcon(path) as Texture2D;
path = string.IsNullOrEmpty(m_Guid) ? null : AssetDatabase.GUIDToAssetPath(m_Guid);
if (path != null)
return UnityEditorInternal.InternalEditorUtility.FindIconForFile(path);
}
else if (type == HierarchyType.GameObjects)
{
// GameObject thumbnail can be set to m_Icon since its an actual icon which means we have a limited set of them
Object go = EditorUtility.InstanceIDToObject(instanceID);
m_Icon = AssetPreview.GetMiniThumbnail(go);
}
else
{
Assert.IsTrue(false, "Unhandled HierarchyType");
}
}
return m_Icon;
}
set
{
m_Icon = value;
}
}
private Texture2D m_Icon;
internal string m_Guid;
public string guid
{
get
{
if (type == HierarchyType.Assets)
{
if (instanceID != 0 && string.IsNullOrEmpty(m_Guid))
{
string path = AssetDatabase.GetAssetPath(instanceID);
if (path != null)
m_Guid = AssetDatabase.AssetPathToGUID(path);
}
return m_Guid;
}
return null;
}
}
}
SearchFilter m_SearchFilter = new SearchFilter();
FilterResult[] m_Results = new FilterResult[0]; // When filtering of folder we have all sub assets here
FilterResult[] m_VisibleItems = new FilterResult[0]; // Subset of m_Results used for showing/hiding sub assets
SearchService.SceneSearchSessionHandler m_SearchSessionHandler = new SearchService.SceneSearchSessionHandler();
SearchService.SearchSessionOptions m_SearchSessionOptions;
HierarchyType m_HierarchyType;
public const int maxSearchAddCount = 12000;
public FilteredHierarchy(HierarchyType type)
{
m_HierarchyType = type;
m_SearchSessionOptions = SearchService.SearchSessionOptions.Default;
}
public FilteredHierarchy(HierarchyType type, SearchService.SearchSessionOptions searchSessionOptions)
{
m_HierarchyType = type;
m_SearchSessionOptions = searchSessionOptions;
}
public HierarchyType hierarchyType
{
get { return m_HierarchyType; }
}
public FilterResult[] results
{
get
{
if (m_VisibleItems.Length > 0)
return m_VisibleItems;
return m_Results;
}
}
public SearchFilter searchFilter
{
get { return m_SearchFilter; }
set
{
if (m_SearchFilter.SetNewFilter(value))
ResultsChanged();
}
}
public bool foldersFirst { get; set; }
public void SetResults(int[] instanceIDs)
{
var instanceIdSet = new HashSet<int>(instanceIDs);
if (m_HierarchyType == HierarchyType.Assets)
{
var idsUnderEachRoot = new Dictionary<string, int>();
for (int i = 0; i < instanceIDs.Length; ++i)
{
var rootPath = "Assets";
var path = AssetDatabase.GetAssetPath(instanceIDs[i]);
var packageInfo = PackageManager.PackageInfo.FindForAssetPath(path);
// Find the right rootPath if folderPath is part of a package
if (packageInfo != null)
rootPath = packageInfo.assetPath;
if (!idsUnderEachRoot.ContainsKey(rootPath))
idsUnderEachRoot.Add(rootPath, 0);
++idsUnderEachRoot[rootPath];
}
SetAssetsResults(instanceIdSet, idsUnderEachRoot);
}
else
{
HierarchyProperty property = new HierarchyProperty(m_HierarchyType, false);
property.Reset();
System.Array.Resize(ref m_Results, instanceIDs.Length);
for (int i = 0; i < instanceIDs.Length; ++i)
{
if (property.Find(instanceIDs[i], null))
CopyPropertyData(ref m_Results[i], property);
}
}
}
internal void SetResults(int[] instanceIDs, string[] rootPaths)
{
var instanceIdSet = new HashSet<int>(instanceIDs);
if (m_HierarchyType == HierarchyType.Assets)
{
var idsUnderEachRoot = new Dictionary<string, int>();
foreach (var rootPath in rootPaths)
{
if (!idsUnderEachRoot.ContainsKey(rootPath))
idsUnderEachRoot.Add(rootPath, 0);
++idsUnderEachRoot[rootPath];
}
SetAssetsResults(instanceIdSet, idsUnderEachRoot);
}
else
{
HierarchyProperty property = new HierarchyProperty(m_HierarchyType, false);
property.Reset();
System.Array.Resize(ref m_Results, instanceIDs.Length);
for (int i = 0; i < instanceIDs.Length; ++i)
{
if (property.Find(instanceIDs[i], null))
CopyPropertyData(ref m_Results[i], property);
}
}
}
void SetAssetsResults(HashSet<int> instanceIdsSet, Dictionary<string, int> idsUnderEachRoot)
{
System.Array.Resize(ref m_Results, instanceIdsSet.Count);
var currentResultIndex = 0;
var rootPaths = idsUnderEachRoot.Keys.ToArray();
var idCounts = idsUnderEachRoot.Values.ToArray();
for (var i = 0; i < rootPaths.Length; ++i)
{
var rootPath = rootPaths[i];
var nbIds = idCounts[i];
HierarchyProperty property = new HierarchyProperty(rootPath, false);
var propertiesFound = 0;
while (property.Next(null) && propertiesFound < nbIds)
{
var instanceId = property.GetInstanceIDIfImported();
if (instanceIdsSet.Contains(instanceId))
{
++propertiesFound;
CopyPropertyData(ref m_Results[currentResultIndex], property);
++currentResultIndex;
}
}
}
}
void CopyPropertyData(ref FilterResult result, HierarchyProperty property)
{
if (result == null)
result = new FilterResult();
result.instanceID = property.GetInstanceIDIfImported();
result.name = property.name;
result.hasChildren = property.hasChildren;
result.colorCode = property.colorCode;
result.isMainRepresentation = property.isMainRepresentation;
result.hasFullPreviewImage = property.hasFullPreviewImage;
result.iconDrawStyle = property.iconDrawStyle;
result.isFolder = property.isFolder;
result.type = hierarchyType;
// If this is not the main representation, cache the icon, as we don't have an API to access it later.
// Otherwise, don't - as this may cause Textures to load unintendedly (e.g if we have 3000 search results we do not want to load icons before needed when rendering)
if (!property.isMainRepresentation)
result.icon = property.icon;
else if (property.isFolder && !property.hasChildren)
result.icon = EditorGUIUtility.FindTexture(EditorResources.emptyFolderIconName);
else
result.icon = null;
if (m_HierarchyType == HierarchyType.Assets)
result.m_Guid = property.guid;
}
void SearchAllAssets(SearchFilter.SearchArea area)
{
if (m_HierarchyType == HierarchyType.Assets)
{
List<FilterResult> list = new List<FilterResult>();
list.AddRange(m_Results);
var maxAddCount = maxSearchAddCount;
m_SearchFilter.searchArea = area;
var enumerator = AssetDatabase.EnumerateAllAssets(m_SearchFilter);
while (enumerator.MoveNext() && --maxAddCount >= 0)
{
var result = new FilterResult();
CopyPropertyData(ref result, enumerator.Current);
list.Add(result);
}
m_Results = list.ToArray();
}
else if (m_HierarchyType == HierarchyType.GameObjects)
{
HierarchyProperty property = new HierarchyProperty(m_HierarchyType, false);
m_SearchSessionHandler.BeginSession(() =>
{
return new SearchService.SceneSearchContext
{
searchFilter = m_SearchFilter,
rootProperty = property,
requiredTypeNames = m_SearchFilter.classNames,
requiredTypes = searchFilter.classNames.Select(name => TypeCache.GetTypesDerivedFrom<Object>().FirstOrDefault(t => name == t.FullName || name == t.Name))
};
}, m_SearchSessionOptions);
var searchQuery = m_SearchFilter.originalText;
m_SearchSessionHandler.BeginSearch(searchQuery);
if (m_SearchFilter.sceneHandles != null &&
m_SearchFilter.sceneHandles.Length > 0)
{
property.SetCustomScenes(m_SearchFilter.sceneHandles);
}
var newResults = new List<FilterResult>();
while (property.Next(null))
{
if (!m_SearchSessionHandler.Filter(searchQuery, property))
continue;
FilterResult newResult = new FilterResult();
CopyPropertyData(ref newResult, property);
newResults.Add(newResult);
}
int elements = newResults.Count;
elements = Mathf.Min(elements, maxSearchAddCount);
int i = m_Results.Length;
System.Array.Resize(ref m_Results, m_Results.Length + elements);
for (var j = 0; j < elements && i < m_Results.Length; ++j, ++i)
{
m_Results[i] = newResults[j];
}
m_SearchSessionHandler.EndSearch();
}
}
void SearchInFolders()
{
List<FilterResult> list = new List<FilterResult>();
List<string> baseFolders = new List<string>();
baseFolders.AddRange(ProjectWindowUtil.GetBaseFolders(m_SearchFilter.folders));
if (baseFolders.Remove(PackageManager.Folders.GetPackagesPath()))
{
var packages = PackageManagerUtilityInternal.GetAllVisiblePackages(m_SearchFilter.skipHidden);
foreach (var package in packages)
{
if (!baseFolders.Contains(package.assetPath))
baseFolders.Add(package.assetPath);
}
}
m_SearchFilter.searchArea = SearchFilter.SearchArea.SelectedFolders;
foreach (string folderPath in baseFolders)
{
// Ensure we do not have a filter when finding folder
HierarchyProperty property = new HierarchyProperty(folderPath);
property.SetSearchFilter(m_SearchFilter);
// Set filter after we found the folder
int folderDepth = property.depth;
int[] expanded = null; // enter all children of folder
while (property.NextWithDepthCheck(expanded, folderDepth + 1))
{
FilterResult result = new FilterResult();
CopyPropertyData(ref result, property);
list.Add(result);
}
}
m_Results = list.ToArray();
}
void FolderBrowsing()
{
// We are not concerned with assets being added multiple times as we only show the contents
// of each selected folder. This is an issue when searching recursively into child folders.
List<FilterResult> list = new List<FilterResult>();
HierarchyProperty property;
foreach (string folderPath in m_SearchFilter.folders)
{
if (folderPath == PackageManager.Folders.GetPackagesPath())
{
var packages = PackageManagerUtilityInternal.GetAllVisiblePackages(m_SearchFilter.skipHidden);
foreach (var package in packages)
{
var packageFolderInstanceId = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(package.assetPath);
property = new HierarchyProperty(package.assetPath);
if (property.Find(packageFolderInstanceId, null))
{
FilterResult result = new FilterResult();
CopyPropertyData(ref result, property);
result.name = !string.IsNullOrEmpty(package.displayName) ? package.displayName : package.name;
list.Add(result);
}
}
continue;
}
if (m_SearchFilter.skipHidden && !PackageManagerUtilityInternal.IsPathInVisiblePackage(folderPath))
continue;
int folderInstanceID = AssetDatabase.GetMainAssetOrInProgressProxyInstanceID(folderPath);
property = new HierarchyProperty(folderPath);
property.SetSearchFilter(m_SearchFilter);
int folderDepth = property.depth;
int[] expanded = { folderInstanceID };
Dictionary<string , List<FilterResult>> subAssets = new Dictionary<string, List<FilterResult>>();
List<FilterResult> parentAssets = new List<FilterResult>();
while (property.Next(expanded))
{
if (property.depth <= folderDepth)
break; // current property is outside folder
FilterResult result = new FilterResult();
CopyPropertyData(ref result, property);
//list.Add(result);
// Fetch sub assets by expanding the main asset (ignore folders)
if (property.hasChildren && !property.isFolder)
{
parentAssets.Add(result);
List<FilterResult> subAssetList = new List<FilterResult>();
subAssets.Add(result.guid, subAssetList);
System.Array.Resize(ref expanded, expanded.Length + 1);
expanded[expanded.Length - 1] = property.instanceID;
}
else
{
List<FilterResult> subAssetList;
if (subAssets.TryGetValue(result.guid, out subAssetList))
{
subAssetList.Add(result);
subAssets[result.guid] = subAssetList;
}
else
{
parentAssets.Add(result);
}
}
}
parentAssets.Sort((result1, result2) => EditorUtility.NaturalCompare(result1.name, result2.name));
foreach (FilterResult result in parentAssets)
{
list.Add(result);
List<FilterResult> subAssetList;
if (subAssets.TryGetValue(result.guid, out subAssetList))
{
subAssetList.Sort((result1, result2) => EditorUtility.NaturalCompare(result1.name, result2.name));
foreach (FilterResult subasset in subAssetList)
{
list.Add(subasset);
}
}
}
}
m_Results = list.ToArray();
}
void AddResults()
{
switch (m_SearchFilter.GetState())
{
case SearchFilter.State.FolderBrowsing: FolderBrowsing(); break;
case SearchFilter.State.SearchingInAllAssets: SearchAllAssets(SearchFilter.SearchArea.AllAssets); break;
case SearchFilter.State.SearchingInAssetsOnly: SearchAllAssets(SearchFilter.SearchArea.InAssetsOnly); break;
case SearchFilter.State.SearchingInPackagesOnly: SearchAllAssets(SearchFilter.SearchArea.InPackagesOnly); break;
case SearchFilter.State.SearchingInFolders: SearchInFolders(); break;
case SearchFilter.State.EmptySearchFilter: /*do nothing*/ break;
default: Debug.LogError("Unhandled enum!"); break;
}
}
public void ResultsChanged()
{
m_Results = new FilterResult[0];
if (m_SearchFilter.GetState() != SearchFilter.State.EmptySearchFilter)
{
AddResults();
// When filtering on folder we use the order we get from BaseHiearchyProperty.cpp (to keep indented children under parent) otherwise we sort
if (m_SearchFilter.IsSearching())
{
System.Array.Sort(m_Results, (result1, result2) => EditorUtility.NaturalCompare(result1.name, result2.name));
}
if (foldersFirst)
{
for (int nonFolderPos = 0; nonFolderPos < m_Results.Length; ++nonFolderPos)
{
if (m_Results[nonFolderPos].isFolder)
continue;
for (int folderPos = nonFolderPos + 1; folderPos < m_Results.Length; ++folderPos)
{
if (!m_Results[folderPos].isFolder)
continue;
FilterResult folder = m_Results[folderPos];
int length = folderPos - nonFolderPos;
System.Array.Copy(m_Results, nonFolderPos, m_Results, nonFolderPos + 1, length);
m_Results[nonFolderPos] = folder;
break;
}
}
}
}
else
{
// Reset visible flags if filter string is empty (see BaseHiearchyProperty::SetSearchFilter)
if (m_HierarchyType == HierarchyType.GameObjects)
{
HierarchyProperty gameObjects = new HierarchyProperty(HierarchyType.GameObjects, false);
gameObjects.SetSearchFilter(m_SearchFilter);
m_SearchSessionHandler.EndSession();
}
}
}
public void RefreshVisibleItems(List<int> expandedInstanceIDs)
{
bool isSearching = m_SearchFilter.IsSearching();
List<FilterResult> visibleItems = new List<FilterResult>();
for (int i = 0; i < m_Results.Length; ++i)
{
visibleItems.Add(m_Results[i]);
if (m_Results[i].isMainRepresentation && m_Results[i].hasChildren && !m_Results[i].isFolder)
{
bool isParentExpanded = expandedInstanceIDs.IndexOf(m_Results[i].instanceID) >= 0;
bool addSubItems = isParentExpanded || isSearching;
int numSubItems = AddSubItemsOfMainRepresentation(i, addSubItems ? visibleItems : null);
i += numSubItems;
}
}
m_VisibleItems = visibleItems.ToArray();
}
public List<int> GetSubAssetInstanceIDs(int mainAssetInstanceID)
{
for (int i = 0; i < m_Results.Length; ++i)
{
if (m_Results[i].instanceID == mainAssetInstanceID)
{
List<int> subAssetInstanceIDs = new List<int>();
int index = i + 1; // Start after the main representation
while (index < m_Results.Length && !m_Results[index].isMainRepresentation)
{
subAssetInstanceIDs.Add(m_Results[index].instanceID);
index++;
}
return subAssetInstanceIDs;
}
}
Debug.LogError("Not main rep " + mainAssetInstanceID);
return new List<int>();
}
public int AddSubItemsOfMainRepresentation(int mainRepresentionIndex, List<FilterResult> visibleItems)
{
int count = 0;
int index = mainRepresentionIndex + 1; // Start after the main representation
while (index < m_Results.Length && !m_Results[index].isMainRepresentation)
{
if (visibleItems != null)
visibleItems.Add(m_Results[index]);
index++;
count++;
}
return count;
}
}
internal class FilteredHierarchyProperty : IHierarchyProperty
{
FilteredHierarchy m_Hierarchy;
int m_Position = -1;
public static IHierarchyProperty CreateHierarchyPropertyForFilter(FilteredHierarchy filteredHierarchy)
{
if (filteredHierarchy.searchFilter.GetState() != SearchFilter.State.EmptySearchFilter)
return new FilteredHierarchyProperty(filteredHierarchy);
else
return new HierarchyProperty(filteredHierarchy.hierarchyType, false);
}
public FilteredHierarchyProperty(FilteredHierarchy filter)
{
m_Hierarchy = filter;
}
public void Reset()
{
m_Position = -1;
}
public int instanceID
{
get
{
var id = m_Hierarchy.results[m_Position].instanceID;
if (id == 0)
m_Hierarchy.results[m_Position].instanceID = AssetDatabase.GetMainAssetInstanceID(guid);
return m_Hierarchy.results[m_Position].instanceID;
}
}
public Object pptrValue
{
get { return EditorUtility.InstanceIDToObject(instanceID); }
}
public string name
{
get { return m_Hierarchy.results[m_Position].name; }
}
public bool hasChildren
{
get { return m_Hierarchy.results[m_Position].hasChildren; }
}
public bool isMainRepresentation
{
get { return m_Hierarchy.results[m_Position].isMainRepresentation; }
}
public bool hasFullPreviewImage
{
get { return m_Hierarchy.results[m_Position].hasFullPreviewImage; }
}
public IconDrawStyle iconDrawStyle
{
get { return m_Hierarchy.results[m_Position].iconDrawStyle; }
}
public bool isFolder
{
get { return m_Hierarchy.results[m_Position].isFolder; }
}
public GUID[] dynamicDependencies
{
get { return new GUID[] {}; }
}
public int depth
{
get { return 0; }
}
public int row
{
get { return m_Position; }
}
public int colorCode
{
get { return m_Hierarchy.results[m_Position].colorCode; }
}
public bool IsExpanded(int[] expanded)
{
return false;
}
public string guid
{
get { return m_Hierarchy.results[m_Position].guid; }
}
public bool isValid
{
get { return m_Hierarchy.results != null && m_Position < m_Hierarchy.results.Length && m_Position >= 0; }
}
public Texture2D icon
{
get { return m_Hierarchy.results[m_Position].icon; }
}
public bool Next(int[] expanded)
{
m_Position++;
return m_Position < m_Hierarchy.results.Length;
}
public bool NextWithDepthCheck(int[] expanded, int minDepth)
{
// Depth check does not make sense for filtered properties as tree info is lost
return Next(expanded);
}
public bool Previous(int[] expanded)
{
m_Position--;
return m_Position >= 0;
}
public bool Parent()
{
return false;
}
public int[] ancestors
{
get
{
return new int[0];
}
}
public bool Find(int _instanceID, int[] expanded)
{
Reset();
while (Next(expanded))
{
if (instanceID == _instanceID)
return true;
}
return false;
}
public int[] FindAllAncestors(int[] instanceIDs)
{
return new int[0];
}
public bool Skip(int count, int[] expanded)
{
m_Position += count;
return m_Position < m_Hierarchy.results.Length;
}
public int CountRemaining(int[] expanded)
{
return m_Hierarchy.results.Length - m_Position - 1;
}
public int GetInstanceIDIfImported()
{
return m_Hierarchy.results[m_Position].instanceID;
}
}
}
| UnityCsReference/Editor/Mono/ProjectBrowser/CachedFilteredHierachy.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ProjectBrowser/CachedFilteredHierachy.cs",
"repo_id": "UnityCsReference",
"token_count": 15095
} | 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 System.Reflection;
using UnityEditor.UIElements;
using UnityEditor.UIElements.ProjectSettings;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UIElements;
using UnityEditor.Categorization;
namespace UnityEditor.Rendering.GraphicsSettingsInspectors
{
//internal for tests
[CustomPropertyDrawer(typeof(RenderPipelineGraphicsSettingsCollection))]
internal class RenderPipelineGraphicsSettingsCollectionPropertyDrawer : PropertyDrawer
{
const string k_LineClass = "contextual-menu-button--handler";
const string k_GraphicsSettingsClass = "project-settings-section__graphics-settings";
const string k_GraphicsSettingsHighlightableClass = "graphics-settings__highlightable";
const string k_GraphicsSettingsContentFollowupClass = "project-settings-section__content-followup";
internal struct SettingsInfo : ICategorizable
{
public SerializedProperty property { get; private set; }
public Type type { get; private set; }
public HelpURLAttribute helpURLAttribute { get; private set; }
public bool onlyForDevMode { get; private set; }
public IRenderPipelineGraphicsSettings target => property?.boxedValue as IRenderPipelineGraphicsSettings;
public static SettingsInfo? ExtractFrom(SerializedProperty property)
{
//boxedProperty can be null if we keep in the list a data blob for a type that have disappears
//this can happens if user remove a IRenderPipelineGraphicsSettings from his project for instance
Type type = property?.boxedValue?.GetType();
if (type == null || !typeof(IRenderPipelineGraphicsSettings).IsAssignableFrom(type))
return null;
// If GraphicsSettings is hidden, discard it
bool hidden = type.GetCustomAttribute<HideInInspector>() != null;
if (!Unsupported.IsDeveloperMode() && hidden)
return null;
return new SettingsInfo()
{
property = property.Copy(),
type = type,
helpURLAttribute = type.GetCustomAttribute<HelpURLAttribute>(),
onlyForDevMode = hidden,
};
}
}
//internal for tests
internal static List<Category<LeafElement<SettingsInfo>>> Categorize(SerializedProperty property)
{
List<SettingsInfo> elements = new();
var propertyIterator = property.Copy();
var end = propertyIterator.GetEndProperty();
propertyIterator.NextVisible(true);
while (!SerializedProperty.EqualContents(propertyIterator, end))
{
var info = SettingsInfo.ExtractFrom(propertyIterator);
if (info == null)
{
propertyIterator.NextVisible(false);
continue; //remove array length and hidden properties
}
elements.Add(info.Value);
propertyIterator.NextVisible(false);
}
return elements.SortByCategory();
}
void DrawHelpButton(VisualElement root, HelpURLAttribute helpURLAttribute)
{
if (helpURLAttribute?.URL != null)
{
var button = new Button(Background.FromTexture2D(EditorGUIUtility.LoadIcon("_Help")), () => Help.BrowseURL(helpURLAttribute.URL));
root.Add(button);
}
}
void ShowContextualMenu(Rect rect, List<LeafElement<SettingsInfo>> siblings, SerializedProperty property)
{
List<IRenderPipelineGraphicsSettings> targets = new(siblings.Count);
foreach (SettingsInfo sibling in siblings)
targets.Add(sibling.target);
var contextualMenu = new GenericMenu(); //use ImGUI for now, need to be updated later
RenderPipelineGraphicsSettingsContextMenuManager.PopulateContextMenu(targets, property, ref contextualMenu);
contextualMenu.DropDown(new Rect(rect.position + Vector2.up * rect.size.y, Vector2.zero), shouldDiscardMenuOnSecondClick: true);
}
void DrawContextualMenuButton(VisualElement root, LeafElement<SettingsInfo> settingsInfo)
{
var button = new Button(Background.FromTexture2D(EditorGUIUtility.LoadIcon("pane options")));
button.clicked += () => ShowContextualMenu(button.worldBound, settingsInfo.parent.content, settingsInfo.data.property);
root.Add(button);
}
void DrawHeader(VisualElement root, Category<LeafElement<SettingsInfo>> category)
{
var line = new VisualElement();
line.style.flexDirection = FlexDirection.Row;
line.AddToClassList(k_LineClass);
var label = new Label(category.name);
label.AddToClassList(ProjectSettingsSection.Styles.header);
line.Add(label);
root.Add(line);
var firstSetting = category[0];
DrawHelpButton(line, firstSetting.data.helpURLAttribute);
DrawContextualMenuButton(line, firstSetting);
}
void DrawContent(VisualElement root, SettingsInfo settingsInfo, bool first)
{
var graphicsSettings = new PropertyField(settingsInfo.property)
{
name = settingsInfo.type.Name,
classList =
{
ProjectSettingsSection.Styles.content,
k_GraphicsSettingsClass,
}
};
if (!first)
graphicsSettings.classList.Add(k_GraphicsSettingsContentFollowupClass);
root.Add(graphicsSettings);
}
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
var root = new VisualElement { name = "GlobalSettingsCollection" };
var graphicsSettings = property.FindPropertyRelative("m_List");
Debug.Assert(graphicsSettings != null);
foreach (var category in Categorize(graphicsSettings))
{
DrawHeader(root, category);
DrawContent(root, category[0], first: true);
for (int i = 1; i < category.count; ++i)
DrawContent(root, category[i], first: false);
}
return root;
}
}
}
| UnityCsReference/Editor/Mono/RenderPipelineGraphicsSettingsCollectionPropertyDrawer.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/RenderPipelineGraphicsSettingsCollectionPropertyDrawer.cs",
"repo_id": "UnityCsReference",
"token_count": 2824
} | 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 UnityEngine;
namespace UnityEditor.IMGUI.Controls
{
class BreadcrumbBar
{
List<Item> m_Breadcrumbs = new List<Item>();
public static class DefaultStyles
{
public static GUIStyle label;
public static GUIStyle labelMissing;
public static GUIStyle labelBold;
public static GUIStyle labelBoldMissing;
public static GUIStyle background;
public static GUIStyle separatorLine = "BreadcrumbsSeparator";
public static GUIStyle separatorArrow = "ArrowNavigationRight";
static DefaultStyles()
{
label = new GUIStyle(EditorStyles.label);
label.alignment = TextAnchor.MiddleLeft;
label.margin = new RectOffset(0, 0, 0, 0);
labelMissing = new GUIStyle(label);
labelMissing.normal.textColor = GameObjectTreeViewGUI.GameObjectStyles.brokenPrefabLabel.normal.textColor;
labelBold = new GUIStyle(label);
labelBold.fontStyle = FontStyle.Bold;
labelBoldMissing = new GUIStyle(labelMissing);
labelBoldMissing.fontStyle = FontStyle.Bold;
background = new GUIStyle("ProjectBrowserTopBarBg");
background.padding = new RectOffset(4, 4, 0, 0);
background.border = new RectOffset(3, 3, 3, 3);
background.fixedHeight = 25f;
}
}
public enum SeparatorStyle
{
None,
Line,
Arrow
}
public class Item
{
public GUIContent content { get; set; }
public GUIStyle guistyle { get; set; }
public object userdata { get; set; }
public SeparatorStyle separatorstyle { get; set; }
}
public event Action<Item> onBreadCrumbClicked = null;
public List<Item> breadcrumbs { get { return m_Breadcrumbs; } }
float lastBreadcrumbWidth { get; set; }
public void SetBreadCrumbs(List<Item> breadCrumbItems)
{
m_Breadcrumbs = breadCrumbItems;
// Set default style if needed
foreach (var item in m_Breadcrumbs)
if (item.guistyle == null)
item.guistyle = DefaultStyles.label;
if (m_Breadcrumbs.Count > 0)
{
EditorGUIUtility.SetIconSize(new Vector2(16, 16));
var lastItem = m_Breadcrumbs[m_Breadcrumbs.Count - 1];
lastBreadcrumbWidth = lastItem.guistyle.CalcSize(lastItem.content).x;
EditorGUIUtility.SetIconSize(new Vector2(0, 0));
}
}
public void OnGUI()
{
EditorGUIUtility.SetIconSize(new Vector2(16, 16));
for (int i = 0; i < m_Breadcrumbs.Count; ++i)
{
Item item = m_Breadcrumbs[i];
if (item.separatorstyle != SeparatorStyle.None)
{
var separatorGUIStyle = item.separatorstyle == SeparatorStyle.Arrow ? DefaultStyles.separatorArrow : DefaultStyles.separatorLine;
GUILayout.Label(GUIContent.none, separatorGUIStyle);
}
// Ensures last breadcrumb does not shrink
var minWidth = (i == m_Breadcrumbs.Count - 1) ? lastBreadcrumbWidth : 32;
if (GUILayout.Button(item.content, item.guistyle, GUILayout.MinWidth(minWidth)))
{
if (onBreadCrumbClicked != null)
onBreadCrumbClicked(item);
}
}
GUILayout.FlexibleSpace();
EditorGUIUtility.SetIconSize(new Vector2(0, 0));
}
}
}
| UnityCsReference/Editor/Mono/SceneManagement/StageManager/BreadcrumbBar.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneManagement/StageManager/BreadcrumbBar.cs",
"repo_id": "UnityCsReference",
"token_count": 1980
} | 312 |
// 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.Linq;
namespace UnityEditor
{
public class LightingExplorerTab
{
SerializedPropertyTable m_LightTable;
GUIContent m_Title;
internal GUIContent title { get { return m_Title; } }
public LightingExplorerTab(string title, Func<UnityEngine.Object[]> objects, Func<LightingExplorerTableColumn[]> columns)
: this(title, objects, columns, true) {}
public LightingExplorerTab(string title, Func<UnityEngine.Object[]> objects, Func<LightingExplorerTableColumn[]> columns, bool showFilterGUI)
{
if (objects() == null)
throw new ArgumentException("Objects are not allowed to be null", "objects");
if (columns() == null)
throw new ArgumentException("Columns are not allowed to be null", "columns");
m_LightTable = new SerializedPropertyTable(title.Replace(" ", string.Empty), new SerializedPropertyDataStore.GatherDelegate(objects), () => {
return columns().Select(item => item.internalColumn).ToArray();
}, showFilterGUI);
m_Title = EditorGUIUtility.TrTextContent(title);
}
internal void OnDisable()
{
if (m_LightTable != null)
m_LightTable.OnDisable();
}
internal void OnInspectorUpdate()
{
if (m_LightTable != null)
m_LightTable.OnInspectorUpdate();
}
internal void OnSelectionChange(int[] instanceIDs)
{
if (m_LightTable != null)
m_LightTable.OnSelectionChange(instanceIDs);
}
internal void OnSelectionChange()
{
if (m_LightTable != null)
m_LightTable.OnSelectionChange();
}
internal void OnHierarchyChange()
{
if (m_LightTable != null)
m_LightTable.OnHierarchyChange();
}
internal void OnGUI()
{
EditorGUI.indentLevel += 1;
int cur_indent = EditorGUI.indentLevel;
float cur_indent_px = EditorGUI.indent;
EditorGUI.indentLevel = 0;
EditorGUILayout.BeginHorizontal();
GUILayout.Space(cur_indent_px);
using (new EditorGUILayout.VerticalScope())
{
if (m_LightTable != null)
m_LightTable.OnGUI();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUI.indentLevel = cur_indent;
EditorGUI.indentLevel -= 1;
}
}
public sealed class LightingExplorerTableColumn
{
public enum DataType
{
Name = 0,
Checkbox = 1,
Enum = 2,
Int = 3,
Float = 4,
Color = 5,
// ..
Custom = 20
}
SerializedPropertyTreeView.Column m_Column;
internal SerializedPropertyTreeView.Column internalColumn { get { return m_Column; } }
public delegate void OnGUIDelegate(Rect r, SerializedProperty prop, SerializedProperty[] dependencies);
public delegate int ComparePropertiesDelegate(SerializedProperty lhs, SerializedProperty rhs);
public delegate void CopyPropertiesDelegate(SerializedProperty target, SerializedProperty source);
public LightingExplorerTableColumn(DataType type, GUIContent headerContent, string propertyName = null, int width = 100, OnGUIDelegate onGUIDelegate = null, ComparePropertiesDelegate compareDelegate = null, CopyPropertiesDelegate copyDelegate = null, int[] dependencyIndices = null)
{
m_Column = new SerializedPropertyTreeView.Column();
m_Column.headerContent = headerContent;
m_Column.width = width;
m_Column.minWidth = width / 2;
m_Column.propertyName = propertyName;
m_Column.dependencyIndices = dependencyIndices;
m_Column.sortedAscending = true;
m_Column.sortingArrowAlignment = TextAlignment.Center;
m_Column.autoResize = false;
m_Column.allowToggleVisibility = true;
m_Column.headerTextAlignment = type == DataType.Checkbox ? TextAlignment.Center : TextAlignment.Left;
switch (type)
{
case DataType.Name:
m_Column.compareDelegate = SerializedPropertyTreeView.DefaultDelegates.CompareName;
m_Column.drawDelegate = SerializedPropertyTreeView.DefaultDelegates.DrawName;
m_Column.filter = new SerializedPropertyFilters.Name();
break;
case DataType.Checkbox:
m_Column.compareDelegate = SerializedPropertyTreeView.DefaultDelegates.CompareCheckbox;
m_Column.drawDelegate = SerializedPropertyTreeView.DefaultDelegates.DrawCheckbox;
break;
case DataType.Enum:
m_Column.compareDelegate = SerializedPropertyTreeView.DefaultDelegates.CompareEnum;
m_Column.drawDelegate = SerializedPropertyTreeView.DefaultDelegates.DrawDefault;
break;
case DataType.Int:
m_Column.compareDelegate = SerializedPropertyTreeView.DefaultDelegates.CompareInt;
m_Column.drawDelegate = SerializedPropertyTreeView.DefaultDelegates.DrawDefault;
break;
case DataType.Float:
m_Column.compareDelegate = SerializedPropertyTreeView.DefaultDelegates.CompareFloat;
m_Column.drawDelegate = SerializedPropertyTreeView.DefaultDelegates.DrawDefault;
break;
case DataType.Color:
m_Column.compareDelegate = SerializedPropertyTreeView.DefaultDelegates.CompareColor;
m_Column.drawDelegate = SerializedPropertyTreeView.DefaultDelegates.DrawDefault;
break;
default:
break;
}
if (onGUIDelegate != null)
{
// when allowing the user to draw checkboxes, we will make sure that the rect is in the center
if (type == DataType.Checkbox)
{
m_Column.drawDelegate = (r, prop, dep) => {
float off = System.Math.Max(0.0f, ((r.width / 2) - 8));
r.x += off;
r.width -= off;
onGUIDelegate(r, prop, dep);
};
}
else
m_Column.drawDelegate = new SerializedPropertyTreeView.Column.DrawEntry(onGUIDelegate);
}
if (compareDelegate != null)
m_Column.compareDelegate = new SerializedPropertyTreeView.Column.CompareEntry(compareDelegate);
if (copyDelegate != null)
m_Column.copyDelegate = new SerializedPropertyTreeView.Column.CopyDelegate(copyDelegate);
}
}
}
| UnityCsReference/Editor/Mono/SceneModeWindows/LightingExplorerTab.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneModeWindows/LightingExplorerTab.cs",
"repo_id": "UnityCsReference",
"token_count": 3488
} | 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;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using UnityEditor.Actions;
using UnityEditor.AnimatedValues;
using UnityEditor.SceneManagement;
using UnityEditor.ShortcutManagement;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Profiling;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;
using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute;
using UnityEditor.EditorTools;
using UnityEditor.Overlays;
using UnityEditor.Profiling;
using UnityEditor.UIElements;
using UnityEngine.Serialization;
using UnityEngine.UIElements;
using Component = UnityEngine.Component;
namespace UnityEditor
{
[EditorWindowTitle(title = "Scene", useTypeNameAsIconName = true)]
public partial class SceneView : SearchableEditorWindow, IHasCustomMenu, ISupportsOverlays
{
[Serializable]
public struct CameraMode
{
internal CameraMode(DrawCameraMode drawMode, string name, string section, bool show = true)
{
this.drawMode = drawMode;
this.name = name;
this.section = section;
this.show = show;
}
public DrawCameraMode drawMode;
public string name;
public string section;
internal bool show;
public static bool operator==(CameraMode a, CameraMode z)
{
return a.drawMode == z.drawMode && a.name == z.name && a.section == z.section;
}
public static bool operator!=(CameraMode a, CameraMode z)
{
return !(a == z);
}
public override bool Equals(System.Object otherObject)
{
if (ReferenceEquals(otherObject, null))
return false;
if (!(otherObject is CameraMode))
return false;
return this == (CameraMode)otherObject;
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
return UnityString.Format("{0}||{1}||{2}", drawMode, name, section);
}
}
static SceneView s_LastActiveSceneView;
[RequiredByNativeCode]
internal static DrawCameraMode[] GetInteractiveDrawCameraModeValues()
{
List<DrawCameraMode> drawCameraModes = new List<DrawCameraMode>();
foreach (SceneView sceneView in SceneView.sceneViews)
{
if (sceneView.usesInteractiveLightBakingData)
drawCameraModes.Add(sceneView.cameraMode.drawMode);
}
return drawCameraModes.ToArray();
}
internal static bool NeedsInteractiveBaking()
{
foreach (SceneView sceneView in SceneView.sceneViews)
{
if (sceneView.usesInteractiveLightBakingData)
return true;
}
return false;
}
static string GetLegacyOverlayId(OverlayWindow overlayData)
{
return "legacy-overlay::" + overlayData.title.text;
}
internal void ShowLegacyOverlay(OverlayWindow overlayData)
{
var overlay = overlayCanvas.GetOrCreateOverlay<LegacyOverlay>(GetLegacyOverlayId(overlayData));
if (overlay != null)
{
overlay.displayName = overlayData.title.text;
overlay.data = overlayData;
overlay.showRequested = true;
}
}
void LegacyOverlayPreOnGUI()
{
if (Event.current.type == EventType.Layout)
foreach (var overlay in overlayCanvas.overlays)
if(overlay is LegacyOverlay legacyOverlay)
legacyOverlay.showRequested = false;
}
public static Action<SceneView, SceneView> lastActiveSceneViewChanged;
static SceneView s_CurrentDrawingSceneView;
public static SceneView lastActiveSceneView
{
get
{
if (s_LastActiveSceneView == null && s_SceneViews.Count > 0)
s_LastActiveSceneView = s_SceneViews[0] as SceneView;
return s_LastActiveSceneView;
}
private set
{
if (value == s_LastActiveSceneView)
return;
var oldValue = s_LastActiveSceneView;
s_LastActiveSceneView = value;
lastActiveSceneViewChanged?.Invoke(oldValue, value);
MoveOverlaysToActiveView(oldValue, value);
}
}
public static SceneView currentDrawingSceneView { get { return s_CurrentDrawingSceneView; } }
internal static readonly PrefColor kSceneViewBackground = new PrefColor("Scene/Background", 0.278431f, 0.278431f, 0.278431f, 1);
internal static readonly PrefColor kSceneViewPrefabBackground = new PrefColor("Scene/Background for Prefabs", 0.132f, 0.231f, 0.330f, 1);
static readonly PrefColor kSceneViewWire = new PrefColor("Scene/Wireframe", 0.0f, 0.0f, 0.0f, 0.5f);
static readonly PrefColor kSceneViewWireOverlay = new PrefColor("Scene/Wireframe Overlay", 0.0f, 0.0f, 0.0f, 0.25f);
static readonly PrefColor kSceneViewSelectedOutline = new PrefColor("Scene/Selected Outline", 255.0f / 255.0f, 102.0f / 255.0f, 0.0f / 255.0f, 0.0f / 255.0f);
static readonly PrefColor kSceneViewSelectedSubmeshOutline = new PrefColor("Scene/Selected Material Highlight", 200.0f / 255.0f, 0f / 255.0f, 0f / 255.0f, 100.0f / 255.0f);
static readonly PrefColor kSceneViewSelectedChildrenOutline = new PrefColor("Scene/Selected Children Outline", 94.0f / 255.0f, 119.0f / 255.0f, 155.0f / 255.0f, 0.0f / 255.0f);
static readonly PrefColor kSceneViewSelectedWire = new PrefColor("Scene/Wireframe Selected", 94.0f / 255.0f, 119.0f / 255.0f, 155.0f / 255.0f, 64.0f / 255.0f);
internal static Color kSceneViewFrontLight = new Color(0.769f, 0.769f, 0.769f, 1);
internal static Color kSceneViewUpLight = new Color(0.212f, 0.227f, 0.259f, 1);
internal static Color kSceneViewMidLight = new Color(0.114f, 0.125f, 0.133f, 1);
internal static Color kSceneViewDownLight = new Color(0.047f, 0.043f, 0.035f, 1);
const string k_StyleCommon = "StyleSheets/SceneView/SceneViewCommon.uss";
const string k_StyleDark = "StyleSheets/SceneView/SceneViewDark.uss";
const string k_StyleLight = "StyleSheets/SceneView/SceneViewLight.uss";
public static Color selectedOutlineColor => kSceneViewSelectedOutline.Color;
public bool isUsingSceneFiltering => UseSceneFiltering();
internal static SavedBool s_PreferenceIgnoreAlwaysRefreshWhenNotFocused = new SavedBool("SceneView.ignoreAlwaysRefreshWhenNotFocused", false);
internal static SavedBool s_PreferenceEnableFilteringWhileSearching = new SavedBool("SceneView.enableFilteringWhileSearching", true);
internal static SavedBool s_PreferenceEnableFilteringWhileLodGroupEditing = new SavedBool("SceneView.enableFilteringWhileLodGroupEditing", true);
internal static SavedFloat s_DrawModeExposure = new SavedFloat("SceneView.drawModeExposure", 0.0f);
private static SavedBool s_DrawBackfaceHighlights = new SavedBool("SceneView.drawBackfaceHighlights", false);
internal static event Action<bool> onDrawBackfaceHighlightsChanged;
[RequiredByNativeCode]
internal static float GetDrawModeExposure()
{
return SceneView.s_DrawModeExposure;
}
[RequiredByNativeCode]
internal static bool GetDrawBackfaceHighlights()
{
return SceneView.s_DrawBackfaceHighlights;
}
internal static void SetDrawBackfaceHighlights(bool value)
{
if (value != SceneView.s_DrawBackfaceHighlights.value)
{
SceneView.s_DrawBackfaceHighlights.value = value;
onDrawBackfaceHighlightsChanged?.Invoke(value);
}
}
static readonly HashSet<DrawCameraMode> s_ShowExposureDrawCameraModes = new HashSet<DrawCameraMode>()
{
DrawCameraMode.BakedEmissive, DrawCameraMode.BakedLightmap,
DrawCameraMode.RealtimeEmissive, DrawCameraMode.RealtimeIndirect
};
internal bool showExposureSettings => s_ShowExposureDrawCameraModes.Contains(this.cameraMode.drawMode);
static readonly HashSet<DrawCameraMode> s_ShowLightmapResolutionDrawCameraModes = new HashSet<DrawCameraMode>()
{
DrawCameraMode.BakedEmissive, DrawCameraMode.RealtimeEmissive,
DrawCameraMode.BakedLightmap, DrawCameraMode.RealtimeIndirect,
DrawCameraMode.BakedDirectionality, DrawCameraMode.RealtimeDirectionality,
DrawCameraMode.BakedAlbedo, DrawCameraMode.RealtimeAlbedo,
DrawCameraMode.BakedCharting, DrawCameraMode.RealtimeCharting,
DrawCameraMode.BakedTexelValidity, DrawCameraMode.BakedUVOverlap,
DrawCameraMode.ShadowMasks, DrawCameraMode.Systems,
DrawCameraMode.GIContributorsReceivers, DrawCameraMode.BakedLightmapCulling,
DrawCameraMode.BakedIndices, DrawCameraMode.LightOverlap,
};
internal bool showLightmapResolutionToggle => s_ShowLightmapResolutionDrawCameraModes.Contains(this.cameraMode.drawMode);
internal bool showBackfaceHighlightsToggle => this.showLightmapResolutionToggle;
static readonly HashSet<DrawCameraMode> s_ShowInteractiveLightBakingToggleCameraModes = new HashSet<DrawCameraMode>()
{
DrawCameraMode.BakedLightmap, DrawCameraMode.BakedDirectionality,
DrawCameraMode.ShadowMasks, DrawCameraMode.BakedAlbedo,
DrawCameraMode.BakedEmissive, DrawCameraMode.BakedCharting,
DrawCameraMode.BakedTexelValidity, DrawCameraMode.BakedUVOverlap,
DrawCameraMode.BakedIndices, DrawCameraMode.LightOverlap,
};
internal bool currentDrawModeMayUseInteractiveLightBakingData => s_ShowInteractiveLightBakingToggleCameraModes.Contains(this.cameraMode.drawMode);
internal bool showLightingVisualizationPanel => this.showExposureSettings || this.showBackfaceHighlightsToggle || this.showLightmapResolutionToggle || this.currentDrawModeMayUseInteractiveLightBakingData;
internal static Transform GetDefaultParentObjectIfSet()
{
Transform parentObject = null;
var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
string activeSceneGUID = prefabStage != null ? prefabStage.scene.guid : EditorSceneManager.GetActiveScene().guid;
int id = SceneHierarchy.GetDefaultParentForSession(activeSceneGUID);
if (id != 0)
{
var objectFromInstanceID = EditorUtility.InstanceIDToObject(id) as GameObject;
parentObject = objectFromInstanceID?.gameObject?.transform;
}
return parentObject;
}
static void OnSelectedObjectWasDestroyed(int unused)
{
s_ActiveEditorsDirty = true;
s_SelectionCacheDirty = true;
}
static void OnNonSelectedObjectWasDestroyed(int instanceID)
{
if (s_CachedChildRenderersForOutlining != null && s_CachedChildRenderersForOutlining.Contains(instanceID))
{
s_ActiveEditorsDirty = true;
s_SelectionCacheDirty = true;
}
}
static void OnEditorTrackerRebuilt()
{
s_ActiveEditorsDirty = true;
s_SelectionCacheDirty = true;
}
internal static void SetActiveEditorsDirty(bool forceRepaint = false)
{
s_ActiveEditorsDirty = true;
//Needs to force repaint the scene in case the inspector :
//- switched from Normal to Debug mode (or inverse)
//- visible inspector changed and inspector modes changed
if(forceRepaint)
RepaintAll();
}
static List<Editor> s_ActiveEditors = new List<Editor>();
static bool s_ActiveEditorsDirty;
static bool s_SelectionCacheDirty;
internal static IEnumerable<Editor> activeEditors
{
get
{
CollectActiveEditors();
return s_ActiveEditors;
}
}
static void CollectActiveEditors()
{
if (!s_ActiveEditorsDirty)
return;
s_ActiveEditorsDirty = false;
s_ActiveEditors.Clear();
bool activeSharedTracker = false;
foreach (var inspector in InspectorWindow.GetInspectors())
{
if(inspector.isLocked)
{
foreach (var editor in inspector.tracker.activeEditors)
s_ActiveEditors.Add(editor);
}
else if(!activeSharedTracker
&& inspector.isVisible
&& inspector.inspectorMode == InspectorMode.Normal)
{
activeSharedTracker = true;
foreach (var editor in inspector.tracker.activeEditors)
s_ActiveEditors.Add(editor);
}
}
//Just a fallback in case no editor is visible or locked
if(!activeSharedTracker)
{
if (s_SharedTracker == null)
s_SharedTracker = ActiveEditorTracker.sharedTracker;
foreach (var editor in s_SharedTracker.activeEditors)
s_ActiveEditors.Add(editor);
}
}
[SerializeField]
string m_WindowGUID;
internal string windowGUID => m_WindowGUID;
//Used internally to set the overlay layout to the same than the previous sceneview
SceneView m_PreviousScene = null;
[SerializeField] bool m_Gizmos = true;
public bool drawGizmos
{
get => m_Gizmos;
set
{
if (m_Gizmos == value) return;
m_Gizmos = value;
drawGizmosChanged?.Invoke(value);
}
}
const float kSubmeshPingDuration = 1.0f;
internal bool isPingingObject { get; set; } = false;
internal float alphaMultiplier { get; set; } = 0;
internal int submeshOutlineMaterialId { get; set; } = 0;
Scene m_CustomScene;
protected internal Scene customScene
{
get { return m_CustomScene; }
set
{
m_CustomScene = value;
m_Camera.scene = m_CustomScene;
var stage = StageUtility.GetStageHandle(m_CustomScene);
StageUtility.SetSceneToRenderInStage(m_CustomLightsScene, stage);
}
}
[SerializeField] ulong m_OverrideSceneCullingMask;
internal ulong overrideSceneCullingMask
{
get { return m_OverrideSceneCullingMask; }
set
{
m_OverrideSceneCullingMask = value;
m_Camera.overrideSceneCullingMask = value;
}
}
SceneViewStageHandling m_StageHandling;
public Rect cameraViewport => cameraViewVisualElement.rect;
Transform m_CustomParentForNewGameObjects;
protected internal Transform customParentForDraggedObjects
{
get => customParentForNewGameObjects;
set => customParentForNewGameObjects = value;
}
internal Transform customParentForNewGameObjects
{
get => m_CustomParentForNewGameObjects;
set => m_CustomParentForNewGameObjects = value;
}
[NonSerialized]
static readonly Quaternion kDefaultRotation = Quaternion.LookRotation(new Vector3(-1, -.7f, -1));
const float kDefaultViewSize = 10f;
[NonSerialized]
static readonly Vector3 kDefaultPivot = Vector3.zero;
const float kOrthoThresholdAngle = 3f;
const float kOneOverSqrt2 = 0.707106781f;
// Don't allow scene view zoom/size to go to crazy high values, or otherwise various
// operations will start going to infinities etc.
internal const float k_MaxSceneViewSize = 3.2e34f;
// Limit the max draw distance to Sqrt(float.MaxValue) because transparent sorting function uses dist^2, and
// Asserts that values are finite.
internal const float k_MaxCameraFarClip = 1.844674E+19f;
internal const float k_MinCameraNearClip = 1e-5f;
[NonSerialized]
static ActiveEditorTracker s_SharedTracker;
[SerializeField]
bool m_SceneIsLit = true;
[Obsolete("m_SceneLighting has been deprecated. Use sceneLighting instead (UnityUpgradable) -> UnityEditor.SceneView.sceneLighting", true)]
[EditorBrowsable(EditorBrowsableState.Never)]
public bool m_SceneLighting = true;
public bool sceneLighting
{
get => m_SceneIsLit;
set
{
if (m_SceneIsLit != value)
{
m_SceneIsLit = value;
sceneLightingChanged?.Invoke(value);
}
}
}
public event Func<CameraMode, bool> onValidateCameraMode;
public event Action<CameraMode> onCameraModeChanged;
public event Action<bool> gridVisibilityChanged;
internal event Action<bool> sceneLightingChanged;
internal event Action<bool> sceneAudioChanged;
internal event Action<bool> debugDrawModesUseInteractiveLightBakingDataChanged;
internal event Action<bool> sceneVisActiveChanged;
internal event Action<bool> drawGizmosChanged;
internal event Action<bool> modeChanged2D;
// used by tests
internal bool m_WasFocused = false;
static int[] s_CachedParentRenderersForOutlining, s_CachedChildRenderersForOutlining;
[Serializable]
public class SceneViewState
{
[SerializeField, FormerlySerializedAs("showMaterialUpdate")]
bool m_AlwaysRefresh;
public bool showFog = true;
// marked obsolete by @karlh 2020/4/14
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Obsolete msg (UnityUpgradable) -> alwaysRefresh")]
public bool showMaterialUpdate
{
get => m_AlwaysRefresh;
set => m_AlwaysRefresh = value;
}
public bool alwaysRefresh
{
get => m_AlwaysRefresh;
set => m_AlwaysRefresh = value;
}
public bool showClouds
{
get => m_ShowClouds;
set => m_ShowClouds = value;
}
public bool showSkybox = true;
public bool showFlares = true;
public bool showImageEffects = true;
public bool showParticleSystems = true;
public bool showVisualEffectGraphs = true;
bool m_ShowClouds = true;
public bool fogEnabled => fxEnabled && showFog;
// marked obsolete by @karlh 2020/4/14
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("Obsolete msg (UnityUpgradable) -> alwaysRefreshEnabled")]
public bool materialUpdateEnabled => alwaysRefreshEnabled;
public bool alwaysRefreshEnabled => fxEnabled && alwaysRefresh;
public bool skyboxEnabled => fxEnabled && showSkybox;
public bool cloudsEnabled => fxEnabled && showClouds;
public bool flaresEnabled => fxEnabled && showFlares;
public bool imageEffectsEnabled => fxEnabled && showImageEffects;
public bool particleSystemsEnabled => fxEnabled && showParticleSystems;
public bool visualEffectGraphsEnabled => fxEnabled && showVisualEffectGraphs;
internal event Action<bool> fxEnableChanged;
[SerializeField]
bool m_FxEnabled = true;
public SceneViewState()
{
}
public SceneViewState(SceneViewState other)
{
fxEnabled = other.fxEnabled;
showFog = other.showFog;
alwaysRefresh = other.alwaysRefresh;
showSkybox = other.showSkybox;
showClouds = other.showClouds;
showFlares = other.showFlares;
showImageEffects = other.showImageEffects;
showParticleSystems = other.showParticleSystems;
showVisualEffectGraphs = other.showVisualEffectGraphs;
}
[Obsolete("IsAllOn() has been deprecated. Use allEnabled instead (UnityUpgradable) -> allEnabled")]
public bool IsAllOn()
{
return allEnabled;
}
public bool allEnabled
{
get
{
bool all = showFog && alwaysRefresh && showSkybox && showClouds && showFlares && showImageEffects && showParticleSystems;
if (UnityEngine.VFX.VFXManager.activateVFX)
all = all && showVisualEffectGraphs;
return all;
}
}
[Obsolete("Toggle() has been deprecated. Use SetAllEnabled() instead (UnityUpgradable) -> SetAllEnabled(*)")]
public void Toggle(bool value)
{
SetAllEnabled(value);
}
public void SetAllEnabled(bool value)
{
showFog = value;
alwaysRefresh = value;
showSkybox = value;
showClouds = value;
showFlares = value;
showImageEffects = value;
showParticleSystems = value;
showVisualEffectGraphs = value;
}
public bool fxEnabled
{
get => m_FxEnabled;
set
{
if (m_FxEnabled == value) return;
m_FxEnabled = value;
fxEnableChanged?.Invoke(value);
}
}
}
[SerializeField]
private bool m_2DMode;
public bool in2DMode
{
get => m_2DMode;
set
{
if (m_2DMode != value)
{
m_2DMode = value;
On2DModeChange();
modeChanged2D?.Invoke(value);
}
}
}
[SerializeField]
bool m_isRotationLocked = false;
public bool isRotationLocked
{
get => m_isRotationLocked;
set => m_isRotationLocked = value;
}
internal static List<CameraMode> userDefinedModes { get; } = new List<CameraMode>();
[SerializeField]
bool m_PlayAudio = false;
[Obsolete("m_AudioPlay has been deprecated. Use audioPlay instead (UnityUpgradable) -> audioPlay", true)]
public bool m_AudioPlay = false;
public bool audioPlay
{
get => m_PlayAudio;
set
{
if (value == m_PlayAudio)
return;
m_PlayAudio = value;
sceneAudioChanged?.Invoke(value);
RefreshAudioPlay();
}
}
static SceneView s_AudioSceneView;
[SerializeField]
bool m_DebugDrawModesUseInteractiveLightBakingData = false;
internal bool debugDrawModesUseInteractiveLightBakingData
{
get => m_DebugDrawModesUseInteractiveLightBakingData;
set
{
if (value == m_DebugDrawModesUseInteractiveLightBakingData)
return;
m_DebugDrawModesUseInteractiveLightBakingData = value;
debugDrawModesUseInteractiveLightBakingDataChanged?.Invoke(m_DebugDrawModesUseInteractiveLightBakingData);
// Force repaint to update lightmap previews immediately
Lightmapping.Internal_CallLightingDataUpdatedFunctions();
}
}
internal bool usesInteractiveLightBakingData => this.debugDrawModesUseInteractiveLightBakingData && this.currentDrawModeMayUseInteractiveLightBakingData;
[SerializeField]
// used by Tests/EditModeAndPlayModeTests/SceneView/CameraFlyModeContextTests
internal AnimVector3 m_Position = new AnimVector3(kDefaultPivot);
#pragma warning disable 618
[Obsolete("OnSceneFunc() has been deprecated. Use System.Action instead.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public delegate void OnSceneFunc(SceneView sceneView);
// Marked obsolete 2018-11-28
[Obsolete("onSceneGUIDelegate has been deprecated. Use duringSceneGui instead.")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static OnSceneFunc onSceneGUIDelegate;
#pragma warning restore 618
public static event Action<SceneView> beforeSceneGui;
public static event Action<SceneView> duringSceneGui;
internal static event Func<SceneView, VisualElement> addCustomVisualElementToSceneView;
// Used for performance tests
internal static event Action<SceneView> onGUIStarted;
internal static event Action<SceneView> onGUIEnded;
[Obsolete("Use cameraMode instead", false)]
public DrawCameraMode m_RenderMode = 0;
[Obsolete("Use cameraMode instead", false)]
public DrawCameraMode renderMode
{
get => m_CameraMode.drawMode;
set
{
if (value == DrawCameraMode.UserDefined)
throw new ArgumentException("Use cameraMode to set user-defined modes");
cameraMode = SceneRenderModeWindow.GetBuiltinCameraMode(value);
}
}
[SerializeField]
CameraMode m_CameraMode;
internal SceneOrientationGizmo m_OrientationGizmo;
public CameraMode cameraMode
{
get
{
// fix for case 969889 where the toolbar is empty when we haven't fully initialized the value
if (string.IsNullOrEmpty(m_CameraMode.name))
{
m_CameraMode = SceneRenderModeWindow.GetBuiltinCameraMode(m_CameraMode.drawMode);
}
return m_CameraMode;
}
set
{
if (!IsValidCameraMode(value))
{
throw new ArgumentException(string.Format("The provided camera mode {0} is not registered!", value));
}
m_CameraMode = value;
if (onCameraModeChanged != null)
onCameraModeChanged(m_CameraMode);
}
}
[Obsolete("m_ValidateTrueMetals has been deprecated. Use validateTrueMetals instead (UnityUpgradable) -> validateTrueMetals", true)]
public bool m_ValidateTrueMetals = false;
[SerializeField]
bool m_DoValidateTrueMetals = false;
public bool validateTrueMetals
{
get => m_DoValidateTrueMetals;
set
{
if (m_DoValidateTrueMetals == value)
return;
m_DoValidateTrueMetals = value;
Shader.SetGlobalFloat("_CheckPureMetal", m_DoValidateTrueMetals ? 1.0f : 0.0f);
}
}
[SerializeField]
SceneViewState m_SceneViewState;
public SceneViewState sceneViewState
{
get { return m_SceneViewState; }
set { m_SceneViewState = value; }
}
[SerializeField]
SceneViewGrid m_Grid;
public bool showGrid
{
get => sceneViewGrids.showGrid;
set => sceneViewGrids.showGrid = value;
}
[SerializeField]
internal AnimQuaternion m_Rotation = new AnimQuaternion(kDefaultRotation);
// How large an area the scene view covers (measured vertically)
[SerializeField]
AnimFloat m_Size = new AnimFloat(kDefaultViewSize);
[SerializeField]
internal AnimBool m_Ortho = new AnimBool();
[NonSerialized]
Camera m_Camera;
VisualElement m_CameraViewVisualElement;
static readonly string s_CameraRectVisualElementName = "unity-scene-view-camera-rect";
internal VisualElement cameraViewVisualElement
{
get
{
if (m_CameraViewVisualElement == null)
m_CameraViewVisualElement = CreateCameraRectVisualElement();
return m_CameraViewVisualElement;
}
}
static List<Overlay> s_ActiveViewOverlays = new List<Overlay>();
[Serializable]
public class CameraSettings
{
const float defaultEasingDuration = .4f;
internal const float kAbsoluteSpeedMin = .0001f;
internal const float kAbsoluteSpeedMax = 10000f;
const float kAbsoluteEasingDurationMin = .1f;
const float kAbsoluteEasingDurationMax = 2f;
[SerializeField]
float m_Speed;
[SerializeField]
float m_SpeedNormalized;
[SerializeField]
float m_SpeedMin;
[SerializeField]
float m_SpeedMax;
[SerializeField]
bool m_EasingEnabled;
[SerializeField]
float m_EasingDuration;
[SerializeField]
bool m_AccelerationEnabled;
[SerializeField]
float m_FieldOfViewHorizontalOrVertical; // either horizontal or vertical depending on aspect ratio
[SerializeField]
float m_NearClip;
[SerializeField]
float m_FarClip;
[SerializeField]
bool m_DynamicClip;
[SerializeField]
bool m_OcclusionCulling;
public CameraSettings()
{
m_Speed = 1f;
m_SpeedNormalized = .5f;
m_SpeedMin = .01f;
m_SpeedMax = 2f;
m_EasingEnabled = true;
m_EasingDuration = defaultEasingDuration;
fieldOfView = kDefaultPerspectiveFov;
m_DynamicClip = true;
m_OcclusionCulling = false;
m_NearClip = .03f;
m_FarClip = 10000f;
m_AccelerationEnabled = true;
}
internal CameraSettings(CameraSettings other)
{
m_Speed = other.m_Speed;
m_SpeedNormalized = other.m_SpeedNormalized;
m_SpeedMin = other.m_SpeedMin;
m_SpeedMax = other.m_SpeedMax;
m_EasingEnabled = other.m_EasingEnabled;
m_EasingDuration = other.m_EasingDuration;
fieldOfView = other.fieldOfView;
m_DynamicClip = other.m_DynamicClip;
m_OcclusionCulling = other.m_OcclusionCulling;
m_NearClip = other.m_NearClip;
m_FarClip = other.m_FarClip;
m_AccelerationEnabled = other.m_AccelerationEnabled;
}
public float speed
{
get
{
return m_Speed;
}
set
{
speedNormalized = Mathf.InverseLerp(m_SpeedMin, m_SpeedMax, value);
}
}
public float speedNormalized
{
get
{
return m_SpeedNormalized;
}
set
{
m_SpeedNormalized = Mathf.Clamp01(value);
m_Speed = Mathf.Lerp(m_SpeedMin, m_SpeedMax, m_SpeedNormalized);
}
}
public float speedMin
{
get => m_SpeedMin;
set => SetSpeedMinMax(value, m_SpeedMax);
}
public float speedMax
{
get => m_SpeedMax;
set => SetSpeedMinMax(m_SpeedMin, value);
}
// Easing is applied when starting and stopping movement. When enabled, the camera will lerp from it's
// current speed to the target speed over the course of `CameraSettings.easingDuration` seconds.
public bool easingEnabled
{
get { return m_EasingEnabled; }
set { m_EasingEnabled = value; }
}
// How many seconds should the camera take to go from stand-still to initial full speed. When setting an animated value
// speed, use `1 / duration`.
public float easingDuration
{
get
{
return m_EasingDuration;
}
set
{
// Clamp and round to 1 decimal point
m_EasingDuration = (float)Math.Round(Mathf.Clamp(value, kAbsoluteEasingDurationMin, kAbsoluteEasingDurationMax), 1);
}
}
// When acceleration is enabled, camera speed is continuously increased while in motion. When acceleration
// is disabled, speed is a constant value defined by `CameraSettings.speed`
public bool accelerationEnabled
{
get { return m_AccelerationEnabled; }
set { m_AccelerationEnabled = value; }
}
// this ensures that the resolution the slider snaps to is sufficient given the minimum speed, and the
// range of appropriate values
internal float RoundSpeedToNearestSignificantDecimal(float value)
{
if (value <= speedMin)
return speedMin;
if (value >= speedMax)
return speedMax;
float rng = speedMax - speedMin;
int min_rnd = speedMin < .001f ? 4 : speedMin < .01f ? 3 : speedMin < .1f ? 2 : speedMin < 1f ? 1 : 0;
int rng_rnd = rng < .1f ? 3 : rng < 1f ? 2 : rng < 10f ? 1 : 0;
return (float)Math.Round(value, Mathf.Max(min_rnd, rng_rnd));
}
internal void SetSpeedMinMax(float min, float max)
{
// Clamp min to valid ranges
float minRange = min < .001f ? .0001f : min < .01f ? .001f : min < .1f ? .01f : min < 1f ? .1f : 1f;
min = Mathf.Clamp(min, kAbsoluteSpeedMin, kAbsoluteSpeedMax - minRange);
max = Mathf.Clamp(max, min + minRange, kAbsoluteSpeedMax);
m_SpeedMin = min;
m_SpeedMax = max;
// This will clamp the speed to the new range
speed = m_Speed;
}
internal void SetClipPlanes(float near, float far)
{
farClip = Mathf.Clamp(far, float.Epsilon, k_MaxCameraFarClip);
nearClip = Mathf.Max(k_MinCameraNearClip, near);
}
public float fieldOfView
{
get { return m_FieldOfViewHorizontalOrVertical; }
set { m_FieldOfViewHorizontalOrVertical = value; }
}
public float nearClip
{
get { return m_NearClip; }
set { m_NearClip = value; }
}
public float farClip
{
get { return m_FarClip; }
set { m_FarClip = value; }
}
public bool dynamicClip
{
get { return m_DynamicClip; }
set { m_DynamicClip = value; }
}
public bool occlusionCulling
{
get { return m_OcclusionCulling; }
set { m_OcclusionCulling = value; }
}
}
[SerializeField]
private CameraSettings m_CameraSettings;
public CameraSettings cameraSettings
{
get { return m_CameraSettings; }
set { m_CameraSettings = value; }
}
internal Vector2 GetDynamicClipPlanes()
{
float farClip = Mathf.Clamp(2000f * size, 1000f, k_MaxCameraFarClip);
return new Vector2(farClip * 0.000005f, farClip);
}
internal SceneViewGrid sceneViewGrids
{
get { return m_Grid; }
}
public void ResetCameraSettings()
{
m_CameraSettings = new CameraSettings();
}
// Thomas Tu: 2019-06-20. Will be marked as Obsolete.
// We need to deal with code dependency in packages first.
internal bool showGlobalGrid { get { return showGrid; } set { showGrid = value; } }
[SerializeField]
private Quaternion m_LastSceneViewRotation;
public Quaternion lastSceneViewRotation
{
get
{
if (m_LastSceneViewRotation == new Quaternion(0f, 0f, 0f, 0f))
m_LastSceneViewRotation = Quaternion.identity;
return m_LastSceneViewRotation;
}
set { m_LastSceneViewRotation = value; }
}
[SerializeField]
private bool m_LastSceneViewOrtho;
// Cursor rect handling
private struct CursorRect
{
public Rect rect;
public MouseCursor cursor;
public CursorRect(Rect rect, MouseCursor cursor)
{
this.rect = rect;
this.cursor = cursor;
}
}
private static MouseCursor s_LastCursor = MouseCursor.Arrow;
private static readonly List<CursorRect> s_MouseRects = new List<CursorRect>();
internal static void AddCursorRect(Rect rect, MouseCursor cursor)
{
var eventType = Event.current.type;
if (eventType == EventType.Repaint || eventType == EventType.MouseMove)
s_MouseRects.Add(new CursorRect(rect, cursor));
}
static float GetPerspectiveCameraDistance(float objectSize, float fov)
{
// A
// |\ We want to place camera at a
// | \ distance that, at the given FOV,
// | \ would enclose a sphere of radius
// _..+.._\ "size". Here |BC|=size, and we
// .' | '\ need to find |AB|. ACB is a right
// / | _C angle, andBAC is half the FOV. So
// | | _- | that gives: sin(BAC)=|BC|/|AB|,
// | B | and thus |AB|=|BC|/sin(BAC).
// | |
// \ /
// '._ _.'
// `````
return objectSize / Mathf.Sin(fov * 0.5f * Mathf.Deg2Rad);
}
public float cameraDistance
{
get
{
float res;
if (!camera.orthographic)
{
float fov = m_Ortho.Fade(perspectiveFov, 0);
res = GetPerspectiveCameraDistance(size, fov);
}
else
res = size * 2f;
// clamp to allowed range in case scene view size was huge
return Mathf.Clamp(res, -k_MaxSceneViewSize, k_MaxSceneViewSize);
}
}
[System.NonSerialized]
Scene m_CustomLightsScene;
[System.NonSerialized]
Light[] m_Light = new Light[3];
RectSelection m_RectSelection;
internal RectSelection rectSelection => m_RectSelection;
SceneViewMotion m_SceneViewMotion;
internal SceneViewMotion sceneViewMotion => m_SceneViewMotion;
[SerializeField]
SceneViewViewpoint m_Viewpoint = new SceneViewViewpoint();
internal SceneViewViewpoint viewpoint => m_Viewpoint;
const float kDefaultPerspectiveFov = 60;
static ArrayList s_SceneViews = new ArrayList();
public static ArrayList sceneViews { get { return s_SceneViews; } }
static List<Camera> s_AllSceneCameraList = new List<Camera>();
static Camera[] s_AllSceneCameras = new Camera[] {};
static Material s_AlphaOverlayMaterial;
static Material s_DeferredOverlayMaterial;
static Shader s_ShowOverdrawShader;
static Shader s_ShowMipsShader;
static Shader s_ShowTextureStreamingShader;
static Shader s_AuraShader;
static Material s_FadeMaterial;
static Material s_ApplyFilterMaterial;
static Texture2D s_MipColorsTexture;
// Handle Dragging of stuff over scene view
//static ArrayList s_DraggedEditors = null;
//static GameObject[] s_PickedObject = { null };
internal static class Styles
{
public static GUIContent toolsContent = EditorGUIUtility.TrIconContent("SceneViewTools", "Hide or show the Component Editor Tools panel in the Scene view.");
public static GUIContent lighting = EditorGUIUtility.TrIconContent("SceneviewLighting", "When toggled on, the Scene lighting is used. When toggled off, a light attached to the Scene view camera is used.");
public static GUIContent fx = EditorGUIUtility.TrIconContent("SceneviewFx", "Toggle skybox, fog, and various other effects.");
public static GUIContent audioPlayContent = EditorGUIUtility.TrIconContent("SceneviewAudio", "Toggle audio on or off.");
public static GUIContent gizmosContent = EditorGUIUtility.TrTextContent("Gizmos", "Toggle visibility of all Gizmos in the Scene view");
public static GUIContent gizmosDropDownContent = EditorGUIUtility.TrTextContent("", "Toggle the visibility of different Gizmos in the Scene view.");
public static GUIContent mode2DContent = EditorGUIUtility.TrIconContent("SceneView2D", "When toggled on, the Scene is in 2D view. When toggled off, the Scene is in 3D view.");
public static GUIContent gridXToolbarContent = EditorGUIUtility.TrIconContent("GridAxisX", "Toggle the visibility of the grid");
public static GUIContent gridYToolbarContent = EditorGUIUtility.TrIconContent("GridAxisY", "Toggle the visibility of the grid");
public static GUIContent gridZToolbarContent = EditorGUIUtility.TrIconContent("GridAxisZ", "Toggle the visibility of the grid");
public static GUIContent metalFrameCaptureContent = EditorGUIUtility.TrIconContent("FrameCapture", "Capture the current view and open in Xcode frame debugger");
public static GUIContent sceneVisToolbarButtonContent = EditorGUIUtility.TrIconContent("SceneViewVisibility", "Number of hidden objects, click to toggle scene visibility");
public static GUIStyle gizmoButtonStyle;
public static GUIContent sceneViewCameraContent = EditorGUIUtility.TrIconContent("SceneViewCamera", "Settings for the Scene view camera.");
static Styles()
{
gizmoButtonStyle = "GV Gizmo DropDown";
}
}
internal float pingStartTime { get; set; } = 0;
double m_StartSearchFilterTime = -1;
RenderTexture m_SceneTargetTexture;
int m_MainViewControlID;
public Camera camera { get { return m_Camera; } }
[SerializeField]
Shader m_ReplacementShader;
[SerializeField]
string m_ReplacementString;
[SerializeField]
bool m_SceneVisActive = true;
internal bool sceneVisActive
{
get => m_SceneVisActive;
set
{
if (m_SceneVisActive == value) return;
m_SceneVisActive = value;
sceneVisActiveChanged?.Invoke(value);
}
}
string m_SceneVisHiddenCount = "0";
public void SetSceneViewShaderReplace(Shader shader, string replaceString)
{
m_ReplacementShader = shader;
m_ReplacementString = replaceString;
}
internal bool m_ShowSceneViewWindows = false;
internal EditorCache m_DragEditorCache;
// While Locking the view to object, we have different behaviour for different scenarios:
// Smooth camera behaviour: User dragging the handles
// Instant camera behaviour: Position changed externally (via inspector, physics or scripts etc.)
internal enum DraggingLockedState
{
NotDragging, // Default state. Scene view camera is snapped to selected object instantly
Dragging, // User is dragging from handles. Scene view camera holds still.
LookAt // Temporary state after dragging or selection change, where we return scene view camera smoothly to selected object
}
DraggingLockedState m_DraggingLockedState;
internal DraggingLockedState draggingLocked { set { m_DraggingLockedState = value; } get { return m_DraggingLockedState; } }
[SerializeField]
private Object m_LastLockedObject;
[SerializeField]
private DrawCameraMode m_LastDebugDrawMode = DrawCameraMode.GIContributorsReceivers;
[SerializeField]
bool m_ViewIsLockedToObject;
internal bool viewIsLockedToObject
{
get { return m_ViewIsLockedToObject; }
set
{
if (value)
m_LastLockedObject = Selection.activeObject;
else
m_LastLockedObject = null;
m_ViewIsLockedToObject = value;
draggingLocked = DraggingLockedState.LookAt;
}
}
[RequiredByNativeCode]
static void FrameSelectedMenuItem(bool locked)
{
var command = locked ? EventCommandNames.FrameSelectedWithLock : EventCommandNames.FrameSelected;
var win = focusedWindow;
var ret = win != null && win.SendEvent(EditorGUIUtility.CommandEvent(command));
if (!ret)
{
win = mouseOverWindow;
ret = win != null && win.SendEvent(EditorGUIUtility.CommandEvent(command));
}
// if no hovered or focused window used the frame command, send the command to the last active scene view.
// as a special case, if the window that used the frame command was hierarchy, also send a frame event to
// the last active scene view.
if ((!ret || win is SceneHierarchyWindow) && lastActiveSceneView != null)
lastActiveSceneView.SendEvent(EditorGUIUtility.CommandEvent(command));
}
public static bool FrameLastActiveSceneView()
{
if (lastActiveSceneView == null)
return false;
return lastActiveSceneView.SendEvent(EditorGUIUtility.CommandEvent(EventCommandNames.FrameSelected));
}
public static bool FrameLastActiveSceneViewWithLock()
{
if (lastActiveSceneView == null)
return false;
return lastActiveSceneView.SendEvent(EditorGUIUtility.CommandEvent(EventCommandNames.FrameSelectedWithLock));
}
private static List<Camera> GetAllSceneCamerasAsList()
{
s_AllSceneCameraList.Clear();
for (int i = 0; i < s_SceneViews.Count; ++i)
{
Camera cam = ((SceneView)s_SceneViews[i]).m_Camera;
if (cam != null)
s_AllSceneCameraList.Add(cam);
}
return s_AllSceneCameraList;
}
[RequiredByNativeCode]
public static Camera[] GetAllSceneCameras()
{
List<Camera> newSceneCameras = GetAllSceneCamerasAsList();
if (newSceneCameras.Count == s_AllSceneCameras.Length)
{
bool cacheValid = true;
for (int i = 0; i < newSceneCameras.Count; ++i)
{
if (!Object.ReferenceEquals(s_AllSceneCameras[i], newSceneCameras[i]))
{
cacheValid = false;
break;
}
}
if (cacheValid)
return s_AllSceneCameras;
}
s_AllSceneCameras = newSceneCameras.ToArray();
return s_AllSceneCameras;
}
[RequiredByNativeCode]
public static void RepaintAll()
{
foreach (SceneView sv in s_SceneViews)
{
sv.Repaint();
}
}
internal override void SetSearchFilter(string searchFilter, SearchMode mode, bool setAll, bool delayed)
{
if (m_SearchFilter == "" || searchFilter == "")
m_StartSearchFilterTime = EditorApplication.timeSinceStartup;
base.SetSearchFilter(searchFilter, mode, setAll, delayed);
}
internal void OnLostFocus()
{
if (lastActiveSceneView == this)
{
m_SceneViewMotion.ResetMotion();
m_SceneViewMotion.CompleteSceneViewMotionTool();
}
}
private void OnBeforeRemovedAsTab()
{
m_PreviousScene = null;
}
//Internal for tests
internal void OnAddedAsTab()
{
var inPlayMode = (EditorApplication.isPlaying || EditorApplication.isPaused);
if (inPlayMode && m_Parent.vSyncEnabled)
m_Parent.EnableVSync(false);
//OnAddedAsTab is called after the lastActiveSceneView has been updated, so m_PreviousScene is there to keep this reference
if (m_PreviousScene != null && s_SceneViews.Count > 0)
{
m_PreviousScene.overlayCanvas.CopySaveData(out var overlaySaveData);
overlayCanvas.ApplySaveData(overlaySaveData);
}
}
public override void OnEnable()
{
baseRootVisualElement.Insert(0, prefabToolbar);
rootVisualElement.Add(cameraViewVisualElement);
m_SceneViewMotion = new SceneViewMotion();
rootVisualElement.RegisterCallback<MouseEnterEvent>(e => m_SceneViewMotion.viewportsUnderMouse = true);
rootVisualElement.RegisterCallback<MouseLeaveEvent>(e => m_SceneViewMotion.viewportsUnderMouse = false);
m_OrientationGizmo = overlayCanvas.overlays.FirstOrDefault(x => x is SceneOrientationGizmo) as SceneOrientationGizmo;
titleContent = GetLocalizedTitleContent();
m_RectSelection = new RectSelection();
m_SceneViewMotion.CompleteSceneViewMotionTool();
m_Viewpoint.AssignSceneView(this);
if (m_Grid == null)
m_Grid = new SceneViewGrid();
sceneViewGrids.OnEnable(this);
ResetGridPivot();
autoRepaintOnSceneChange = true;
m_Rotation.valueChanged.AddListener(Repaint);
m_Position.valueChanged.AddListener(Repaint);
m_Size.valueChanged.AddListener(Repaint);
m_Ortho.valueChanged.AddListener(Repaint);
sceneViewGrids.gridVisibilityChanged += GridOnGridVisibilityChanged;
wantsMouseMove = true;
wantsLessLayoutEvents = true;
wantsMouseEnterLeaveWindow = true;
s_SceneViews.Add(this);
UpdateHiddenObjectCount();
ObjectFactory.componentWasAdded += OnComponentWasAdded;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
EditorApplication.modifierKeysChanged += RepaintAll; // Because we show handles on shift
SceneVisibilityManager.visibilityChanged += VisibilityChanged;
SceneVisibilityManager.currentStageIsIsolated += CurrentStageIsolated;
ActiveEditorTracker.editorTrackerRebuilt += OnEditorTrackerRebuilt;
Selection.selectedObjectWasDestroyed += OnSelectedObjectWasDestroyed;
Selection.nonSelectedObjectWasDestroyed += OnNonSelectedObjectWasDestroyed;
Lightmapping.lightingDataUpdated += RepaintAll;
onCameraModeChanged += delegate
{
if (cameraMode.drawMode == DrawCameraMode.ShadowCascades) sceneLighting = true;
// If this a draw mode for debugging purposes, take note of it, so we can toggle back and forth between it and the previous mode.
if (cameraMode.drawMode != DrawCameraMode.Textured && cameraMode.drawMode != DrawCameraMode.Wireframe && cameraMode.drawMode != DrawCameraMode.TexturedWire)
{
m_LastDebugDrawMode = cameraMode.drawMode;
}
};
m_DraggingLockedState = DraggingLockedState.NotDragging;
CreateSceneCameraAndLights();
if (m_2DMode)
LookAt(pivot, Quaternion.identity, size, true, true);
if (m_CameraMode.drawMode == DrawCameraMode.UserDefined && !userDefinedModes.Contains(m_CameraMode))
AddCameraMode(m_CameraMode.name, m_CameraMode.section);
base.OnEnable();
if (SupportsStageHandling())
{
m_StageHandling = new SceneViewStageHandling(this);
m_StageHandling.OnEnable();
}
s_ActiveEditorsDirty = true;
baseRootVisualElement.styleSheets.Add(EditorGUIUtility.Load(k_StyleCommon) as StyleSheet);
baseRootVisualElement.styleSheets.Add(EditorGUIUtility.Load(EditorGUIUtility.isProSkin ? k_StyleDark : k_StyleLight) as StyleSheet);
s_SelectionCacheDirty = true;
}
IMGUIContainer m_PrefabToolbar;
IMGUIContainer prefabToolbar
{
get
{
if (m_PrefabToolbar == null)
{
m_PrefabToolbar = new IMGUIContainer()
{
onGUIHandler = () =>
{
if (m_StageHandling != null && m_StageHandling.isShowingBreadcrumbBar)
{
m_PrefabToolbar.style.height = m_StageHandling.breadcrumbHeight;
m_StageHandling.BreadcrumbGUI();
}
else
{
m_PrefabToolbar.style.height = 0;
}
},
name = VisualElementUtils.GetUniqueName("prefab-toolbar"),
pickingMode = PickingMode.Position,
viewDataKey = name,
renderHints = RenderHints.ClipWithScissors
};
UIElementsEditorUtility.AddDefaultEditorStyleSheets(m_PrefabToolbar);
m_PrefabToolbar.style.overflow = UnityEngine.UIElements.Overflow.Hidden;
}
return m_PrefabToolbar;
}
}
VisualElement CreateCameraRectVisualElement()
{
var root = new IMGUIContainer()
{
onGUIHandler = OnSceneGUI,
name = s_CameraRectVisualElementName,
pickingMode = PickingMode.Position,
viewDataKey = name,
renderHints = RenderHints.ClipWithScissors,
requireMeasureFunction = false
};
UIElementsEditorUtility.AddDefaultEditorStyleSheets(root);
root.style.overflow = Overflow.Hidden;
root.style.flexGrow = 1;
if (addCustomVisualElementToSceneView != null)
{
foreach (var del in addCustomVisualElementToSceneView.GetInvocationList())
{
root.Add((VisualElement)del.DynamicInvoke(this));
}
}
return root;
}
void OnComponentWasAdded(Component component)
{
var renderer = component as Renderer;
if (renderer != null)
s_SelectionCacheDirty = true;
}
void GridOnGridVisibilityChanged(bool visible)
{
gridVisibilityChanged?.Invoke(visible);
}
protected virtual bool SupportsStageHandling()
{
return true;
}
void CurrentStageIsolated(bool isolated)
{
if (isolated)
{
m_SceneVisActive = true;
Repaint();
}
}
void VisibilityChanged()
{
UpdateHiddenObjectCount();
Repaint();
}
void UpdateHiddenObjectCount()
{
int hiddenGameObjects = SceneVisibilityState.GetHiddenObjectCount();
m_SceneVisHiddenCount = hiddenGameObjects.ToString();
}
public SceneView()
{
m_HierarchyType = HierarchyType.GameObjects;
// Note: Rendering for Scene view picking depends on the depth buffer of the window
depthBufferBits = 32;
}
internal void Awake()
{
if (string.IsNullOrEmpty(m_WindowGUID))
m_WindowGUID = GUID.Generate().ToString();
// Try copy last active scene view window settings if creating a new window
if (sceneViewState == null && m_CameraSettings == null && lastActiveSceneView != null)
{
CopyLastActiveSceneViewSettings();
}
else
{
if (sceneViewState == null)
{
m_SceneViewState = new SceneViewState();
}
if (m_CameraSettings == null)
{
m_CameraSettings = new CameraSettings();
}
}
if (m_2DMode || EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D)
{
m_LastSceneViewRotation = Quaternion.LookRotation(new Vector3(-1, -.7f, -1));
m_LastSceneViewOrtho = false;
m_Rotation.value = Quaternion.identity;
m_Ortho.value = true;
if(!m_2DMode)
{
m_2DMode = true;
modeChanged2D?.Invoke(m_2DMode);
}
// Enforcing Rect tool as the default in 2D mode.
if (Tools.current == Tool.Move)
Tools.current = Tool.Rect;
}
m_PreviousScene = lastActiveSceneView;
}
[RequiredByNativeCode]
internal static void PlaceGameObjectInFrontOfSceneView(GameObject go)
{
if (s_SceneViews.Count >= 1)
{
SceneView view = lastActiveSceneView;
if (view)
view.MoveToView(go.transform);
}
}
internal static Camera GetLastActiveSceneViewCamera()
{
SceneView view = lastActiveSceneView;
return view ? view.camera : null;
}
public override void OnDisable()
{
EditorApplication.modifierKeysChanged -= RepaintAll;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
SceneVisibilityManager.visibilityChanged -= VisibilityChanged;
SceneVisibilityManager.currentStageIsIsolated -= CurrentStageIsolated;
Lightmapping.lightingDataUpdated -= RepaintAll;
ActiveEditorTracker.editorTrackerRebuilt -= OnEditorTrackerRebuilt;
Selection.selectedObjectWasDestroyed -= OnSelectedObjectWasDestroyed;
Selection.nonSelectedObjectWasDestroyed -= OnNonSelectedObjectWasDestroyed;
sceneViewGrids.gridVisibilityChanged -= GridOnGridVisibilityChanged;
sceneViewGrids.OnDisable(this);
if (m_Camera)
DestroyImmediate(m_Camera.gameObject, true);
if (m_Light[0])
DestroyImmediate(m_Light[0].gameObject, true);
if (m_Light[1])
DestroyImmediate(m_Light[1].gameObject, true);
if (m_Light[2])
DestroyImmediate(m_Light[2].gameObject, true);
EditorSceneManager.ClosePreviewScene(m_CustomLightsScene);
if (s_MipColorsTexture)
DestroyImmediate(s_MipColorsTexture, true);
s_SceneViews.Remove(this);
if (s_LastActiveSceneView == this)
lastActiveSceneView = s_SceneViews.Count > 0 ? s_SceneViews[0] as SceneView : null;
CleanupEditorDragFunctions();
if (m_StageHandling != null)
m_StageHandling.OnDisable();
ObjectFactory.componentWasAdded -= OnComponentWasAdded;
base.OnDisable();
}
public void OnDestroy()
{
if (audioPlay)
audioPlay = false;
}
internal void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (audioPlay)
audioPlay = false;
}
// This has to be called explicitly from SceneViewStageHandling to ensure,
// this happens *after* SceneViewStageHandling has updated the camera scene.
// Thus, we can't just register to the StageNavigationManager.instance.stageChanged
// event since that would not guarantee the order dependency.
internal void OnStageChanged(Stage previousStage, Stage newStage)
{
VisibilityChanged();
// audioPlay may be different in the new stage,
// so update regardless of whether it's on or off.
// Not if we're in Play Mode however, as audio preview
// is entirely disabled in that case.
if (!EditorApplication.isPlaying)
RefreshAudioPlay();
}
internal override void OnMaximized()
{
m_SceneViewMotion.CompleteSceneViewMotionTool();
Repaint();
}
internal void ToolbarSearchFieldGUI()
{
if (m_MainViewControlID != GUIUtility.keyboardControl
&& Event.current.type == EventType.KeyDown
&& !string.IsNullOrEmpty(m_SearchFilter)
)
{
switch (Event.current.keyCode)
{
case KeyCode.UpArrow:
case KeyCode.DownArrow:
if (Event.current.keyCode == KeyCode.UpArrow)
SelectPreviousSearchResult();
else
SelectNextSearchResult();
FrameSelected(false);
Event.current.Use();
GUIUtility.ExitGUI();
return;
}
}
EditorGUIUtility.labelWidth = 0;
SearchFieldGUI(EditorGUILayout.kLabelFloatMaxW);
}
// This method should be called after the audio play button has been toggled,
// and after other events that require a refresh.
void RefreshAudioPlay()
{
if ((s_AudioSceneView != null) && (s_AudioSceneView != this))
{
// turn *other* sceneview off
if (s_AudioSceneView.m_PlayAudio)
{
s_AudioSceneView.m_PlayAudio = false;
s_AudioSceneView.Repaint();
}
}
// We have to find all loaded AudioSources, not just the ones in main scenes.
var sources = (AudioSource[])Resources.FindObjectsOfTypeAll(typeof(AudioSource));
foreach (AudioSource source in sources)
{
if (EditorUtility.IsPersistent(source))
continue;
if (source.playOnAwake)
{
if (!m_PlayAudio || !StageUtility.IsGameObjectRenderedByCamera(source.gameObject, m_Camera))
{
source.Stop();
}
else
{
if (!source.isPlaying && source.isActiveAndEnabled)
source.Play();
}
}
}
// We have to find all loaded ReverbZones, not just the ones in main scenes.
var zones = (AudioReverbZone[])Resources.FindObjectsOfTypeAll(typeof(AudioReverbZone));
foreach (AudioReverbZone zone in zones)
{
if (EditorUtility.IsPersistent(zone))
continue;
zone.active = m_PlayAudio && StageUtility.IsGameObjectRenderedByCamera(zone.gameObject, m_Camera);
}
AudioUtil.SetListenerTransform(m_PlayAudio ? m_Camera.transform : null);
s_AudioSceneView = this;
if (m_PlayAudio)
{
AudioMixerWindow.RepaintAudioMixerWindow();
}
}
void OnSelectionChange()
{
if (Selection.activeObject != null && m_LastLockedObject != Selection.activeObject)
viewIsLockedToObject = false;
m_WasFocused = false;
s_SelectionCacheDirty = true;
Repaint();
}
public virtual void AddItemsToMenu(GenericMenu menu)
{
if (RenderDoc.IsInstalled() && !RenderDoc.IsLoaded())
{
menu.AddItem(RenderDocUtil.LoadRenderDocMenuItem, false, RenderDoc.LoadRenderDoc);
}
}
public static void AddOverlayToActiveView<T>(T overlay) where T : Overlay
{
s_ActiveViewOverlays.Add(overlay);
if(lastActiveSceneView != null)
lastActiveSceneView.overlayCanvas.Add(overlay);
}
public static void RemoveOverlayFromActiveView<T>(T overlay) where T : Overlay
{
if (!s_ActiveViewOverlays.Remove(overlay))
return;
if (lastActiveSceneView != null)
lastActiveSceneView.overlayCanvas.Remove(overlay);
}
static void MoveOverlaysToActiveView(SceneView previous, SceneView active)
{
if (previous != null)
{
foreach (var overlay in s_ActiveViewOverlays)
previous.overlayCanvas.Remove(overlay);
}
if (active != null)
{
foreach (var overlay in s_ActiveViewOverlays)
active.overlayCanvas.Add(overlay);
}
}
private static bool ValidateMenuMoveToFrontOrBack(Transform[] transforms, bool isFront)
{
if (transforms.Length == 0)
{
return false;
}
int alreadyInPlaceCounter = 0;
foreach (Transform transform in transforms)
{
if (transform == null || transform.parent == null || PrefabUtility.IsPartOfNonAssetPrefabInstance(transform.parent))
{
return false;
}
int alreadyInPlaceSiblingIndex = isFront ? 0 : transform.parent.childCount - 1;
if (transform.GetSiblingIndex() == alreadyInPlaceSiblingIndex)
{
alreadyInPlaceCounter += 1;
}
}
return alreadyInPlaceCounter < transforms.Length;
}
private static void RegisterMenuMoveChildrenUndo(Transform[] transforms, string message)
{
var parents = new HashSet<Transform>();
foreach (Transform t in transforms)
{
if (!parents.Contains(t.parent))
{
Undo.RegisterChildrenOrderUndo(t.parent, message);
parents.Add(t.parent);
}
}
}
[MenuItem("GameObject/Set as first sibling %=", secondaryPriority = 1)]
internal static void MenuMoveToFront()
{
var selectedTransforms = Selection.transforms;
RegisterMenuMoveChildrenUndo(selectedTransforms, "Set as first sibling");
foreach (Transform t in selectedTransforms)
{
t.SetAsFirstSibling();
}
}
[MenuItem("GameObject/Set as first sibling %=", true)]
internal static bool ValidateMenuMoveToFront()
{
return ValidateMenuMoveToFrontOrBack(Selection.transforms, true);
}
[MenuItem("GameObject/Set as last sibling %-", secondaryPriority = 2)]
internal static void MenuMoveToBack()
{
var selectedTransforms = Selection.transforms;
RegisterMenuMoveChildrenUndo(selectedTransforms, "Set as last sibling");
foreach (Transform t in selectedTransforms)
{
t.SetAsLastSibling();
}
}
[MenuItem("GameObject/Set as last sibling %-", true)]
internal static bool ValidateMenuMoveToBack()
{
return ValidateMenuMoveToFrontOrBack(Selection.transforms, false);
}
[MenuItem("GameObject/Move To View %&f", secondaryPriority = 3)]
internal static void MenuMoveToView()
{
if (ValidateMoveToView())
lastActiveSceneView.MoveToView();
}
[MenuItem("GameObject/Move To View %&f", true)]
static bool ValidateMoveToView()
{
return lastActiveSceneView != null && (Selection.transforms.Length != 0);
}
[MenuItem("GameObject/Align With View %#f", secondaryPriority = 4)]
internal static void MenuAlignWithView()
{
if (ValidateAlignWithView())
lastActiveSceneView.AlignWithView();
}
[MenuItem("GameObject/Align With View %#f", true)]
internal static bool ValidateAlignWithView()
{
return lastActiveSceneView != null && (Selection.activeTransform != null);
}
[MenuItem("GameObject/Align View to Selected", secondaryPriority = 5)]
internal static void MenuAlignViewToSelected()
{
if (ValidateAlignViewToSelected())
lastActiveSceneView.AlignViewToObject(Selection.activeTransform);
}
[MenuItem("GameObject/Align View to Selected", true)]
internal static bool ValidateAlignViewToSelected()
{
return lastActiveSceneView != null && (Selection.activeTransform != null);
}
[MenuItem("GameObject/Toggle Active State &#a", secondaryPriority = 6)]
internal static void ActivateSelection()
{
if (Selection.activeTransform != null)
{
GameObject[] gos = Selection.gameObjects;
Undo.RecordObjects(gos, "Toggle Active State");
bool val = !Selection.activeGameObject.activeSelf;
foreach (GameObject go in gos)
go.SetActive(val);
}
}
[MenuItem("GameObject/Toggle Active State &#a", true)]
internal static bool ValidateActivateSelection()
{
return (Selection.activeTransform != null);
}
static void CreateMipColorsTexture()
{
if (s_MipColorsTexture)
return;
s_MipColorsTexture = new Texture2D(32, 32, TextureFormat.RGBA32, true) {hideFlags = HideFlags.HideAndDontSave};
Color[] colors = new Color[6];
colors[0] = new Color(0.0f, 0.0f, 1.0f, 0.8f);
colors[1] = new Color(0.0f, 0.5f, 1.0f, 0.4f);
colors[2] = new Color(1.0f, 1.0f, 1.0f, 0.0f); // optimal level
colors[3] = new Color(1.0f, 0.7f, 0.0f, 0.2f);
colors[4] = new Color(1.0f, 0.3f, 0.0f, 0.6f);
colors[5] = new Color(1.0f, 0.0f, 0.0f, 0.8f);
int mipCount = Mathf.Min(6, s_MipColorsTexture.mipmapCount);
for (int mip = 0; mip < mipCount; ++mip)
{
int width = Mathf.Max(s_MipColorsTexture.width >> mip, 1);
int height = Mathf.Max(s_MipColorsTexture.height >> mip, 1);
Color[] cols = new Color[width * height];
for (int i = 0; i < cols.Length; ++i)
cols[i] = colors[mip];
s_MipColorsTexture.SetPixels(cols, mip);
}
s_MipColorsTexture.filterMode = FilterMode.Trilinear;
s_MipColorsTexture.Apply(false);
Shader.SetGlobalTexture("_SceneViewMipcolorsTexture", s_MipColorsTexture);
}
bool m_ForceSceneViewFiltering;
bool m_ForceSceneViewFilteringForLodGroupEditing;
bool m_ForceSceneViewFilteringForStageHandling;
double m_lastRenderedTime;
internal void SetSceneViewFiltering(bool enable)
{
m_ForceSceneViewFiltering = enable;
}
internal void SetSceneViewFilteringForLODGroups(bool enable)
{
m_ForceSceneViewFilteringForLodGroupEditing = enable;
}
internal void SetSceneViewFilteringForStages(bool enable)
{
m_ForceSceneViewFilteringForStageHandling = enable;
}
bool forceSceneViewFilteringForLodGroupEditing => m_ForceSceneViewFilteringForLodGroupEditing && s_PreferenceEnableFilteringWhileLodGroupEditing;
bool UseSceneFiltering()
{
return (!string.IsNullOrEmpty(m_SearchFilter) && s_PreferenceEnableFilteringWhileSearching) || forceSceneViewFilteringForLodGroupEditing || m_ForceSceneViewFilteringForStageHandling || m_ForceSceneViewFiltering;
}
internal bool SceneViewIsRenderingHDR()
{
return m_Camera != null && m_Camera.allowHDR;
}
void OnFocus()
{
lastActiveSceneView = this;
}
void HandleClickAndDragToFocus()
{
Event evt = Event.current;
if (evt.type == EventType.MouseDrag)
draggingLocked = DraggingLockedState.Dragging;
else if (GUIUtility.hotControl == 0 && draggingLocked == DraggingLockedState.Dragging)
draggingLocked = DraggingLockedState.LookAt;
if (evt.type == EventType.MouseDown)
{
Tools.s_ButtonDown = evt.button;
if (Application.platform == RuntimePlatform.OSXEditor)
Focus();
}
// this is necessary because FPS tool won't get is cleanup logic
// executed if another control uses the Event (i.e OnSceneGUI) (case 777346)
else if (evt.type == EventType.MouseUp && Tools.s_ButtonDown == evt.button)
{
Tools.s_ButtonDown = -1;
}
}
private void SetupFogAndShadowDistance(out bool oldFog, out float oldShadowDistance)
{
oldFog = RenderSettings.fog;
oldShadowDistance = QualitySettings.shadowDistance;
if (Event.current.type == EventType.Repaint)
{
if (!sceneViewState.fogEnabled)
Unsupported.SetRenderSettingsUseFogNoDirty(false);
if (m_Camera.orthographic)
Unsupported.SetQualitySettingsShadowDistanceTemporarily(QualitySettings.shadowDistance + 0.5f * cameraDistance);
}
}
private void RestoreFogAndShadowDistance(bool oldFog, float oldShadowDistance)
{
if (Event.current.type == EventType.Repaint)
{
Unsupported.SetRenderSettingsUseFogNoDirty(oldFog);
Unsupported.SetQualitySettingsShadowDistanceTemporarily(oldShadowDistance);
}
}
private void CreateCameraTargetTexture(Rect cameraRect, bool hdr)
{
// make sure we actually support R16G16B16A16_SFloat
GraphicsFormat format = (hdr && SystemInfo.IsFormatSupported(GraphicsFormat.R16G16B16A16_SFloat, GraphicsFormatUsage.Render)) ? GraphicsFormat.R16G16B16A16_SFloat : SystemInfo.GetGraphicsFormat(DefaultFormat.LDR);
if (m_SceneTargetTexture != null)
{
if (m_SceneTargetTexture.graphicsFormat != format)
{
Object.DestroyImmediate(m_SceneTargetTexture);
m_SceneTargetTexture = null;
}
}
Rect actualCameraRect = Handles.GetCameraRect(cameraRect);
int width = (int)Mathf.Max(1f, actualCameraRect.width);
int height = (int)Mathf.Max(1f, actualCameraRect.height);
if (m_SceneTargetTexture == null)
{
m_SceneTargetTexture = new RenderTexture(0, 0, format, SystemInfo.GetGraphicsFormat(DefaultFormat.DepthStencil))
{
name = "SceneView RT",
antiAliasing = 1,
hideFlags = HideFlags.HideAndDontSave
};
}
if (m_SceneTargetTexture.width != width || m_SceneTargetTexture.height != height)
{
m_SceneTargetTexture.Release();
m_SceneTargetTexture.width = width;
m_SceneTargetTexture.height = height;
}
m_SceneTargetTexture.Create();
}
public bool IsCameraDrawModeSupported(CameraMode mode)
{
if (!Handles.IsCameraDrawModeSupported(m_Camera, mode.drawMode))
return false;
return (onValidateCameraMode == null ||
onValidateCameraMode.GetInvocationList().All(validate => ((Func<CameraMode, bool>)validate)(mode)));
}
public bool IsCameraDrawModeEnabled(CameraMode mode)
{
if (!Handles.IsCameraDrawModeEnabled(m_Camera, mode.drawMode))
return false;
return (onValidateCameraMode == null ||
onValidateCameraMode.GetInvocationList().All(validate => ((Func<CameraMode, bool>)validate)(mode)));
}
internal bool IsSceneCameraDeferred()
{
bool usingScriptableRenderPipeline = (GraphicsSettings.currentRenderPipeline != null);
if (m_Camera == null || usingScriptableRenderPipeline)
return false;
if (m_Camera.actualRenderingPath == RenderingPath.DeferredShading)
return true;
return false;
}
internal static bool DoesCameraDrawModeSupportDeferred(DrawCameraMode mode)
{
// many of special visualization modes don't support deferred shading/lighting
// overdraw/mipmaps visualizations need special forward shader
// various lightmaps/visualization modes, don't use deferred for safety (previous code also did not use deferred)
return
mode == DrawCameraMode.Normal ||
mode == DrawCameraMode.Textured ||
mode == DrawCameraMode.TexturedWire ||
mode == DrawCameraMode.ShadowCascades ||
mode == DrawCameraMode.RenderPaths ||
mode == DrawCameraMode.AlphaChannel ||
mode == DrawCameraMode.DeferredDiffuse ||
mode == DrawCameraMode.DeferredSpecular ||
mode == DrawCameraMode.DeferredSmoothness ||
mode == DrawCameraMode.DeferredNormal ||
mode == DrawCameraMode.RealtimeCharting ||
mode == DrawCameraMode.Systems ||
mode == DrawCameraMode.Clustering ||
mode == DrawCameraMode.LitClustering ||
mode == DrawCameraMode.RealtimeAlbedo ||
mode == DrawCameraMode.RealtimeEmissive ||
mode == DrawCameraMode.RealtimeIndirect ||
mode == DrawCameraMode.RealtimeDirectionality ||
mode == DrawCameraMode.BakedLightmap ||
mode == DrawCameraMode.ValidateAlbedo ||
mode == DrawCameraMode.ValidateMetalSpecular;
}
internal static bool DoesCameraDrawModeSupportHDR(DrawCameraMode mode)
{
// HDR/Tonemap only supported on regular views, and not on any special visualizations
return mode == DrawCameraMode.Textured || mode == DrawCameraMode.TexturedWire;
}
private void PrepareCameraTargetTexture(Rect cameraRect)
{
// Always render camera into a RT
bool hdr = SceneViewIsRenderingHDR();
CreateCameraTargetTexture(cameraRect, hdr);
m_Camera.targetTexture = m_SceneTargetTexture;
// Do not use deferred rendering when using search filtering or wireframe/overdraw/mipmaps rendering modes.
if (UseSceneFiltering() || !DoesCameraDrawModeSupportDeferred(m_CameraMode.drawMode))
{
if (IsSceneCameraDeferred())
m_Camera.renderingPath = RenderingPath.Forward;
}
}
private void PrepareCameraReplacementShader()
{
if (Event.current.type != EventType.Repaint)
return;
// Set scene view colors
Handles.SetSceneViewColors(kSceneViewWire, kSceneViewWireOverlay, kSceneViewSelectedOutline, kSceneViewSelectedChildrenOutline, kSceneViewSelectedWire);
// Setup shader replacement if needed by overlay mode
if (m_CameraMode.drawMode == DrawCameraMode.Overdraw)
{
// show overdraw
if (!s_ShowOverdrawShader)
s_ShowOverdrawShader = EditorGUIUtility.LoadRequired("SceneView/SceneViewShowOverdraw.shader") as Shader;
m_Camera.SetReplacementShader(s_ShowOverdrawShader, "RenderType");
}
else if (m_CameraMode.drawMode == DrawCameraMode.Mipmaps)
{
Texture.SetStreamingTextureMaterialDebugProperties();
// show mip levels
if (!s_ShowMipsShader)
s_ShowMipsShader = EditorGUIUtility.LoadRequired("SceneView/SceneViewShowMips.shader") as Shader;
if (s_ShowMipsShader != null && s_ShowMipsShader.isSupported)
{
CreateMipColorsTexture();
m_Camera.SetReplacementShader(s_ShowMipsShader, "RenderType");
}
else
{
m_Camera.SetReplacementShader(m_ReplacementShader, m_ReplacementString);
}
}
else if (m_CameraMode.drawMode == DrawCameraMode.TextureStreaming)
{
Texture.SetStreamingTextureMaterialDebugProperties();
// show mip levels
if (!s_ShowTextureStreamingShader)
s_ShowTextureStreamingShader = EditorGUIUtility.LoadRequired("SceneView/SceneViewShowTextureStreaming.shader") as Shader;
if (s_ShowTextureStreamingShader != null && s_ShowTextureStreamingShader.isSupported)
{
m_Camera.SetReplacementShader(s_ShowTextureStreamingShader, "RenderType");
}
else
{
m_Camera.SetReplacementShader(m_ReplacementShader, m_ReplacementString);
}
}
else
{
m_Camera.SetReplacementShader(m_ReplacementShader, m_ReplacementString);
}
}
bool SceneCameraRendersIntoRT()
{
return m_Camera.targetTexture != null;
}
private void DoDrawCamera(Rect windowSpaceCameraRect, Rect groupSpaceCameraRect, out bool pushedGUIClipNeedsToBePopped)
{
pushedGUIClipNeedsToBePopped = false;
if (!m_Camera.gameObject.activeInHierarchy)
return;
bool oldAsync = ShaderUtil.allowAsyncCompilation;
ShaderUtil.allowAsyncCompilation = EditorSettings.asyncShaderCompilation;
DrawGridParameters gridParam = sceneViewGrids.PrepareGridRender(camera, pivot, m_Rotation.target, size, m_Ortho.target);
Event evt = Event.current;
if (UseSceneFiltering())
{
bool sceneRendersToRT = SceneCameraRendersIntoRT();
if (sceneRendersToRT)
{
GUIClip.Push(groupSpaceCameraRect, Vector2.zero, Vector2.zero, true);
GUIClip.Internal_PushParentClip(Matrix4x4.identity, GUIClip.GetParentMatrix(), groupSpaceCameraRect);
}
if (evt.type == EventType.Repaint)
RenderFilteredScene(groupSpaceCameraRect);
if (sceneRendersToRT)
{
GUIClip.Internal_PopParentClip();
GUIClip.Pop();
}
if (evt.type == EventType.Repaint)
RenderTexture.active = null;
GUI.EndGroup();
GUI.BeginGroup(windowSpaceCameraRect);
if (evt.type == EventType.Repaint)
Graphics.DrawTexture(groupSpaceCameraRect, m_SceneTargetTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, GUI.blitMaterial);
Handles.SetCamera(groupSpaceCameraRect, m_Camera);
}
else
{
// If the camera is rendering into a Render Texture we need to reset the offsets of the GUIClip stack
// otherwise all GUI drawing after here will get offset incorrectly.
if (SceneCameraRendersIntoRT())
{
GUIClip.Push(new Rect(0f, 0f, position.width, position.height), Vector2.zero, Vector2.zero, true);
GUIClip.Internal_PushParentClip(Matrix4x4.identity, GUIClip.GetParentMatrix(), groupSpaceCameraRect);
pushedGUIClipNeedsToBePopped = true;
}
Handles.DrawCameraStep1(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode, gridParam, drawGizmos, true);
if (evt.type == EventType.Repaint)
{
if (s_SelectionCacheDirty)
{
HandleUtility.FilterInstanceIDs(Selection.gameObjects, out s_CachedParentRenderersForOutlining, out s_CachedChildRenderersForOutlining);
s_SelectionCacheDirty = false;
}
OutlineDrawMode selectionOutlineWireFlags = 0;
if (AnnotationUtility.showSelectionOutline) selectionOutlineWireFlags |= OutlineDrawMode.SelectionOutline;
if (AnnotationUtility.showSelectionWire) selectionOutlineWireFlags |= OutlineDrawMode.SelectionWire;
if (selectionOutlineWireFlags != 0)
Handles.DrawOutlineOrWireframeInternal(kSceneViewSelectedOutline, kSceneViewSelectedChildrenOutline, 1 - alphaMultiplier, s_CachedParentRenderersForOutlining, s_CachedChildRenderersForOutlining, selectionOutlineWireFlags);
}
DrawRenderModeOverlay(groupSpaceCameraRect);
}
if (isPingingObject)
{
var currentTime = Time.realtimeSinceStartup;
if (currentTime - pingStartTime > kSubmeshPingDuration)
{
isPingingObject = false;
alphaMultiplier = 0;
submeshOutlineMaterialId = 0;
}
else
{
var elapsed = currentTime - pingStartTime;
float t = (float)elapsed / (float)kSubmeshPingDuration;
alphaMultiplier = Mathf.SmoothStep(1, 0, t);
if (Event.current.type == EventType.Repaint)
{
Handles.DrawSubmeshOutline(kSceneViewSelectedSubmeshOutline, kSceneViewSelectedSubmeshOutline, alphaMultiplier, submeshOutlineMaterialId);
Repaint();
}
}
}
ShaderUtil.allowAsyncCompilation = oldAsync;
}
void RenderFilteredScene(Rect groupSpaceCameraRect)
{
var oldRenderingPath = m_Camera.renderingPath;
// First pass: Draw the scene normally in destination render texture, save color buffer for later
DoClearCamera(groupSpaceCameraRect);
Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode, drawGizmos);
var colorDesc = m_SceneTargetTexture.descriptor;
colorDesc.depthBufferBits = 0;
var colorRT = RenderTexture.GetTemporary(colorDesc);
colorRT.name = "SavedColorRT";
Graphics.Blit(m_SceneTargetTexture, colorRT);
// Second pass: Blit the scene faded out in the scene target texture
float fade = UseSceneFiltering() ? 1f : Mathf.Clamp01((float)(EditorApplication.timeSinceStartup - m_StartSearchFilterTime));
if (!s_FadeMaterial)
s_FadeMaterial = EditorGUIUtility.LoadRequired("SceneView/SceneViewGrayscaleEffectFade.mat") as Material;
s_FadeMaterial.SetFloat("_Fade", fade);
Graphics.Blit(colorRT, m_SceneTargetTexture, s_FadeMaterial);
// Third pass: Draw aura for objects which meet the search filter, but are occluded. Save color buffer for later.
m_Camera.renderingPath = RenderingPath.Forward;
if (!s_AuraShader)
s_AuraShader = EditorGUIUtility.LoadRequired("SceneView/SceneViewAura.shader") as Shader;
m_Camera.SetReplacementShader(s_AuraShader, "");
Handles.SetCameraFilterMode(m_Camera, Handles.CameraFilterMode.ShowFiltered);
Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode, drawGizmos);
var fadedDesc = m_SceneTargetTexture.descriptor;
colorDesc.depthBufferBits = 0;
var fadedRT = RenderTexture.GetTemporary(fadedDesc);
fadedRT.name = "FadedColorRT";
Graphics.Blit(m_SceneTargetTexture, fadedRT);
// Fourth pass: Draw objects which do meet filter in a mask
// cache old state, we need to disable post and similar for the mask pass
var oldSceneViewState = sceneViewState.fxEnabled;
var oldImageEffects = sceneViewState.imageEffectsEnabled;
UpdateImageEffects(false);
sceneViewState.fxEnabled = false;
var skybox = RenderSettings.skybox;
RenderSettings.skybox = null;
RenderTexture.active = m_SceneTargetTexture;
GL.Clear(false, true, Color.clear);
m_Camera.ResetReplacementShader();
Handles.DrawCamera(groupSpaceCameraRect, m_Camera, m_CameraMode.drawMode, drawGizmos);
// restore old state
UpdateImageEffects(oldImageEffects);
sceneViewState.fxEnabled = oldSceneViewState;
RenderSettings.skybox = skybox;
// Final pass: Blit the faded scene where the mask isn't set
if (!s_ApplyFilterMaterial)
s_ApplyFilterMaterial = EditorGUIUtility.LoadRequired("SceneView/SceneViewApplyFilter.mat") as Material;
s_ApplyFilterMaterial.SetTexture("_MaskTex", m_SceneTargetTexture);
Graphics.Blit(fadedRT, colorRT, s_ApplyFilterMaterial);
Graphics.Blit(colorRT, m_SceneTargetTexture);
RenderTexture.ReleaseTemporary(colorRT);
RenderTexture.ReleaseTemporary(fadedRT);
OutlineDrawMode selectionDrawModeMask = 0;
if (AnnotationUtility.showSelectionOutline)
selectionDrawModeMask |= OutlineDrawMode.SelectionOutline;
if (AnnotationUtility.showSelectionWire)
selectionDrawModeMask |= OutlineDrawMode.SelectionWire;
if (Event.current.type == EventType.Repaint && selectionDrawModeMask != 0)
{
if (s_SelectionCacheDirty)
{
HandleUtility.FilterInstanceIDs(Selection.gameObjects, out s_CachedParentRenderersForOutlining, out s_CachedChildRenderersForOutlining);
s_SelectionCacheDirty = false;
}
Handles.DrawOutlineOrWireframeInternal(kSceneViewSelectedOutline, kSceneViewSelectedChildrenOutline, 1 - alphaMultiplier, s_CachedParentRenderersForOutlining, s_CachedChildRenderersForOutlining, selectionDrawModeMask);
Handles.Internal_FinishDrawingCamera(m_Camera, drawGizmos);
}
// Reset camera
m_Camera.SetReplacementShader(m_ReplacementShader, m_ReplacementString);
m_Camera.renderingPath = oldRenderingPath;
if (fade < 1)
Repaint();
}
void DoClearCamera(Rect cameraRect)
{
// Clear (color/skybox)
// We do funky FOV interpolation when switching between ortho and perspective. However,
// for the skybox we always want to use the same FOV.
float skyboxFOV = GetVerticalFOV(m_CameraSettings.fieldOfView);
float realFOV = m_Camera.fieldOfView;
var clearFlags = m_Camera.clearFlags;
if (GraphicsSettings.currentRenderPipeline != null)
m_Camera.clearFlags = CameraClearFlags.Color;
m_Camera.fieldOfView = skyboxFOV;
Handles.ClearCamera(cameraRect, m_Camera);
m_Camera.clearFlags = clearFlags;
m_Camera.fieldOfView = realFOV;
}
void SetupCustomSceneLighting()
{
if (m_SceneIsLit)
return;
m_Light[0].transform.rotation = m_Camera.transform.rotation;
if (Event.current.type == EventType.Repaint)
InternalEditorUtility.SetCustomLighting(m_Light, kSceneViewMidLight);
}
void CleanupCustomSceneLighting()
{
if (m_SceneIsLit)
return;
if (Event.current.type == EventType.Repaint)
InternalEditorUtility.RemoveCustomLighting();
}
// Give editors a chance to kick in. Disable in search mode, editors rendering to the scene
void HandleViewToolCursor(Rect cameraRect)
{
if (!Tools.viewToolActive || Event.current.type != EventType.Repaint)
return;
var cursor = MouseCursor.Arrow;
switch (Tools.viewTool)
{
case ViewTool.Pan:
cursor = MouseCursor.Pan;
break;
case ViewTool.Orbit:
cursor = MouseCursor.Orbit;
break;
case ViewTool.FPS:
cursor = MouseCursor.FPS;
break;
case ViewTool.Zoom:
cursor = MouseCursor.Zoom;
break;
}
if (cursor != MouseCursor.Arrow)
AddCursorRect(cameraRect, cursor);
}
private static bool ComponentHasImageEffectAttribute(Component c)
{
if (c == null)
return false;
return Attribute.IsDefined(c.GetType(), typeof(ImageEffectAllowedInSceneView));
}
void UpdateImageEffects(bool enable)
{
if (Event.current.type != EventType.Repaint)
return;
Camera mainCam = GetMainCamera();
if (!enable || mainCam == null)
{
ComponentUtility.DestroyComponentsMatching(m_Camera.gameObject, ComponentHasImageEffectAttribute);
return;
}
ComponentUtility.ReplaceComponentsIfDifferent(mainCam.gameObject, m_Camera.gameObject, ComponentHasImageEffectAttribute);
}
void DoOnPreSceneGUICallbacks(Rect cameraRect)
{
// Don't do callbacks in search mode, as editors calling Handles.BeginGUI
// will break camera setup.
if (hasSearchFilter)
return;
CallOnPreSceneGUI();
}
// Virtual/Abstract methods are not supported by the APIUpdater
[Obsolete("OnGUI has been deprecated. Use OnSceneGUI instead.")]
protected virtual void OnGUI() {}
protected virtual void OnSceneGUI() => DoOnGUI();
void DoOnGUI()
{
onGUIStarted?.Invoke(this);
Event evt = Event.current;
//overlay.displayed cannot be changed during the layout event
if (evt.type != EventType.Layout)
{
bool shouldShow = lastActiveSceneView == this;
foreach(var overlay in overlayCanvas.overlays)
{
if(overlay is ITransientOverlay transient)
overlay.displayed = shouldShow && transient.visible;
}
}
LegacyOverlayPreOnGUI();
s_CurrentDrawingSceneView = this;
if (evt.type == EventType.Layout)
{
s_MouseRects.Clear();
Tools.InvalidateHandlePosition(); // Some cases that should invalidate the cached position are not handled correctly yet so we refresh it once per frame
}
sceneViewGrids.UpdateGridColor();
Color origColor = GUI.color;
Rect origCameraRect = m_Camera.rect;
Rect windowSpaceCameraRect = cameraViewport;
HandleClickAndDragToFocus();
BeginWindows();
if (evt.type == EventType.Layout)
m_ShowSceneViewWindows = (lastActiveSceneView == this);
SetupFogAndShadowDistance(out var oldFog, out var oldShadowDistance);
GUI.skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Scene);
// Don't apply any playmode tinting to scene views
GUI.color = Color.white;
EditorGUIUtility.labelWidth = 100;
SetupCamera();
RenderingPath oldRenderingPath = m_Camera.renderingPath;
// Use custom scene RenderSettings (if currently showing a custom scene)
bool restoreOverrideRenderSettings = false;
if (m_CustomScene.IsValid())
restoreOverrideRenderSettings = Unsupported.SetOverrideLightingSettings(m_CustomScene);
m_StageHandling?.StartOnGUI();
SetupCustomSceneLighting();
GUI.BeginGroup(windowSpaceCameraRect);
Rect groupSpaceCameraRect = new Rect(0, 0, windowSpaceCameraRect.width, windowSpaceCameraRect.height);
Rect groupSpaceCameraRectInPixels = EditorGUIUtility.PointsToPixels(groupSpaceCameraRect);
HandleViewToolCursor(windowSpaceCameraRect);
PrepareCameraTargetTexture(groupSpaceCameraRectInPixels);
DoClearCamera(groupSpaceCameraRectInPixels);
m_Camera.cullingMask = Tools.visibleLayers;
Handles.SetCamera(groupSpaceCameraRectInPixels, m_Camera);
DoOnPreSceneGUICallbacks(groupSpaceCameraRectInPixels);
PrepareCameraReplacementShader();
// Unfocus search field on mouse clicks into content, so that key presses work to navigate.
m_MainViewControlID = GUIUtility.GetControlID(FocusType.Keyboard);
if (evt.GetTypeForControl(m_MainViewControlID) == EventType.MouseDown && groupSpaceCameraRect.Contains(evt.mousePosition))
GUIUtility.keyboardControl = m_MainViewControlID;
// Draw camera
bool pushedGUIClipNeedsToBePopped;
DoDrawCamera(windowSpaceCameraRect, groupSpaceCameraRect, out pushedGUIClipNeedsToBePopped);
CleanupCustomSceneLighting();
if (restoreOverrideRenderSettings)
Unsupported.RestoreOverrideLightingSettings();
//Ensure that the target texture is clamped [0-1]
//This is needed because otherwise gizmo rendering gets all
//messed up (think HDR target with value of 50 + alpha blend gizmo... gonna be white!)
bool hdrDisplayActive = (m_Parent != null && m_Parent.actualView == this && m_Parent.hdrActive);
if (!UseSceneFiltering() && evt.type == EventType.Repaint && GraphicsFormatUtility.IsIEEE754Format(m_SceneTargetTexture.graphicsFormat) && !hdrDisplayActive)
{
var rtDesc = m_SceneTargetTexture.descriptor;
rtDesc.graphicsFormat = SystemInfo.GetGraphicsFormat(DefaultFormat.LDR);
rtDesc.depthBufferBits = 0;
RenderTexture ldrSceneTargetTexture = RenderTexture.GetTemporary(rtDesc);
ldrSceneTargetTexture.name = "LDRSceneTarget";
Graphics.Blit(m_SceneTargetTexture, ldrSceneTargetTexture);
Graphics.Blit(ldrSceneTargetTexture, m_SceneTargetTexture);
Graphics.SetRenderTarget(m_SceneTargetTexture.colorBuffer, m_SceneTargetTexture.depthBuffer);
RenderTexture.ReleaseTemporary(ldrSceneTargetTexture);
}
if (!UseSceneFiltering() && !isPingingObject)
{
// Blit to final target RT in deferred mode
if (m_Camera.gameObject.activeInHierarchy)
Handles.DrawCameraStep2(m_Camera, m_CameraMode.drawMode, drawGizmos);
}
RestoreFogAndShadowDistance(oldFog, oldShadowDistance);
m_Camera.renderingPath = oldRenderingPath;
if (!UseSceneFiltering())
{
if (evt.type == EventType.Repaint)
{
Profiler.BeginSample("SceneView.BlitRT");
Graphics.SetRenderTarget(null);
}
// If we reset the offsets pop that clip off now.
if (pushedGUIClipNeedsToBePopped)
{
GUIClip.Internal_PopParentClip();
GUIClip.Pop();
}
if (evt.type == EventType.Repaint)
{
Graphics.DrawTexture(groupSpaceCameraRect, m_SceneTargetTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, EditorGUIUtility.GUITextureBlit2SRGBMaterial);
Profiler.EndSample();
}
}
// By this time the 3D scene is done being drawn, and we're left with gizmos, handles and SceneViewGUI stuff.
// Reusing the same 3D scene render target, we draw those things and blit them on the back buffer without
// doing sRGB conversions on them since they were always intended to draw without sRGB conversions.
GUIClip.Push(new Rect(0f, 0f, m_SceneTargetTexture.width, m_SceneTargetTexture.height), Vector2.zero, Vector2.zero, true);
if (evt.type == EventType.Repaint)
{
Graphics.SetRenderTarget(m_SceneTargetTexture);
GL.Clear(false, true, new Color(0, 0, 0, 0)); // Only clear color. Keep depth intact.
GUIClip.Internal_PushParentClip(Matrix4x4.identity, GUIClip.GetParentMatrix(), groupSpaceCameraRect);
}
// Calling OnSceneGUI before DefaultHandles, so users can use events before the Default Handles
HandleSelectionAndOnSceneGUI();
// Draw default scene manipulation tools (Move/Rotate/...)
DefaultHandles();
// Handle scene view motion when this scene view is active (always after duringSceneGui and Tools, so that
// user tools can access RMB and alt keys if they want to override the event)
// Do not pass the camera transform to the SceneViewMotion calculations.
// The camera transform is calculation *output* not *input*.
// Avoiding using it as input too avoids errors accumulating.
m_SceneViewMotion.DoViewTool();
// Update active viewpoint if there's one.
// Must happen after SceneViewMotion.DoViewTool() so it knows
// it needs to reflect a motion to the viewpoint (regardless of their nature).
m_Viewpoint.UpdateViewpointMotion(m_Position.isAnimating || m_Rotation.isAnimating);
Handles.SetCameraFilterMode(Camera.current, UseSceneFiltering() ? Handles.CameraFilterMode.ShowFiltered : Handles.CameraFilterMode.Off);
// Handle scene commands after EditorTool.OnSceneGUI so that tools can handle commands
if (evt.type == EventType.ExecuteCommand || evt.type == EventType.ValidateCommand || evt.keyCode == KeyCode.Escape)
CommandsGUI();
Handles.SetCameraFilterMode(Camera.current, Handles.CameraFilterMode.Off);
Handles.SetCameraFilterMode(m_Camera, Handles.CameraFilterMode.Off);
// Handle Dragging of stuff over scene view
HandleDragging(evt);
if (evt.type == EventType.Repaint)
{
Graphics.SetRenderTarget(null);
GUIClip.Internal_PopParentClip();
}
GUIClip.Pop();
GUI.EndGroup();
GUI.BeginGroup(windowSpaceCameraRect);
if (evt.type == EventType.Repaint)
{
// Blit the results with a pre-multiplied alpha shader to compose them correctly on top of the 3D scene on the back buffer
Graphics.DrawTexture(groupSpaceCameraRect, m_SceneTargetTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, EditorGUIUtility.GUITextureBlitSceneGUIMaterial);
}
GUI.EndGroup();
GUI.color = origColor;
EndWindows();
HandleMouseCursor();
s_CurrentDrawingSceneView = null;
m_Camera.rect = origCameraRect;
if (m_Viewpoint.hasActiveViewpoint)
m_Viewpoint.OnGUIDrawCameraOverscan();
onGUIEnded?.Invoke(this);
if (m_StageHandling != null)
m_StageHandling.EndOnGUI();
}
[Shortcut("Scene View/Show Scene View Context Menu", typeof(SceneView), KeyCode.Mouse1)]
static void OpenActionMenu(ShortcutArguments args)
{
// The mouseOverWindow check is necessary for MacOS because right-clicking does not
// focus the window under the cursor. This is so the action menu does not appear
// when the scene view is in focus and a right-click on another window occurs.
if (mouseOverWindow?.GetType() != typeof(SceneView))
return;
var mousePos = Event.current.mousePosition;
var ve = focusedWindow.rootVisualElement.panel.Pick(mousePos);
if (ve == null)
return;
var context = args.context as SceneView;
if (ve == context.cameraViewVisualElement)
{
ContextMenuUtility.ShowActionMenu();
context.Repaint();
}
}
internal void SwitchToRenderMode(DrawCameraMode mode, bool sceneLighting = true)
{
this.sceneLighting = sceneLighting;
this.cameraMode = GetBuiltinCameraMode(mode);
}
internal void SwitchToUnlit() => SwitchToRenderMode(DrawCameraMode.Textured, false);
internal void ToggleLastDebugDrawMode()
{
if (cameraMode.drawMode == m_LastDebugDrawMode)
{
SwitchToRenderMode(DrawCameraMode.Textured);
}
else
{
SwitchToRenderMode(m_LastDebugDrawMode);
}
}
[Shortcut("Scene View/Render Mode/Wireframe", typeof(SceneView), KeyCode.Alpha1, ShortcutModifiers.Alt)]
static void SetWireframeMode(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
view.SwitchToRenderMode(DrawCameraMode.Wireframe);
}
}
[Shortcut("Scene View/Render Mode/Shaded Wireframe", typeof(SceneView), KeyCode.Alpha2, ShortcutModifiers.Alt)]
static void SetShadedWireframeMode(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
view.SwitchToRenderMode(DrawCameraMode.TexturedWire);
}
}
[Shortcut("Scene View/Render Mode/Unlit", typeof(SceneView), KeyCode.Alpha3, ShortcutModifiers.Alt)]
static void SetUnlitMode(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
view.SwitchToUnlit();
}
}
[Shortcut("Scene View/Render Mode/Shaded", typeof(SceneView), KeyCode.Alpha4, ShortcutModifiers.Alt)]
static void SetShadedMode(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
view.SwitchToRenderMode(DrawCameraMode.Normal);
}
}
[Shortcut("Scene View/Render Mode/Last Debug Draw Mode", typeof(SceneView), KeyCode.Alpha6, ShortcutModifiers.Alt)]
static void SetLastDebugDrawMode(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
view.SwitchToRenderMode(view.m_LastDebugDrawMode);
}
}
[Shortcut("Scene View/Toggle 2D Mode", typeof(SceneView), KeyCode.Alpha2)]
[FormerlyPrefKeyAs("Tools/2D Mode", "2")]
static void Toggle2DMode(ShortcutArguments args)
{
var window = args.context as SceneView;
if (window != null)
window.in2DMode = !window.in2DMode;
}
[Shortcut("Scene View/Toggle Orthographic Projection", typeof(SceneView))]
static void ToggleOrthoView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewSetOrtho(view, !view.orthographic);
}
}
[Shortcut("Scene View/Set Orthographic Right View", typeof(SceneView))]
static void SetOrthoRightView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 0, true);
}
}
[Shortcut("Scene View/Set Right View", typeof(SceneView))]
static void SetRightView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 0, view.orthographic);
}
}
[Shortcut("Scene View/Set Top View", typeof(SceneView))]
static void SetTopView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 1, view.orthographic);
}
}
[Shortcut("Scene View/Set Orthographic Top View", typeof(SceneView))]
static void SetOrthoTopView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 1, true);
}
}
[Shortcut("Scene View/Set Front View", typeof(SceneView))]
static void SetFrontView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 2, view.orthographic);
}
}
[Shortcut("Scene View/Set Orthographic Front View", typeof(SceneView))]
static void SetOrthoFrontView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 2, true);
}
}
[Shortcut("Scene View/Set Left View", typeof(SceneView))]
static void SetLeftView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 3, view.orthographic);
}
}
[Shortcut("Scene View/Set Orthographic Left View", typeof(SceneView))]
static void SetOrthoLeftView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 3, true);
}
}
[Shortcut("Scene View/Set Bottom View", typeof(SceneView))]
static void SetBottomView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 4, view.orthographic);
}
}
[Shortcut("Scene View/Set Orthographic Bottom View", typeof(SceneView))]
static void SetOrthoBottomView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 4, true);
}
}
[Shortcut("Scene View/Set Back View", typeof(SceneView))]
static void SetBackView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 5, view.orthographic);
}
}
[Shortcut("Scene View/Set Orthographic Back View", typeof(SceneView))]
static void SetOrthoBackView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewAxisDirection(view, 5, true);
}
}
[Shortcut("Scene View/Set Free View", typeof(SceneView))]
static void SetFreeView(ShortcutArguments args)
{
var view = args.context as SceneView;
if (view != null)
{
if (!view.isRotationLocked)
view.m_OrientationGizmo?.ViewFromNiceAngle(view, false);
}
}
void HandleMouseCursor()
{
Event evt = Event.current;
Rect cursorRect = new Rect(0, 0, position.width, position.height);
var checkMouseRects = evt.type == EventType.MouseMove || evt.type == EventType.Repaint;
// Determine if mouse is inside a new cursor rect
if (checkMouseRects)
{
bool repaintView = false;
MouseCursor cursor = MouseCursor.Arrow;
foreach (CursorRect r in s_MouseRects)
{
if (r.rect.Contains(evt.mousePosition))
{
cursor = r.cursor;
cursorRect = r.rect;
repaintView = true;
}
}
var cursorChanged = cursor != s_LastCursor;
if (cursorChanged)
{
s_LastCursor = cursor;
InternalEditorUtility.ResetCursor();
}
if (repaintView || cursorChanged)
{
Repaint();
}
}
// Apply the one relevant cursor rect
if (checkMouseRects && s_LastCursor != MouseCursor.Arrow)
EditorGUIUtility.AddCursorRect(cursorRect, s_LastCursor);
}
void DrawRenderModeOverlay(Rect cameraRect)
{
// show destination alpha channel
if (m_CameraMode.drawMode == DrawCameraMode.AlphaChannel)
{
if (!s_AlphaOverlayMaterial)
s_AlphaOverlayMaterial = EditorGUIUtility.LoadRequired("SceneView/SceneViewAlphaMaterial.mat") as Material;
Handles.BeginGUI();
if (Event.current.type == EventType.Repaint)
Graphics.DrawTexture(cameraRect, EditorGUIUtility.whiteTexture, s_AlphaOverlayMaterial);
Handles.EndGUI();
}
// show one of deferred buffers
if (m_CameraMode.drawMode == DrawCameraMode.DeferredDiffuse ||
m_CameraMode.drawMode == DrawCameraMode.DeferredSpecular ||
m_CameraMode.drawMode == DrawCameraMode.DeferredSmoothness ||
m_CameraMode.drawMode == DrawCameraMode.DeferredNormal)
{
if (!s_DeferredOverlayMaterial)
s_DeferredOverlayMaterial = EditorGUIUtility.LoadRequired("SceneView/SceneViewDeferredMaterial.mat") as Material;
Handles.BeginGUI();
if (Event.current.type == EventType.Repaint)
{
s_DeferredOverlayMaterial.SetFloat("_DisplayMode", (float)((int)m_CameraMode.drawMode - (int)DrawCameraMode.DeferredDiffuse));
Graphics.DrawTexture(cameraRect, EditorGUIUtility.whiteTexture, s_DeferredOverlayMaterial);
}
Handles.EndGUI();
}
}
private void HandleSelectionAndOnSceneGUI()
{
m_RectSelection.OnGUI();
CallOnSceneGUI();
}
// Center point of the scene view. Modify it to move the sceneview immediately, or use LookAt to animate it nicely.
public Vector3 pivot { get { return m_Position.value; } set { m_Position.value = value; } }
// The direction of the scene view.
public Quaternion rotation
{
get => m_2DMode ? Quaternion.identity : m_Rotation.value;
set
{
if (m_2DMode)
Debug.LogWarning("SceneView rotation is fixed to identity when in 2D mode. This will be an error in future versions of Unity.");
else
m_Rotation.value = value;
}
}
static float ValidateSceneSize(float value)
{
if (value == 0f || float.IsNaN(value))
return float.Epsilon;
if (value > k_MaxSceneViewSize)
return k_MaxSceneViewSize;
if (value < -k_MaxSceneViewSize)
return -k_MaxSceneViewSize;
return value;
}
public float size
{
get { return m_Size.value; }
set { m_Size.value = ValidateSceneSize(value); }
}
// ReSharper disable once UnusedMember.Global - used only in editor tests
internal float targetSize
{
get { return m_Size.target; }
set { m_Size.target = ValidateSceneSize(value); }
}
float perspectiveFov => m_CameraSettings.fieldOfView;
public bool orthographic
{
get { return m_Ortho.value; }
set
{
m_Ortho.value = value;
m_OrientationGizmo?.UpdateGizmoLabel(this, m_Rotation.target * Vector3.forward, m_Ortho.target);
}
}
public void FixNegativeSize()
{
if (size == 0f)
size = float.Epsilon;
float fov = perspectiveFov;
if (size < 0)
{
float distance = GetPerspectiveCameraDistance(size, fov);
Vector3 p = m_Position.value + rotation * new Vector3(0, 0, -distance);
size = -size;
distance = GetPerspectiveCameraDistance(size, fov);
m_Position.value = p + rotation * new Vector3(0, 0, distance);
}
}
internal float CalcCameraDist()
{
float fov = m_Ortho.Fade(perspectiveFov, 0);
if (fov > kOrthoThresholdAngle)
{
m_Camera.orthographic = false;
return GetPerspectiveCameraDistance(size, fov);
}
return 0;
}
void ResetIfNaN()
{
// If you zoom out enough, m_Position would get corrupted with no way to reset it,
// even after restarting Unity. Crude hack to at least get the scene view working again!
if (Single.IsInfinity(m_Position.value.x) || Single.IsNaN(m_Position.value.x))
m_Position.value = Vector3.zero;
if (Single.IsInfinity(m_Rotation.value.x) || Single.IsNaN(m_Rotation.value.x))
m_Rotation.value = Quaternion.identity;
}
internal static Camera GetMainCamera()
{
// main camera, if we have any
var mainCamera = Camera.main;
if (mainCamera != null)
return mainCamera;
// if we have one camera, return it
Camera[] allCameras = Camera.allCameras;
if (allCameras != null && allCameras.Length == 1)
return allCameras[0];
// otherwise no "main" camera
return null;
}
// Note: this can return "use player settings" value too!
// In order to check things like "is using deferred", use IsUsingDeferredRenderingPath
internal static RenderingPath GetSceneViewRenderingPath()
{
var mainCamera = GetMainCamera();
if (mainCamera != null)
return mainCamera.renderingPath;
return RenderingPath.UsePlayerSettings;
}
internal static bool IsUsingDeferredRenderingPath()
{
RenderingPath renderingPath = GetSceneViewRenderingPath();
return (renderingPath == RenderingPath.DeferredShading) ||
(renderingPath == RenderingPath.UsePlayerSettings && Rendering.EditorGraphicsSettings.GetCurrentTierSettings().renderingPath == RenderingPath.DeferredShading);
}
internal bool CheckDrawModeForRenderingPath(DrawCameraMode mode)
{
RenderingPath path = m_Camera.actualRenderingPath;
if (mode == DrawCameraMode.DeferredDiffuse ||
mode == DrawCameraMode.DeferredSpecular ||
mode == DrawCameraMode.DeferredSmoothness ||
mode == DrawCameraMode.DeferredNormal)
{
return path == RenderingPath.DeferredShading;
}
return true;
}
private void UpdateSceneCameraSettings()
{
var mainCamera = GetMainCamera();
m_Camera.useInteractiveLightBakingData = usesInteractiveLightBakingData;
// update physical camera properties
if (mainCamera != null)
{
m_Camera.iso = mainCamera.iso;
m_Camera.shutterSpeed = mainCamera.shutterSpeed;
m_Camera.aperture = mainCamera.aperture;
m_Camera.anamorphism = mainCamera.anamorphism;
}
if (!m_SceneIsLit || !DoesCameraDrawModeSupportHDR(m_CameraMode.drawMode))
{
m_Camera.allowHDR = false;
m_Camera.depthTextureMode = DepthTextureMode.None;
m_Camera.clearStencilAfterLightingPass = false;
return;
}
if (mainCamera == null)
{
m_Camera.allowHDR = false;
m_Camera.depthTextureMode = DepthTextureMode.None;
m_Camera.clearStencilAfterLightingPass = false;
return;
}
m_Camera.allowHDR = mainCamera.allowHDR;
m_Camera.depthTextureMode = mainCamera.depthTextureMode;
m_Camera.clearStencilAfterLightingPass = mainCamera.clearStencilAfterLightingPass;
}
void SetupCamera()
{
if (m_CameraMode.drawMode == DrawCameraMode.Overdraw)
{
// overdraw
m_Camera.backgroundColor = Color.black;
}
else
{
if (m_StageHandling != null)
m_Camera.backgroundColor = StageNavigationManager.instance.currentStage.GetBackgroundColor();
else
m_Camera.backgroundColor = kSceneViewBackground;
}
if (Event.current.type == EventType.Repaint)
{
bool enableImageEffects = m_CameraMode.drawMode == DrawCameraMode.Textured && sceneViewState.imageEffectsEnabled;
UpdateImageEffects(enableImageEffects);
}
EditorUtility.SetCameraAnimateMaterials(m_Camera, sceneViewState.alwaysRefreshEnabled);
ParticleSystemEditorUtils.renderInSceneView = m_SceneViewState.particleSystemsEnabled;
UnityEngine.VFX.VFXManager.renderInSceneView = m_SceneViewState.visualEffectGraphsEnabled;
SceneVisibilityManager.instance.enableSceneVisibility = m_SceneVisActive;
m_Camera.renderCloudsInSceneView = m_SceneViewState.cloudsEnabled;
ResetIfNaN();
m_Camera.transform.rotation = GetTransformRotation();
m_Camera.transform.position = GetTransformPosition();
if (m_Viewpoint.hasActiveViewpoint)
{
bool isPerspective = m_Ortho.Fade(perspectiveFov, 0) > kOrthoThresholdAngle;
m_Viewpoint.ApplyCameraLensFromViewpoint(isPerspective);
}
else
ApplyDefaultCameraLens();
// In 2D mode, camera position z should not go to positive value
if (m_2DMode && m_Camera.transform.position.z >= 0)
{
var p = m_Camera.transform.position;
// when clamping the camera distance, choose a point far from origin to avoid obscuring objects with the
// near clip plane. see https://fogbugz.unity3d.com/f/cases/1353387/
var z = -(100f + m_Camera.nearClipPlane + 0.01f);
m_Camera.farClipPlane += p.z - z;
p.z = z;
m_Camera.transform.position = p;
}
m_Camera.renderingPath = GetSceneViewRenderingPath();
if (!CheckDrawModeForRenderingPath(m_CameraMode.drawMode))
m_CameraMode = GetBuiltinCameraMode(DrawCameraMode.Textured);
UpdateSceneCameraSettings();
if (m_CameraMode.drawMode == DrawCameraMode.Textured ||
m_CameraMode.drawMode == DrawCameraMode.TexturedWire ||
m_CameraMode.drawMode == DrawCameraMode.UserDefined)
{
Handles.EnableCameraFlares(m_Camera, sceneViewState.flaresEnabled);
Handles.EnableCameraSkybox(m_Camera, sceneViewState.skyboxEnabled);
}
else
{
Handles.EnableCameraFlares(m_Camera, false);
Handles.EnableCameraSkybox(m_Camera, false);
}
// Update the light
m_Light[0].transform.position = m_Camera.transform.position;
m_Light[0].transform.rotation = m_Camera.transform.rotation;
// Update audio engine
if (m_PlayAudio)
{
AudioUtil.SetListenerTransform(m_Camera.transform);
AudioUtil.UpdateAudio();
}
if (m_ViewIsLockedToObject && Selection.gameObjects.Length > 0)
{
var bounds = InternalEditorUtility.CalculateSelectionBounds(false, Tools.pivotMode == PivotMode.Pivot);
switch (draggingLocked)
{
case (DraggingLockedState.Dragging):
// While dragging via handles, we don't want to move the camera
break;
case (DraggingLockedState.LookAt):
if (!m_Position.value.Equals(m_Position.target))
Frame(bounds, EditorApplication.isPlaying);
else
draggingLocked = DraggingLockedState.NotDragging;
break;
case (DraggingLockedState.NotDragging):
// Once framed, we only need to lock position rather than all the parameters Frame() sets
m_Position.value = bounds.center;
break;
}
}
}
/// <summary>
/// Applies CameraSettings properties to the camera.
/// </summary>
internal void ApplyDefaultCameraLens()
{
float fov = m_Ortho.Fade(perspectiveFov, 0);
if (fov > kOrthoThresholdAngle)
{
// View is in perspective mode.
m_Camera.orthographic = false;
m_Camera.fieldOfView = GetVerticalFOV(fov);
}
else
{
// View is orthographic.
m_Camera.orthographic = true;
m_Camera.orthographicSize = GetVerticalOrthoSize();
}
if (cameraSettings.dynamicClip)
{
var clip = GetDynamicClipPlanes();
m_Camera.nearClipPlane = clip.x;
m_Camera.farClipPlane = clip.y;
}
else
{
m_Camera.nearClipPlane = m_CameraSettings.nearClip;
m_Camera.farClipPlane = m_CameraSettings.farClip;
}
m_Camera.useOcclusionCulling = m_CameraSettings.occlusionCulling;
}
void OnBecameVisible()
{
var inPlayMode = (EditorApplication.isPlaying || EditorApplication.isPaused);
if (inPlayMode && m_Parent.vSyncEnabled)
m_Parent.EnableVSync(false);
EditorApplication.update += UpdateAnimatedMaterials;
}
void OnBecameInvisible()
{
EditorApplication.update -= UpdateAnimatedMaterials;
}
void UpdateAnimatedMaterials()
{
var repaint = false;
// Ensure that we in fact do want to paint when not in focus.
if (!EditorApplication.isFocused && s_PreferenceIgnoreAlwaysRefreshWhenNotFocused.value)
{
// We're going to capture this condition, so that it doesnt fall through.
}
else if (m_lastRenderedTime + 0.033f < EditorApplication.timeSinceStartup)
{
repaint = sceneViewState.alwaysRefreshEnabled;
}
repaint |= LODUtility.IsLODAnimating(m_Camera);
if (repaint)
{
m_lastRenderedTime = EditorApplication.timeSinceStartup;
Repaint();
}
}
// ReSharper disable once UnusedMember.Global - used in tests
internal Quaternion cameraTargetRotation => m_Rotation.target;
// ReSharper disable once UnusedMember.Global - used in tests
internal Vector3 cameraTargetPosition => m_Position.target + m_Rotation.target * new Vector3(0, 0, -cameraDistance);
// ReSharper disable once MemberCanBePrivate.Global - used in tests
internal float GetVerticalFOV(float aspectNeutralFOV, float multiplier = 1.0f)
{
// We want Scene view camera "FOV" to be the vertical FOV if the
// Scene view is wider than tall, and the horizontal FOV otherwise.
if (m_Camera.aspect < 1)
multiplier /= m_Camera.aspect;
float halfFovRad = aspectNeutralFOV * 0.5f * Mathf.Deg2Rad;
float halfFovTan = Mathf.Tan(halfFovRad) * multiplier;
return Mathf.Atan(halfFovTan) * 2 * Mathf.Rad2Deg;
}
float GetVerticalOrthoSize()
{
// We want scene view ortho size to enclose sphere of
// radius "size". If scene view is more tall than wide,
// we want to take that into account so that the bounds
// fit in horizontally.
float res = size;
if (m_Camera.aspect < 1.0)
res /= m_Camera.aspect;
return res;
}
/// <summary>
/// Get the final representation of the rotation data that
/// will be applied to the camera transform.
/// </summary>
/// <returns></returns>
internal Quaternion GetTransformRotation()
{
return m_2DMode && !m_Rotation.isAnimating ? Quaternion.identity : m_Rotation.value;
}
/// <summary>
/// Get the final representation of the position data that
/// will be applied to the camera transform.
/// </summary>
/// <returns></returns>
internal Vector3 GetTransformPosition()
{
return m_Position.value + m_Camera.transform.rotation * new Vector3(0, 0, -cameraDistance);
}
// Look at a specific point.
public void LookAt(Vector3 point)
{
FixNegativeSize();
m_Position.target = point;
}
// Look at a specific point from a given direction.
public void LookAt(Vector3 point, Quaternion direction)
{
FixNegativeSize();
m_Position.target = point;
m_Rotation.target = direction;
m_OrientationGizmo?.UpdateGizmoLabel(this, direction * Vector3.forward, m_Ortho.target);
}
// Look directly at a specific point from a given direction.
public void LookAtDirect(Vector3 point, Quaternion direction)
{
FixNegativeSize();
m_Position.value = point;
m_Rotation.value = direction;
m_OrientationGizmo?.UpdateGizmoLabel(this, direction * Vector3.forward, m_Ortho.target);
}
// Look at a specific point from a given direction with a given zoom level.
public void LookAt(Vector3 point, Quaternion direction, float newSize)
{
FixNegativeSize();
m_Position.target = point;
m_Rotation.target = direction;
m_Size.target = ValidateSceneSize(Mathf.Abs(newSize));
m_OrientationGizmo?.UpdateGizmoLabel(this, direction * Vector3.forward, m_Ortho.target);
}
// Look directionally at a specific point from a given direction with a given zoom level.
public void LookAtDirect(Vector3 point, Quaternion direction, float newSize)
{
FixNegativeSize();
m_Position.value = point;
m_Rotation.value = direction;
size = Mathf.Abs(newSize);
m_OrientationGizmo?.UpdateGizmoLabel(this, direction * Vector3.forward, m_Ortho.target);
}
// Look at a specific point from a given direction with a given zoom level, enabling and disabling perspective
public void LookAt(Vector3 point, Quaternion direction, float newSize, bool ortho)
{
LookAt(point, direction, newSize, ortho, false);
}
// Look at a specific point from a given direction with a given zoom level, enabling and disabling perspective
public void LookAt(Vector3 point, Quaternion direction, float newSize, bool ortho, bool instant)
{
m_SceneViewMotion.ResetMotion();
FixNegativeSize();
if (instant)
{
m_Position.value = point;
m_Rotation.value = direction;
size = Mathf.Abs(newSize);
m_Ortho.value = ortho;
draggingLocked = DraggingLockedState.NotDragging;
}
else
{
m_Position.target = point;
m_Rotation.target = direction;
m_Size.target = ValidateSceneSize(Mathf.Abs(newSize));
m_Ortho.target = ortho;
}
m_OrientationGizmo?.UpdateGizmoLabel(this, direction * Vector3.forward, m_Ortho.target);
}
void DefaultHandles()
{
// Note event state.
EditorGUI.BeginChangeCheck();
bool IsDragEvent = Event.current.GetTypeForControl(GUIUtility.hotControl) == EventType.MouseDrag;
bool IsMouseUpEvent = Event.current.GetTypeForControl(GUIUtility.hotControl) == EventType.MouseUp;
EditorToolManager.OnToolGUI(this);
// If we are actually dragging the object(s) then disable 2D physics movement.
if (EditorGUI.EndChangeCheck() && EditorApplication.isPlaying && IsDragEvent)
Physics2D.SetEditorDragMovement(true, Selection.gameObjects);
// If we have finished dragging the object(s) then enable 2D physics movement.
if (EditorApplication.isPlaying && IsMouseUpEvent)
Physics2D.SetEditorDragMovement(false, Selection.gameObjects);
}
void CleanupEditorDragFunctions()
{
m_DragEditorCache?.Dispose();
m_DragEditorCache = null;
}
bool CallEditorDragFunctions(IList<Object> dragAndDropObjects)
{
Event evt = Event.current;
SpriteUtility.OnSceneDrag(this);
if (evt.type == EventType.Used || dragAndDropObjects.Count == 0) return true;
if (m_DragEditorCache == null)
m_DragEditorCache = new EditorCache(EditorFeatures.OnSceneDrag);
bool allHandled = true;
// We iterate through dragged items backwards to preserve the alphabetical order
// of GameObjects when they are created in hierarchy once drag is performed
for (int i = dragAndDropObjects.Count - 1; i >= 0; i--)
{
if (dragAndDropObjects[i] == null)
continue;
EditorWrapper w = m_DragEditorCache[dragAndDropObjects[i]];
if (w == null)
{
allHandled = false;
continue;
}
w.OnSceneDrag(this, dragAndDropObjects.Count - 1 - i);
}
return allHandled;
}
internal static bool CanDoDrag(ICollection<Object> objects)
{
if (objects.Count < 2) return true;
int gameObjectCount = 0;
int assetCount = 0;
int materialCount = 0;
// Only allow dragging multiple GameObjects, or multiple non-GameObjects, but not mixed sets.
// For example when dragging GameObjects and Materials would sometimes apply material to
// already existing scene object, and other times to the object being spawned. It depends
// on the order in which the user selects those assets. We decided it was not an intuitive
// behavior and it should just not be allowed.
// Also we don't want multiple materials be dropped into scene because there is no case
// where we can handle it in a way that benefit the user. For example multiple skybox
// materials doesn't make sense and dropping multiple materials onto geometry will only
// drop the first material on the hovered material entry.
foreach (Object obj in objects)
{
if (obj.GetType() == typeof(GameObject))
{
gameObjectCount++;
}
else
{
assetCount++;
if (obj.GetType() == typeof(Material))
{
materialCount++;
}
}
if (gameObjectCount > 0 && assetCount > 0 || materialCount > 1) return false;
}
return true;
}
internal void HandleDragging(Event evt)
{
Object[] dragAndDropObjects = DragAndDrop.objectReferences;
switch (evt.type)
{
case EventType.DragPerform:
case EventType.DragUpdated:
if (evt.type == EventType.DragPerform && GameObjectInspector.s_CyclicNestingDetected)
{
PrefabUtility.ShowCyclicNestingWarningDialog();
return;
}
if (!CanDoDrag(dragAndDropObjects))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
return;
}
bool isPerform = evt.type == EventType.DragPerform;
GameObject pickedObject = null;
Transform parentTransform = null;
bool dropHandled = false;
// Allow user defined Custom Drop Handler
if (DragAndDrop.HasHandler(DragAndDropWindowTarget.sceneView))
{
PickObject(ref pickedObject, ref parentTransform);
Vector3 worldPosition = HandleUtility.PlaceObject(Event.current.mousePosition, out Vector3 placedPosition, out _) ? placedPosition : pivot;
DragAndDrop.visualMode = DragAndDrop.DropOnSceneWindow(pickedObject, worldPosition, Event.current.mousePosition, parentTransform, isPerform);
dropHandled = DragAndDrop.visualMode != DragAndDropVisualMode.None;
}
// Allow editor Wrapper Drop Handler
var allObjectsHandled = false;
if (!dropHandled)
{
allObjectsHandled = CallEditorDragFunctions(dragAndDropObjects);
}
if (evt.type == EventType.Used || allObjectsHandled)
return;
// C++ legacy Drop Handler
if (!dropHandled)
{
if (pickedObject == null || parentTransform == null)
PickObject(ref pickedObject, ref parentTransform);
Vector3 worldPosition = HandleUtility.PlaceObject(Event.current.mousePosition, out Vector3 placedPosition, out _) ? placedPosition : pivot;
DragAndDrop.visualMode = InternalEditorUtility.SceneViewDrag(pickedObject, worldPosition, Event.current.mousePosition, parentTransform, isPerform);
}
evt.Use();
if (isPerform && DragAndDrop.visualMode != DragAndDropVisualMode.None && DragAndDrop.visualMode != DragAndDropVisualMode.Rejected)
{
DragAndDrop.AcceptDrag();
// Bail out as state can be messed up by now.
GUIUtility.ExitGUI();
}
break;
case EventType.DragExited:
CallEditorDragFunctions(dragAndDropObjects);
CleanupEditorDragFunctions();
break;
}
}
void PickObject(ref GameObject dropUpon, ref Transform parentTransform)
{
var defaultParentObject = GetDefaultParentObjectIfSet();
parentTransform = defaultParentObject != null ? defaultParentObject : customParentForDraggedObjects;
dropUpon = HandleUtility.PickGameObject(Event.current.mousePosition, true);
}
void CommandsGUI()
{
// @TODO: Validation should be more accurate based on what the view supports
bool execute = Event.current.type == EventType.ExecuteCommand;
switch (Event.current.commandName)
{
case EventCommandNames.Find:
if (execute)
FocusSearchField();
Event.current.Use();
break;
case EventCommandNames.FrameSelected:
if (execute && Tools.s_ButtonDown != 1)
{
FrameSelected(false);
}
Event.current.Use();
break;
case EventCommandNames.FrameSelectedWithLock:
if (execute && Tools.s_ButtonDown != 1)
{
FrameSelected(true);
}
Event.current.Use();
break;
case EventCommandNames.SoftDelete:
case EventCommandNames.Delete:
if (execute)
Unsupported.DeleteGameObjectSelection();
Event.current.Use();
break;
case EventCommandNames.Duplicate:
if (execute)
{
ClipboardUtility.DuplicateGO(customParentForNewGameObjects);
}
Event.current.Use();
break;
case EventCommandNames.Copy:
if (execute)
{
ClipboardUtility.CopyGO();
}
Event.current.Use();
break;
case EventCommandNames.Cut:
if (execute)
{
ClipboardUtility.CutGO();
}
Event.current.Use();
break;
case EventCommandNames.Paste:
if (execute)
{
ClipboardUtility.PasteGO(customParentForNewGameObjects);
}
Event.current.Use();
break;
case EventCommandNames.SelectAll:
if (execute)
{
var gameObjects = FindObjectsByType<GameObject>(FindObjectsSortMode.InstanceID);
var objs = new List<Object>(gameObjects.Length);
foreach (var go in gameObjects)
if (SceneVisibilityManager.instance.IsSelectable(go))
objs.Add(go);
Selection.objects = objs.ToArray();
}
Event.current.Use();
break;
case EventCommandNames.DeselectAll:
if (execute)
Selection.activeGameObject = null;
Event.current.Use();
break;
case EventCommandNames.InvertSelection:
if (execute)
{
Selection.objects = FindObjectsByType<GameObject>(FindObjectsSortMode.InstanceID).Except(Selection.gameObjects).Where(SceneVisibilityManager.instance.IsSelectable).ToArray();
}
Event.current.Use();
break;
case EventCommandNames.SelectChildren:
if (execute)
{
List<GameObject> gameObjects = new List<GameObject>(Selection.gameObjects);
foreach (var gameObject in Selection.gameObjects)
{
gameObjects.AddRange(gameObject.transform.GetComponentsInChildren<Transform>(true).Select(t => t.gameObject));
}
Selection.objects = gameObjects.Distinct().Cast<Object>().ToArray();
}
Event.current.Use();
break;
case EventCommandNames.SelectPrefabRoot:
if (execute)
{
List<GameObject> gameObjects = new List<GameObject>(Selection.gameObjects.Length);
foreach (var gameObject in Selection.gameObjects)
{
var root = PrefabUtility.GetOutermostPrefabInstanceRoot(gameObject);
if (root != null)
{
gameObjects.Add(root);
}
}
Selection.objects = gameObjects.Distinct().Cast<Object>().ToArray();
}
Event.current.Use();
break;
}
// Detect if we are canceling 'Cut' operation
if (Event.current.keyCode == KeyCode.Escape && CutBoard.hasCutboardData)
{
ClipboardUtility.ResetCutboardAndRepaintHierarchyWindows();
Repaint();
}
}
public void AlignViewToObject(Transform t)
{
FixNegativeSize();
size = 10;
LookAt(t.position + t.forward * CalcCameraDist(), t.rotation);
}
public void AlignWithView()
{
FixNegativeSize();
Vector3 center = camera.transform.position;
Vector3 dif = center - Tools.handlePosition;
Quaternion delta = Quaternion.Inverse(Selection.activeTransform.rotation) * camera.transform.rotation;
float angle;
Vector3 axis;
delta.ToAngleAxis(out angle, out axis);
axis = Selection.activeTransform.TransformDirection(axis);
Undo.RecordObjects(Selection.transforms, "Align with view");
foreach (Transform t in Selection.transforms)
{
t.position += dif;
t.RotateAround(center, axis, angle);
}
}
public void MoveToView()
{
FixNegativeSize();
Vector3 dif = pivot - Tools.handlePosition;
Undo.RecordObjects(Selection.transforms, "Move to view");
foreach (Transform t in Selection.transforms)
{
t.position += dif;
}
}
public void MoveToView(Transform target)
{
target.position = pivot;
}
internal bool IsGameObjectInThisSceneView(GameObject gameObject)
{
if (gameObject == null)
return false;
return !StageUtility.IsGizmoCulledBySceneCullingMasksOrFocusedScene(gameObject, camera);
}
public bool FrameSelected()
{
return FrameSelected(false);
}
public bool FrameSelected(bool lockView)
{
return FrameSelected(lockView, false);
}
public virtual bool FrameSelected(bool lockView, bool instant)
{
if (!IsGameObjectInThisSceneView(Selection.activeGameObject))
return false;
viewIsLockedToObject = lockView;
FixNegativeSize();
Bounds bounds;
if (!m_WasFocused)
{
bounds = InternalEditorUtility.CalculateSelectionBounds(false, Tools.pivotMode == PivotMode.Pivot, true);
}
else
{
bounds = new Bounds(Tools.handlePosition, Vector3.one);
}
// Check active editor for OnGetFrameBounds
foreach (Editor editor in activeEditors)
{
MethodInfo hasBoundsMethod = editor.GetType().GetMethod("HasFrameBounds", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
if (hasBoundsMethod != null)
{
object hasBounds = hasBoundsMethod.Invoke(editor, null);
if (hasBounds is bool && (bool)hasBounds)
{
MethodInfo getBoundsMethod = editor.GetType().GetMethod("OnGetFrameBounds", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
if (getBoundsMethod != null)
{
object obj = getBoundsMethod.Invoke(editor, null);
if (obj is Bounds)
bounds = (Bounds)obj;
}
}
}
}
m_WasFocused = !m_WasFocused;
return Frame(bounds, EditorApplication.isPlaying || instant);
}
public bool Frame(Bounds bounds, bool instant = true)
{
float newSize = bounds.extents.magnitude;
if (float.IsInfinity(newSize))
return false;
// If we have no size to focus on, bound default 10 units
if (newSize < Mathf.Epsilon)
newSize = 10;
// We snap instantly into target on playmode, because things might be moving fast and lerping lags behind
LookAt(bounds.center, m_Rotation.target, newSize, m_Ortho.value, instant);
return true;
}
void CreateSceneCameraAndLights()
{
GameObject cameraGO = EditorUtility.CreateGameObjectWithHideFlags("SceneCamera", HideFlags.HideAndDontSave, typeof(Camera));
cameraGO.AddComponent<FlareLayer>();
m_Camera = cameraGO.GetComponent<Camera>();
m_Camera.enabled = false;
m_Camera.cameraType = CameraType.SceneView;
m_Camera.scene = m_CustomScene;
if (m_OverrideSceneCullingMask != 0)
m_Camera.overrideSceneCullingMask = m_OverrideSceneCullingMask;
m_CustomLightsScene = EditorSceneManager.NewPreviewScene();
m_CustomLightsScene.name = "CustomLightsScene-SceneView" + m_WindowGUID;
for (int i = 0; i < 3; i++)
{
GameObject lightGO = EditorUtility.CreateGameObjectWithHideFlags("SceneLight", HideFlags.HideAndDontSave, typeof(Light));
m_Light[i] = lightGO.GetComponent<Light>();
m_Light[i].type = LightType.Directional;
m_Light[i].intensity = 1.0f;
m_Light[i].enabled = false;
SceneManager.MoveGameObjectToScene(lightGO, m_CustomLightsScene);
}
m_Light[0].color = kSceneViewFrontLight;
m_Light[1].color = kSceneViewUpLight - kSceneViewMidLight;
m_Light[1].transform.LookAt(Vector3.down);
m_Light[1].renderMode = LightRenderMode.ForceVertex;
m_Light[2].color = kSceneViewDownLight - kSceneViewMidLight;
m_Light[2].transform.LookAt(Vector3.up);
m_Light[2].renderMode = LightRenderMode.ForceVertex;
HandleUtility.handleMaterial.SetColor("_SkyColor", kSceneViewUpLight * 1.5f);
HandleUtility.handleMaterial.SetColor("_GroundColor", kSceneViewDownLight * 1.5f);
HandleUtility.handleMaterial.SetColor("_Color", kSceneViewFrontLight * 1.5f);
}
struct EditorActionCache
{
private readonly Dictionary<Type, Action<Editor>> m_Cache;
private readonly string m_MethodName;
public EditorActionCache(string methodName)
{
m_MethodName = methodName;
m_Cache = new Dictionary<Type, Action<Editor>>();
}
public Action<Editor> GetAction(Type type)
{
if (!m_Cache.TryGetValue(type, out var onSceneGui))
{
MethodInfo method = type.GetMethod(
m_MethodName,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy,
null,
Type.EmptyTypes,
null);
if (method == null)
m_Cache[type] = null;
else
{
var param = Expression.Parameter(typeof(Editor), "a");
onSceneGui = m_Cache[type] = Expression.Lambda<Action<Editor>>(
Expression.Call(Expression.Convert(param, type), method),
param
).Compile();
}
}
return onSceneGui;
}
}
private static EditorActionCache s_OnSceneGuiCache = new EditorActionCache("OnSceneGUI");
private static EditorActionCache s_OnPreSceneGuiCache = new EditorActionCache("OnPreSceneGUI");
void CallOnSceneGUI()
{
if (drawGizmos)
{
foreach (Editor editor in activeEditors)
{
if (!EditorGUIUtility.IsGizmosAllowedForObject(editor.target))
continue;
var onSceneGui = s_OnSceneGuiCache.GetAction(editor.GetType());
if (onSceneGui != null)
{
MethodInfo methodEnabled = editor.GetType().GetMethod(
"IsSceneGUIEnabled",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static |
BindingFlags.FlattenHierarchy,
null,
Type.EmptyTypes,
null);
bool enabled = (methodEnabled != null) ? (bool) methodEnabled.Invoke(null, null) : true;
if (enabled)
{
using (new EditorPerformanceMarker($"Editor.{editor.GetType().Name}.OnSceneGUI", editor.GetType()).Auto())
{
Editor.m_AllowMultiObjectAccess = true;
bool canEditMultipleObjects = editor.canEditMultipleObjects;
for (int n = 0; n < editor.targets.Length; n++)
{
ResetOnSceneGUIState();
editor.referenceTargetIndex = n;
EditorGUI.BeginChangeCheck();
// Ironically, only allow multi object access inside OnSceneGUI if editor does NOT support multi-object editing.
// since there's no harm in going through the serializedObject there if there's always only one target.
Editor.m_AllowMultiObjectAccess = !canEditMultipleObjects;
onSceneGui(editor);
Editor.m_AllowMultiObjectAccess = true;
if (EditorGUI.EndChangeCheck())
editor.serializedObject.SetIsDifferentCacheDirty();
}
ResetOnSceneGUIState();
}
}
// This would mean that OnSceneGUI has changed the scene and it is not drawn
if (s_CurrentDrawingSceneView == null)
GUIUtility.ExitGUI();
}
}
EditorToolManager.InvokeOnSceneGUICustomEditorTools();
}
if (duringSceneGui != null)
{
ResetOnSceneGUIState();
if (duringSceneGui != null)
duringSceneGui(this);
#pragma warning disable 618
if (onSceneGUIDelegate != null)
onSceneGUIDelegate(this);
#pragma warning restore 618
ResetOnSceneGUIState();
}
}
void ResetOnSceneGUIState()
{
Handles.ClearHandles();
HandleUtility.s_CustomPickDistance = HandleUtility.kPickDistance;
EditorGUIUtility.ResetGUIState();
// Don't apply any playmode tinting to scene views
GUI.color = Color.white;
}
void CallOnPreSceneGUI()
{
foreach (Editor editor in activeEditors)
{
// reset the handles matrix, OnPreSceneGUI calls may change it.
Handles.ClearHandles();
// Don't call function for editors whose target's GameObject is not active.
Component comp = editor.target as Component;
if (comp && !comp.gameObject.activeInHierarchy)
continue;
var onPreSceneGui = s_OnPreSceneGuiCache.GetAction(editor.GetType());
if (onPreSceneGui != null)
{
using (new EditorPerformanceMarker($"Editor.{editor.GetType().Name}.OnPreSceneGUI", editor.GetType()).Auto())
{
bool canEditMultipleObjects = editor.canEditMultipleObjects;
Editor.m_AllowMultiObjectAccess = true;
for (int n = 0; n < editor.targets.Length; n++)
{
editor.referenceTargetIndex = n;
// Ironically, only allow multi object access inside OnPreSceneGUI if editor does NOT support multi-object editing.
// since there's no harm in going through the serializedObject there if there's always only one target.
Editor.m_AllowMultiObjectAccess = !canEditMultipleObjects;
onPreSceneGui(editor);
Editor.m_AllowMultiObjectAccess = true;
}
}
}
}
if (beforeSceneGui != null)
{
Handles.ClearHandles();
beforeSceneGui(this);
}
// reset the handles matrix, calls above calls might have changed it
Handles.ClearHandles();
}
internal static void ShowNotification(string notificationText)
{
Object[] allSceneViews = Resources.FindObjectsOfTypeAll(typeof(SceneView));
var notificationViews = new List<EditorWindow>();
foreach (SceneView sceneView in allSceneViews)
{
if (sceneView.m_Parent is DockArea)
{
var dock = (DockArea)sceneView.m_Parent;
if (dock)
{
if (dock.actualView == sceneView)
{
notificationViews.Add(sceneView);
}
}
}
}
if (notificationViews.Count > 0)
{
foreach (EditorWindow notificationView in notificationViews)
notificationView.ShowNotification(GUIContent.Temp(notificationText));
}
else
{
Debug.LogError(notificationText);
}
}
[RequiredByNativeCode]
static void ShowCompileErrorNotification()
{
ShowNotification("All compiler errors have to be fixed before you can enter playmode!");
}
[RequiredByNativeCode]
internal static void ShowSceneViewPlayModeSaveWarning()
{
// In this case, we want to explicitly try the GameView before passing it on to whatever notificationView we have
var playModeView = (PlayModeView)WindowLayout.FindEditorWindowOfType(typeof(PlayModeView));
if (playModeView != null && playModeView.hasFocus)
playModeView.ShowNotification(EditorGUIUtility.TrTextContent("You must exit play mode to save the scene!"));
else
ShowNotification("You must exit play mode to save the scene!");
}
void ResetToDefaults(EditorBehaviorMode behaviorMode)
{
switch (behaviorMode)
{
case EditorBehaviorMode.Mode2D:
m_2DMode = true;
m_Rotation.value = Quaternion.identity;
m_Position.value = kDefaultPivot;
size = kDefaultViewSize;
m_Ortho.value = true;
m_LastSceneViewRotation = kDefaultRotation;
m_LastSceneViewOrtho = false;
break;
default: // Default to 3D mode (BUGFIX:569204)
m_2DMode = false;
m_Rotation.value = kDefaultRotation;
m_Position.value = kDefaultPivot;
size = kDefaultViewSize;
m_Ortho.value = false;
break;
}
}
internal void OnNewProjectLayoutWasCreated()
{
ResetToDefaults(EditorSettings.defaultBehaviorMode);
}
void On2DModeChange()
{
if (m_2DMode)
{
lastSceneViewRotation = m_Rotation.target;
m_LastSceneViewOrtho = orthographic;
LookAt(pivot, Quaternion.identity, size, true);
if (Tools.current == Tool.Move)
Tools.current = Tool.Rect;
}
else
{
LookAt(pivot, lastSceneViewRotation, size, m_LastSceneViewOrtho);
if (Tools.current == Tool.Rect)
Tools.current = Tool.Move;
}
// Let's not persist the vertex snapping mode on 2D/3D mode change
HandleUtility.ignoreRaySnapObjects = null;
Tools.vertexDragging = false;
Tools.handleOffset = Vector3.zero;
}
public static CameraMode AddCameraMode(string name, string section)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("Cannot be null or empty", "name");
if (string.IsNullOrEmpty(section))
throw new ArgumentException("Cannot be null or empty", "section");
var newMode = new CameraMode(DrawCameraMode.UserDefined, name, section);
if (userDefinedModes.Contains(newMode))
throw new InvalidOperationException(string.Format("A mode named {0} already exists in section {1}", name, section));
userDefinedModes.Add(newMode);
return newMode;
}
private static bool IsValidCameraMode(CameraMode cameraMode)
{
foreach (var mode in Enum.GetValues(typeof(DrawCameraMode)))
{
if (SceneRenderModeWindow.DrawCameraModeExists((DrawCameraMode)mode) && cameraMode == GetBuiltinCameraMode((DrawCameraMode)mode))
{
return true;
}
}
foreach (var tempCameraMode in userDefinedModes)
{
if (tempCameraMode == cameraMode)
{
return true;
}
}
return false;
}
public static void ClearUserDefinedCameraModes()
{
userDefinedModes.Clear();
}
public static CameraMode GetBuiltinCameraMode(DrawCameraMode mode)
{
return SceneRenderModeWindow.GetBuiltinCameraMode(mode);
}
internal void RebuildBreadcrumbBar()
{
if (SupportsStageHandling())
m_StageHandling.RebuildBreadcrumbBar();
}
internal static void RebuildBreadcrumbBarInAll()
{
foreach (SceneView sv in s_SceneViews)
{
sv.RebuildBreadcrumbBar();
}
}
internal void ResetGridPivot()
{
sceneViewGrids.SetAllGridsPivot(Vector3.zero);
}
void CopyLastActiveSceneViewSettings()
{
SceneView view = lastActiveSceneView;
m_CameraMode = view.m_CameraMode;
sceneLighting = view.sceneLighting;
m_SceneViewState = new SceneViewState(lastActiveSceneView.m_SceneViewState);
m_CameraSettings = new CameraSettings(lastActiveSceneView.m_CameraSettings);
m_2DMode = view.m_2DMode;
pivot = view.pivot;
if(!m_2DMode)
rotation = view.rotation;
size = view.size;
m_Ortho.value = view.orthographic;
if (m_Grid == null)
m_Grid = new SceneViewGrid();
m_Grid.showGrid = view.showGrid;
}
internal void SetOverlayVisible(string id, bool show)
{
if (TryGetOverlay(id, out Overlay overlay))
overlay.displayed = show;
}
}
} // namespace
| UnityCsReference/Editor/Mono/SceneView/SceneView.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneView/SceneView.cs",
"repo_id": "UnityCsReference",
"token_count": 82957
} | 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 UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.SceneManagement;
using UnityEngine.Scripting;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[NativeClass(null)]
[NativeType(Header = "Editor/Src/SceneVisibility/SceneVisibilityState.h")]
[StaticAccessor("GetSceneVisibilityState()", StaticAccessorType.Dot)]
[ExcludeFromObjectFactory]
[ExcludeFromPreset]
internal class SceneVisibilityState : Object
{
[FreeFunction("GetSceneVisibilityState")]
public static extern Object GetInstance();
public static extern void SetGameObjectHidden([NotNull] GameObject gameObject, bool isHidden, bool includeChildren);
public static extern void SetGameObjectsHidden([NotNull] GameObject[] gameObjects, bool isHidden, bool includeChildren);
public static extern bool IsGameObjectHidden([NotNull] GameObject gameObject);
public static extern bool IsHierarchyHidden([NotNull] GameObject gameObject);
public static extern void SetGameObjectPickingDisabled([NotNull] GameObject gameObject, bool pickingDisabled, bool includeChildren);
public static extern void SetGameObjectsPickingDisabled([NotNull] GameObject[] gameObjects, bool pickingDisabled, bool includeChildren);
public static extern bool IsGameObjectPickingDisabled([NotNull] GameObject gameObject);
public static extern bool IsHierarchyPickingDisabled([NotNull] GameObject gameObject);
public static extern bool AreAllChildrenVisible([NotNull] GameObject gameObject);
public static extern bool IsPickingEnabledOnAllChildren([NotNull] GameObject gameObject);
public static extern bool AreAllChildrenHidden([NotNull] GameObject gameObject);
public static extern bool AreAllRootObjectsHiddenHierarchy(Scene scene);
public static extern bool IsPickingDisabledOnAllChildren([NotNull] GameObject gameObject);
public static extern bool IsPickingDisabledOnAllDescendants(Scene scene);
public static extern void ShowScene(Scene scene);
public static extern void HideScene(Scene scene);
public static extern void EnablePicking(Scene scene);
public static extern void DisablePicking(Scene scene);
public static extern bool HasHiddenGameObjects(Scene scene);
public static extern bool ContainsGameObjectsWithPickingDisabled(Scene scene);
public static extern void ClearScene(Scene scene);
public static extern void OnSceneSaving(Scene scene, string scenePath);
public static extern void GeneratePersistentDataForAllLoadedScenes();
public static extern void GeneratePersistentDataForLoadedScene(Scene scene);
public static extern void OnSceneSaved(Scene scene);
public static extern int GetHiddenObjectCount();
public static extern int GetPickingDisabledObjectCount();
public static extern void ForceDataUpdate();
public static extern void CleanTempScenes();
public static Action internalStructureChanged;
[RequiredByNativeCode]
private static void Internal_InternalStructureChanged()
{
internalStructureChanged?.Invoke();
}
public static extern bool visibilityActive { get; set; }
public static extern bool pickingActive { get; set; }
public static extern bool isolation { get; set; }
}
}
| UnityCsReference/Editor/Mono/SceneVisibility/SceneVisibilityState.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SceneVisibility/SceneVisibilityState.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1137
} | 315 |
// 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.Text.RegularExpressions;
namespace UnityEditor.Scripting.Compilers
{
internal class MicrosoftCSharpCompilerOutputParser : CompilerOutputParserBase
{
public static Regex sCompilerOutput = new Regex(@"(?<filename>.+)(\((?<line>\d+),(?<column>\d+)\)):\s*(?<type>warning|error|info)\s*(?<id>[^:]*):\s*(?<message>.*)", RegexOptions.ExplicitCapture | RegexOptions.Compiled);
protected override bool ShouldParseLine(string line)
{
return line.Contains("warning", StringComparison.Ordinal) ||
line.Contains("error", StringComparison.Ordinal) ||
line.Contains("info", StringComparison.Ordinal);
}
protected override string GetInformationIdentifier()
{
return "info";
}
protected override Regex GetOutputRegex()
{
return sCompilerOutput;
}
protected override string GetErrorIdentifier()
{
return "error";
}
}
}
| UnityCsReference/Editor/Mono/Scripting/Compilers/MicrosoftCSharpCompilerOutputParser.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/Compilers/MicrosoftCSharpCompilerOutputParser.cs",
"repo_id": "UnityCsReference",
"token_count": 489
} | 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 System.Collections.Generic;
using System.Linq;
using static UnityEditor.Scripting.ScriptCompilation.EditorBuildRules;
namespace UnityEditor.Scripting.ScriptCompilation
{
static class AutoReferencedPackageAssemblies
{
static HashSet<string> runtimeAssemblyNames = new HashSet<string>(new[]
{
"UnityEngine.UI.dll",
},
StringComparer.Ordinal);
static HashSet<string> editorAssemblyNames = new HashSet<string>(new[]
{
"UnityEditor.UI.dll",
},
StringComparer.Ordinal);
// Do not add automatic package references to these assemblies,
// as they also add themselves to all .asmdefs
static HashSet<string> ignoreAssemblies = new HashSet<string>(new[]
{
"UnityEngine.TestRunner.dll",
"UnityEditor.TestRunner.dll",
},
StringComparer.Ordinal);
static AutoReferencedPackageAssemblies()
{
editorAssemblyNames.UnionWith(runtimeAssemblyNames);
ignoreAssemblies.UnionWith(editorAssemblyNames);
}
public static void AddReferences(Dictionary<string, TargetAssembly> customTargetAssemblies, EditorScriptCompilationOptions options, Func<TargetAssembly, bool> shouldAdd)
{
if (customTargetAssemblies == null || customTargetAssemblies.Count == 0)
return;
bool buildingForEditor = (options & EditorScriptCompilationOptions.BuildingForEditor) == EditorScriptCompilationOptions.BuildingForEditor;
// Add runtime assembly references for the players and
// runtime and editor assembly references for the editor.
var autoReferencedAssemblies = buildingForEditor ? editorAssemblyNames : runtimeAssemblyNames;
var additionalReferences = new HashSet<TargetAssembly>();
foreach (var assemblyName in autoReferencedAssemblies)
{
TargetAssembly targetAssembly;
// If the automatic referenced package assemblies are in
// the project, then they should be add to all .asmdefs.
if (customTargetAssemblies.TryGetValue(assemblyName, out targetAssembly))
{
additionalReferences.Add(targetAssembly);
}
}
// If none of the automatic references package assemblies are in
// the project, do not add anything.
if (!additionalReferences.Any())
{
return;
}
foreach (var entry in customTargetAssemblies)
{
var assembly = entry.Value;
if (!shouldAdd?.Invoke(assembly) ?? false)
{
continue;
}
// Do not add additional references to any of the
// automatically referenced or ignored assemblies
if (ignoreAssemblies.Contains(assembly.Filename))
continue;
// Add the automatic references.
var newReferences = assembly.References.Concat(additionalReferences).Distinct().ToList();
assembly.References = newReferences;
}
}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/AutoReferencedPackageAssemblies.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/AutoReferencedPackageAssemblies.cs",
"repo_id": "UnityCsReference",
"token_count": 1449
} | 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.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using NiceIO;
using Bee.BeeDriver;
using Bee.BinLog;
using ScriptCompilationBuildProgram.Data;
using Unity.Profiling;
using UnityEditor.Compilation;
using UnityEditor.Modules;
using UnityEditor.Scripting.Compilers;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Profiling;
using CompilerMessage = UnityEditor.Scripting.Compilers.CompilerMessage;
using CompilerMessageType = UnityEditor.Scripting.Compilers.CompilerMessageType;
using Directory = System.IO.Directory;
using File = System.IO.File;
using UnityEditor.Build;
namespace UnityEditor.Scripting.ScriptCompilation
{
internal interface IEditorCompilation
{
PrecompiledAssemblyProviderBase PrecompiledAssemblyProvider { get; set; }
ScriptAssembly[] GetAllScriptAssemblies(
EditorScriptCompilationOptions options,
PrecompiledAssembly[] unityAssembliesArg,
Dictionary<string, PrecompiledAssembly> precompiledAssembliesArg,
string[] defines);
}
class EditorCompilation : IEditorCompilation
{
const int kLogIdentifierFor_EditorMessages = 1234;
const int kLogIdentifierFor_PlayerMessages = 1235;
public enum CompileStatus
{
Idle,
Compiling,
CompilationStarted,
CompilationFailed,
CompilationComplete
}
public enum DeleteFileOptions
{
NoLogError = 0,
LogError = 1,
}
[StructLayout(LayoutKind.Sequential)]
public struct TargetAssemblyInfo
{
public string Name;
public AssemblyFlags Flags;
public static readonly TargetAssemblyInfo Unknown = new TargetAssemblyInfo { Flags = AssemblyFlags.None, Name = null };
}
public struct CustomScriptAssemblyAndReference
{
public CustomScriptAssembly Assembly;
public CustomScriptAssembly Reference;
}
public PrecompiledAssemblyProviderBase PrecompiledAssemblyProvider { get; set; } = new PrecompiledAssemblyProvider();
public ICompilationSetupErrorsTracker CompilationSetupErrorsTracker { get; set; } = new CompilationSetupErrorsTracker();
public ResponseFileProvider ResponseFileProvider { get; set; } = new MicrosoftCSharpResponseFileProvider();
public ILoadingAssemblyDefinition loadingAssemblyDefinition { get; set; } = new LoadingAssemblyDefinition();
public IVersionDefinesConsoleLogs VersionDefinesConsoleLogs { get; set; } = new VersionDefinesConsoleLogs();
public ICompilationSetupWarningTracker CompilationSetupWarningTracker { get; set; } = new CompilationSetupWarningTracker();
public ISafeModeInfo SafeModeInfo { get; set; } = new SafeModeInfo();
public bool EnableDiagnostics => (bool)Debug.GetDiagnosticSwitch("EnableDomainReloadTimings").value;
internal string projectDirectory = string.Empty;
Dictionary<string, string> allScripts = new Dictionary<string, string>();
bool m_ScriptsForEditorHaveBeenCompiledSinceLastDomainReload;
RequestScriptCompilationOptions? m_ScriptCompilationRequest = null;
List<CustomScriptAssemblyReference> customScriptAssemblyReferences = new List<CustomScriptAssemblyReference>();
Dictionary<string, TargetAssembly> customTargetAssemblies = new Dictionary<string, TargetAssembly>(); // TargetAssemblies for customScriptAssemblies.
PrecompiledAssembly[] unityAssemblies;
string outputDirectory;
bool skipCustomScriptAssemblyGraphValidation = false;
[Obsolete]
List<AssemblyBuilder> assemblyBuilders = new List<AssemblyBuilder>();
bool _logCompilationMessages = true;
AssetPathMetaData[] m_AssetPathsMetaData;
Dictionary<string, VersionMetaData> m_VersionMetaDatas;
private readonly CachedVersionRangesFactory<UnityVersion> m_UnityVersionRanges = new CachedVersionRangesFactory<UnityVersion>();
private readonly CachedVersionRangesFactory<SemVersion> m_SemVersionRanges = new CachedVersionRangesFactory<SemVersion>();
public event Action<object> compilationStarted;
public event Action<object> compilationFinished;
public event Action<ScriptAssembly> assemblyCompilationNotRequired;
public event Action<ScriptAssembly, UnityEditor.Compilation.CompilerMessage[]> assemblyCompilationFinished;
class BeeScriptCompilationState
{
public CancellationTokenSource CancellationTokenSource { get; set; }
public ScriptAssembly[] ScriptAssemblies { get; set; }
public ScriptAssemblySettings Settings { get; set; }
public ActiveBuild ActiveBuild { get; set; }
public NPath BeeDriverProfilerFile { get; set; }
public int AsyncProgressBarToken { get; set; }
}
BeeScriptCompilationState _currentBeeScriptCompilationState;
CompilerMessage[] _currentEditorCompilationCompilerMessages = new CompilerMessage[0];
public void SetProjectDirectory(string projectDirectory)
{
this.projectDirectory = projectDirectory;
}
public Exception[] SetAssetPathsMetaData(AssetPathMetaData[] assetPathMetaDatas)
{
m_AssetPathsMetaData = assetPathMetaDatas;
var versionMetaDataComparer = new VersionMetaDataComparer();
m_VersionMetaDatas = assetPathMetaDatas?
.Where(x => x.VersionMetaData != null)
.Select(x => x.VersionMetaData)
.Distinct(versionMetaDataComparer)
.ToDictionary(x => x.Name, x => x);
return UpdateCustomTargetAssembliesAssetPathsMetaData(
loadingAssemblyDefinition.CustomScriptAssemblies,
assetPathMetaDatas,
forceUpdate: true);
}
public void SetAdditionalVersionMetaDatas(VersionMetaData[] versionMetaDatas)
{
Assert.IsTrue(m_VersionMetaDatas != null, "EditorCompilation.SetAssetPathsMetaData() must be called before EditorCompilation.SetAdditionalVersionMetaDatas()");
foreach (var versionMetaData in versionMetaDatas)
{
m_VersionMetaDatas[versionMetaData.Name] = versionMetaData;
}
}
public AssetPathMetaData[] GetAssetPathsMetaData()
{
return m_AssetPathsMetaData;
}
public Dictionary<string, VersionMetaData> GetVersionMetaDatas()
{
return m_VersionMetaDatas;
}
private IAssemblyGraphBuilder GetAssemblyGraphBuilder()
{
return AssemblyGraphBuilderFactory.GetOrCreate(Path.Combine(projectDirectory, "Assets"),
loadingAssemblyDefinition.CustomScriptAssemblies,
loadingAssemblyDefinition.CustomScriptAssemblyReferences);
}
public void SetAllScripts(string[] allScripts)
{
Assert.IsNotNull(customTargetAssemblies);
var graphBuilder = GetAssemblyGraphBuilder();
var graph = graphBuilder.Match(allScripts);
this.allScripts.Clear();
foreach (var assemblyScriptsPair in graph)
{
foreach (var scriptPath in assemblyScriptsPair.Value)
{
this.allScripts.Add(scriptPath, assemblyScriptsPair.Key.Name + ".dll");
}
}
}
public bool HaveScriptsForEditorBeenCompiledSinceLastDomainReload()
{
return m_ScriptsForEditorHaveBeenCompiledSinceLastDomainReload;
}
public void RequestScriptCompilation(string reason = null, RequestScriptCompilationOptions options = RequestScriptCompilationOptions.None)
{
if (reason != null)
{
Console.WriteLine($"[ScriptCompilation] Requested script compilation because: {reason}");
}
PrecompiledAssemblyProvider.Dirty();
m_ScriptCompilationRequest = options;
CancelActiveBuild();
}
internal static void ClearBeeBuildArtifacts()
{
NPath beeFolder = "Library/Bee";
if (beeFolder.DirectoryExists())
{
foreach (var path in beeFolder.Contents()
.Where(p =>
// We should not delete the tundra build state file, as we then lose any information on which files we built.
// This information is used to delete stale output files which are no longer needed. If we delete this file,
// you can end up with old output files included in your builds, which we should not ship with.
p.FileName != "TundraBuildState.state" &&
// If the bee_backend.info file changes, we delete the dag folder (See `UnityBeeDriver.RecreateDagDirectoryIfNeeded`)
// which makes the above not work, unless we also keep this file.
p.FileName != "bee_backend.info"))
path.Delete(DeleteMode.Soft);
}
Mono.Utils.Pram.PramDataDirectory.DeleteIfExists(DeleteMode.Soft);
}
public void SetAllUnityAssemblies(PrecompiledAssembly[] unityAssemblies)
{
this.unityAssemblies = unityAssemblies;
}
// Burst package depends on this method, so we can't remove it.
public void SetCompileScriptsOutputDirectory(string directory)
{
outputDirectory = directory;
}
public string GetCompileScriptsOutputDirectory()
{
if (string.IsNullOrEmpty(outputDirectory))
{
throw new Exception("Must set an output directory through SetCompileScriptsOutputDirectory before compiling");
}
return outputDirectory;
}
//Used by the TestRunner package.
public PrecompiledAssembly[] GetAllPrecompiledAssemblies()
{
return PrecompiledAssemblyProvider.GetPrecompiledAssemblies(
EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingWithAsserts,
EditorUserBuildSettings.activeBuildTarget);
}
public void GetAssemblyDefinitionReferencesWithMissingAssemblies(out List<CustomScriptAssemblyReference> referencesWithMissingAssemblies)
{
var nameLookup = loadingAssemblyDefinition.CustomScriptAssemblies.ToDictionary(x => x.Name);
referencesWithMissingAssemblies = new List<CustomScriptAssemblyReference>();
foreach (var asmref in loadingAssemblyDefinition.CustomScriptAssemblyReferences)
{
if (!nameLookup.ContainsKey(asmref.Reference))
{
referencesWithMissingAssemblies.Add(asmref);
}
}
}
public TargetAssembly GetCustomTargetAssemblyFromName(string name)
{
TargetAssembly targetAssembly;
if (name.EndsWith(".dll", StringComparison.Ordinal))
{
customTargetAssemblies.TryGetValue(name, out targetAssembly);
}
else
{
customTargetAssemblies.TryGetValue(name + ".dll", out targetAssembly);
}
if (targetAssembly == null)
{
throw new ArgumentException("Assembly not found", name);
}
return targetAssembly;
}
public TargetAssemblyInfo[] GetAllCompiledAndResolvedTargetAssemblies(
EditorScriptCompilationOptions options,
BuildTarget buildTarget,
out CustomScriptAssemblyAndReference[] assembliesWithMissingReference)
{
var allTargetAssemblies = GetTargetAssemblies();
var targetAssemblyCompiledPaths = CollectCompiledAssemblies(allTargetAssemblies);
var removedCustomAssemblies = new List<CustomScriptAssemblyAndReference>();
var assembliesWithScripts = GetTargetAssembliesWithScriptsHashSet(options);
bool removed;
do
{
removed = false;
if (targetAssemblyCompiledPaths.Count <= 0)
{
continue;
}
foreach (var assembly in allTargetAssemblies)
{
if (!targetAssemblyCompiledPaths.ContainsKey(assembly))
{
continue;
}
removed = VerifyReferencesIsCompiled(options, buildTarget, assembly, assembliesWithScripts, targetAssemblyCompiledPaths, removedCustomAssemblies, removed);
}
}
while (removed);
var count = targetAssemblyCompiledPaths.Count;
var targetAssemblies = new TargetAssemblyInfo[count];
int index = 0;
foreach (var entry in targetAssemblyCompiledPaths)
{
var assembly = entry.Key;
targetAssemblies[index++] = ToTargetAssemblyInfo(assembly);
}
assembliesWithMissingReference = removedCustomAssemblies.ToArray();
return targetAssemblies;
}
/// <returns>A map of all target assemblies that exists on disk and their full path</returns>
Dictionary<TargetAssembly, string> CollectCompiledAssemblies(TargetAssembly[] allTargetAssemblies)
{
var targetAssemblyCompiledPaths = new Dictionary<TargetAssembly, string>();
foreach (var assembly in allTargetAssemblies)
{
var path = assembly.FullPath(outputDirectory);
if (File.Exists(path))
{
targetAssemblyCompiledPaths.Add(assembly, path);
}
}
return targetAssemblyCompiledPaths;
}
/// <summary>
/// Check for each compiled assembly that all its references have also been compiled.
/// If not, remove it from the list of compiled assemblies.
/// We update the removedCustomAssemblies with the assembly and the removed reference.
///
/// References that are not compatible with the current build target, will not be checked as these haven't been compiled.
/// The same is true if the reference does not have any scripts,
/// or if the compiled assembly type is undefined or predefined
/// </summary>
/// <returns>Whether a reference was removed</returns>
bool VerifyReferencesIsCompiled(
EditorScriptCompilationOptions options,
BuildTarget buildTarget,
TargetAssembly assembly,
HashSet<TargetAssembly> assembliesWithScripts,
Dictionary<TargetAssembly, string> targetAssemblyCompiledPaths,
List<CustomScriptAssemblyAndReference> removedCustomAssemblies,
bool removed)
{
foreach (var reference in assembly.References)
{
if (!EditorBuildRules.IsCompatibleWithPlatformAndDefines(reference, buildTarget, options))
{
continue;
}
if (!assembliesWithScripts.Contains(reference))
{
continue;
}
if (assembly.Type == TargetAssemblyType.Predefined
|| assembly.Type == TargetAssemblyType.Undefined
|| targetAssemblyCompiledPaths.ContainsKey(reference))
{
continue;
}
targetAssemblyCompiledPaths.Remove(assembly);
var removedAssemblyAndReference = new CustomScriptAssemblyAndReference
{
Assembly = FindCustomTargetAssemblyFromTargetAssembly(assembly),
Reference = FindCustomTargetAssemblyFromTargetAssembly(reference)
};
removedCustomAssemblies.Add(removedAssemblyAndReference);
removed = true;
break;
}
return removed;
}
public static Exception[] UpdateCustomScriptAssemblies(CustomScriptAssembly[] customScriptAssemblies,
List<CustomScriptAssemblyReference> customScriptAssemblyReferences,
AssetPathMetaData[] assetPathsMetaData,
ResponseFileProvider responseFileProvider)
{
var asmrefLookup = customScriptAssemblyReferences.ToLookup(x => x.Reference);
AddAdditionalPrefixes(customScriptAssemblies, asmrefLookup);
UpdateCustomTargetAssembliesResponseFileData(customScriptAssemblies, responseFileProvider);
return UpdateCustomTargetAssembliesAssetPathsMetaData(customScriptAssemblies, assetPathsMetaData);
}
/// <summary>
/// Assign the found references or null.
/// We need to assign null so as not to hold onto references that may have been removed/changed.
/// </summary>
static void AddAdditionalPrefixes(CustomScriptAssembly[] customScriptAssemblies, ILookup<string, CustomScriptAssemblyReference> asmrefLookup)
{
foreach (var assembly in customScriptAssemblies)
{
var foundAsmRefs = asmrefLookup[assembly.Name];
assembly.AdditionalPrefixes = foundAsmRefs.Any() ? foundAsmRefs.Select(ar => ar.PathPrefix).ToArray() : null;
}
}
static void UpdateCustomTargetAssembliesResponseFileData(CustomScriptAssembly[] customScriptAssemblies, ResponseFileProvider responseFileProvider)
{
foreach (var assembly in customScriptAssemblies)
{
string rspFile = responseFileProvider.Get(assembly.PathPrefix)
.SingleOrDefault();
if (!string.IsNullOrEmpty(rspFile))
{
var responseFileContent = MicrosoftResponseFileParser.GetResponseFileContent(Directory.GetParent(Application.dataPath).FullName, rspFile);
var compilerOptions = MicrosoftResponseFileParser.GetCompilerOptions(responseFileContent);
assembly.ResponseFileDefines = MicrosoftResponseFileParser.GetDefines(compilerOptions).ToArray();
}
}
}
static Exception[] UpdateCustomTargetAssembliesAssetPathsMetaData(
CustomScriptAssembly[] customScriptAssemblies,
AssetPathMetaData[] assetPathsMetaData,
bool forceUpdate = false)
{
if (assetPathsMetaData == null)
{
return new Exception[0];
}
var assetMetaDataPaths = new string[assetPathsMetaData.Length];
var lowerAssetMetaDataPaths = new string[assetPathsMetaData.Length];
for (int i = 0; i < assetPathsMetaData.Length; ++i)
{
var assetPathMetaData = assetPathsMetaData[i];
assetMetaDataPaths[i] = AssetPath.ReplaceSeparators(assetPathMetaData.DirectoryPath + AssetPath.Separator);
lowerAssetMetaDataPaths[i] = Utility.FastToLower(assetMetaDataPaths[i]);
}
var exceptions = new List<Exception>();
foreach (var assembly in customScriptAssemblies)
{
if (assembly.AssetPathMetaData != null && !forceUpdate)
{
continue;
}
try
{
for (int i = 0; i < assetMetaDataPaths.Length; ++i)
{
var path = assetMetaDataPaths[i];
var lowerPath = lowerAssetMetaDataPaths[i];
if (Utility.FastStartsWith(assembly.PathPrefix, path, lowerPath))
{
assembly.AssetPathMetaData = assetPathsMetaData[i];
break;
}
}
}
catch (Exception e)
{
exceptions.Add(e);
}
}
return exceptions.ToArray();
}
Exception[] UpdateCustomTargetAssemblies()
{
var exceptions = UpdateCustomScriptAssemblies(
loadingAssemblyDefinition.CustomScriptAssemblies,
loadingAssemblyDefinition.CustomScriptAssemblyReferences,
m_AssetPathsMetaData,
ResponseFileProvider);
if (exceptions.Length > 0)
{
CompilationSetupErrorsTracker.SetCompilationSetupErrors(CompilationSetupErrors.LoadError);
}
customTargetAssemblies = EditorBuildRules.CreateTargetAssemblies(loadingAssemblyDefinition.CustomScriptAssemblies);
return exceptions;
}
public void SkipCustomScriptAssemblyGraphValidation(bool skipChecks)
{
// If we have successfully compiled and reloaded all assemblies, then we can skip asmdef compilation graph checks
// for setup errors like cyclic references, self-references, duplicate assembly names, etc.
// If there is compilation errors in a Safe Mode domain or a partially loaded domain (when SafeMode is forcefully exited),
// then we need to keep the graph validation checks to rediscover potential setup errors in subsequent compilations.
skipCustomScriptAssemblyGraphValidation = skipChecks;
}
public IEnumerable<Exception> SetAllCustomScriptAssemblyReferenceJsons(string[] paths)
{
return SetAllCustomScriptAssemblyReferenceJsonsContents(paths, null);
}
public IEnumerable<Exception> SetAllCustomScriptAssemblyReferenceJsonsContents(string[] paths, string[] contents)
{
RefreshLoadingAssemblyDefinition();
loadingAssemblyDefinition.SetAllCustomScriptAssemblyReferenceJsonsContents(paths, contents);
var updateExceptions = UpdateCustomTargetAssemblies();
return loadingAssemblyDefinition.Exceptions.Concat(updateExceptions);
}
public IEnumerable<Exception> SetAllCustomScriptAssemblyJsons(string[] paths, string[] guids)
{
return SetAllCustomScriptAssemblyJsonContents(paths, null, guids);
}
public IEnumerable<Exception> SetAllCustomScriptAssemblyJsonContents(string[] paths, string[] contents, string[] guids)
{
RefreshLoadingAssemblyDefinition();
loadingAssemblyDefinition.SetAllCustomScriptAssemblyJsonContents(paths, contents, guids);
var updateExceptions = UpdateCustomTargetAssemblies();
return loadingAssemblyDefinition.Exceptions.Concat(updateExceptions);
}
void RefreshLoadingAssemblyDefinition()
{
loadingAssemblyDefinition.Refresh(
CompilationSetupErrorsTracker,
skipCustomScriptAssemblyGraphValidation,
projectDirectory);
}
public void ClearCustomScriptAssemblies()
{
loadingAssemblyDefinition.ClearCustomScriptAssemblies();
}
public bool IsPathInPackageDirectory(string path)
{
if (m_AssetPathsMetaData == null)
{
return false;
}
return m_AssetPathsMetaData.Any(p => path.StartsWith(p.DirectoryPath, StringComparison.OrdinalIgnoreCase));
}
public void DeleteScriptAssemblies()
{
NPath fullEditorAssemblyPath = AssetPath.Combine(projectDirectory, GetCompileScriptsOutputDirectory());
fullEditorAssemblyPath.DeleteIfExists(DeleteMode.Soft);
}
public bool TryFindCustomScriptAssemblyFromAssemblyName(string assemblyName, out CustomScriptAssembly customScriptAssembly)
{
assemblyName = AssetPath.GetAssemblyNameWithoutExtension(assemblyName);
if (loadingAssemblyDefinition.CustomScriptAssemblies == null)
{
customScriptAssembly = null;
return false;
}
foreach (var assembly in loadingAssemblyDefinition.CustomScriptAssemblies)
{
if (assembly.Name != assemblyName)
{
continue;
}
customScriptAssembly = assembly;
return true;
}
customScriptAssembly = null;
return false;
}
public CustomScriptAssembly FindCustomScriptAssemblyFromAssemblyName(string assemblyName)
{
if (TryFindCustomScriptAssemblyFromAssemblyName(assemblyName, out CustomScriptAssembly customScriptAssembly))
{
return customScriptAssembly;
}
assemblyName = AssetPath.GetAssemblyNameWithoutExtension(assemblyName);
var result = loadingAssemblyDefinition.CustomScriptAssemblies?.FirstOrDefault(a => a.Name == assemblyName);
if (result != null)
{
return result;
}
var exceptionMessage = "Cannot find CustomScriptAssembly with name '" + assemblyName + "'.";
if (loadingAssemblyDefinition.CustomScriptAssemblies == null)
{
exceptionMessage += " customScriptAssemblies is null.";
}
else
{
var assemblyNames = loadingAssemblyDefinition.CustomScriptAssemblies.Select(a => a.Name);
var assemblyNamesString = string.Join(", ", assemblyNames);
exceptionMessage += " Assembly names: " + assemblyNamesString;
}
throw new InvalidOperationException(exceptionMessage);
}
public bool TryFindCustomScriptAssemblyFromScriptPath(string scriptPath, out CustomScriptAssembly customScriptAssembly)
{
var fullPath = AssetPath.IsPathRooted(scriptPath)
? AssetPath.GetFullPath(scriptPath)
: AssetPath.Combine(projectDirectory, scriptPath);
var assemblyGraphBuilder = GetAssemblyGraphBuilder();
var dictionary = assemblyGraphBuilder.Match(new []{fullPath});
customScriptAssembly = dictionary.Keys.SingleOrDefault();;
if (customScriptAssembly is {IsPredefined: true})
customScriptAssembly = null;
return customScriptAssembly != null;
}
public CustomScriptAssembly FindCustomScriptAssemblyFromScriptPath(string scriptPath)
{
var fullPath = AssetPath.IsPathRooted(scriptPath)
? AssetPath.GetFullPath(scriptPath)
: AssetPath.Combine(projectDirectory, scriptPath);
var foundCustomScriptAssemblies = GetAssemblyGraphBuilder().Match(new []{fullPath});
return foundCustomScriptAssemblies.SingleOrDefault().Key;
}
public CustomScriptAssembly FindCustomTargetAssemblyFromTargetAssembly(TargetAssembly assembly)
{
var assemblyName = AssetPath.GetAssemblyNameWithoutExtension(assembly.Filename);
return FindCustomScriptAssemblyFromAssemblyName(assemblyName);
}
public bool TryFindCustomScriptAssemblyFromAssemblyReference(string reference, out CustomScriptAssembly customScriptAssembly)
{
if (!GUIDReference.IsGUIDReference(reference))
{
return TryFindCustomScriptAssemblyFromAssemblyName(reference, out customScriptAssembly);
}
if (loadingAssemblyDefinition.CustomScriptAssemblies != null)
{
var guid = GUIDReference.GUIDReferenceToGUID(reference);
var result = loadingAssemblyDefinition.CustomScriptAssemblies.FirstOrDefault(a => string.Equals(a.GUID, guid, StringComparison.OrdinalIgnoreCase));
if (result != null)
{
customScriptAssembly = result;
return true;
}
}
customScriptAssembly = null;
return false;
}
public CustomScriptAssembly FindCustomScriptAssemblyFromAssemblyReference(string reference)
{
if (TryFindCustomScriptAssemblyFromAssemblyReference(reference, out CustomScriptAssembly customScriptAssembly))
{
return customScriptAssembly;
}
throw new InvalidOperationException($"Cannot find CustomScriptAssembly with reference '{reference}'");
}
public CompileStatus CompileScripts(
EditorScriptCompilationOptions editorScriptCompilationOptions,
BuildTarget platform,
int subtarget,
string[] extraScriptingDefines
)
{
var scriptAssemblySettings = CreateScriptAssemblySettings(platform, subtarget, editorScriptCompilationOptions, extraScriptingDefines);
CompileStatus compilationResult;
using (new ProfilerMarker("Initiating Script Compilation").Auto())
{
compilationResult = CompileScriptsWithSettings(scriptAssemblySettings);
}
return compilationResult;
}
static string PDBPath(string dllPath)
{
return dllPath.Replace(".dll", ".pdb");
}
static string MDBPath(string dllPath)
{
return dllPath + ".mdb";
}
// Delete all .dll's that aren't used anymore
public void DeleteUnusedAssemblies(ScriptAssemblySettings settings)
{
string fullEditorAssemblyPath = AssetPath.Combine(projectDirectory, GetCompileScriptsOutputDirectory());
if (!Directory.Exists(fullEditorAssemblyPath))
{
return;
}
var deleteFiles = Directory.GetFiles(fullEditorAssemblyPath).Select(AssetPath.ReplaceSeparators).ToList();
var targetAssemblies = GetTargetAssembliesWithScripts(settings);
foreach (var assembly in targetAssemblies)
{
string path = AssetPath.Combine(fullEditorAssemblyPath, assembly.Name);
deleteFiles.Remove(path);
deleteFiles.Remove(MDBPath(path));
deleteFiles.Remove(PDBPath(path));
}
foreach (var path in deleteFiles)
{
path.ToNPath().Delete(DeleteMode.Soft);
}
}
void CancelActiveBuild()
{
_currentBeeScriptCompilationState?.CancellationTokenSource.Cancel();
}
void WarnIfThereAreAssembliesWithoutAnyScripts(ScriptAssemblySettings scriptAssemblySettings, ScriptAssembly[] scriptAssemblies)
{
foreach (var targetAssembly in customTargetAssemblies.Values)
{
if (!EditorBuildRules.IsCompatibleWithPlatformAndDefines(targetAssembly, scriptAssemblySettings))
{
continue;
}
if (scriptAssemblies.Any(s => s.Filename == targetAssembly.Filename))
{
continue;
}
var customTargetAssembly = FindCustomTargetAssemblyFromTargetAssembly(targetAssembly);
Debug.LogWarningFormat(
"Assembly for Assembly Definition File '{0}' will not be compiled, because it has no scripts associated with it.",
customTargetAssembly.FilePath);
}
}
public IEnumerable<string> GetScriptsThatDoNotBelongToAnyAssembly()
{
return allScripts
.Where(e => EditorBuildRules.GetTargetAssembly(e.Key, e.Value, projectDirectory, customTargetAssemblies) == null)
.Select(e => e.Key);
}
static TargetAssembly[] GetPredefinedAssemblyReferences(IDictionary<string, TargetAssembly> targetAssemblies)
{
var targetAssembliesResult = targetAssemblies.Values
.Where(x => (x.Flags & AssemblyFlags.ExplicitlyReferenced) == AssemblyFlags.None)
.ToArray();
return targetAssembliesResult;
}
public CompileStatus CompileScriptsWithSettings(ScriptAssemblySettings scriptAssemblySettings)
{
if (m_ScriptCompilationRequest == RequestScriptCompilationOptions.CleanBuildCache)
scriptAssemblySettings.CompilationOptions |= EditorScriptCompilationOptions.BuildingCleanCompilation;
if (scriptAssemblySettings.CompilationOptions.HasFlag(EditorScriptCompilationOptions.BuildingCleanCompilation))
ClearBeeBuildArtifacts();
m_ScriptCompilationRequest = null;
DeleteUnusedAssemblies(scriptAssemblySettings);
VersionDefinesConsoleLogs?.ClearVersionDefineErrors();
m_UnityVersionRanges.Clear();
m_SemVersionRanges.Clear();
ScriptAssembly[] scriptAssemblies;
if (scriptAssemblySettings.CompilationOptions.HasFlag(EditorScriptCompilationOptions.BuildingSkipCompile))
scriptAssemblies = Array.Empty<ScriptAssembly>();
else
{
CompilationSetupWarningTracker.ClearAssetWarnings();
scriptAssemblies = GetAllScriptAssembliesOfType(scriptAssemblySettings,
TargetAssemblyType.Undefined, CompilationSetupWarningTracker);
}
// Do no start compilation if there is an setup error.
if (CompilationSetupErrorsTracker.HaveCompilationSetupErrors())
{
return CompileStatus.Idle;
}
if ((scriptAssemblySettings.CompilationOptions & EditorScriptCompilationOptions.BuildingSkipCompile) == 0)
WarnIfThereAreAssembliesWithoutAnyScripts(scriptAssemblySettings, scriptAssemblies);
var debug = scriptAssemblySettings.CodeOptimization == CodeOptimization.Debug;
//we're going to hash the output directory path into the dag name. We do this because when users build players into different directories,
//we'd like to treat those as different dags. If we wouldn't do this, you could run into situations where building into directory2 will make
//bee delete the previously built game from directory1.
Hash128 hash = Hash128.Parse(scriptAssemblySettings.OutputDirectory);
var config =
hash.ToString().Substring(0, 5) +
$"{(scriptAssemblySettings.BuildingForEditor ? "E" : "P")}" +
$"{(scriptAssemblySettings.BuildingDevelopmentBuild ? "Dev" : "")}" +
$"{(debug ? "Dbg" : "")}" +
$"{(scriptAssemblySettings.CompilationOptions.HasFlag(EditorScriptCompilationOptions.BuildingSkipCompile) ? "SkipCompile" : "")}";
BuildTarget buildTarget = scriptAssemblySettings.BuildTarget;
var cacheMode = scriptAssemblySettings.CompilationOptions.HasFlag(EditorScriptCompilationOptions.BuildingCleanCompilation)
? UnityBeeDriver.CacheMode.WriteOnly
: UnityBeeDriver.CacheMode.ReadWrite;
var buildRequest = UnityBeeDriver.BuildRequestFor(ScriptCompilationBuildProgram, this, $"{(int)buildTarget}{config}", cacheMode, useScriptUpdater: !scriptAssemblySettings.BuildingWithoutScriptUpdater);
buildRequest.DeferDagVerification = true;
buildRequest.ContinueBuildingAfterFirstFailure = true;
buildRequest.Target = scriptAssemblySettings.CompilationOptions.HasFlag(EditorScriptCompilationOptions.BuildingExtractTypeDB)
? Constants.ScriptAssembliesAndTypeDBTarget
: Constants.ScriptAssembliesTarget;
buildRequest.DataForBuildProgram.Add(() => BeeScriptCompilation.ScriptCompilationDataFor(
this,
scriptAssemblies,
debug,
scriptAssemblySettings.OutputDirectory,
buildTarget,
scriptAssemblySettings.BuildingForEditor,
!scriptAssemblySettings.BuildingWithoutScriptUpdater));
var cts = new CancellationTokenSource();
var activeBeeBuild = BeeDriver.BuildAsync(buildRequest, cts.Token);
_currentBeeScriptCompilationState = new BeeScriptCompilationState()
{
ActiveBuild = activeBeeBuild,
CancellationTokenSource = cts,
ScriptAssemblies = scriptAssemblies,
Settings = scriptAssemblySettings,
BeeDriverProfilerFile = buildRequest.ProfilerOutputFile,
AsyncProgressBarToken = Progress.Start("Compiling Scripts")
};
InvokeCompilationStarted(activeBeeBuild);
return CompileStatus.CompilationStarted;
}
public static RunnableProgram ScriptCompilationBuildProgram { get; } = MakeScriptCompilationBuildProgram();
static RunnableProgram MakeScriptCompilationBuildProgram()
{
var buildProgramAssembly = new NPath($"{EditorApplication.applicationContentsPath}/Tools/BuildPipeline/ScriptCompilationBuildProgram.exe");
return new SystemProcessRunnableProgram($"{EditorApplication.applicationContentsPath}/Tools/netcorerun/netcorerun{BeeScriptCompilation.ExecutableExtension}", new[] {buildProgramAssembly.InQuotes(SlashMode.Native)}, new () {{ "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", "1" }}
);
}
public void InvokeCompilationStarted(object context)
{
compilationStarted?.Invoke(context);
}
public void InvokeCompilationFinished(object context)
{
compilationFinished?.Invoke(context);
}
public bool DoesProjectFolderHaveAnyScripts()
{
return allScripts != null && allScripts.Count > 0;
}
public ScriptAssemblySettings CreateScriptAssemblySettings(BuildTarget buildTarget, EditorScriptCompilationOptions options)
{
return CreateScriptAssemblySettings(buildTarget, EditorUserBuildSettings.GetActiveSubtargetFor(buildTarget), options, new string[] { });
}
public ScriptAssemblySettings CreateScriptAssemblySettings(BuildTarget buildTarget, int subtarget, EditorScriptCompilationOptions options)
{
return CreateScriptAssemblySettings(buildTarget, subtarget, options, new string[] { });
}
public ScriptAssemblySettings CreateScriptAssemblySettings(BuildTarget buildTarget, EditorScriptCompilationOptions options, string[] extraScriptingDefines)
{
return CreateScriptAssemblySettings(buildTarget, EditorUserBuildSettings.GetActiveSubtargetFor(buildTarget), options, extraScriptingDefines);
}
public ScriptAssemblySettings CreateScriptAssemblySettings(BuildTarget buildTarget, int subtarget, EditorScriptCompilationOptions options, string[] extraScriptingDefines)
{
var predefinedAssembliesCompilerOptions = new ScriptCompilerOptions();
var namedBuildTarget = NamedBuildTarget.FromActiveSettings(buildTarget);
if ((options & EditorScriptCompilationOptions.BuildingPredefinedAssembliesAllowUnsafeCode) == EditorScriptCompilationOptions.BuildingPredefinedAssembliesAllowUnsafeCode)
{
predefinedAssembliesCompilerOptions.AllowUnsafeCode = true;
}
if ((options & EditorScriptCompilationOptions.BuildingUseDeterministicCompilation) == EditorScriptCompilationOptions.BuildingUseDeterministicCompilation)
{
predefinedAssembliesCompilerOptions.UseDeterministicCompilation = true;
}
predefinedAssembliesCompilerOptions.ApiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(namedBuildTarget);
ICompilationExtension compilationExtension = null;
if ((options & EditorScriptCompilationOptions.BuildingForEditor) == 0)
{
compilationExtension = ModuleManager.FindPlatformSupportModule(ModuleManager.GetTargetStringFromBuildTarget(buildTarget))?.CreateCompilationExtension();
}
List<string> additionalCompilationArguments = new List<string>(PlayerSettings.GetAdditionalCompilerArguments(namedBuildTarget));
if (PlayerSettings.suppressCommonWarnings)
{
additionalCompilationArguments.Add("/nowarn:0169");
additionalCompilationArguments.Add("/nowarn:0649");
additionalCompilationArguments.Add("/nowarn:0282");
// The msbuild tool disables warnings 1701 and 1702 by default, so Unity should do the same.
additionalCompilationArguments.Add("/nowarn:1701");
additionalCompilationArguments.Add("/nowarn:1702");
}
var additionalCompilationArgumentsArray = additionalCompilationArguments.Where(s => !string.IsNullOrEmpty(s)).Distinct().ToArray();
var settings = new ScriptAssemblySettings
{
BuildTarget = buildTarget,
Subtarget = subtarget,
OutputDirectory = GetCompileScriptsOutputDirectory(),
CompilationOptions = options,
PredefinedAssembliesCompilerOptions = predefinedAssembliesCompilerOptions,
CompilationExtension = compilationExtension,
EditorCodeOptimization = CompilationPipeline.codeOptimization,
ExtraGeneralDefines = extraScriptingDefines,
ProjectRootNamespace = EditorSettings.projectGenerationRootNamespace,
ProjectDirectory = projectDirectory,
AdditionalCompilerArguments = additionalCompilationArgumentsArray
};
return settings;
}
ScriptAssemblySettings CreateEditorScriptAssemblySettings(EditorScriptCompilationOptions options)
{
return CreateScriptAssemblySettings(EditorUserBuildSettings.activeBuildTarget, options);
}
//only used in for tests to peek in.
public CompilerMessage[] GetCompileMessages() => _currentEditorCompilationCompilerMessages;
public bool IsScriptCompilationRequested()
{
return m_ScriptCompilationRequest != null;
}
[Obsolete]
public bool IsAnyAssemblyBuilderCompiling()
{
if (assemblyBuilders.Count <= 0)
{
return false;
}
var isCompiling = false;
var removeAssemblyBuilders = new HashSet<AssemblyBuilder>();
// Check status of compile tasks
foreach (var assemblyBuilder in assemblyBuilders)
{
switch (assemblyBuilder.status)
{
case AssemblyBuilderStatus.IsCompiling:
isCompiling = true;
break;
case AssemblyBuilderStatus.Finished:
removeAssemblyBuilders.Add(assemblyBuilder);
break;
case AssemblyBuilderStatus.NotStarted:
break;
default:
throw new ArgumentOutOfRangeException($"Unknown builder status: {assemblyBuilder.status}");
}
}
// Remove all compile tasks that finished compiling.
if (removeAssemblyBuilders.Count > 0)
{
assemblyBuilders.RemoveAll(t => removeAssemblyBuilders.Contains(t));
}
return isCompiling;
}
public bool IsCompiling()
{
// Native code expects IsCompiling to be true after requesting a script reload,
// therefore return true if the compilation is pending
#pragma warning disable CS0612 // Type or member is obsolete
return IsCompilationTaskCompiling() || IsScriptCompilationRequested() || IsAnyAssemblyBuilderCompiling();
#pragma warning restore CS0612 // Type or member is obsolete
}
public bool IsCompilationTaskCompiling()
{
return _currentBeeScriptCompilationState != null;
}
public CompileStatus TickCompilationPipeline(EditorScriptCompilationOptions options, BuildTarget platform, int subtarget, string[] extraScriptingDefines, bool allowBlocking)
{
// Return CompileStatus.Compiling if any compile task is still compiling.
// This ensures that the compile tasks finish compiling before any
// scripts in the Assets folder are compiled and a domain reload
// is triggered.
#pragma warning disable CS0612 // Type or member is obsolete
if (IsAnyAssemblyBuilderCompiling())
{
return CompileStatus.Compiling;
}
#pragma warning restore CS0612 // Type or member is obsolete
// If we are not currently compiling and there are new dirty assemblies, start compilation.
if (!IsCompilationTaskCompiling() && IsScriptCompilationRequested())
{
Profiler.BeginSample("CompilationPipeline.CompileScripts");
CompileStatus compileStatus;
try
{
compileStatus = CompileScripts(options, platform, subtarget, extraScriptingDefines);
}
finally
{
Profiler.EndSample();
}
if (allowBlocking)
return TickCompilationPipeline(options, platform, subtarget, extraScriptingDefines, allowBlocking);
return compileStatus;
}
if (_currentBeeScriptCompilationState == null)
{
return CompileStatus.Idle;
}
var scriptCompilationState = _currentBeeScriptCompilationState;
var activeBuild = scriptCompilationState.ActiveBuild;
var activeBuildTaskObject = activeBuild.TaskObject;
if (!activeBuildTaskObject.IsCompleted)
{
if (!allowBlocking)
{
Progress.SetDescription(scriptCompilationState.AsyncProgressBarToken, activeBuild.Status.Description);
return CompileStatus.Compiling;
}
CompleteActiveBuildWhilePumping();
}
// At this point we know we completed the build - successfully or not
_currentBeeScriptCompilationState = null;
UnityBeeDriver.RunCleanBeeCache();
Progress.Finish(scriptCompilationState.AsyncProgressBarToken);
if (activeBuildTaskObject.IsCanceled || activeBuildTaskObject.IsFaulted)
{
if (activeBuildTaskObject.IsFaulted)
Debug.LogError("Internal BuildSystem Error: " + activeBuildTaskObject.Exception);
return CompileStatus.CompilationFailed;
}
BeeDriverResult result = activeBuildTaskObject.Result;
if (!result.Success)
{
foreach (var msg in result.NodeFinishedMessages)
if (msg.ExitCode != 0)
{
Console.WriteLine($"## Script Compilation Error for: {msg.Node.Annotation}");
Console.WriteLine($"## CmdLine: {msg.CmdLine}");
Console.WriteLine($"## Output:");
Console.WriteLine(msg.Output);
}
}
var messagesForNodeResults = ProcessCompilationResult(scriptCompilationState.ScriptAssemblies, result, scriptCompilationState.Settings.BuildingForEditor, scriptCompilationState.ActiveBuild);
var compilerMessages = messagesForNodeResults.SelectMany(a => a).ToArray();
int logIdentifier = scriptCompilationState.Settings.BuildingForEditor
//these numbers are "randomly picked". they are used to so that when you log a message with a certain identifier, later all messages with that identifier can be cleared.
//one means "compilation error for compiling-assemblies-for-editor" the other means "compilation error for building a player".
? kLogIdentifierFor_EditorMessages
: kLogIdentifierFor_PlayerMessages;
var buildingForEditor = scriptCompilationState.Settings.BuildingForEditor;
if (buildingForEditor)
{
_currentEditorCompilationCompilerMessages = compilerMessages;
}
if (_logCompilationMessages)
{
LogCompilerMessages(logIdentifier, compilerMessages, buildingForEditor);
}
result.ProfileOutputWritingTask?.Wait();
return result.Success
? CompileStatus.CompilationComplete
: CompileStatus.CompilationFailed;
}
private static void LogCompilerMessages(int logIdentifier, IEnumerable<CompilerMessage> compilerMessages, bool buildingForEditor)
{
Debug.RemoveLogEntriesByIdentifier(logIdentifier);
var fileInstanceIdCache = new Dictionary<string, int>();
foreach (var message in compilerMessages)
{
if (message.type == CompilerMessageType.Information)
{
// ensure that we don't emit info messages (user cannot do anything with these and they are generated by DiagnosticSuppressors)
continue;
}
// the instance id identifies an asset in the project window, used for pinging the asset when double clicking on a log message with a compilation error
var instanceId = LookupInstanceId(fileInstanceIdCache, message.file);
Debug.LogCompilerMessage(message.message, message.file, message.line, message.column,
buildingForEditor, message.type == CompilerMessageType.Error, logIdentifier, instanceId);
}
}
private static int LookupInstanceId(IDictionary<string, int> fileInstanceIdCache, string filePath)
{
// in batch mode, we don't have a Console Window, so we don't need an instance id
if (Application.isBatchMode || string.IsNullOrEmpty(filePath))
{
return 0;
}
if (fileInstanceIdCache.TryGetValue(filePath, out var instanceId))
{
return instanceId;
}
// The AssetDatabase does not expect absolute paths. In this case, we
// try to get the Logical path for the supplied filePath and pass that along
var logicalFilePath = FileUtil.GetLogicalPath(filePath);
if (string.IsNullOrEmpty(logicalFilePath))
{
return 0;
}
var guid = AssetDatabase.GUIDFromAssetPath(logicalFilePath);
// script compilation errors can happen before the asset database is initialized, so we reserve the instance id ahead of time (it is deterministic)
instanceId = AssetDatabase.ReserveMonoScriptInstanceID(guid);
fileInstanceIdCache.Add(filePath, instanceId);
return instanceId;
}
void CompleteActiveBuildWhilePumping()
{
var synchroContext = (UnitySynchronizationContext) SynchronizationContext.Current;
var activeBuild = _currentBeeScriptCompilationState.ActiveBuild;
while (true)
{
var activeBuildStatus = activeBuild.Status;
float progress = activeBuildStatus.Progress.HasValue
? activeBuildStatus.Progress.Value.nodesFinishedOrUpToDate / (float) activeBuildStatus.Progress.Value.totalNodesQeueued
: 0f;
if (EditorUtility.DisplayCancelableProgressBar("Compiling Scripts", activeBuildStatus.Description, progress))
{
EditorUtility.DisplayCancelableProgressBar("Compiling Scripts", "Canceling compilation", 1.0f);
_currentBeeScriptCompilationState.CancellationTokenSource.Cancel();
}
try
{
activeBuild.TaskObject.Wait(100);
}
catch (AggregateException)
{
// ignored
}
if (activeBuild.TaskObject.IsCompleted)
return;
synchroContext.Exec();
}
}
public void DisableLoggingEditorCompilerMessages()
{
_logCompilationMessages = false;
}
public CompilerMessage[][] ProcessCompilationResult(ScriptAssembly[] assemblies, BeeDriverResult result, bool buildingForEditor, object context)
{
var compilerMessagesForNodeResults = BeeScriptCompilation.ParseAllNodeResultsIntoCompilerMessages(result.BeeDriverMessages, result.NodeFinishedMessages, this);
InvokeAssemblyCompilationFinished(assemblies, result, buildingForEditor, compilerMessagesForNodeResults);
InvokeCompilationFinished(context);
return compilerMessagesForNodeResults;
}
void InvokeAssemblyCompilationFinished(ScriptAssembly[] assemblies, BeeDriverResult beeDriverResult, bool buildingForEditor, CompilerMessage[][] compilerMessagesForNodeResults)
{
var relatedMessages = new Dictionary<string, List<int>>();
var requiresCallbackInvocation = new HashSet<string>();
for (int i = 0; i < beeDriverResult.NodeFinishedMessages.Length; i++)
{
var msg = beeDriverResult.NodeFinishedMessages[i];
string filePath = new NPath(msg.Node.OutputFile).FileName;
if (!relatedMessages.TryGetValue(filePath, out var list))
relatedMessages[filePath] = list = new List<int>();
list.Add(i);
if (msg.ExitCode != 0 || msg.Node.Annotation.StartsWith("CopyFiles", StringComparison.Ordinal))
requiresCallbackInvocation.Add(filePath);
}
foreach (var scriptAssembly in assemblies)
{
var fileName = scriptAssembly.Filename;
if (!requiresCallbackInvocation.Contains(fileName))
{
// Report that an assembly was unchanged as a result of compilation.
assemblyCompilationNotRequired?.Invoke(scriptAssembly);
continue;
}
// Only set this flag if we actually changed any assemblies
if (buildingForEditor)
m_ScriptsForEditorHaveBeenCompiledSinceLastDomainReload = true;
IEnumerable<int> nodeResultIndicesRelatedToAssembly;
if (relatedMessages.TryGetValue(fileName, out var nodeResultIndices))
nodeResultIndicesRelatedToAssembly = nodeResultIndices;
else
nodeResultIndicesRelatedToAssembly = Enumerable.Empty<int>();
var messagesForAssembly = nodeResultIndicesRelatedToAssembly.SelectMany(index => compilerMessagesForNodeResults[index]).ToArray();
scriptAssembly.HasCompileErrors = !beeDriverResult.Success;
assemblyCompilationFinished?.Invoke(scriptAssembly, ConvertCompilerMessages(messagesForAssembly));
}
}
public TargetAssemblyInfo[] GetTargetAssemblyInfos(ScriptAssemblySettings scriptAssemblySettings = null)
{
TargetAssembly[] predefindTargetAssemblies = EditorBuildRules.GetPredefinedTargetAssemblies();
TargetAssemblyInfo[] targetAssemblyInfo = new TargetAssemblyInfo[predefindTargetAssemblies.Length + (customTargetAssemblies?.Count ?? 0)];
int assembliesSize = 0;
foreach (var assembly in predefindTargetAssemblies)
{
if (!ShouldAddTargetAssemblyToList(assembly, scriptAssemblySettings))
{
continue;
}
targetAssemblyInfo[assembliesSize] = ToTargetAssemblyInfo(predefindTargetAssemblies[assembliesSize]);
assembliesSize++;
}
if (customTargetAssemblies != null)
{
foreach (var entry in customTargetAssemblies)
{
var customTargetAssembly = entry.Value;
if (!ShouldAddTargetAssemblyToList(customTargetAssembly, scriptAssemblySettings))
{
continue;
}
targetAssemblyInfo[assembliesSize] = ToTargetAssemblyInfo(customTargetAssembly);
assembliesSize++;
}
Array.Resize(ref targetAssemblyInfo, assembliesSize);
}
return targetAssemblyInfo;
bool ShouldAddTargetAssemblyToList(TargetAssembly targetAssembly, ScriptAssemblySettings scriptAssemblySettings)
{
if (scriptAssemblySettings != null)
{
return EditorBuildRules.IsCompatibleWithPlatformAndDefines(targetAssembly, scriptAssemblySettings);
}
return true;
}
}
TargetAssembly[] GetTargetAssemblies()
{
TargetAssembly[] predefindTargetAssemblies = EditorBuildRules.GetPredefinedTargetAssemblies();
TargetAssembly[] targetAssemblies = new TargetAssembly[predefindTargetAssemblies.Length + (customTargetAssemblies?.Count ?? 0)];
for (int i = 0; i < predefindTargetAssemblies.Length; ++i)
{
targetAssemblies[i] = predefindTargetAssemblies[i];
}
if (customTargetAssemblies != null)
{
int i = predefindTargetAssemblies.Length;
foreach (var entry in customTargetAssemblies)
{
var customTargetAssembly = entry.Value;
targetAssemblies[i] = customTargetAssembly;
i++;
}
}
return targetAssemblies;
}
public TargetAssemblyInfo[] GetTargetAssembliesWithScripts(EditorScriptCompilationOptions options)
{
ScriptAssemblySettings settings = CreateEditorScriptAssemblySettings(EditorScriptCompilationOptions.BuildingForEditor | options);
return GetTargetAssembliesWithScripts(settings);
}
public TargetAssemblyInfo[] GetTargetAssembliesWithScripts(ScriptAssemblySettings settings)
{
UpdateAllTargetAssemblyDefines(customTargetAssemblies, EditorBuildRules.GetPredefinedTargetAssemblies(), m_VersionMetaDatas, settings);
var targetAssemblies = EditorBuildRules.GetTargetAssembliesWithScripts(allScripts, projectDirectory, customTargetAssemblies, settings);
var targetAssemblyInfos = new TargetAssemblyInfo[targetAssemblies.Length];
for (int i = 0; i < targetAssemblies.Length; ++i)
{
targetAssemblyInfos[i] = ToTargetAssemblyInfo(targetAssemblies[i]);
}
return targetAssemblyInfos;
}
public HashSet<TargetAssembly> GetTargetAssembliesWithScriptsHashSet(EditorScriptCompilationOptions options)
{
ScriptAssemblySettings settings = CreateEditorScriptAssemblySettings(EditorScriptCompilationOptions.BuildingForEditor | options);
var targetAssemblies = EditorBuildRules.GetTargetAssembliesWithScriptsHashSet(allScripts, projectDirectory, customTargetAssemblies, settings);
return targetAssemblies;
}
public TargetAssembly[] GetCustomTargetAssemblies()
{
return customTargetAssemblies.Values.ToArray();
}
public CustomScriptAssembly[] GetCustomScriptAssemblies()
{
return loadingAssemblyDefinition.CustomScriptAssemblies;
}
public PrecompiledAssembly[] GetUnityAssemblies()
{
return unityAssemblies;
}
public TargetAssemblyInfo GetTargetAssembly(string scriptPath)
{
string path = scriptPath;
if (!Path.IsPathRooted(scriptPath))
{
path = Path.Combine(projectDirectory, scriptPath);
}
var matchedAssembly = GetAssemblyGraphBuilder().Match(new []{path}, false);
if (matchedAssembly.Count == 0)
{
return TargetAssemblyInfo.Unknown;
}
TargetAssembly targetAssembly;
var scriptAssembly = matchedAssembly.Single().Key;
customTargetAssemblies.TryGetValue(scriptAssembly.Name + ".dll", out targetAssembly);
if (targetAssembly == null)
{
if (EditorBuildRules.predefinedTargetAssemblies.TryGetValue(scriptAssembly.Name + ".dll",
out var assembly))
targetAssembly = assembly;
}
TargetAssemblyInfo targetAssemblyInfo = ToTargetAssemblyInfo(targetAssembly);
return targetAssemblyInfo;
}
public TargetAssembly GetTargetAssemblyDetails(string scriptPath)
{
var matchedAssembly = GetAssemblyGraphBuilder().Match(new []{scriptPath});
return customTargetAssemblies[matchedAssembly.Single().Key.Name];
}
public ScriptAssembly[] GetAllEditorScriptAssemblies(EditorScriptCompilationOptions additionalOptions)
{
return GetAllScriptAssemblies(EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingIncludingTestAssemblies | additionalOptions, null);
}
public ScriptAssembly[] GetAllEditorScriptAssemblies(EditorScriptCompilationOptions additionalOptions, string[] defines)
{
return GetAllScriptAssemblies(EditorScriptCompilationOptions.BuildingForEditor | EditorScriptCompilationOptions.BuildingIncludingTestAssemblies | additionalOptions, defines);
}
public ScriptAssembly[] GetAllScriptAssemblies(EditorScriptCompilationOptions options, string[] defines)
{
var precompiledAssemblies = PrecompiledAssemblyProvider.GetPrecompiledAssembliesDictionary(
options, EditorUserBuildSettings.activeBuildTarget, defines);
return GetAllScriptAssemblies(options, unityAssemblies, precompiledAssemblies, defines);
}
public ScriptAssembly[] GetAllScriptAssemblies(
EditorScriptCompilationOptions options,
PrecompiledAssembly[] unityAssembliesArg,
Dictionary<string, PrecompiledAssembly> precompiledAssembliesArg,
string[] defines)
{
var settings = CreateEditorScriptAssemblySettings(options);
return GetAllScriptAssemblies(
settings,
unityAssembliesArg,
precompiledAssembliesArg,
defines);
}
public ScriptAssembly[] GetAllScriptAssemblies(
ScriptAssemblySettings settings,
PrecompiledAssembly[] unityAssembliesArg,
Dictionary<string, PrecompiledAssembly> precompiledAssembliesArg,
string[] defines,
Func<TargetAssembly, bool> targetAssemblyCondition = null)
{
if (defines != null)
{
settings.ExtraGeneralDefines = defines;
}
UpdateAllTargetAssemblyDefines(customTargetAssemblies, EditorBuildRules.GetPredefinedTargetAssemblies(), m_VersionMetaDatas, settings);
var assemblies = new EditorBuildRules.CompilationAssemblies
{
UnityAssemblies = unityAssembliesArg,
PrecompiledAssemblies = precompiledAssembliesArg,
CustomTargetAssemblies = customTargetAssemblies,
RoslynAnalyzerDllPaths = PrecompiledAssemblyProvider.GetRoslynAnalyzerPaths(),
PredefinedAssembliesCustomTargetReferences = GetPredefinedAssemblyReferences(customTargetAssemblies),
EditorAssemblyReferences = ModuleUtils.GetAdditionalReferencesForUserScripts(),
};
return EditorBuildRules.GetAllScriptAssemblies(
allScripts,
projectDirectory,
settings,
assemblies,
SafeModeInfo,
targetAssemblyCondition: targetAssemblyCondition);
}
public string[] GetTargetAssemblyDefines(TargetAssembly targetAssembly, ScriptAssemblySettings settings)
{
var versionMetaDatas = GetVersionMetaDatas();
var editorApiCompatibility = PlayerSettings.EditorAssemblyCompatibilityToApiCompatibility(PlayerSettings.GetEditorAssembliesCompatibilityLevel());
var editorOnlyCompatibleDefines = InternalEditorUtility.GetCompilationDefines(settings.CompilationOptions, settings.BuildTarget, settings.Subtarget, editorApiCompatibility, settings.ExtraGeneralDefines);
var playerAssembliesDefines = InternalEditorUtility.GetCompilationDefines(settings.CompilationOptions, settings.BuildTarget, settings.Subtarget, settings.PredefinedAssembliesCompilerOptions.ApiCompatibilityLevel, settings.ExtraGeneralDefines);
return GetTargetAssemblyDefines(targetAssembly, versionMetaDatas, editorOnlyCompatibleDefines, playerAssembliesDefines, settings);
}
// TODO: Get rid of calls to this method and ensure that the defines are always setup correctly at all times.
void UpdateAllTargetAssemblyDefines(IDictionary<string, TargetAssembly> customScriptAssemblies, TargetAssembly[] predefinedTargetAssemblies,
Dictionary<string, VersionMetaData> versionMetaDatas, ScriptAssemblySettings settings)
{
var allTargetAssemblies = customScriptAssemblies.Values.ToArray()
.Concat(predefinedTargetAssemblies ?? new TargetAssembly[0]);
var editorApiCompatibility = PlayerSettings.EditorAssemblyCompatibilityToApiCompatibility(PlayerSettings.GetEditorAssembliesCompatibilityLevel());
string[] editorOnlyCompatibleDefines = InternalEditorUtility.GetCompilationDefines(settings.CompilationOptions, settings.BuildTarget, settings.Subtarget, editorApiCompatibility, settings.ExtraGeneralDefines);
var playerAssembliesDefines = InternalEditorUtility.GetCompilationDefines(settings.CompilationOptions, settings.BuildTarget, settings.Subtarget, settings.PredefinedAssembliesCompilerOptions.ApiCompatibilityLevel, settings.ExtraGeneralDefines);
foreach (var targetAssembly in allTargetAssemblies)
{
SetTargetAssemblyDefines(targetAssembly, versionMetaDatas, editorOnlyCompatibleDefines, playerAssembliesDefines, settings);
}
}
void SetTargetAssemblyDefines(TargetAssembly targetAssembly, Dictionary<string, VersionMetaData> versionMetaDatas, string[] editorOnlyCompatibleDefines, string[] playerAssembliesDefines, ScriptAssemblySettings settings)
{
targetAssembly.Defines = GetTargetAssemblyDefines(targetAssembly, versionMetaDatas, editorOnlyCompatibleDefines, playerAssembliesDefines, settings);
}
string[] GetTargetAssemblyDefines(TargetAssembly targetAssembly, Dictionary<string, VersionMetaData> versionMetaDatas, string[] editorOnlyCompatibleDefines, string[] playerAssembliesDefines, ScriptAssemblySettings settings)
{
string[] settingsExtraGeneralDefines = settings.ExtraGeneralDefines;
int populatedVersionDefinesCount = 0;
var compilationDefines =
(targetAssembly.Flags & AssemblyFlags.EditorOnly) == AssemblyFlags.EditorOnly
? editorOnlyCompatibleDefines
: playerAssembliesDefines;
string[] defines = new string[compilationDefines.Length + targetAssembly.VersionDefines.Count + settingsExtraGeneralDefines.Length];
Array.Copy(settingsExtraGeneralDefines, defines, settingsExtraGeneralDefines.Length);
populatedVersionDefinesCount += settingsExtraGeneralDefines.Length;
Array.Copy(compilationDefines, 0, defines, populatedVersionDefinesCount, compilationDefines.Length);
populatedVersionDefinesCount += compilationDefines.Length;
if (versionMetaDatas == null)
{
return defines;
}
var targetAssemblyVersionDefines = targetAssembly.VersionDefines;
foreach (var targetAssemblyVersionDefine in targetAssemblyVersionDefines)
{
if (!versionMetaDatas.ContainsKey(targetAssemblyVersionDefine.name))
{
continue;
}
if (string.IsNullOrEmpty(targetAssemblyVersionDefine.expression))
{
var define = targetAssemblyVersionDefine.define;
if (!string.IsNullOrEmpty(define))
{
defines[populatedVersionDefinesCount] = define;
++populatedVersionDefinesCount;
}
continue;
}
try
{
var versionMetaData = versionMetaDatas[targetAssemblyVersionDefine.name];
var versionString = versionMetaData.Version;
bool isValid;
switch (versionMetaData.Type)
{
case VersionType.VersionTypeUnity:
{
var versionDefineExpression = m_UnityVersionRanges.GetExpression(targetAssemblyVersionDefine.expression);
if (versionDefineExpression.ValidationError != null)
{
VersionDefinesConsoleLogs?.LogVersionDefineError(targetAssembly, versionDefineExpression.ValidationError);
isValid = false;
break;
}
var unityVersion = UnityVersionParser.Parse(versionString);
isValid = versionDefineExpression.Expression.IsValid(unityVersion);
break;
}
case VersionType.VersionTypePackage:
{
var versionDefineExpression = m_SemVersionRanges.GetExpression(targetAssemblyVersionDefine.expression);
if (versionDefineExpression.ValidationError != null)
{
VersionDefinesConsoleLogs?.LogVersionDefineError(targetAssembly, versionDefineExpression.ValidationError);
isValid = false;
break;
}
var semVersion = SemVersionParser.Parse(versionString);
isValid = versionDefineExpression.Expression.IsValid(semVersion);
break;
}
default:
throw new NotImplementedException($"EditorCompilation does not recognize versionMetaData.Type {versionMetaData.Type}. UNIMPLEMENTED");
}
if (isValid)
{
defines[populatedVersionDefinesCount] = targetAssemblyVersionDefine.define;
++populatedVersionDefinesCount;
}
}
catch (Exception e)
{
var asset = AssetDatabase.LoadAssetAtPath<AssemblyDefinitionAsset>(EditorCompilationInterface.Instance.FindCustomTargetAssemblyFromTargetAssembly(targetAssembly).FilePath);
Debug.LogException(e, asset);
}
}
Array.Resize(ref defines, populatedVersionDefinesCount);
return defines;
}
public ScriptAssembly[] GetAllScriptAssembliesOfType(ScriptAssemblySettings settings, TargetAssemblyType type, ICompilationSetupWarningTracker warningSink)
{
using (new ProfilerMarker(nameof(GetAllScriptAssembliesOfType)).Auto())
{
var precompiledAssemblies =
PrecompiledAssemblyProvider.GetPrecompiledAssembliesDictionary(settings.CompilationOptions,
settings.BuildTarget, settings.ExtraGeneralDefines);
UpdateAllTargetAssemblyDefines(customTargetAssemblies, EditorBuildRules.GetPredefinedTargetAssemblies(), m_VersionMetaDatas, settings);
var assemblies = new EditorBuildRules.CompilationAssemblies
{
UnityAssemblies = unityAssemblies,
PrecompiledAssemblies = precompiledAssemblies,
CustomTargetAssemblies = customTargetAssemblies,
RoslynAnalyzerDllPaths = PrecompiledAssemblyProvider.GetRoslynAnalyzerPaths(),
PredefinedAssembliesCustomTargetReferences = GetPredefinedAssemblyReferences(customTargetAssemblies),
EditorAssemblyReferences = ModuleUtils.GetAdditionalReferencesForUserScripts(),
};
return EditorBuildRules.GetAllScriptAssemblies(allScripts, projectDirectory, settings, assemblies, SafeModeInfo, type, warningSink: CompilationSetupWarningTracker);
}
}
public bool IsRuntimeScriptAssembly(string assemblyNameOrPath)
{
var assemblyFilename = AssetPath.GetFileName(assemblyNameOrPath);
if (!assemblyFilename.EndsWith(".dll"))
{
assemblyFilename += ".dll";
}
var predefinedAssemblyTargets = EditorBuildRules.GetPredefinedTargetAssemblies();
if (predefinedAssemblyTargets.Any(a => ((a.Flags & AssemblyFlags.EditorOnly) != AssemblyFlags.EditorOnly) && a.Filename == assemblyFilename))
{
return true;
}
if (customTargetAssemblies != null && customTargetAssemblies.Any(a => ((a.Value.Flags & AssemblyFlags.EditorOnly) != AssemblyFlags.EditorOnly) && a.Value.Filename == assemblyFilename))
{
return true;
}
return false;
}
TargetAssemblyInfo ToTargetAssemblyInfo(TargetAssembly targetAssembly)
{
TargetAssemblyInfo targetAssemblyInfo = new TargetAssemblyInfo();
if (targetAssembly != null)
{
targetAssemblyInfo.Name = targetAssembly.Filename;
targetAssemblyInfo.Flags = targetAssembly.Flags;
}
else
{
targetAssemblyInfo.Name = "";
targetAssemblyInfo.Flags = AssemblyFlags.None;
}
return targetAssemblyInfo;
}
static EditorScriptCompilationOptions ToEditorScriptCompilationOptions(AssemblyBuilderFlags flags)
{
EditorScriptCompilationOptions options = EditorScriptCompilationOptions.BuildingEmpty;
if ((flags & AssemblyBuilderFlags.DevelopmentBuild) == AssemblyBuilderFlags.DevelopmentBuild)
{
options |= EditorScriptCompilationOptions.BuildingDevelopmentBuild;
}
if ((flags & AssemblyBuilderFlags.EditorAssembly) == AssemblyBuilderFlags.EditorAssembly)
{
options |= EditorScriptCompilationOptions.BuildingForEditor;
}
return options;
}
static AssemblyFlags ToAssemblyFlags(AssemblyBuilderFlags assemblyBuilderFlags)
{
AssemblyFlags assemblyFlags = AssemblyFlags.None;
if ((assemblyBuilderFlags & AssemblyBuilderFlags.EditorAssembly) == AssemblyBuilderFlags.EditorAssembly)
{
assemblyFlags |= AssemblyFlags.EditorOnly;
}
return assemblyFlags;
}
static EditorBuildRules.UnityReferencesOptions ToUnityReferencesOptions(ReferencesOptions options)
{
var result = EditorBuildRules.UnityReferencesOptions.ExcludeModules;
if ((options & ReferencesOptions.UseEngineModules) == ReferencesOptions.UseEngineModules)
{
result = EditorBuildRules.UnityReferencesOptions.None;
}
return result;
}
[Obsolete]
ScriptAssembly InitializeScriptAssemblyWithoutReferencesAndDefines(AssemblyBuilder assemblyBuilder)
{
var scriptFiles = assemblyBuilder.scriptPaths.Select(p => AssetPath.Combine(projectDirectory, p)).ToArray();
var assemblyPath = AssetPath.Combine(projectDirectory, assemblyBuilder.assemblyPath);
var scriptAssembly = new ScriptAssembly
{
Flags = ToAssemblyFlags(assemblyBuilder.flags),
BuildTarget = assemblyBuilder.buildTarget,
Files = scriptFiles,
Filename = AssetPath.GetFileName(assemblyPath),
OutputDirectory = AssetPath.GetDirectoryName(assemblyPath),
CompilerOptions = new ScriptCompilerOptions(assemblyBuilder.compilerOptions),
ScriptAssemblyReferences = new ScriptAssembly[0],
RootNamespace = string.Empty
};
scriptAssembly.CompilerOptions.ApiCompatibilityLevel = PlayerSettings.GetApiCompatibilityLevel(NamedBuildTarget.FromActiveSettings(assemblyBuilder.buildTarget));
return scriptAssembly;
}
[Obsolete]
public ScriptAssembly CreateScriptAssembly(AssemblyBuilder assemblyBuilder)
{
var scriptAssembly = InitializeScriptAssemblyWithoutReferencesAndDefines(assemblyBuilder);
var options = ToEditorScriptCompilationOptions(assemblyBuilder.flags);
var referencesOptions = ToUnityReferencesOptions(assemblyBuilder.referencesOptions);
var references = GetAssemblyBuilderDefaultReferences(scriptAssembly, options, referencesOptions);
if (assemblyBuilder.additionalReferences != null && assemblyBuilder.additionalReferences.Length > 0)
{
references = references.Concat(assemblyBuilder.additionalReferences).ToArray();
}
if (assemblyBuilder.excludeReferences != null && assemblyBuilder.excludeReferences.Length > 0)
{
references = references.Where(r => !assemblyBuilder.excludeReferences.Contains(r)).ToArray();
}
var defines = GetAssemblyBuilderDefaultDefines(assemblyBuilder);
if (assemblyBuilder.additionalDefines != null)
{
defines = defines.Concat(assemblyBuilder.additionalDefines).ToArray();
}
scriptAssembly.References = references.ToArray();
scriptAssembly.Defines = defines.ToArray();
RoslynAnalyzers.SetAnalyzers(
new[] { scriptAssembly },
customTargetAssemblies.Values.ToArray(),
PrecompiledAssemblyProvider.GetRoslynAnalyzerPaths(),
true);
// AssemblyBuilder can explicitly set analyzers and rule set
if (assemblyBuilder.compilerOptions.RoslynAnalyzerDllPaths != null)
scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths = assemblyBuilder.compilerOptions.RoslynAnalyzerDllPaths
.Concat(scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths)
.Distinct()
.ToArray();
if (!string.IsNullOrEmpty(assemblyBuilder.compilerOptions.RoslynAnalyzerRulesetPath))
scriptAssembly.CompilerOptions.RoslynAnalyzerRulesetPath = assemblyBuilder.compilerOptions.RoslynAnalyzerRulesetPath;
return scriptAssembly;
}
string[] GetAssemblyBuilderDefaultReferences(ScriptAssembly scriptAssembly, EditorScriptCompilationOptions options, EditorBuildRules.UnityReferencesOptions unityReferencesOptions)
{
bool buildingForEditor = (scriptAssembly.Flags & AssemblyFlags.EditorOnly) == AssemblyFlags.EditorOnly;
var monolithicEngineAssemblyPath = InternalEditorUtility.GetMonolithicEngineAssemblyPath();
var unityReferences = EditorBuildRules.GetUnityReferences(scriptAssembly, unityAssemblies, options, unityReferencesOptions);
var customReferences = EditorBuildRules.GetCompiledCustomAssembliesReferences(scriptAssembly, customTargetAssemblies, GetCompileScriptsOutputDirectory());
var precompiledAssemblies = PrecompiledAssemblyProvider.GetPrecompiledAssemblies(options, EditorUserBuildSettings.activeBuildTarget);
// todo split implicit/explicit precompiled references
var precompiledReferences = EditorBuildRules.GetPrecompiledReferences(scriptAssembly, TargetAssemblyType.Custom, options, EditorCompatibility.CompatibleWithEditor, precompiledAssemblies, null, null);
var additionalReferences = MonoLibraryHelpers.GetSystemLibraryReferences(scriptAssembly.CompilerOptions.ApiCompatibilityLevel);
string[] editorReferences = buildingForEditor ? ModuleUtils.GetAdditionalReferencesForUserScripts() : new string[0];
var references = new List<string>();
if (unityReferencesOptions == EditorBuildRules.UnityReferencesOptions.ExcludeModules)
{
references.Add(monolithicEngineAssemblyPath);
}
references.AddRange(unityReferences.Select(a => a.Path)); // unity references paths
references.AddRange(customReferences);
references.AddRange(precompiledReferences);
references.AddRange(editorReferences);
references.AddRange(additionalReferences);
var editorOnlyTargetAssembly = (options & EditorScriptCompilationOptions.BuildingEditorOnlyAssembly) == EditorScriptCompilationOptions.BuildingEditorOnlyAssembly;
if (editorOnlyTargetAssembly)
{
var editorApiCompatibility = PlayerSettings.EditorAssemblyCompatibilityToApiCompatibility(PlayerSettings.GetEditorAssembliesCompatibilityLevel());
references.AddRange(MonoLibraryHelpers.GetEditorExtensionsReferences(editorApiCompatibility));
}
return references.ToArray();
}
#pragma warning disable CS0618 // Type or member is obsolete
public string[] GetAssemblyBuilderDefaultReferences(AssemblyBuilder assemblyBuilder)
#pragma warning restore CS0618 // Type or member is obsolete
{
#pragma warning disable CS0612 // Type or member is obsolete
var scriptAssembly = InitializeScriptAssemblyWithoutReferencesAndDefines(assemblyBuilder);
#pragma warning restore CS0612 // Type or member is obsolete
var options = ToEditorScriptCompilationOptions(assemblyBuilder.flags);
var referencesOptions = ToUnityReferencesOptions(assemblyBuilder.referencesOptions);
var references = GetAssemblyBuilderDefaultReferences(scriptAssembly, options, referencesOptions);
return references;
}
[Obsolete]
public string[] GetAssemblyBuilderDefaultDefines(AssemblyBuilder assemblyBuilder)
{
var options = ToEditorScriptCompilationOptions(assemblyBuilder.flags);
var defines = InternalEditorUtility.GetCompilationDefines(options, assemblyBuilder.buildTarget, assemblyBuilder.subtarget);
return defines;
}
[Obsolete]
public void AddAssemblyBuilder(AssemblyBuilder assemblyBuilder)
{
assemblyBuilders.Add(assemblyBuilder);
}
public static UnityEditor.Compilation.CompilerMessage[] ConvertCompilerMessages(CompilerMessage[] messages)
{
static Compilation.CompilerMessageType TypeFor(CompilerMessageType compilerMessageType)
{
switch (compilerMessageType)
{
case CompilerMessageType.Error:
return UnityEditor.Compilation.CompilerMessageType.Error;
case CompilerMessageType.Warning:
return UnityEditor.Compilation.CompilerMessageType.Warning;
case CompilerMessageType.Information:
return UnityEditor.Compilation.CompilerMessageType.Info;
default:
throw new ArgumentOutOfRangeException();
}
}
return messages.Select(message => new UnityEditor.Compilation.CompilerMessage
{
message = message.message,
file = message.file,
line = message.line,
column = message.column,
type = TypeFor(message.type)
}).ToArray();
}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/EditorCompilation.cs",
"repo_id": "UnityCsReference",
"token_count": 35950
} | 318 |
// 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;
namespace UnityEditor.Scripting.ScriptCompilation
{
internal static class RoslynAnalyzers
{
private static readonly string[] Unset = null;
private static readonly string[] CyclicDependencies = {};
private static string[] SetAnalyzers(ScriptAssembly scriptAssembly, IEnumerable<(string scriptAssemblyFileName, string analyzerDll)> allAnalyzers, bool scanPrecompiledReferences)
{
if (scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths == Unset)
{
// If this is a cyclic chain we want to detect that and do two iterations
// Doing two iterations ensures that all participants in the chain will see all the analyzers of all members involved in the chain.
scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths = CyclicDependencies;
}
else if (scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths == CyclicDependencies)
{
// On second iteration return an empty array (this will be replaced be actual content of the cyclic chain)
scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths = Array.Empty<string>();
}
else
{
// Analyzers for this ScriptAssembly has already been setup
return scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths;
}
scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths =
scriptAssembly.ScriptAssemblyReferences
.SelectMany(sa => SetAnalyzers(sa, allAnalyzers, scanPrecompiledReferences))
.Concat(allAnalyzers
.Where(a => a.scriptAssemblyFileName == null ||
a.scriptAssemblyFileName == scriptAssembly.Filename ||
scanPrecompiledReferences && scriptAssembly.References.Select(Path.GetFileName).Contains(a.scriptAssemblyFileName))
.Select(a => a.analyzerDll))
.Distinct()
.ToArray();
if (scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths.Length > 0)
{
if(scriptAssembly.TargetAssemblyType == TargetAssemblyType.Predefined)
{
var originPath = Path.ChangeExtension(scriptAssembly.Filename, null);
scriptAssembly.CompilerOptions.RoslynAnalyzerRulesetPath = RuleSetFileCache.GetRuleSetFilePathInRootFolder(originPath);
scriptAssembly.CompilerOptions.AnalyzerConfigPath = RoslynAnalyzerConfigFiles.GetAnalyzerConfigRootFolder(originPath);
}
else
{
scriptAssembly.CompilerOptions.RoslynAnalyzerRulesetPath = RuleSetFileCache.GetPathForAssembly(scriptAssembly.OriginPath);
scriptAssembly.CompilerOptions.AnalyzerConfigPath = RoslynAnalyzerConfigFiles.GetAnalyzerConfigForAssembly(scriptAssembly.OriginPath);
}
scriptAssembly.CompilerOptions.RoslynAdditionalFilePaths = scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths
.SelectMany(a=>RoslynAdditionalFiles.GetAnalyzerAdditionalFilesForTargetAssembly(a, scriptAssembly.OriginPath))
.Distinct()
.ToArray();
}
return scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths;
}
internal static void SetAnalyzers(ScriptAssembly[] scriptAssemblies, TargetAssembly[] potentialAnalyzerOwners, string[] analyzerDlls, bool scanPrecompiledReferences)
{
// Figure out what assemblies own each analyzer
var analyzerAssemblies = analyzerDlls.Select(analyzerDll =>
{
var potentialAnalyzerOwner = potentialAnalyzerOwners
.Where(targetAssembly => targetAssembly.PathFilter(analyzerDll) > 0)
.OrderBy(targetAssembly => targetAssembly.PathFilter(analyzerDll))
.LastOrDefault();
return (potentialOwnerOfAnalyzer: potentialAnalyzerOwner?.Filename, dll: analyzerDll);
}).ToArray();
// Null out all RoslynAnalyzerDllPaths to indicate they need to be set
foreach (var scriptAssembly in scriptAssemblies)
scriptAssembly.CompilerOptions.RoslynAnalyzerDllPaths = Unset;
foreach (var scriptAssembly in scriptAssemblies)
SetAnalyzers(scriptAssembly, analyzerAssemblies, scanPrecompiledReferences);
}
}
}
| UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/RoslynAnalyzers.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/RoslynAnalyzers.cs",
"repo_id": "UnityCsReference",
"token_count": 2038
} | 319 |
// 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;
namespace UnityEditor;
internal static class ScriptingDefinesHelper
{
private static readonly char[] DefineSeparators = { ';', ',', ' ' };
internal static string ConvertScriptingDefineArrayToString(string[] defines)
{
if (defines == null)
{
throw new ArgumentNullException(nameof(defines));
}
var flattenedDefines = new List<string>();
foreach (var define in defines)
{
flattenedDefines.AddRange(define.Split(DefineSeparators, StringSplitOptions.RemoveEmptyEntries));
}
var distinctDefines = new HashSet<string>();
foreach (var define in flattenedDefines)
{
distinctDefines.Add(define);
}
return string.Join(";", distinctDefines);
}
internal static string[] ConvertScriptingDefineStringToArray(string defines)
{
var splitDefines = string.IsNullOrEmpty(defines)
? Array.Empty<string>()
: defines.Split(DefineSeparators, StringSplitOptions.RemoveEmptyEntries);
var distinctDefines = new HashSet<string>();
foreach (var define in splitDefines)
{
distinctDefines.Add(define);
}
var distinctDefinesArray = new string[distinctDefines.Count];
distinctDefines.CopyTo(distinctDefinesArray);
return distinctDefinesArray;
}
}
| UnityCsReference/Editor/Mono/ScriptingDefinesHelper.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/ScriptingDefinesHelper.cs",
"repo_id": "UnityCsReference",
"token_count": 617
} | 320 |
// 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;
using UnityEngine.Scripting;
using System;
using Object = UnityEngine.Object;
namespace UnityEditor
{
[NativeHeader("Editor/Src/Utility/SerializationDebug.bindings.h")]
internal sealed partial class SerializationDebug
{
internal static extern string ToYAMLString(Object obj);
internal static void Log(Object obj)
{
Debug.Log(ToYAMLString(obj));
}
internal static void Log(SerializedObject serializerObject)
{
Debug.Log(GetLogString(serializerObject));
}
// GetLogString() is useful when a quick Object/SerializedObject dump is needed
// It can be used directly from the debugger compared to Log which will print the object in UnityEditor console with some delay
internal static string GetLogString(Object obj)
{
return ToYAMLString(obj);
}
private static string GetLogString(SerializedObject serializerObject)
{
string serializedObjectStr = "";
SerializedProperty property = serializerObject.GetIterator();
while (property.Next(property.hasVisibleChildren))
{
string propertyValue = "";
switch (property.propertyType)
{
case SerializedPropertyType.Generic:
propertyValue = "Generic type value";
break;
case SerializedPropertyType.Integer:
propertyValue = $"{property.intValue}";
break;
case SerializedPropertyType.Boolean:
propertyValue = $"{property.boolValue}";
break;
case SerializedPropertyType.Float:
propertyValue = $"{property.floatValue}";
break;
case SerializedPropertyType.String:
propertyValue = property.stringValue;
break;
case SerializedPropertyType.Color:
propertyValue = $"{property.colorValue}";
break;
case SerializedPropertyType.ObjectReference:
propertyValue = $"{{instanceID: {property.objectReferenceInstanceIDValue} ({property.objectReferenceStringValue})}}";
break;
case SerializedPropertyType.LayerMask:
propertyValue = $"{property.layerMaskBits}";
break;
case SerializedPropertyType.RenderingLayerMask:
propertyValue = $"{property.layerMaskBits}";
break;
case SerializedPropertyType.Enum:
propertyValue = $"{property.enumValueIndex}";
break;
case SerializedPropertyType.Vector2:
propertyValue = $"{property.vector2Value}";
break;
case SerializedPropertyType.Vector3:
propertyValue = $"{property.vector3Value}";
break;
case SerializedPropertyType.Vector4:
propertyValue = $"{property.vector4Value}";
break;
case SerializedPropertyType.Rect:
propertyValue = $"{property.rectValue}";
break;
case SerializedPropertyType.ArraySize:
propertyValue = $"{property.intValue}";
break;
case SerializedPropertyType.Character:
propertyValue = $"{(char)property.intValue}";
break;
case SerializedPropertyType.AnimationCurve:
propertyValue = $"{property.animationCurveValue}";
break;
case SerializedPropertyType.Bounds:
propertyValue = $"{property.boundsValue}";
break;
case SerializedPropertyType.Gradient:
propertyValue = $"{property.gradientValue}";
break;
case SerializedPropertyType.Quaternion:
propertyValue = $"{property.quaternionValue}";
break;
case SerializedPropertyType.ExposedReference:
propertyValue = $"{{instanceID: {property.objectReferenceInstanceIDValue} ({property.objectReferenceStringValue})}}";
break;
case SerializedPropertyType.FixedBufferSize:
propertyValue = $"{property.fixedBufferSize}";
break;
case SerializedPropertyType.Vector2Int:
propertyValue = $"{property.vector2IntValue}";
break;
case SerializedPropertyType.Vector3Int:
propertyValue = $"{property.vector3IntValue}";
break;
case SerializedPropertyType.RectInt:
propertyValue = $"{property.rectIntValue}";
break;
case SerializedPropertyType.BoundsInt:
propertyValue = $"{property.boundsIntValue}";
break;
case SerializedPropertyType.ManagedReference:
propertyValue = $"{{instanceID: {property.objectReferenceInstanceIDValue} ({property.objectReferenceStringValue})}}";
break;
case SerializedPropertyType.Hash128:
propertyValue = $"{property.hash128Value}";
break;
}
if (property.prefabOverride)
{
propertyValue += "(Prefab Override)";
}
serializedObjectStr += $"{property.propertyPath}: {propertyValue}\n";
}
return serializedObjectStr;
}
}
}
| UnityCsReference/Editor/Mono/SerializationDebug.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SerializationDebug.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 3374
} | 321 |
// 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.Collections.Generic;
using UnityEngine.Rendering;
using UnityEditor.AnimatedValues;
using System.Linq;
namespace UnityEditor
{
internal enum DefaultReflectionMode
{
FromSkybox = 0,
Custom
}
[CustomEditor(typeof(RenderSettings))]
internal class LightingEditor : Editor
{
internal static class Styles
{
static Styles() {}
public static readonly GUIContent env_top = EditorGUIUtility.TrTextContent("Environment");
public static readonly GUIContent env_skybox_mat = EditorGUIUtility.TrTextContent("Skybox Material", "Specifies the material that is used to simulate the sky or other distant background in the Scene.");
public static readonly GUIContent env_skybox_sun = EditorGUIUtility.TrTextContent("Sun Source", "Specifies the directional light that is used to indicate the direction of the sun when a procedural skybox is used. If set to None, the brightest directional light in the Scene is used to represent the sun.");
public static readonly GUIContent env_amb_top = EditorGUIUtility.TrTextContent("Environment Lighting");
public static readonly GUIContent env_amb_src = EditorGUIUtility.TrTextContent("Source", "Specifies whether to use a skybox, gradient, or color for ambient light contributed to the Scene.");
public static readonly GUIContent env_amb_int = EditorGUIUtility.TrTextContent("Intensity Multiplier", "Controls the brightness of the skybox lighting in the Scene.");
public static readonly GUIContent env_refl_top = EditorGUIUtility.TrTextContent("Environment Reflections");
public static readonly GUIContent env_refl_src = EditorGUIUtility.TrTextContent("Source", "Specifies whether to use the skybox or a custom cube map for reflection effects in the Scene.");
public static readonly GUIContent env_refl_res = EditorGUIUtility.TrTextContent("Resolution", "Controls the resolution for the cube map assigned to the skybox material for reflection effects in the Scene.");
public static readonly GUIContent env_refl_cmp = EditorGUIUtility.TrTextContent("Compression", "Controls how Unity compresses the reflection cube maps. Options are Auto, Compressed, and Uncompressed. Auto compresses the cube maps if the compression format is suitable.");
public static readonly GUIContent env_refl_int = EditorGUIUtility.TrTextContent("Intensity Multiplier", "Controls how much the skybox or custom cubemap affects reflections in the Scene. A value of 1 produces physically correct results.");
public static readonly GUIContent env_refl_bnc = EditorGUIUtility.TrTextContent("Bounces", "Controls how many times a reflection includes other reflections. A value of 1 results in the Scene being rendered once so mirrored reflections will be black. A value of 2 results in mirrored reflections being visible in the Scene.");
public static readonly GUIContent skyboxWarning = EditorGUIUtility.TrTextContent("Shader of this material does not support skybox rendering.");
public static readonly GUIContent createLight = EditorGUIUtility.TrTextContent("Create Light");
public static readonly GUIContent ambientUp = EditorGUIUtility.TrTextContent("Sky Color", "Controls the color of light emitted from the sky in the Scene.");
public static readonly GUIContent ambientMid = EditorGUIUtility.TrTextContent("Equator Color", "Controls the color of light emitted from the sides of the Scene.");
public static readonly GUIContent ambientDown = EditorGUIUtility.TrTextContent("Ground Color", "Controls the color of light emitted from the ground of the Scene.");
public static readonly GUIContent ambient = EditorGUIUtility.TrTextContent("Ambient Color", "Controls the color of the ambient light contributed to the Scene.");
public static readonly GUIContent customReflection = EditorGUIUtility.TrTextContent("Cubemap", "Specifies the custom cube map used for reflection effects in the Scene.");
public static readonly GUIContent SubtractiveColor = EditorGUIUtility.TrTextContent("Realtime Shadow Color", "The color used for mixing realtime shadows with baked lightmaps in Subtractive lighting mode. The color defines the darkest point of the realtime shadow.");
public static readonly GUIContent[] kFullAmbientSource =
{
EditorGUIUtility.TrTextContent("Skybox"),
EditorGUIUtility.TrTextContent("Gradient"),
EditorGUIUtility.TrTextContent("Color"),
};
public static readonly int[] kFullAmbientSourceValues = { (int)AmbientMode.Skybox, (int)AmbientMode.Trilight, (int)AmbientMode.Flat };
}
protected SerializedProperty m_Sun;
protected SerializedProperty m_SubtractiveShadowColor;
protected SerializedProperty m_AmbientSource;
protected SerializedProperty m_AmbientSkyColor;
protected SerializedProperty m_AmbientEquatorColor;
protected SerializedProperty m_AmbientGroundColor;
protected SerializedProperty m_AmbientIntensity;
protected SerializedProperty m_ReflectionIntensity;
protected SerializedProperty m_ReflectionBounces;
protected SerializedProperty m_SkyboxMaterial;
protected SerializedProperty m_DefaultReflectionMode;
protected SerializedProperty m_DefaultReflectionResolution;
protected SerializedProperty m_CustomReflection;
protected SerializedProperty m_ReflectionCompression;
protected SerializedObject m_RenderSettings;
protected SerializedObject m_LightmapSettings;
SerializedObject renderSettings
{
get
{
// if we set a new scene as the active scene, we need to make sure to respond to those changes
if (m_RenderSettings == null || m_RenderSettings.targetObject == null || m_RenderSettings.targetObject != RenderSettings.GetRenderSettings())
{
m_RenderSettings = new SerializedObject(RenderSettings.GetRenderSettings());
m_Sun = m_RenderSettings.FindProperty("m_Sun");
m_SubtractiveShadowColor = m_RenderSettings.FindProperty("m_SubtractiveShadowColor");
m_AmbientSource = m_RenderSettings.FindProperty("m_AmbientMode");
m_AmbientSkyColor = m_RenderSettings.FindProperty("m_AmbientSkyColor");
m_AmbientEquatorColor = m_RenderSettings.FindProperty("m_AmbientEquatorColor");
m_AmbientGroundColor = m_RenderSettings.FindProperty("m_AmbientGroundColor");
m_AmbientIntensity = m_RenderSettings.FindProperty("m_AmbientIntensity");
m_ReflectionIntensity = m_RenderSettings.FindProperty("m_ReflectionIntensity");
m_ReflectionBounces = m_RenderSettings.FindProperty("m_ReflectionBounces");
m_SkyboxMaterial = m_RenderSettings.FindProperty("m_SkyboxMaterial");
m_DefaultReflectionMode = m_RenderSettings.FindProperty("m_DefaultReflectionMode");
m_DefaultReflectionResolution = m_RenderSettings.FindProperty("m_DefaultReflectionResolution");
m_CustomReflection = m_RenderSettings.FindProperty("m_CustomReflection");
}
return m_RenderSettings;
}
}
SerializedObject lightmapSettings
{
get
{
// if we set a new scene as the active scene, we need to make sure to respond to those changes
if (m_LightmapSettings == null || m_LightmapSettings.targetObject == null || m_LightmapSettings.targetObject != LightmapEditorSettings.GetLightmapSettings())
{
m_LightmapSettings = new SerializedObject(LightmapEditorSettings.GetLightmapSettings());
m_ReflectionCompression = m_LightmapSettings.FindProperty("m_LightmapEditorSettings.m_ReflectionCompression");
}
return m_LightmapSettings;
}
}
private bool m_bShowEnvironment;
private const string kShowEnvironment = "ShowEnvironment";
public virtual void OnEnable()
{
m_bShowEnvironment = SessionState.GetBool(kShowEnvironment, true);
}
public virtual void OnDisable()
{
SessionState.SetBool(kShowEnvironment, m_bShowEnvironment);
}
private void DrawGUI()
{
Material skyboxMaterial = m_SkyboxMaterial.objectReferenceValue as Material;
m_bShowEnvironment = EditorGUILayout.FoldoutTitlebar(m_bShowEnvironment, Styles.env_top, true);
if (m_bShowEnvironment)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_SkyboxMaterial, Styles.env_skybox_mat);
if (skyboxMaterial && !EditorMaterialUtility.IsBackgroundMaterial(skyboxMaterial))
{
EditorGUILayout.HelpBox(Styles.skyboxWarning.text, MessageType.Warning);
}
EditorGUILayout.PropertyField(m_Sun, Styles.env_skybox_sun);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_SubtractiveShadowColor, Styles.SubtractiveColor);
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.env_amb_top);
EditorGUI.indentLevel++;
EditorGUILayout.IntPopup(m_AmbientSource, Styles.kFullAmbientSource, Styles.kFullAmbientSourceValues, Styles.env_amb_src);
switch ((AmbientMode)m_AmbientSource.intValue)
{
case AmbientMode.Trilight:
{
EditorGUI.BeginChangeCheck();
Color newValueUp = EditorGUILayout.ColorField(Styles.ambientUp, m_AmbientSkyColor.colorValue, true, false, true);
Color newValueMid = EditorGUILayout.ColorField(Styles.ambientMid, m_AmbientEquatorColor.colorValue, true, false, true);
Color newValueDown = EditorGUILayout.ColorField(Styles.ambientDown, m_AmbientGroundColor.colorValue, true, false, true);
if (EditorGUI.EndChangeCheck())
{
m_AmbientSkyColor.colorValue = newValueUp;
m_AmbientEquatorColor.colorValue = newValueMid;
m_AmbientGroundColor.colorValue = newValueDown;
}
}
break;
case AmbientMode.Flat:
{
EditorGUI.BeginChangeCheck();
Color newValue = EditorGUILayout.ColorField(Styles.ambient, m_AmbientSkyColor.colorValue, true, false, true);
if (EditorGUI.EndChangeCheck())
m_AmbientSkyColor.colorValue = newValue;
}
break;
case AmbientMode.Skybox:
if (skyboxMaterial == null)
{
EditorGUI.BeginChangeCheck();
Color newValue = EditorGUILayout.ColorField(Styles.ambient, m_AmbientSkyColor.colorValue, true, false, true);
if (EditorGUI.EndChangeCheck())
m_AmbientSkyColor.colorValue = newValue;
}
else
{
// Ambient intensity - maximum is kEmissiveRGBMMax
EditorGUILayout.Slider(m_AmbientIntensity, 0.0F, 8.0F, Styles.env_amb_int);
}
break;
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.env_refl_top);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_DefaultReflectionMode, Styles.env_refl_src);
DefaultReflectionMode defReflectionMode = (DefaultReflectionMode)m_DefaultReflectionMode.intValue;
switch (defReflectionMode)
{
case DefaultReflectionMode.FromSkybox:
{
int[] reflectionResolutionValuesArray = null;
GUIContent[] reflectionResolutionTextArray = null;
ReflectionProbeEditor.GetResolutionArray(ref reflectionResolutionValuesArray, ref reflectionResolutionTextArray);
EditorGUILayout.IntPopup(m_DefaultReflectionResolution, reflectionResolutionTextArray, reflectionResolutionValuesArray, Styles.env_refl_res, GUILayout.MinWidth(40));
}
break;
case DefaultReflectionMode.Custom:
EditorGUILayout.PropertyField(m_CustomReflection, Styles.customReflection);
break;
}
EditorGUILayout.PropertyField(m_ReflectionCompression, Styles.env_refl_cmp);
EditorGUILayout.Slider(m_ReflectionIntensity, 0.0F, 1.0F, Styles.env_refl_int);
EditorGUILayout.IntSlider(m_ReflectionBounces, 1, 5, Styles.env_refl_bnc);
EditorGUI.indentLevel--;
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
}
public override void OnInspectorGUI()
{
renderSettings.Update();
lightmapSettings.Update();
DrawGUI();
renderSettings.ApplyModifiedProperties();
lightmapSettings.ApplyModifiedProperties();
}
}
}
| UnityCsReference/Editor/Mono/SettingsWindow/LightingEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/SettingsWindow/LightingEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 5955
} | 322 |
// 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 UnityEngineInternal;
using Object = UnityEngine.Object;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace UnityEditor.Animations
{
public enum AnimatorConditionMode
{
If = 1,
IfNot = 2,
Greater = 3,
Less = 4,
//ExitTime = 5,
Equals = 6,
NotEqual = 7,
}
public enum TransitionInterruptionSource
{
None,
Source,
Destination,
SourceThenDestination,
DestinationThenSource
}
[NativeHeader("Editor/Src/Animation/Transition.h")]
public struct AnimatorCondition
{
public AnimatorConditionMode mode { get {return m_ConditionMode; } set {m_ConditionMode = value; } }
public string parameter { get {return m_ConditionEvent; } set {m_ConditionEvent = value; } }
public float threshold { get {return m_EventTreshold; } set {m_EventTreshold = value; } }
AnimatorConditionMode m_ConditionMode; //eConditionMode
string m_ConditionEvent;
float m_EventTreshold;// m_ParameterThreshold
}
[NativeHeader("Editor/Src/Animation/Transition.h")]
[NativeHeader("Modules/Animation/MecanimUtility.h")]
public partial class AnimatorTransitionBase : Object
{
protected AnimatorTransitionBase() {}
public string GetDisplayName(Object source)
{
return (source is AnimatorState) ? GetDisplayNameStateSource(source as AnimatorState) : GetDisplayNameStateMachineSource(source as AnimatorStateMachine);
}
[NativeMethod("GetDisplayName")]
extern internal string GetDisplayNameStateSource(AnimatorState source);
[NativeMethod("GetDisplayName")]
extern internal string GetDisplayNameStateMachineSource(AnimatorStateMachine source);
[FreeFunction]
extern static internal string BuildTransitionName(string source, string destination);
extern public bool solo { get; set; }
extern public bool mute { get; set; }
extern public bool isExit { get; set; }
extern public AnimatorStateMachine destinationStateMachine
{
[NativeMethod("GetDstStateMachine")]
get;
[NativeMethod("SetDstStateMachine")]
set;
}
extern public AnimatorState destinationState
{
[NativeMethod("GetDstState")]
get;
[NativeMethod("SetDstState")]
set;
}
extern public AnimatorCondition[] conditions
{
get;
set;
}
}
[NativeHeader("Editor/Src/Animation/Transition.h")]
[NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")]
public class AnimatorTransition : AnimatorTransitionBase
{
public AnimatorTransition()
{
Internal_CreateAnimatorTransition(this);
}
[FreeFunction("StateMachineBindings::Internal_CreateAnimatorTransition")]
extern private static void Internal_CreateAnimatorTransition([Writable] AnimatorTransition mono);
}
[NativeHeader("Editor/Src/Animation/Transition.h")]
[NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")]
public class AnimatorStateTransition : AnimatorTransitionBase
{
public AnimatorStateTransition()
{
Internal_CreateAnimatorStateTransition(this);
}
[FreeFunction("StateMachineBindings::Internal_CreateAnimatorStateTransition")]
extern private static void Internal_CreateAnimatorStateTransition([Writable] AnimatorStateTransition self);
extern public float duration
{
[NativeMethod("GetTransitionDuration")]
get;
[NativeMethod("SetTransitionDuration")]
set;
}
extern public float offset
{
[NativeMethod("GetTransitionOffset")]
get;
[NativeMethod("SetTransitionOffset")]
set;
}
extern public TransitionInterruptionSource interruptionSource
{
[NativeMethod("GetTransitionInterruptionSource")]
get;
[NativeMethod("SetTransitionInterruptionSource")]
set;
}
extern public bool orderedInterruption { get; set; }
extern public float exitTime { get; set; }
extern public bool hasExitTime { get; set; }
extern public bool hasFixedDuration { get; set; }
extern public bool canTransitionToSelf { get; set; }
}
[NativeHeader("Editor/Src/Animation/StateMachine.h")]
[NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")]
[NativeHeader("Editor/Src/Animation/StateMachineBehaviourScripting.h")]
public sealed partial class AnimatorState : Object
{
public AnimatorState()
{
Internal_CreateAnimatorState(this);
}
[FreeFunction("StateMachineBindings::Internal_CreateAnimatorState")]
extern private static void Internal_CreateAnimatorState([Writable] AnimatorState self);
extern public int nameHash
{
get;
}
extern public Motion motion { get; set; }
extern public float speed { get; set; }
extern public float cycleOffset { get; set; }
extern public bool mirror { get; set; }
extern public bool iKOnFeet { get; set; }
extern public bool writeDefaultValues { get; set; }
extern public string tag { get; set; }
extern public string speedParameter { get; set; }
extern public string cycleOffsetParameter { get; set; }
extern public string mirrorParameter { get; set; }
extern public string timeParameter { get; set; }
extern public bool speedParameterActive
{
[NativeMethod("IsSpeedParameterActive")]
get;
set;
}
extern public bool cycleOffsetParameterActive
{
[NativeMethod("IsCycleOffsetParameterActive")]
get;
set;
}
extern public bool mirrorParameterActive
{
[NativeMethod("IsMirrorParameterActive")]
get;
set;
}
extern public bool timeParameterActive
{
[NativeMethod("IsTimeParameterActive")]
get;
set;
}
extern internal void AddBehaviour(int instanceID);
extern internal void RemoveBehaviour(int index);
extern public AnimatorStateTransition[] transitions { get; set; }
[FreeFunction(Name = "ScriptingAddStateMachineBehaviourWithType", HasExplicitThis = true)]
extern private ScriptableObject ScriptingAddStateMachineBehaviourWithType(Type stateMachineBehaviourType);
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public StateMachineBehaviour AddStateMachineBehaviour(Type stateMachineBehaviourType)
{
return (StateMachineBehaviour)ScriptingAddStateMachineBehaviourWithType(stateMachineBehaviourType);
}
public T AddStateMachineBehaviour<T>() where T : StateMachineBehaviour
{
return AddStateMachineBehaviour(typeof(T)) as T;
}
public StateMachineBehaviour[] behaviours
{
get { return Array.ConvertAll(behaviours_Internal, so => (StateMachineBehaviour)so); }
set { behaviours_Internal = Array.ConvertAll(value, smb => (ScriptableObject)smb); }
}
[NativeName("Behaviours")]
private extern ScriptableObject[] behaviours_Internal { get; set; }
internal extern MonoScript GetBehaviourMonoScript(int index);
}
[NativeHeader("Editor/Src/Animation/StateMachine.h")]
[NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")]
[RequiredByNativeCode]
public struct ChildAnimatorState
{
AnimatorState m_State;
Vector3 m_Position;
public AnimatorState state { get { return m_State; } set { m_State = value; } }
public Vector3 position { get {return m_Position; } set { m_Position = value; } }
}
[NativeHeader("Editor/Src/Animation/StateMachine.h")]
[NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")]
[RequiredByNativeCode]
public struct ChildAnimatorStateMachine
{
AnimatorStateMachine m_StateMachine;
Vector3 m_Position;
public AnimatorStateMachine stateMachine { get { return m_StateMachine; } set { m_StateMachine = value; } }
public Vector3 position { get {return m_Position; } set { m_Position = value; } }
}
[NativeHeader("Editor/Src/Animation/StateMachine.h")]
[NativeHeader("Editor/Src/Animation/StateMachine.bindings.h")]
[NativeHeader("Editor/Src/Animation/StateMachineBehaviourScripting.h")]
public sealed partial class AnimatorStateMachine : Object
{
public AnimatorStateMachine()
{
Internal_CreateAnimatorStateMachine(this);
}
[FreeFunction("StateMachineBindings::Internal_CreateAnimatorStateMachine")]
extern private static void Internal_CreateAnimatorStateMachine([Writable] AnimatorStateMachine self);
extern public ChildAnimatorState[] states { get; set; }
extern public ChildAnimatorStateMachine[] stateMachines { get; set; }
extern public AnimatorState defaultState
{
[NativeMethod("DefaultState")]
get;
set;
}
extern public Vector3 anyStatePosition { get; set; }
extern public Vector3 entryPosition { get; set; }
extern public Vector3 exitPosition { get; set; }
extern public Vector3 parentStateMachinePosition { get; set; }
extern public AnimatorStateTransition[] anyStateTransitions { get; set; }
extern public AnimatorTransition[] entryTransitions { get; set; }
extern public AnimatorTransition[] GetStateMachineTransitions(AnimatorStateMachine sourceStateMachine);
extern public void SetStateMachineTransitions(AnimatorStateMachine sourceStateMachine, AnimatorTransition[] transitions);
extern internal void AddBehaviour(int instanceID);
extern internal void RemoveBehaviour(int index);
[FreeFunction(Name = "ScriptingAddStateMachineBehaviourWithType", HasExplicitThis = true)]
extern private ScriptableObject ScriptingAddStateMachineBehaviourWithType(Type stateMachineBehaviourType);
[TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)]
public StateMachineBehaviour AddStateMachineBehaviour(Type stateMachineBehaviourType)
{
return (StateMachineBehaviour)ScriptingAddStateMachineBehaviourWithType(stateMachineBehaviourType);
}
public T AddStateMachineBehaviour<T>() where T : StateMachineBehaviour
{
return AddStateMachineBehaviour(typeof(T)) as T;
}
extern public string MakeUniqueStateName(string name);
extern public string MakeUniqueStateMachineName(string name);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Internals
extern internal void Clear();
[NativeMethod("RemoveState")]
extern internal void RemoveStateInternal(AnimatorState state);
[NativeMethod("RemoveStateMachine")]
extern internal void RemoveStateMachineInternal(AnimatorStateMachine stateMachine);
extern internal void MoveState(AnimatorState state, AnimatorStateMachine target);
extern internal void MoveStateMachine(AnimatorStateMachine stateMachine, AnimatorStateMachine target);
extern internal bool HasState(AnimatorState state, bool recursive);
extern internal bool HasStateMachine(AnimatorStateMachine state, bool recursive);
extern internal int transitionCount
{
get;
}
public StateMachineBehaviour[] behaviours
{
get { return Array.ConvertAll(behaviours_Internal, so => (StateMachineBehaviour)so); }
set { behaviours_Internal = Array.ConvertAll(value, smb => (ScriptableObject)smb); }
}
[NativeName("Behaviours")]
private extern ScriptableObject[] behaviours_Internal { get; set; }
internal extern MonoScript GetBehaviourMonoScript(int index);
}
}
| UnityCsReference/Editor/Mono/StateMachine.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/StateMachine.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 5471
} | 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;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Overlays;
using UnityEngine;
using UObject = UnityEngine.Object;
namespace UnityEditor.EditorTools
{
static class EditorToolUtility
{
static readonly Regex k_NewLine = new Regex(@"\r|\n", RegexOptions.Compiled | RegexOptions.Multiline);
static readonly Regex k_TrailingForwardSlashOrWhiteSpace = new Regex(@"[/|\s]*\Z", RegexOptions.Compiled);
static EditorToolCache s_ToolCache = new EditorToolCache(typeof(EditorToolAttribute));
static EditorToolCache s_ContextCache = new EditorToolCache(typeof(EditorToolContextAttribute));
static Dictionary<Type, GUIContent> s_ToolbarIcons = new Dictionary<Type, GUIContent>();
// Caution: Returns all types without filtering for EditorToolContext
internal static IEnumerable<EditorTypeAssociation> GetCustomEditorToolsForType(Type type)
{
return s_ToolCache.GetEditorsForTargetType(type);
}
internal static IEnumerable<EditorTypeAssociation> availableGlobalToolContexts
{
get => s_ContextCache.GetEditorsForTargetType(null);
}
internal static int toolContextsInProject => s_ContextCache.Count;
internal static string GetToolName(Type tool)
{
var path = GetToolMenuPath(tool);
return GetNameFromToolPath(path);
}
internal static string GetNameFromToolPath(string path)
{
var index = path.LastIndexOf("/", StringComparison.Ordinal);
if (index < 0)
return path;
return path.Substring(index + 1, path.Length - (index + 1));
}
internal static string SanitizeToolPath(string path)
{
path = k_TrailingForwardSlashOrWhiteSpace.Replace(path, string.Empty);
return k_NewLine.Replace(path, " ").Trim();
}
internal static string GetToolMenuPath(Type tool)
{
if (typeof(EditorTool).IsAssignableFrom(tool) || typeof(EditorToolContext).IsAssignableFrom(tool))
{
var toolAttribute = tool.GetCustomAttributes(typeof(ToolAttribute), false).FirstOrDefault();
if (toolAttribute is ToolAttribute attrib && !string.IsNullOrEmpty(attrib.displayName))
{
string path = SanitizeToolPath(attrib.displayName);
if (!string.IsNullOrEmpty(path))
return L10n.Tr(path);
}
}
else if (typeof(EditorToolContext).IsAssignableFrom(tool))
{
var editorToolAttribute = tool.GetCustomAttributes(typeof(EditorToolContextAttribute), false).FirstOrDefault();
if (editorToolAttribute is EditorToolContextAttribute attrib && !string.IsNullOrEmpty(attrib.displayName))
{
string path = SanitizeToolPath(attrib.displayName);
if (!string.IsNullOrEmpty(path))
return L10n.Tr(path);
}
}
return L10n.Tr(ObjectNames.NicifyVariableName(tool.Name.Replace("ToolContext", string.Empty)));
}
internal static string GetToolMenuPath(EditorTool tool)
{
return GetToolMenuPath(tool != null ? tool.GetType() : typeof(EditorTool));
}
internal static EditorToolAttribute GetEditorToolAttribute(Type type)
{
if (type == null)
return null;
return (EditorToolAttribute)type.GetCustomAttributes(typeof(EditorToolAttribute), false).FirstOrDefault();
}
internal static int GetNonBuiltinToolCount()
{
var globalEditorTools = GetCustomEditorToolsForType(null).Where(t => EditorToolManager.additionalContextToolTypesCache.All(tc => tc != t.editor));
return globalEditorTools.Count();
}
internal static bool IsComponentEditor(Type type)
{
if (type.GetCustomAttributes(typeof(ToolAttribute), false).FirstOrDefault() is ToolAttribute attrib)
return attrib.targetType != null;
return false;
}
public static void InstantiateComponentContexts(List<ComponentEditor> editors)
{
s_ContextCache.InstantiateEditors(null, editors);
}
public static void InstantiateComponentTools(EditorToolContext ctx, List<ComponentEditor> editors)
{
s_ToolCache.InstantiateEditors(ctx, editors);
}
// Get an EditorTool instance for type of tool enum. This will return an instance of NoneTool if the active
// context does not resolve to a valid tool.
internal static EditorTool GetEditorToolWithEnum(Tool type, EditorToolContext ctx = null)
{
var context = (ctx == null ? EditorToolManager.activeToolContext : ctx);
switch (type)
{
case Tool.View:
return (EditorTool)EditorToolManager.GetSingleton(typeof(ViewModeTool));
case Tool.Custom:
return EditorToolManager.lastCustomTool;
case Tool.None:
return EditorToolManager.GetSingleton<NoneTool>();
default:
var resolved = context.ResolveTool(type);
if (resolved == null)
goto case Tool.None;
// Tool types can resolve to either global or instance tools
if (IsComponentTool(resolved))
{
var instance = EditorToolManager.GetComponentTool(resolved, true);
if (instance == null)
{
Debug.LogError($"{context} resolved Tool.{type} to a Component tool of type `{resolved}`, but " +
$"no component matching the target type is in the active selection. The active tool " +
$"context will be set to the default.");
EditorToolManager.activeToolContext = EditorToolManager.GetSingleton<GameObjectToolContext>();
return (EditorTool)EditorToolManager.GetSingleton(EditorToolManager.activeToolContext.ResolveTool(type));
}
return instance;
}
// EditorToolContext.ResolveTool does type validation, so a fast cast is safe here.
return (EditorTool)EditorToolManager.GetSingleton(resolved);
}
}
static Tool GetToolTypeInContext(EditorToolContext ctx, Type type)
{
for (int i = (int)Tool.Move; i < (int)Tool.Custom; i++)
{
if (ctx.ResolveTool((Tool)i) == type)
return (Tool)i;
}
return Tool.Custom;
}
internal static Tool GetEnumWithEditorTool(EditorTool tool, EditorToolContext ctx = null)
{
if (tool == null || tool is NoneTool)
return Tool.None;
if (tool is ViewModeTool)
return Tool.View;
var type = tool.GetType();
return GetToolTypeInContext(ctx != null ? ctx : EditorToolManager.activeToolContext, type);
}
internal static bool IsManipulationTool(Tool tool)
{
return tool == Tool.Move
|| tool == Tool.Rotate
|| tool == Tool.Scale
|| tool == Tool.Rect
|| tool == Tool.Transform;
}
// In the current context, is this tool considered a built-in tool?
// Built-in tools are the first category of tools in the toolbar, and are always available while their parent
// context is active.
internal static bool IsBuiltinOverride(EditorTool tool)
{
if (tool == null)
return false;
if (IsManipulationTool(GetEnumWithEditorTool(tool)))
return true;
var type = tool.GetType();
foreach(var extra in EditorToolManager.activeToolContext.GetAdditionalToolTypes())
if (type == extra)
return true;
return false;
}
internal static bool IsComponentTool(Type type)
{
return s_ToolCache.GetTargetType(type) != null;
}
internal static bool IsGlobalTool(EditorTool tool)
{
if(GetEnumWithEditorTool(tool) == Tool.Custom)
{
var type = tool.GetType();
return !IsComponentTool(type) // Component tool?
&& !IsManipulationTool(GetEnumWithEditorTool(tool, EditorToolManager.GetSingleton<GameObjectToolContext>())) // Built-in tool?
&& !IsBuiltinOverride(tool) // Built-in tool override?
&& EditorToolManager.additionalContextToolTypesCache.Any(t => t == type); // Additional/Extra tool?
}
return false;
}
internal static GUIContent GetToolbarIcon<T>(T obj) where T : IEditor
{
if (obj == null)
return GetIcon(typeof(T));
if (obj is EditorTool tool && tool.toolbarIcon != null)
return tool.toolbarIcon;
return GetIcon(obj.GetType());
}
internal static GUIContent GetIcon(Type editorToolType, bool forceReload = false)
{
GUIContent res;
if (forceReload)
s_ToolbarIcons.Remove(editorToolType);
if (s_ToolbarIcons.TryGetValue(editorToolType, out res))
return res;
res = new GUIContent() { tooltip = GetToolName(editorToolType) };
// First check if the tool as an icon attribute
var iconPath = EditorGUIUtility.GetIconPathFromAttribute(editorToolType);
if(!string.IsNullOrEmpty(iconPath) && (res.image = EditorGUIUtility.IconContent(iconPath, false).image))
goto ReturnToolbarIcon;
// Second check for the tool type itself
if(( res.image = EditorGUIUtility.FindTexture(editorToolType) ) != null)
goto ReturnToolbarIcon;
// And finally fall back to the significant letters of the tool's typename
res.text = OverlayUtilities.GetSignificantLettersForIcon(editorToolType.Name);
ReturnToolbarIcon:
if (string.IsNullOrEmpty(res.tooltip))
res.tooltip = ObjectNames.NicifyVariableName(editorToolType.Name);
s_ToolbarIcons.Add(editorToolType, res);
return res;
}
internal static EditorTypeAssociation GetMetaData(Type toolType) => s_ToolCache.GetMetaData(toolType);
internal static List<EditorTypeAssociation> GetEditorsForVariant(EditorTypeAssociation type) => s_ToolCache.GetEditorsForVariant(type);
}
}
| UnityCsReference/Editor/Mono/Tools/EditorToolUtility.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Tools/EditorToolUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 5008
} | 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 System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Reflection;
namespace UnityEditor
{
public static partial class TypeCache
{
public static TypeCollection GetTypesWithAttribute<T>()
where T : Attribute
{
return GetTypesWithAttribute(typeof(T));
}
public static MethodCollection GetMethodsWithAttribute<T>()
where T : Attribute
{
return GetMethodsWithAttribute(typeof(T));
}
public static FieldInfoCollection GetFieldsWithAttribute<T>()
where T : Attribute
{
return GetFieldsWithAttribute(typeof(T));
}
public static TypeCollection GetTypesDerivedFrom<T>()
{
var parentType = typeof(T);
return GetTypesDerivedFrom(parentType);
}
public static TypeCollection GetTypesDerivedFrom(Type parentType)
{
return parentType.IsInterface ?
new TypeCollection(Internal_GetTypesDerivedFromInterface(parentType)) :
new TypeCollection(Internal_GetTypesDerivedFromType(parentType));
}
public static TypeCollection GetTypesWithAttribute(Type attrType)
{
return new TypeCollection(Internal_GetTypesWithAttribute(attrType));
}
public static MethodCollection GetMethodsWithAttribute(Type attrType)
{
return new MethodCollection(Internal_GetMethodsWithAttribute(attrType));
}
public static FieldInfoCollection GetFieldsWithAttribute(Type attrType)
{
return new FieldInfoCollection(Internal_GetFieldsWithAttribute(attrType));
}
public static TypeCollection GetTypesWithAttribute<T>(string assemblyName)
where T : Attribute
{
return GetTypesWithAttribute(typeof(T), assemblyName);
}
public static MethodCollection GetMethodsWithAttribute<T>(string assemblyName)
where T : Attribute
{
return GetMethodsWithAttribute(typeof(T), assemblyName);
}
public static FieldInfoCollection GetFieldsWithAttribute<T>(string assemblyName)
where T : Attribute
{
return GetFieldsWithAttribute(typeof(T), assemblyName);
}
public static TypeCollection GetTypesDerivedFrom<T>(string assemblyName)
{
var parentType = typeof(T);
return GetTypesDerivedFrom(parentType, assemblyName);
}
public static TypeCollection GetTypesDerivedFrom(Type parentType, string assemblyName)
{
return parentType.IsInterface ?
new TypeCollection(Internal_GetTypesDerivedFromInterfaceFromAssembly(parentType, assemblyName)) :
new TypeCollection(Internal_GetTypesDerivedFromTypeFromAssembly(parentType, assemblyName));
}
public static TypeCollection GetTypesWithAttribute(Type attrType, string assemblyName)
{
return new TypeCollection(Internal_GetTypesWithAttributeFromAssembly(attrType, assemblyName));
}
public static MethodCollection GetMethodsWithAttribute(Type attrType, string assemblyName)
{
return new MethodCollection(Internal_GetMethodsWithAttributeFromAssembly(attrType, assemblyName));
}
public static FieldInfoCollection GetFieldsWithAttribute(Type attrType, string assemblyName)
{
return new FieldInfoCollection(Internal_GetFieldsWithAttributeFromAssembly(attrType, assemblyName));
}
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[DebuggerTypeProxy(typeof(DebugView))]
public struct TypeCollection : IList<Type>, IList
{
[NonSerialized]
readonly Type[] listOfTypes;
internal TypeCollection(Type[] types) { listOfTypes = types; }
public int Count => listOfTypes.Length;
public bool IsReadOnly => true;
public bool IsFixedSize => true;
public bool IsSynchronized => true;
object ICollection.SyncRoot => null;
public Type this[int index]
{
get
{
return listOfTypes[index];
}
set
{
ThrowNotSupported();
}
}
public bool Contains(Type item) => IndexOf(item) != -1;
public bool Contains(object item) => IndexOf(item) != -1;
public Enumerator GetEnumerator() => new Enumerator(ref this);
public void CopyTo(Type[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (arrayIndex + Count > array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
for (int i = 0; i < Count; ++i)
array[i + arrayIndex] = listOfTypes[i];
}
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (arrayIndex + Count > array.Length)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
var typedArray = array as Type[];
if (typedArray == null)
throw new ArrayTypeMismatchException(nameof(array));
for (int i = 0; i < Count; ++i)
typedArray[i + arrayIndex] = listOfTypes[i];
}
public int IndexOf(Type item)
{
return Array.IndexOf<Type>(listOfTypes, item);
}
public int IndexOf(object item)
{
return Array.IndexOf(listOfTypes, item);
}
IEnumerator<Type> IEnumerable<Type>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
void ICollection<Type>.Add(Type item)
{
ThrowNotSupported();
}
void ICollection<Type>.Clear()
{
ThrowNotSupported();
}
bool ICollection<Type>.Remove(Type item)
{
ThrowNotSupported();
return false;
}
void IList<Type>.Insert(int index, Type item)
{
ThrowNotSupported();
}
void IList<Type>.RemoveAt(int index)
{
ThrowNotSupported();
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
ThrowNotSupported();
}
}
int IList.Add(object value)
{
ThrowNotSupported();
return -1;
}
void IList.Clear()
{
ThrowNotSupported();
}
void IList.Insert(int index, object value)
{
ThrowNotSupported();
}
void IList.Remove(object value)
{
ThrowNotSupported();
}
void IList.RemoveAt(int index)
{
ThrowNotSupported();
}
static void ThrowNotSupported()
{
throw new NotSupportedException(nameof(TypeCollection) + " is read-only. Modification is not supported.");
}
public struct Enumerator : IEnumerator<Type>
{
readonly TypeCollection m_Collection;
int m_Index;
internal Enumerator(ref TypeCollection collection)
{
m_Collection = collection;
m_Index = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
m_Index++;
return m_Index < m_Collection.Count;
}
public Type Current => m_Collection[m_Index];
void IEnumerator.Reset() => m_Index = -1;
object IEnumerator.Current => Current;
}
class DebugView
{
readonly TypeCollection m_Collection;
public DebugView(ref TypeCollection collection)
{
m_Collection = collection;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Type[] values
{
get
{
var values = new Type[m_Collection.Count];
m_Collection.CopyTo(values, 0);
return values;
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[DebuggerTypeProxy(typeof(DebugView))]
public struct MethodCollection : IList<MethodInfo>, IList
{
[NonSerialized]
readonly MethodInfo[] listOfMethods;
internal MethodCollection(MethodInfo[] methods) { listOfMethods = methods; }
public int Count => listOfMethods.Length;
public bool IsReadOnly => true;
public bool IsFixedSize => true;
public bool IsSynchronized => true;
object ICollection.SyncRoot => null;
public MethodInfo this[int index]
{
get
{
return listOfMethods[index];
}
set
{
ThrowNotSupported();
}
}
public bool Contains(MethodInfo item) => IndexOf(item) != -1;
public bool Contains(object item) => IndexOf(item) != -1;
public Enumerator GetEnumerator() => new Enumerator(ref this);
public void CopyTo(MethodInfo[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (arrayIndex + Count > array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
for (int i = 0; i < Count; ++i)
array[i + arrayIndex] = listOfMethods[i];
}
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (arrayIndex + Count > array.Length)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
var typedArray = array as MethodInfo[];
if (typedArray == null)
throw new ArrayTypeMismatchException(nameof(array));
for (int i = 0; i < Count; ++i)
typedArray[i + arrayIndex] = listOfMethods[i];
}
public int IndexOf(MethodInfo item)
{
return Array.IndexOf<MethodInfo>(listOfMethods, item);
}
public int IndexOf(object item)
{
return Array.IndexOf(listOfMethods, item);
}
IEnumerator<MethodInfo> IEnumerable<MethodInfo>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
void ICollection<MethodInfo>.Add(MethodInfo item)
{
ThrowNotSupported();
}
void ICollection<MethodInfo>.Clear()
{
ThrowNotSupported();
}
bool ICollection<MethodInfo>.Remove(MethodInfo item)
{
ThrowNotSupported();
return false;
}
void IList<MethodInfo>.Insert(int index, MethodInfo item)
{
ThrowNotSupported();
}
void IList<MethodInfo>.RemoveAt(int index)
{
ThrowNotSupported();
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
ThrowNotSupported();
}
}
int IList.Add(object value)
{
ThrowNotSupported();
return -1;
}
void IList.Clear()
{
ThrowNotSupported();
}
void IList.Insert(int index, object value)
{
ThrowNotSupported();
}
void IList.Remove(object value)
{
ThrowNotSupported();
}
void IList.RemoveAt(int index)
{
ThrowNotSupported();
}
static void ThrowNotSupported()
{
throw new NotSupportedException(nameof(TypeCollection) + " is read-only. Modification is not supported.");
}
public struct Enumerator : IEnumerator<MethodInfo>
{
readonly MethodCollection m_Collection;
int m_Index;
internal Enumerator(ref MethodCollection collection)
{
m_Collection = collection;
m_Index = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
m_Index++;
return m_Index < m_Collection.Count;
}
public MethodInfo Current => m_Collection[m_Index];
void IEnumerator.Reset() => m_Index = -1;
object IEnumerator.Current => Current;
}
class DebugView
{
readonly MethodCollection m_Collection;
public DebugView(ref MethodCollection collection)
{
m_Collection = collection;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public MethodInfo[] Values
{
get
{
var values = new MethodInfo[m_Collection.Count];
m_Collection.CopyTo(values, 0);
return values;
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Count = {" + nameof(Count) + "}")]
[DebuggerTypeProxy(typeof(DebugView))]
public struct FieldInfoCollection : IList<FieldInfo>, IList
{
[NonSerialized]
readonly FieldInfo[] listOfFields;
internal FieldInfoCollection(FieldInfo[] fields) { listOfFields = fields; }
public int Count => listOfFields.Length;
public bool IsReadOnly => true;
public bool IsFixedSize => true;
public bool IsSynchronized => true;
object ICollection.SyncRoot => null;
public FieldInfo this[int index]
{
get
{
return listOfFields[index];
}
set
{
ThrowNotSupported();
}
}
public bool Contains(FieldInfo item) => IndexOf(item) != -1;
public bool Contains(object item) => IndexOf(item) != -1;
public Enumerator GetEnumerator() => new Enumerator(ref this);
public void CopyTo(FieldInfo[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (arrayIndex + Count > array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
for (int i = 0; i < Count; ++i)
array[i + arrayIndex] = listOfFields[i];
}
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
throw new ArgumentException(nameof(array));
if (arrayIndex < 0)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (arrayIndex + Count > array.Length)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
var typedArray = array as FieldInfo[];
if (typedArray == null)
throw new ArrayTypeMismatchException(nameof(array));
for (int i = 0; i < Count; ++i)
typedArray[i + arrayIndex] = listOfFields[i];
}
public int IndexOf(FieldInfo item)
{
return Array.IndexOf<FieldInfo>(listOfFields, item);
}
public int IndexOf(object item)
{
return Array.IndexOf(listOfFields, item);
}
IEnumerator<FieldInfo> IEnumerable<FieldInfo>.GetEnumerator() => GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
void ICollection<FieldInfo>.Add(FieldInfo item)
{
ThrowNotSupported();
}
void ICollection<FieldInfo>.Clear()
{
ThrowNotSupported();
}
bool ICollection<FieldInfo>.Remove(FieldInfo item)
{
ThrowNotSupported();
return false;
}
void IList<FieldInfo>.Insert(int index, FieldInfo item)
{
ThrowNotSupported();
}
void IList<FieldInfo>.RemoveAt(int index)
{
ThrowNotSupported();
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
ThrowNotSupported();
}
}
int IList.Add(object value)
{
ThrowNotSupported();
return -1;
}
void IList.Clear()
{
ThrowNotSupported();
}
void IList.Insert(int index, object value)
{
ThrowNotSupported();
}
void IList.Remove(object value)
{
ThrowNotSupported();
}
void IList.RemoveAt(int index)
{
ThrowNotSupported();
}
static void ThrowNotSupported()
{
throw new NotSupportedException(nameof(TypeCollection) + " is read-only. Modification is not supported.");
}
public struct Enumerator : IEnumerator<FieldInfo>
{
readonly FieldInfoCollection m_Collection;
int m_Index;
internal Enumerator(ref FieldInfoCollection collection)
{
m_Collection = collection;
m_Index = -1;
}
public void Dispose()
{
}
public bool MoveNext()
{
m_Index++;
return m_Index < m_Collection.Count;
}
public FieldInfo Current => m_Collection[m_Index];
void IEnumerator.Reset() => m_Index = -1;
object IEnumerator.Current => Current;
}
class DebugView
{
readonly FieldInfoCollection m_Collection;
public DebugView(ref FieldInfoCollection collection)
{
m_Collection = collection;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public FieldInfo[] Values
{
get
{
var values = new FieldInfo[m_Collection.Count];
m_Collection.CopyTo(values, 0);
return values;
}
}
}
}
}
}
| UnityCsReference/Editor/Mono/TypeCache.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/TypeCache.cs",
"repo_id": "UnityCsReference",
"token_count": 11579
} | 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.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditorInternal;
namespace UnityEditor.UIElements
{
/// <summary>
/// A <see cref="TagField"/> editor. For more information, refer to [[wiki:UIE-uxml-element-TagField|UXML element TagField]].
/// </summary>
public class TagField : PopupField<string>
{
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : PopupField<string>.UxmlSerializedData
{
#pragma warning disable 649
[TagFieldValueDecorator]
[UxmlAttribute("value")]
[SerializeField] string overrideValue;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags overrideValue_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new TagField();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
if (ShouldWriteAttributeValue(overrideValue_UxmlAttributeFlags))
{
var e = (TagField)obj;
e.overrideValue = overrideValue;
}
}
}
/// <summary>
/// Instantiates a <see cref="TagField"/> 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<TagField, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="TagField"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : PopupField<string>.UxmlTraits
{
UxmlStringAttributeDescription m_Value = new UxmlStringAttributeDescription { name = "value" };
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
var tagField = (TagField)ve;
tagField.SetValueWithoutNotify(m_Value.GetValueFromBag(bag, cc));
}
}
internal override string GetValueToDisplay()
{
return rawValue;
}
internal string overrideValue
{
get => rawValue;
set
{
if (string.IsNullOrEmpty(value))
rawValue = value; // bypass the check on m_Choices
else
this.value = value;
}
}
public override string value
{
get { return base.value; }
set
{
// Allow the setting of value outside of Tags, but do nothing with them...
if (m_Choices.Contains(value))
{
base.value = value;
}
}
}
public override void SetValueWithoutNotify(string newValue)
{
// Allow the setting of value outside of Tags, but do nothing with them...
if (m_Choices.Contains(newValue))
{
base.SetValueWithoutNotify(newValue);
}
}
/// <summary>
/// Unsupported.
/// </summary>
public override Func<string, string> formatSelectedValueCallback
{
get { return null; }
set
{
if (value != null)
{
Debug.LogWarning(L10n.Tr("TagField doesn't support the formatting of the selected value."));
}
m_FormatSelectedValueCallback = null;
}
}
/// <summary>
/// Unsupported.
/// </summary>
public override Func<string, string> formatListItemCallback
{
get { return null; }
set
{
if (value != null)
{
Debug.LogWarning(L10n.Tr("TagField doesn't support the formatting of the list items."));
}
m_FormatListItemCallback = null;
}
}
static List<string> InitializeTags()
{
return new List<string>(InternalEditorUtility.tags);
}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public new static readonly string ussClassName = "unity-tag-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 TagField.
/// </summary>
public TagField()
: this(null) {}
/// <summary>
/// Initializes and returns an instance of TagField.
/// </summary>
/// <param name="label">The text to use as a label for the field.</param>
/// <param name="defaultValue">The initial tag value this field uses.</param>
public TagField(string label, string defaultValue = null)
: base(label)
{
AddToClassList(ussClassName);
labelElement.AddToClassList(labelUssClassName);
visualInput.AddToClassList(inputUssClassName);
choices = InitializeTags();
if (defaultValue != null)
{
SetValueWithoutNotify(defaultValue);
}
}
internal override void AddMenuItems(IGenericMenu menu)
{
if (menu == null)
{
throw new ArgumentNullException(nameof(menu));
}
choices = InitializeTags();
foreach (var menuItem in choices)
{
var isSelected = (menuItem == value);
menu.AddItem(menuItem, isSelected, () => ChangeValueFromMenu(menuItem));
}
menu.AddSeparator(String.Empty);
menu.AddItem(L10n.Tr("Add Tag..."), false, OpenTagInspector);
}
void ChangeValueFromMenu(string menuItem)
{
value = menuItem;
}
static void OpenTagInspector()
{
TagManagerInspector.ShowWithInitialExpansion(TagManagerInspector.InitialExpansionState.Tags);
}
}
}
| UnityCsReference/Editor/Mono/UIElements/Controls/TagField.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/TagField.cs",
"repo_id": "UnityCsReference",
"token_count": 3226
} | 326 |
// 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.UIElements
{
static class EditorMenuExtensions
{
// DropdownMenu
static IGenericMenu PrepareMenu(DropdownMenu menu, EventBase triggerEvent)
{
menu.PrepareForDisplay(triggerEvent);
var genericMenu = new GenericOSMenu();
foreach (var item in menu.MenuItems())
{
var action = item as DropdownMenuAction;
if (action != null)
{
if ((action.status & DropdownMenuAction.Status.Hidden) == DropdownMenuAction.Status.Hidden
|| action.status == 0)
{
continue;
}
bool isChecked = action.status.HasFlag(DropdownMenuAction.Status.Checked);
if ((action.status & DropdownMenuAction.Status.Disabled) == DropdownMenuAction.Status.Disabled)
{
genericMenu.AddDisabledItem(action.name, isChecked);
}
else
{
genericMenu.AddItem(action.name, isChecked, () =>
{
action.Execute();
});
}
}
else
{
var separator = item as DropdownMenuSeparator;
if (separator != null)
{
genericMenu.AddSeparator(separator.subMenuPath);
}
}
}
return genericMenu;
}
public static void DoDisplayEditorMenu(this DropdownMenu menu, Rect rect)
{
PrepareMenu(menu, null).DropDown(rect);
}
public static void DoDisplayEditorMenu(this DropdownMenu menu, EventBase triggerEvent)
{
var genericMenu = PrepareMenu(menu, triggerEvent);
var position = Vector2.zero;
if (triggerEvent is IMouseEvent mouseEvent)
{
position = mouseEvent.mousePosition;
}
else if (triggerEvent is IPointerEvent pointerEvent)
{
position = pointerEvent.position;
}
else if (triggerEvent.elementTarget != null)
{
position = triggerEvent.elementTarget.layout.center;
}
genericMenu.DropDown(new Rect(position, Vector2.zero));
}
}
internal class GenericOSMenu : IGenericMenu
{
GenericMenu m_GenericMenu;
public GenericOSMenu()
{
m_GenericMenu = new GenericMenu();
}
public GenericOSMenu(GenericMenu genericMenu)
{
m_GenericMenu = genericMenu;
}
public void AddItem(string itemName, bool isChecked, System.Action action)
{
if (action == null)
m_GenericMenu.AddItem(new GUIContent(itemName), isChecked, null);
else
m_GenericMenu.AddItem(new GUIContent(itemName), isChecked, action.Invoke);
}
public void AddItem(string itemName, bool isChecked, System.Action<object> action, object data)
{
if (action == null)
m_GenericMenu.AddItem(new GUIContent(itemName), isChecked, null, data);
else
m_GenericMenu.AddItem(new GUIContent(itemName), isChecked, action.Invoke, data);
}
public void AddDisabledItem(string itemName, bool isChecked)
{
m_GenericMenu.AddDisabledItem(new GUIContent(itemName), isChecked);
}
public void AddSeparator(string path)
{
m_GenericMenu.AddSeparator(path);
}
public void DropDown(Rect position, VisualElement targetElement = null, bool anchored = false)
{
m_GenericMenu.DropDown(position);
}
}
}
| UnityCsReference/Editor/Mono/UIElements/EditorMenuExtensions.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/EditorMenuExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 2108
} | 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 System.IO;
using System.Linq;
using System.Text;
using UnityEditor.AssetImporters;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.UIElements;
using Object = UnityEngine.Object;
namespace UnityEditor.UIElements.StyleSheets
{
[CustomEditor(typeof(ThemeStyleSheetImporter))]
class ThemeStyleSheetImporterEditor : ScriptedImporterEditor
{
ReorderableList m_ThemeStyleSheetsList;
ReorderableList m_InheritedThemesThemeList;
SerializedProperty m_StyleSheetsProperty;
SerializedProperty m_InheritedThemesProperty;
public override void OnEnable()
{
base.OnEnable();
m_StyleSheetsProperty = extraDataSerializedObject.FindProperty("StyleSheets");
m_InheritedThemesProperty = extraDataSerializedObject.FindProperty("InheritedThemes");
m_ThemeStyleSheetsList = MakeReorderableList(m_StyleSheetsProperty, "Style Sheets");
m_InheritedThemesThemeList = MakeReorderableList(m_InheritedThemesProperty, "Inherited Themes");
}
ReorderableList MakeReorderableList(SerializedProperty serializedProperty, string header)
{
var reorderableList = new ReorderableList(extraDataSerializedObject,
serializedProperty,
true, true, true, true);
reorderableList.drawElementCallback += (rect, index, active, focused) =>
{
DrawStyleSheetElement(rect, index, serializedProperty);
};
reorderableList.onAddCallback += list =>
{
list.serializedProperty.arraySize += 1;
var element = list.serializedProperty.GetArrayElementAtIndex(list.serializedProperty.arraySize - 1);
element.objectReferenceValue = null;
};
reorderableList.drawHeaderCallback += rect =>
{
EditorGUI.LabelField(rect, header);
};
return reorderableList;
}
void DrawStyleSheetElement(Rect rect, int index, SerializedProperty property)
{
rect.height -= EditorGUIUtility.standardVerticalSpacing;
var element = property.GetArrayElementAtIndex(index);
var label = element.objectReferenceValue == null ? L10n.Tr("(Missing Reference)") : ObjectNames.NicifyVariableName(element.objectReferenceValue.name);
EditorGUI.ObjectField(rect, element, GUIContent.Temp(label));
}
protected override void Apply()
{
var stringBuilder = new StringBuilder();
var state = extraDataTarget as ThemeAssetDefinitionState;
var targetPath = AssetDatabase.GetAssetPath(target);
AddStyleSheets(stringBuilder, state.InheritedThemes.Cast<StyleSheet>());
stringBuilder.AppendLine();
AddStyleSheets(stringBuilder, state.StyleSheets);
var rulesContent = GetThemeRulesContent(targetPath);
if (!string.IsNullOrEmpty(rulesContent))
{
stringBuilder.Append(rulesContent);
}
File.WriteAllText(targetPath, stringBuilder.ToString());
}
public string GetThemeRulesContent(string targetPath)
{
var stringBuilder = new StringBuilder();
foreach (var line in File.ReadAllLines(targetPath))
{
if (!line.StartsWith("@import"))
stringBuilder.AppendLine(line);
}
return stringBuilder.ToString();
}
void AddStyleSheets(StringBuilder stringBuilder, IEnumerable<StyleSheet> styleSheets)
{
var targetPath = AssetDatabase.GetAssetPath(target);
var targetDirectory = Path.GetDirectoryName(targetPath);
targetDirectory = targetDirectory.Replace('\\', '/') + "/";
foreach (var styleSheet in styleSheets)
{
var styleSheetPath = AssetDatabase.GetAssetPath(styleSheet);
if (string.IsNullOrEmpty(styleSheetPath))
continue;
string url;
if (styleSheetPath == targetPath && AssetDatabase.IsSubAsset(styleSheet))
{
url = $"{ThemeRegistry.kThemeScheme}://{styleSheet.name}";
}
else if (styleSheetPath.StartsWith(targetDirectory))
url = styleSheetPath.Remove(0, targetDirectory.Length);
else
url = $"/{styleSheetPath}";
stringBuilder.AppendLine($"@import url(\"{url}\");");
}
}
public override void OnInspectorGUI()
{
extraDataSerializedObject.Update();
EditorGUILayout.LabelField(ObjectNames.NicifyVariableName(assetTarget.name), EditorStyles.largeLabel);
EditorGUILayout.Space();
m_InheritedThemesThemeList.DoLayoutList();
EditorGUILayout.Space();
m_ThemeStyleSheetsList.DoLayoutList();
extraDataSerializedObject.ApplyModifiedProperties();
ApplyRevertGUI();
}
protected override Type extraDataType => typeof(ThemeAssetDefinitionState);
protected override void InitializeExtraDataInstance(Object extraData, int targetIndex)
{
LoadThemeAssetDefinitionState((ThemeAssetDefinitionState)extraData, ((AssetImporter)targets[targetIndex]).assetPath);
}
static void LoadThemeAssetDefinitionState(ThemeAssetDefinitionState extraData, string assetPath)
{
extraData.StyleSheets = new List<StyleSheet>();
extraData.InheritedThemes = new List<ThemeStyleSheet>();
var styleSheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(assetPath);
// styleSheet will be null if the asset has been deleted while the editor was opened
if (styleSheet != null)
{
foreach (var importStruct in styleSheet.imports)
{
if (importStruct.styleSheet is ThemeStyleSheet themeStyleSheet)
extraData.InheritedThemes.Add(themeStyleSheet);
else
extraData.StyleSheets.Add(importStruct.styleSheet);
}
}
}
}
}
| UnityCsReference/Editor/Mono/UIElements/StyleSheets/ThemeStyleSheetImporterEditor.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/UIElements/StyleSheets/ThemeStyleSheetImporterEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 2869
} | 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.Bindings;
namespace UnityEditor
{
// Unwrapping settings.
[NativeHeader("Editor/Mono/Unwrapping.bindings.h")]
public struct UnwrapParam
{
// maximum allowed angle distortion (0..1)
public float angleError;
// maximum allowed area distortion (0..1)
public float areaError;
// this angle (or greater) between triangles will cause seam to be created
public float hardAngle;
// how much uv-islands will be padded
public float packMargin;
internal int recollectVertices;
// Will set default values for params
[FreeFunction("ResetUnwrapParam")]
public static extern void SetDefaults(out UnwrapParam param);
}
// This class holds everything you may need in regard to uv-unwrapping.
[NativeHeader("Editor/Mono/Unwrapping.bindings.h")]
public static class Unwrapping
{
// Will generate per-triangle uv (3 uv pairs for each triangle) with default settings
public static Vector2[] GeneratePerTriangleUV(Mesh src)
{
UnwrapParam settings = new UnwrapParam();
UnwrapParam.SetDefaults(out settings);
return GeneratePerTriangleUV(src, settings);
}
// Will generate per-triangle uv (3 uv pairs for each triangle) with provided settings
public static Vector2[] GeneratePerTriangleUV(Mesh src, UnwrapParam settings)
{
if (src == null)
throw new ArgumentNullException("src");
return GeneratePerTriangleUVImpl(src, settings);
}
[NativeThrows]
[return:Unmarshalled]
static extern Vector2[] GeneratePerTriangleUVImpl(Mesh src, UnwrapParam settings);
// Will auto generate uv2 with default settings for provided mesh, and fill them in
public static bool GenerateSecondaryUVSet(Mesh src)
{
return MeshUtility.SetPerTriangleUV2(src, GeneratePerTriangleUV(src));
}
// Will auto generate uv2 with provided settings for provided mesh, and fill them in
public static bool GenerateSecondaryUVSet(Mesh src, UnwrapParam settings)
{
return MeshUtility.SetPerTriangleUV2(src, GeneratePerTriangleUV(src, settings));
}
}
}
| UnityCsReference/Editor/Mono/Unwrapping.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Unwrapping.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 940
} | 329 |
// 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 NetStandardFinder
{
public const string NetStandardInstallation = "NetStandard";
public static string GetReferenceDirectory()
{
var prefix = GetNetStandardInstallation();
return Path.Combine(prefix, Path.Combine("ref", "2.1.0"));
}
public static string GetCompatShimsDirectory()
{
return Path.Combine("compat", Path.Combine("2.1.0", "shims"));
}
public static string GetNetStandardCompatShimsDirectory()
{
var prefix = GetNetStandardInstallation();
return Path.Combine(prefix, Path.Combine(GetCompatShimsDirectory(), "netstandard"));
}
public static string GetNetStandardExtensionsDirectory()
{
var prefix = GetNetStandardInstallation();
return Path.Combine(prefix, Path.Combine("Extensions", "2.0.0"));
}
public static string GetNetStandardEditorExtensionsDirectory()
{
var prefix = GetNetStandardInstallation();
return Path.Combine(prefix, Path.Combine("EditorExtensions"));
}
public static string GetDotNetFrameworkCompatShimsDirectory()
{
var prefix = GetNetStandardInstallation();
return Path.Combine(prefix, Path.Combine(GetCompatShimsDirectory(), "netfx"));
}
public static string GetNetStandardInstallation()
{
return Path.Combine(MonoInstallationFinder.GetFrameWorksFolder(), NetStandardInstallation);
}
}
}
| UnityCsReference/Editor/Mono/Utils/NetStandardFinder.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/Utils/NetStandardFinder.cs",
"repo_id": "UnityCsReference",
"token_count": 702
} | 330 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor.VersionControl
{
public interface IInspectorWindowExtension
{
void OnVersionControlBar(Editor editor);
void InvalidateVersionControlBarState();
}
}
| UnityCsReference/Editor/Mono/VersionControl/Common/IInspectorWindowExtension.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControl/Common/IInspectorWindowExtension.cs",
"repo_id": "UnityCsReference",
"token_count": 113
} | 331 |
// 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.Generic;
using UnityEditor.VersionControl;
// List control that manages VCAssets. This is used in a number of places in the plugin to display and manipulate asset lists.
namespace UnityEditorInternal.VersionControl
{
[System.Serializable]
public class ListControl
{
internal static class Styles
{
public static readonly GUIStyle evenBackground = "CN EntryBackEven";
public static GUIStyle dragBackground = new GUIStyle("CN EntryBackEven");
public static GUIStyle changeset = new GUIStyle(EditorStyles.boldLabel);
public static GUIStyle asset = new GUIStyle(EditorStyles.label);
public static GUIStyle meta = new GUIStyle(EditorStyles.miniLabel);
static Styles()
{
var yellowTex = new Texture2D(1, 1, TextureFormat.RGBA32, false, false);
yellowTex.SetPixel(0, 0, new Color(0.5f, 0.5f, 0.2f));
yellowTex.name = "YellowTex";
yellowTex.hideFlags = HideFlags.HideAndDontSave;
yellowTex.Apply();
dragBackground.onNormal.background = yellowTex;
changeset.focused.textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black;
asset.focused.textColor = Color.white;
meta.normal.textColor = new Color(0.5f, 0.5f, 0.5f);
meta.active.textColor = meta.onActive.textColor
= meta.focused.textColor = meta.onFocused.textColor
= Color.white;
}
}
public enum SelectDirection
{
Up,
Down,
Current
}
// List state persisted
[System.Serializable]
public class ListState
{
[SerializeField] public float Scroll = 0;
[SerializeField] public List<string> Expanded = new List<string>();
}
// List item explansion event
public delegate void ExpandDelegate(ChangeSet expand, ListItem item);
ExpandDelegate expandDelegate;
// Drag and drop completion event
public delegate void DragDelegate(ChangeSet target);
DragDelegate dragDelegate;
public delegate void ActionDelegate(ListItem item, int actionIdx);
ActionDelegate actionDelegate;
ListItem root = new ListItem();
ListItem active = null;
List<ListItem> visibleList = new List<ListItem>();
[SerializeField] ListState m_listState;
Dictionary<string, ListItem> pathSearch = new Dictionary<string, ListItem>();
bool readOnly = false;
bool scrollVisible = false;
string menuFolder = null;
string menuDefault = null;
bool dragAcceptOnly = false;
ListItem dragTarget = null;
int dragCount = 0;
SelectDirection dragAdjust = SelectDirection.Current;
Dictionary<string, ListItem> selectList = new Dictionary<string, ListItem>();
ListItem singleSelect = null;
GUIContent calcSizeTmpContent = new GUIContent();
string filter;
const float c_lineHeight = 16;
const float c_scrollWidth = 14;
const string c_changeKeyPrefix = "_chkeyprfx_"; // Workaround to make path mapping refresh work with changesets
const string c_metaSuffix = ".meta";
internal const string c_emptyChangeListMessage = "Empty change list";
internal const string c_noSearchResultChangeListMessage = "No search results found in this change list";
internal const string c_noChangeListsMessage = "No changelists found";
// Handle unique id access to the list. This was added to enable us to pass the list as
// an integer. If the unity pop up menu could handle passing simple C# objects then we
// would not need this. This is not thread safe and feels like a bad workaround.
[System.NonSerialized]
int uniqueID = 0;
static int s_uniqueIDCount = 1;
static Dictionary<int, ListControl> s_uniqueIDList = new Dictionary<int, ListControl>();
static public ListControl FromID(int id) { try { return s_uniqueIDList[id]; } catch { return null; } }
public ListState listState => m_listState ?? (m_listState = new ListState());
// Delegate for handling list expansion events
public ExpandDelegate ExpandEvent
{
get { return expandDelegate; }
set { expandDelegate = value; }
}
// Delegate for handling drag and drop events
public DragDelegate DragEvent
{
get { return dragDelegate; }
set { dragDelegate = value; }
}
// Delegate for handling action button clicks
public ActionDelegate ActionEvent
{
get { return actionDelegate; }
set { actionDelegate = value; }
}
// Root item in the list
public ListItem Root => root;
public AssetList SelectedAssets
{
get
{
AssetList list = new AssetList();
foreach (KeyValuePair<string, ListItem> listItem in selectList)
if (listItem.Value?.Item is Asset)
list.Add(listItem.Value.Item as Asset);
return list;
}
}
public ChangeSets SelectedChangeSets
{
get
{
ChangeSets list = new ChangeSets();
foreach (KeyValuePair<string, ListItem> listItem in selectList)
if (listItem.Value?.Item is ChangeSet)
list.Add(listItem.Value.Item as ChangeSet);
return list;
}
}
public ChangeSets EmptyChangeSets
{
get
{
ListItem cur = root.FirstChild;
ChangeSets list = new ChangeSets();
while (cur != null)
{
ChangeSet c = cur.Change;
bool hasEmptyChangeNotice =
c != null &&
cur.HasChildren &&
cur.FirstChild.Item == null &&
cur.FirstChild.Name == c_emptyChangeListMessage;
if (hasEmptyChangeNotice)
list.Add(c);
cur = cur.Next;
}
return list;
}
}
// Is the list read only?
public bool ReadOnly
{
get { return readOnly; }
set { readOnly = value; }
}
// Context menu overide for folders
public string MenuFolder
{
get { return menuFolder; }
set { menuFolder = value; }
}
// Default context menu
public string MenuDefault
{
get { return menuDefault; }
set { menuDefault = value; }
}
// Folder postfix
public bool DragAcceptOnly
{
get { return dragAcceptOnly; }
set { dragAcceptOnly = value; }
}
public int Size
{
get { return visibleList.Count; }
}
internal string Filter
{
get
{
return filter;
}
set
{
filter = value.ToLowerInvariant();
FilterItems();
}
}
public ListControl()
{
// Assign a unique id. A workaround to pass the class as an int
uniqueID = s_uniqueIDCount++;
s_uniqueIDList.Add(uniqueID, this);
// Set the active list
active = root;
Clear();
}
~ListControl()
{
s_uniqueIDList.Remove(uniqueID);
}
public ListItem FindItemWithIdentifier(int identifier)
{
ListItem result = root.FindWithIdentifierRecurse(identifier);
//if (result == null)
// Debug.Log("Failed to find identifier: " + identifier);
return result;
}
public ListItem Add(ListItem parent, string name, Asset asset)
{
ListItem insert = parent ?? root;
ListItem item = new ListItem();
item.Name = name;
// Can this be null
item.Asset = asset;
insert.Add(item);
// Meta files that are next to their asset file are collapsed into
// the asset file when rendered but only if they are the same state.
ListItem twinAsset = GetTwinAsset(item);
if (twinAsset != null && item.Asset != null &&
twinAsset.Asset.state == (item.Asset.state & ~Asset.States.MetaFile))
item.Hidden = true;
if (item.Asset == null)
return item;
// Create a lookup table
if (item.Asset.path.Length > 0)
pathSearch[item.Asset.path.ToLower()] = item;
return item;
}
public ListItem Add(ListItem parent, string name, ChangeSet change)
{
ListItem insert = parent ?? root;
ListItem item = new ListItem();
item.Name = name;
item.Change = change ?? new ChangeSet(name);
insert.Add(item);
// Create a lookup table
pathSearch[c_changeKeyPrefix + change?.id] = item;
return item;
}
internal ListItem GetChangeSetItem(ChangeSet change)
{
if (change == null)
return null;
ListItem i = root.FirstChild;
while (i != null)
{
ChangeSet c = i.Item as ChangeSet;
if (c != null && c.id == change.id)
{
return i;
}
i = i.Next;
}
return null;
}
public void Clear()
{
root.Clear();
pathSearch.Clear();
// Ensure the root nodes are expanded
root.Name = "ROOT";
root.Expanded = true;
}
public void Refresh()
{
Refresh(true);
}
public void Refresh(bool updateExpanded)
{
if (updateExpanded)
{
// Update the expanded state
LoadExpanded(root);
// Ensure the root nodes are expanded
root.Name = "ROOT";
root.Expanded = true;
listState.Expanded.Clear();
CallExpandedEvent(root, false);
}
SelectedRefresh();
}
// Synchronise selection from Unity
public void Sync()
{
SelectedClear();
foreach (UnityEngine.Object obj in Selection.objects)
{
if (AssetDatabase.IsMainAsset(obj))
{
string projectPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6);
string path = projectPath + AssetDatabase.GetAssetPath(obj);
ListItem item = PathSearchFind(path);
if (item != null)
{
SelectedAdd(item);
}
}
}
}
public bool OnGUI(Rect area, bool focus)
{
bool repaint = false;
Event e = Event.current;
int open = active.OpenCount;
int max = (int)((area.height - 1) / c_lineHeight);
// Scroll up/down
if (e.type == EventType.ScrollWheel)
{
listState.Scroll += e.delta.y;
listState.Scroll = Mathf.Clamp(listState.Scroll, 0, open - max);
e.Use();
}
// Draw the scrollbar if required
if (open > max)
{
Rect scrollRect = new Rect(area.x + area.width - 14, area.y, 14, area.height);
area.width -= c_scrollWidth;
float tmp = listState.Scroll;
listState.Scroll = GUI.VerticalScrollbar(scrollRect, listState.Scroll, max, 0, open);
listState.Scroll = Mathf.Clamp(listState.Scroll, 0, open - max);
if (tmp != listState.Scroll)
repaint = true;
// Seems to be some sort of bug with focus when the scrollbar 1st appears
// This is a work around for that so on the first update we clear the hot control.
if (!scrollVisible)
{
//GUIUtility.hotControl = 0;
scrollVisible = true;
}
}
else
{
if (scrollVisible)
{
//GUIUtility.hotControl = 0;
scrollVisible = false;
listState.Scroll = 0;
}
}
// Update the visible list
UpdateVisibleList(area, listState.Scroll);
// Only do the following in non read only mode
if (focus && !readOnly)
{
// Key Handling
if (e.isKey)
{
repaint = true;
HandleKeyInput(e);
}
HandleSelectAll();
repaint = HandleMouse(area) || repaint;
// Adjust scroll position when dragging
if (e.type == EventType.DragUpdated && area.Contains(e.mousePosition))
{
if (e.mousePosition.y < area.y + c_lineHeight)
{
listState.Scroll = Mathf.Clamp(listState.Scroll - 1, 0, open - max);
}
else if (e.mousePosition.y > area.y + area.height - c_lineHeight)
{
listState.Scroll = Mathf.Clamp(listState.Scroll + 1, 0, open - max);
}
}
}
DrawItems(area, focus);
return repaint;
}
private bool HandleMouse(Rect area)
{
Event e = Event.current;
bool repaint = false;
// Handle mouse down clicks
bool mouseInArea = area.Contains(e.mousePosition);
if (e.type == EventType.MouseDown && mouseInArea)
{
repaint = true;
dragCount = 0;
GUIUtility.keyboardControl = 0;
singleSelect = GetItemAt(area, e.mousePosition);
// Ensure a valid selection
if (singleSelect != null && !singleSelect.Dummy)
{
// Double click handling
if (e.button == 0 && e.clickCount > 1)
singleSelect.Asset?.Edit();
// Expand/Contract
if (e.button < 2)
{
float x = area.x + ((singleSelect.Indent - 1) * 18);
if (e.mousePosition.x >= x && e.mousePosition.x < x + 16 && singleSelect.CanExpand)
{
singleSelect.Expanded = !singleSelect.Expanded;
CallExpandedEvent(singleSelect, true);
singleSelect = null;
}
else if (e.control || e.command)
{
// Right clicking can never de-toggle something
if (e.button == 1)
SelectedAdd(singleSelect);
else
SelectedToggle(singleSelect);
singleSelect = null;
}
else if (e.shift)
{
SelectionFlow(singleSelect);
singleSelect = null;
}
else
{
if (!IsSelected(singleSelect))
{
SelectedSet(singleSelect);
// Do not set singleSelect to null in order for drag to
// know what is dragged
singleSelect = null;
}
}
}
}
else if (e.button == 0)
{
// Clear selection when a click was made on nothing
SelectedClear();
singleSelect = null;
}
}
// Handle mouse up clicks
else if ((e.type == EventType.MouseUp || e.type == EventType.ContextClick) && mouseInArea)
{
GUIUtility.keyboardControl = 0;
singleSelect = GetItemAt(area, e.mousePosition);
dragCount = 0;
repaint = true;
if (singleSelect != null && !singleSelect.Dummy)
{
// right click menus - we pass the static index of the list so the menu can find what is selected
if (e.type == EventType.ContextClick)
{
singleSelect = null;
if (!IsSelectedAsset() && !string.IsNullOrEmpty(menuFolder))
{
s_uniqueIDList[uniqueID] = this;
EditorUtility.DisplayPopupMenu(new Rect(e.mousePosition.x, e.mousePosition.y, 0, 0), menuFolder, new MenuCommand(null, uniqueID));
}
else if (!string.IsNullOrEmpty(menuDefault))
{
s_uniqueIDList[uniqueID] = this;
EditorUtility.DisplayPopupMenu(new Rect(e.mousePosition.x, e.mousePosition.y, 0, 0), menuDefault, new MenuCommand(null, uniqueID));
}
}
// Left click up should set selection if singleSelect is in selection since
// this is the case where the user has clicked and hold on a selection (which may start a drag or not)
// and then released it.
else if (e.type != EventType.ContextClick && e.button == 0 && !(e.control || e.command || e.shift))
{
if (IsSelected(singleSelect))
{
SelectedSet(singleSelect);
singleSelect = null;
}
}
}
}
if (e.type == EventType.MouseDrag && mouseInArea)
{
// Ive added this to stop the accidental drag messages that pop up
// you only seem to get one when its not intentional so this should
// give a better effect.
++dragCount;
if (dragCount > 2 && Selection.objects.Length > 0)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.objectReferences = singleSelect?.Asset != null ? new UnityEngine.Object[] {singleSelect.Asset.Load()} : Selection.objects;
DragAndDrop.StartDrag("Move");
}
}
// Drag has been updated
if (e.type == EventType.DragUpdated)
{
repaint = true;
DragAndDrop.visualMode = DragAndDropVisualMode.Move;
dragTarget = GetItemAt(area, e.mousePosition);
// Dont target selected items
if (dragTarget != null)
{
if (IsSelected(dragTarget))
{
dragTarget = null;
}
else
{
if (dragAcceptOnly)
{
if (!dragTarget.CanAccept && dragTarget.Parent.Change == null)
dragTarget = null;
}
else
{
bool canPrev = !dragTarget.CanAccept || dragTarget.PrevOpenVisible != dragTarget.Parent;
bool canNext = !dragTarget.CanAccept || dragTarget.NextOpenVisible != dragTarget.FirstChild;
float size = dragTarget.CanAccept ? 2 : c_lineHeight / 2;
int index = (int)((e.mousePosition.y - area.y) / c_lineHeight);
float pos = area.y + (index * c_lineHeight);
dragAdjust = SelectDirection.Current;
if (canPrev && e.mousePosition.y <= pos + size)
dragAdjust = SelectDirection.Up;
else if (canNext && e.mousePosition.y >= pos + c_lineHeight - size)
dragAdjust = SelectDirection.Down;
}
}
}
}
// Drag and drop completion
if (e.type == EventType.DragPerform)
{
if (dragTarget != null)
{
ListItem drag = dragAdjust == SelectDirection.Current ? dragTarget : dragTarget.Parent;
if (dragDelegate != null && drag != null && (drag.CanAccept || drag.Parent.Change != null))
{
if (drag.Change == null)
dragDelegate(drag.Parent.Change);
else
dragDelegate(drag.Change);
}
dragTarget = null;
}
}
if (e.type == EventType.DragExited)
dragTarget = null;
return repaint;
}
private void DrawItems(Rect area, bool focus)
{
float y = area.y;
foreach (ListItem it in visibleList)
{
float x = area.x + ((it.Indent - 1) * 18);
bool isSelected = !readOnly && IsSelected(it);
if (it.Parent?.Parent != null && it.Parent.Parent.Parent == null)
x += 5;
DrawItem(it, area, x, y, focus, isSelected);
y += c_lineHeight;
}
}
private void HandleSelectAll()
{
if (Event.current.type == EventType.ValidateCommand && Event.current.commandName == EventCommandNames.SelectAll)
{
Event.current.Use();
}
else if (Event.current.type == EventType.ExecuteCommand && Event.current.commandName == EventCommandNames.SelectAll)
{
SelectedAll();
Event.current.Use();
}
}
// Parse all key input supported by the list here
void HandleKeyInput(Event e)
{
// Only handle blip events in here on
if (e.type != EventType.KeyDown)
return;
// Nothing selected?
if (selectList.Count == 0)
return;
// Selected list items values can be null if using during list update
foreach (KeyValuePair<string, ListItem> item in selectList)
{
if (item.Value == null)
return;
}
// Arrow key up
if (e.keyCode == KeyCode.UpArrow || e.keyCode == KeyCode.DownArrow)
{
ListItem sel = null;
if (e.keyCode == KeyCode.UpArrow)
{
sel = SelectedFirstIn(active);
sel = sel?.PrevOpenSkip;
}
else
{
sel = SelectedLastIn(active);
sel = sel?.NextOpenSkip;
}
if (sel != null)
{
// Ensure that the item is in view - linear search but handles all the corner cases
if (!ScrollUpTo(sel))
ScrollDownTo(sel);
if (e.shift)
{
SelectionFlow(sel);
}
else
{
SelectedSet(sel);
}
}
e.Use();
}
// Expand/contract on left/right arrow keys
if (e.keyCode == KeyCode.LeftArrow || e.keyCode == KeyCode.RightArrow)
{
ListItem sel = SelectedCurrentIn(active);
sel.Expanded = (e.keyCode == KeyCode.RightArrow);
CallExpandedEvent(sel, true);
e.Use();
}
// Edit on return key
if (e.keyCode == KeyCode.Return && GUIUtility.keyboardControl == 0)
{
ListItem sel = SelectedCurrentIn(active);
sel.Asset?.Edit();
e.Use();
}
}
// Draw a list item. A few too many magic numbers in here so will need to tidy this a bit
void DrawItem(ListItem item, Rect area, float x, float y, bool focus, bool selected)
{
bool drag = (item == dragTarget);
bool highlight = selected;
if (selected && Event.current.type == EventType.Repaint)
{
Styles.evenBackground.Draw(new Rect(area.x, y, area.width, c_lineHeight), GUIContent.none, false, false, true, false);
}
else if (drag)
{
switch (dragAdjust)
{
case SelectDirection.Up:
if (item.PrevOpenVisible != item.Parent && Event.current.type == EventType.Repaint)
{
Styles.dragBackground.Draw(new Rect(x, y - 1, area.width, 2), GUIContent.none, false, false, true, false);
}
break;
case SelectDirection.Down:
if (Event.current.type == EventType.Repaint)
{
Styles.dragBackground.Draw(new Rect(x, y - 1, area.width, 2), GUIContent.none, false, false, true, false);
}
break;
default:
if (item.CanAccept || item.Parent.Change != null)
{
if (Event.current.type == EventType.Repaint)
{
Styles.dragBackground.Draw(new Rect(area.x, y, area.width, c_lineHeight), GUIContent.none, false, false, true, false);
}
highlight = true;
}
break;
}
}
else if (dragTarget != null && item == dragTarget.Parent && dragAdjust != SelectDirection.Current)
{
if (Event.current.type == EventType.Repaint)
{
Styles.dragBackground.Draw(new Rect(area.x, y, area.width, c_lineHeight), GUIContent.none, false, false, true, false);
}
highlight = true;
}
if (item.HasActions)
{
// Draw any actions available
for (int i = 0; i < item.Actions.Length; ++i)
{
calcSizeTmpContent.text = item.Actions[i];
Vector2 sz = GUI.skin.button.CalcSize(calcSizeTmpContent);
if (GUI.Button(new Rect(x, y, sz.x, c_lineHeight), item.Actions[i]))
{
// Action performed. Callback delegate
actionDelegate(item, i);
}
x += sz.x + 4; // offset by 4 px
}
}
if (item.CanExpand)
{
EditorGUI.Foldout(new Rect(x, y, 16, c_lineHeight), item.Expanded, GUIContent.none);
}
Texture icon = item.Icon;
Color tmpColor = GUI.color;
Color tmpContentColor = GUI.contentColor;
// This should not be an else statement as the previous if can set icon
if (!item.Dummy || item.Change != null)
{
// If there is no icon set then we look for cached items
if (icon == null)
{
icon = InternalEditorUtility.GetIconForFile(item.Name);
// icon = defaultIcon;
}
var iconRect = new Rect(x + 14, y, 16, c_lineHeight);
if (selected)
{
Texture activeIcon = EditorUtility.GetIconInActiveState(icon);
if (activeIcon != null)
{
activeIcon.filterMode = FilterMode.Bilinear;
icon = activeIcon;
}
}
if (icon != null)
GUI.DrawTexture(iconRect, icon);
if (item.Asset != null)
{
bool drawOverlay = true;
string vcsType = VersionControlSettings.mode;
if (vcsType == ExternalVersionControl.Disabled ||
vcsType == ExternalVersionControl.AutoDetect ||
vcsType == ExternalVersionControl.Generic)
drawOverlay = false; // no overlays for these version control systems
if (drawOverlay)
{
Rect overlayRect = iconRect;
overlayRect.width += 12;
overlayRect.x -= 6;
Overlay.DrawOverlay(item.Asset, overlayRect);
}
}
}
if (Event.current.type != EventType.Repaint) return;
GUIStyle label = item.Change != null ? Styles.changeset : Styles.asset;
string displayName = DisplayName(item);
Vector2 displayNameSize = label.CalcSize(EditorGUIUtility.TempContent(displayName));
float labelOffsetX = x + 32;
Rect textRect = new Rect(labelOffsetX, y, area.width - labelOffsetX, c_lineHeight + 2);
int startIndex = -1;
if (!string.IsNullOrEmpty(filter))
{
startIndex = displayName.IndexOf(filter, StringComparison.OrdinalIgnoreCase);
}
GUIContent content = new GUIContent(displayName);
if (item.Dummy)
{
GUI.Label(textRect, content, Styles.meta);
}
else if (startIndex == -1 || item.Asset == null || Event.current.type != EventType.Repaint)
{
label.Draw(textRect, content, false, false, selected, selected);
}
else
{
int endIndex = startIndex + filter.Length;
label.DrawWithTextSelection(textRect, content, selected, selected, startIndex, endIndex, false, GUI.skin.settings.selectionColor);
}
float spaceBefore = labelOffsetX + displayNameSize.x + (item.Change != null ? 10 : 2);
Rect metaPosition = new Rect(spaceBefore, y, area.width - spaceBefore, c_lineHeight + 2);
int visibleChildCount = item.VisibleChildCount;
if (HasHiddenMetaFile(item))
{
Styles.meta.Draw(metaPosition, GUIContent.Temp("+meta"), false, false, selected, selected);
}
if (visibleChildCount > 0)
{
Styles.meta.Draw(metaPosition, GUIContent.Temp($"{visibleChildCount} files"), false, false, selected, selected);
}
}
void FilterItems()
{
for (ListItem item = root.NextOpen; item != null; item = item.NextOpen)
{
item.Hidden = GetTwinAsset(item) != null;
if (!string.IsNullOrEmpty(filter) && item.Change == null)
{
item.Hidden |= !DisplayName(item).ToLowerInvariant().Contains(filter) || item.Dummy;
}
}
}
void UpdateVisibleList(Rect area, float scrollPos)
{
float y = area.y;
float h = area.y + area.height - c_lineHeight;
ListItem first = active.NextOpenVisible; // Skip the root node
visibleList.Clear();
// Move to the first visible item
for (float i = 0; i < scrollPos; ++i)
{
if (first == null)
return;
first = first.NextOpenVisible;
}
for (ListItem it = first; it != null && y < h; it = it.NextOpenVisible)
{
visibleList.Add(it);
y += c_lineHeight;
if (it.Change != null && it.Expanded && it.VisibleItemCount < 1)
{
ListItem item = new ListItem();
item.Icon = null;
item.Dummy = true;
item.Name = c_noSearchResultChangeListMessage;
item.Indent = it.Indent;
visibleList.Add(item);
y += c_lineHeight;
}
}
if (visibleList.Count == 0)
{
ListItem item = new ListItem();
item.Icon = null;
item.Dummy = true;
item.Name = c_noChangeListsMessage;
visibleList.Add(item);
}
}
ListItem GetItemAt(Rect area, Vector2 pos)
{
int index = (int)((pos.y - area.y) / c_lineHeight);
if (index >= 0 && index < visibleList.Count)
return visibleList[index];
return null;
}
// Scroll up towards a target item
bool ScrollUpTo(ListItem item)
{
int count = (int)listState.Scroll;
ListItem find = visibleList.Count > 0 ? visibleList[0] : null;
while (find != null && count >= 0)
{
if (find == item)
{
listState.Scroll = count;
return true;
}
--count;
find = find.PrevOpenVisible;
}
return false;
}
// Scroll up towards a target item
bool ScrollDownTo(ListItem item)
{
int count = (int)listState.Scroll;
ListItem find = visibleList.Count > 0 ? visibleList[visibleList.Count - 1] : null;
while (find != null && count >= 0)
{
if (find == item)
{
listState.Scroll = count;
return true;
}
++count;
find = find.NextOpenVisible;
}
return false;
}
// Load the expanded list state
void LoadExpanded(ListItem item)
{
if (item.Change != null)
item.Expanded = listState.Expanded.Contains(item.Change.id);
ListItem en = item.FirstChild;
while (en != null)
{
LoadExpanded(en);
en = en.Next;
}
}
internal void ExpandLastItem()
{
if (root.LastChild == null) return;
root.LastChild.Expanded = true;
CallExpandedEvent(root.LastChild, true);
}
// Parameter added for removing entries as this isnt necessary when updating the full list
void CallExpandedEvent(ListItem item, bool remove)
{
if (item.Change != null)
{
if (item.Expanded)
{
expandDelegate?.Invoke(item.Change, item);
listState.Expanded.Add(item.Change.id);
}
else if (remove)
{
listState.Expanded.Remove(item.Change.id);
}
}
ListItem en = item.FirstChild;
while (en != null)
{
CallExpandedEvent(en, remove);
en = en.Next;
}
}
// Find an item in the list given a path
ListItem PathSearchFind(string path)
{
try { return pathSearch[path.ToLower()]; }
catch { return null; }
}
// Is the item selected?
internal bool IsSelected(ListItem item)
{
if (item.Asset != null)
return selectList.ContainsKey(item.Asset.path.ToLower());
return item.Change != null && selectList.ContainsKey(c_changeKeyPrefix + item.Change.id);
}
// Is an asset selected in the list
bool IsSelectedAsset()
{
foreach (KeyValuePair<string, ListItem> de in selectList)
{
if (de.Value?.Asset != null)
{
return true;
}
}
return false;
}
// Clear the current selection list
internal void SelectedClear()
{
selectList.Clear();
Selection.activeObject = null;
Selection.instanceIDs = new int[0];
}
// Single selection - clears all previous selections
void SelectedRefresh()
{
Dictionary<string, ListItem> newSelect = new Dictionary<string, ListItem>();
foreach (KeyValuePair<string, ListItem> de in selectList)
{
newSelect[de.Key] = PathSearchFind(de.Key);
}
selectList = newSelect;
}
// Single selection - clears all previous selections
public void SelectedSet(ListItem item)
{
// Dont select or do anything with invalid entries
if (item.Dummy)
return;
SelectedClear();
if (item.Asset != null)
{
SelectedAdd(item);
}
else if (item.Change != null)
{
selectList[c_changeKeyPrefix + item.Change.id] = item;
}
}
public void SelectedAll()
{
SelectedClear();
SelectedAllHelper(Root);
}
void SelectedAllHelper(ListItem _root)
{
ListItem cur = _root.FirstChild;
while (cur != null)
{
if (cur.HasChildren)
{
// Recurse
SelectedAllHelper(cur);
}
if (cur.Asset != null)
{
SelectedAdd(cur);
}
cur = cur.Next;
}
}
ListItem GetTwinAsset(ListItem item)
{
ListItem prev = item.Prev;
if (item.Name.EndsWith(c_metaSuffix)
&& prev?.Asset != null
&& AssetDatabase.GetTextMetaFilePathFromAssetPath(prev.Asset.path).ToLower() == item.Asset.path.ToLower())
return prev;
return null;
}
ListItem GetTwinMeta(ListItem item)
{
ListItem next = item.Next;
if (!item.Name.EndsWith(c_metaSuffix)
&& next?.Asset != null
&& next.Asset.path.ToLower() == AssetDatabase.GetTextMetaFilePathFromAssetPath(item.Asset.path).ToLower())
return next;
return null;
}
ListItem GetTwin(ListItem item)
{
ListItem a = GetTwinAsset(item);
return a ?? GetTwinMeta(item);
}
// Add a selection to the list
public void SelectedAdd(ListItem item)
{
// Dont select or do anything with invalid entries
if (item.Dummy)
return;
ListItem current = SelectedCurrentIn(active);
// Handle exclusive selections
if (item.Exclusive || (current != null && current.Exclusive))
{
SelectedSet(item);
return;
}
//
string name = item.Asset.path.ToLower();
int selectListPrevCount = selectList.Count;
selectList[name] = item;
// Auto select meta files together with asset
ListItem twin = GetTwin(item);
if (twin != null)
selectList[twin.Asset.path.ToLower()] = twin;
if (selectListPrevCount == selectList.Count)
return; // The items were already present
// Update core selection list... Only non-meta files can be selectable
int[] selection = Selection.instanceIDs;
int arrayLen = 0;
if (selection != null) arrayLen = selection.Length;
// UnityEngine.Object tmpObj = item.Asset.Load ();
name = name.EndsWith(c_metaSuffix) ? name.Substring(0, name.Length - 5) : name;
int itemID = AssetDatabase.GetMainAssetInstanceID(name.TrimEnd('/'));
int[] newSel = new int[arrayLen + 1];
//asset is in current project - the correct folder is opened
//asset is in another project - current project root folder is opened
if (itemID != 0)
{
newSel[arrayLen] = itemID;
}
Debug.Assert(selection != null, nameof(selection) + " != null");
Array.Copy(selection, newSel, arrayLen);
Selection.instanceIDs = newSel;
}
void SelectedRemove(ListItem item)
{
string name = item.Asset != null ? item.Asset.path.ToLower() : c_changeKeyPrefix + item.Change.id;
// Remove item
selectList.Remove(name);
// Remove twin item of asset
if (item.Asset != null)
selectList.Remove(name.EndsWith(c_metaSuffix) ? name.Substring(0, name.Length - 5) : name + c_metaSuffix);
// Sync with core selection list.
name = name.EndsWith(c_metaSuffix) ? name.Substring(0, name.Length - 5) : name;
int itemID = AssetDatabase.GetMainAssetInstanceID(name.TrimEnd('/'));
int[] sel = Selection.instanceIDs;
if (itemID != 0 && sel.Length > 0)
{
int idx = Array.IndexOf(sel, itemID);
if (idx < 0)
return;
int[] newSel = new int[sel.Length - 1];
Array.Copy(sel, newSel, idx);
if (idx < (sel.Length - 1))
Array.Copy(sel, idx + 1, newSel, idx, sel.Length - idx - 1);
Selection.instanceIDs = newSel;
}
}
// Toggle the selected state of the item
internal void SelectedToggle(ListItem item)
{
if (IsSelected(item))
SelectedRemove(item);
else
SelectedAdd(item);
}
// Selection flow. Flows all selection towards the item. Used for SHIFT selection.
void SelectionFlow(ListItem item)
{
if (selectList.Count == 0)
{
SelectedSet(item);
}
else
{
if (!SelectionFlowDown(item))
SelectionFlowUp(item);
}
}
// Select all items up the list
bool SelectionFlowUp(ListItem item)
{
ListItem it;
ListItem limit = item;
for (it = item; it != null; it = it.PrevOpenVisible)
{
if (IsSelected(it))
limit = it;
}
if (item == limit)
return false;
SelectedClear();
SelectedAdd(limit);
for (it = item; it != limit; it = it.PrevOpenVisible)
SelectedAdd(it);
return true;
}
// Select all items down the list
bool SelectionFlowDown(ListItem item)
{
ListItem it;
ListItem limit = item;
for (it = item; it != null; it = it.NextOpenVisible)
{
if (IsSelected(it))
limit = it;
}
if (item == limit)
return false;
SelectedClear();
SelectedAdd(limit);
for (it = item; it != limit; it = it.NextOpenVisible)
SelectedAdd(it);
return true;
}
// Utility function to return the 1st selected item in a list item hierarchy
ListItem SelectedCurrentIn(ListItem root)
{
foreach (KeyValuePair<string, ListItem> de in selectList)
{
if (de.Value.IsChildOf(root))
return de.Value;
}
return null;
}
ListItem SelectedFirstIn(ListItem root)
{
ListItem item = SelectedCurrentIn(root);
ListItem find = item;
while (find != null)
{
if (IsSelected(find))
item = find;
find = find.PrevOpenVisible;
}
return item;
}
ListItem SelectedLastIn(ListItem root)
{
ListItem item = SelectedCurrentIn(root);
ListItem find = item;
while (find != null)
{
if (IsSelected(find))
item = find;
find = find.NextOpenVisible;
}
return item;
}
// Display name rules for items.
internal string DisplayName(ListItem item)
{
string name = item.Name;
// Select first nonblank line
string n = "";
string submitMsg = "";
while (n == "")
{
int i = name.IndexOf('\n');
if (i < 0) break;
n = name.Substring(0, i).Trim();
name = name.Substring(i + 1);
submitMsg = name.Trim(new char[] { '\n', '\t' });
}
if (n != "")
name = n;
name = name.Trim();
if (name == "")
{
if (item.Change != null)
{
name = item.Change.id + " " + item.Change.description;
}
}
return name + " " + submitMsg;
}
private bool HasHiddenMetaFile(ListItem item)
{
ListItem twinMeta = GetTwinMeta(item);
return twinMeta != null && twinMeta.Hidden;
}
}
}
| UnityCsReference/Editor/Mono/VersionControl/UI/VCListControl.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControl/UI/VCListControl.cs",
"repo_id": "UnityCsReference",
"token_count": 25684
} | 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 UnityEngine.Bindings;
using UnityEngine.Scripting;
using System.Runtime.InteropServices;
namespace UnityEditor.VersionControl
{
[NativeHeader("Editor/Src/VersionControl/VCConfigField.h")]
[NativeHeader("Editor/Src/VersionControl/VC_bindings.h")]
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public class ConfigField
{
// The bindings generator will set the instance pointer in this field
IntPtr m_Self;
internal ConfigField() {}
~ConfigField()
{
Dispose();
}
public void Dispose()
{
Destroy(m_Self);
m_Self = IntPtr.Zero;
}
[FreeFunction("VersionControlBindings::ConfigField::Destroy", IsThreadSafe = true)]
static extern void Destroy(IntPtr configField);
public extern string name { get; }
public extern string label { get; }
public extern string description { get; }
public extern bool isRequired
{
[NativeMethod("IsRequired")]
get;
}
public extern bool isPassword
{
[NativeMethod("IsPassword")]
get;
}
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(ConfigField configField) => configField.m_Self;
}
}
[NativeHeader("Editor/Src/VersionControl/VCPlugin.h")]
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public class Plugin
{
// The bindings generator will set the instance pointer in this field
IntPtr m_Self;
private Plugin(IntPtr self)
{
m_Self = self;
}
internal Plugin() {}
~Plugin()
{
Dispose();
}
public void Dispose()
{
Destroy(m_Self);
m_Self = IntPtr.Zero;
}
[FreeFunction("VersionControlBindings::Plugin::Destroy", IsThreadSafe = true)]
static extern void Destroy(IntPtr plugin);
static public extern Plugin[] availablePlugins
{
[FreeFunction("VersionControlBindings::Plugin::GetAvailablePlugins")]
get;
}
public extern string name { get; }
public ConfigField[] configFields
{
get
{
return GetConfigFields(m_Self);
}
}
[FreeFunction("VersionControlBindings::Plugin::GetConfigFields")]
static extern ConfigField[] GetConfigFields(IntPtr plugin);
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(Plugin plugin) => plugin.m_Self;
public static Plugin ConvertToManaged(IntPtr ptr) => new Plugin(ptr);
}
}
}
| UnityCsReference/Editor/Mono/VersionControl/VCPlugin.bindings.cs/0 | {
"file_path": "UnityCsReference/Editor/Mono/VersionControl/VCPlugin.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1290
} | 333 |
//
// File autogenerated from Include/C/Baselib_ThreadLocalStorage.h
//
using System;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using size_t = System.UIntPtr;
namespace Unity.Baselib.LowLevel
{
[NativeHeader("baselib/CSharp/BindingsUnity/Baselib_ThreadLocalStorage.gen.binding.h")]
internal static unsafe partial class Binding
{
/// <summary>It's guaranteed that we can allocate at least Baselib_TLS_MinimumGuaranteedSlots values on all platforms.</summary>
public const UInt32 Baselib_TLS_MinimumGuaranteedSlots = 100;
/// <summary>
/// Allocates a new Thread Local Storage slot. In case of an error, abort with Baselib_ErrorCode_OutOfSystemResources will be triggered.
/// On some platforms this might be fiber local storage.
/// </summary>
/// <remarks>The value of a newly create Thread Local Storage slot is guaranteed to be zero on all threads.</remarks>
[FreeFunction(IsThreadSafe = true)]
public static extern UIntPtr Baselib_TLS_Alloc();
/// <summary>Frees provided Thread Local Storage slot.</summary>
[FreeFunction(IsThreadSafe = true)]
public static extern void Baselib_TLS_Free(UIntPtr handle);
/// <summary>Sets value to Thread Local Storage slot.</summary>
[FreeFunction(IsThreadSafe = true)]
public static extern void Baselib_TLS_Set(UIntPtr handle, UIntPtr value);
/// <summary>Gets value from Thread Local Storage slot.</summary>
/// <remarks>If called on just initialized variable, guaranteed to return 0.</remarks>
[FreeFunction(IsThreadSafe = true)]
public static extern UIntPtr Baselib_TLS_Get(UIntPtr handle);
}
}
| UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_ThreadLocalStorage.gen.binding.cs/0 | {
"file_path": "UnityCsReference/External/baselib/baselib/CSharp/BindingsUnity/Baselib_ThreadLocalStorage.gen.binding.cs",
"repo_id": "UnityCsReference",
"token_count": 601
} | 334 |
// 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 UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.AI
{
// Keep this struct in sync with the one defined in "NavMeshBindingTypes.h"
// Result information for NavMesh queries.
[MovedFrom("UnityEngine")]
public struct NavMeshHit
{
Vector3 m_Position;
Vector3 m_Normal;
float m_Distance;
int m_Mask;
int m_Hit;
// Position of hit.
public Vector3 position { get => m_Position; set => m_Position = value; }
// Normal at the point of hit.
public Vector3 normal { get => m_Normal; set => m_Normal = value; }
// Distance to the point of hit.
public float distance { get => m_Distance; set => m_Distance = value; }
// Mask specifying NavMesh area index at point of hit.
public int mask { get => m_Mask; set => m_Mask = value; }
// Flag set when hit.
public bool hit { get => m_Hit != 0; set => m_Hit = value ? 1 : 0; }
}
// Keep this struct in sync with the one defined in "NavMeshBindingTypes.h"
// Contains data describing a triangulation of the navmesh
[UsedByNativeCode]
[MovedFrom("UnityEngine")]
public struct NavMeshTriangulation
{
public Vector3[] vertices;
public int[] indices;
public int[] areas;
[Obsolete("Use areas instead.")]
public int[] layers => areas;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stub class for NavMeshData passing
[NativeHeader("Modules/AI/NavMesh/NavMesh.bindings.h")]
public sealed class NavMeshData : Object
{
public NavMeshData()
{
Internal_Create(this, 0);
}
public NavMeshData(int agentTypeID)
{
Internal_Create(this, agentTypeID);
}
[StaticAccessor("NavMeshDataBindings", StaticAccessorType.DoubleColon)]
static extern void Internal_Create([Writable] NavMeshData mono, int agentTypeID);
public extern Bounds sourceBounds { get; }
public extern Vector3 position { get; set; }
public extern Quaternion rotation { get; set; }
internal extern bool hasHeightMeshData { [NativeMethod("HasHeightMeshData")] get; }
internal extern NavMeshBuildSettings buildSettings { get; }
}
public struct NavMeshDataInstance
{
public bool valid => id != 0 && NavMesh.IsValidNavMeshDataHandle(id);
internal int id { get; set; }
public void Remove()
{
NavMesh.RemoveNavMeshDataInternal(id);
}
public Object owner
{
get => NavMesh.InternalGetOwner(id);
set
{
var ownerID = value != null ? value.GetInstanceID() : 0;
if (!NavMesh.InternalSetOwner(id, ownerID))
Debug.LogError("Cannot set 'owner' on an invalid NavMeshDataInstance");
}
}
internal void FlagAsInSelectionHierarchy()
{
if (valid)
FlagSurfaceAsInSelectionHierarchy(id);
}
[StaticAccessor("GetNavMeshManager()", StaticAccessorType.Dot)]
static extern void FlagSurfaceAsInSelectionHierarchy(int id);
}
// Keep this struct in sync with the one defined in "NavMeshBindingTypes.h"
public struct NavMeshLinkData
{
Vector3 m_StartPosition;
Vector3 m_EndPosition;
float m_CostModifier;
int m_Bidirectional;
float m_Width;
int m_Area;
int m_AgentTypeID;
public Vector3 startPosition { get => m_StartPosition; set => m_StartPosition = value; }
public Vector3 endPosition { get => m_EndPosition; set => m_EndPosition = value; }
public float costModifier { get => m_CostModifier; set => m_CostModifier = value; }
public bool bidirectional { get => m_Bidirectional != 0; set => m_Bidirectional = value ? 1 : 0; }
public float width { get => m_Width; set => m_Width = value; }
public int area { get => m_Area; set => m_Area = value; }
public int agentTypeID { get => m_AgentTypeID; set => m_AgentTypeID = value; }
}
public partial struct NavMeshLinkInstance
{
internal int id { get; set; }
}
public struct NavMeshQueryFilter
{
const int k_AreaCostElementCount = 32;
internal float[] costs { get; private set; }
public int areaMask { get; set; }
public int agentTypeID { get; set; }
public float GetAreaCost(int areaIndex)
{
if (costs == null)
{
if (areaIndex < 0 || areaIndex >= k_AreaCostElementCount)
{
var msg = string.Format("The valid range is [0:{0}]", k_AreaCostElementCount - 1);
throw new IndexOutOfRangeException(msg);
}
return 1.0f;
}
return costs[areaIndex];
}
public void SetAreaCost(int areaIndex, float cost)
{
if (costs == null)
{
costs = new float[k_AreaCostElementCount];
for (int j = 0; j < k_AreaCostElementCount; ++j)
costs[j] = 1.0f;
}
costs[areaIndex] = cost;
}
}
[NativeHeader("Modules/AI/NavMeshManager.h")]
[NativeHeader("Modules/AI/NavMesh/NavMesh.bindings.h")]
[StaticAccessor("NavMeshBindings", StaticAccessorType.DoubleColon)]
[MovedFrom("UnityEngine")]
public static class NavMesh
{
public const int AllAreas = ~0;
public delegate void OnNavMeshPreUpdate();
public static OnNavMeshPreUpdate onPreUpdate;
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void ClearPreUpdateListeners()
{
onPreUpdate = null;
}
[RequiredByNativeCode]
static void Internal_CallOnNavMeshPreUpdate()
{
if (onPreUpdate != null)
onPreUpdate();
}
// Trace a ray between two points on the NavMesh.
public static extern bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int areaMask);
// Calculate a path between two points and store the resulting path.
public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path)
{
path.ClearCorners();
return CalculatePathInternal(sourcePosition, targetPosition, areaMask, path);
}
static extern bool CalculatePathInternal(Vector3 sourcePosition, Vector3 targetPosition, int areaMask, NavMeshPath path);
// Locate the closest NavMesh edge from a point on the NavMesh.
public static extern bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, int areaMask);
// Sample the NavMesh closest to the point specified.
public static extern bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int areaMask);
[Obsolete("Use SetAreaCost instead.")]
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("SetAreaCost")]
public static extern void SetLayerCost(int layer, float cost);
[Obsolete("Use GetAreaCost instead.")]
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaCost")]
public static extern float GetLayerCost(int layer);
[Obsolete("Use GetAreaFromName instead.")]
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaFromName")]
public static extern int GetNavMeshLayerFromName(string layerName);
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("SetAreaCost")]
public static extern void SetAreaCost(int areaIndex, float cost);
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaCost")]
public static extern float GetAreaCost(int areaIndex);
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaFromName")]
public static extern int GetAreaFromName(string areaName);
[StaticAccessor("GetNavMeshProjectSettings()")]
[NativeName("GetAreaNames")]
public static extern string[] GetAreaNames();
public static extern NavMeshTriangulation CalculateTriangulation();
//*undocumented* DEPRECATED
[Obsolete("use NavMesh.CalculateTriangulation() instead.")]
public static void Triangulate(out Vector3[] vertices, out int[] indices)
{
NavMeshTriangulation results = CalculateTriangulation();
vertices = results.vertices;
indices = results.indices;
}
[Obsolete("AddOffMeshLinks has no effect and is deprecated.")]
public static void AddOffMeshLinks() {}
[Obsolete("RestoreNavMesh has no effect and is deprecated.")]
public static void RestoreNavMesh() {}
[StaticAccessor("GetNavMeshManager()")]
public static extern float avoidancePredictionTime { get; set; }
[StaticAccessor("GetNavMeshManager()")]
public static extern int pathfindingIterationsPerFrame { get; set; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData)
{
if (navMeshData == null) throw new ArgumentNullException(nameof(navMeshData));
var handle = new NavMeshDataInstance();
handle.id = AddNavMeshDataInternal(navMeshData);
return handle;
}
public static NavMeshDataInstance AddNavMeshData(NavMeshData navMeshData, Vector3 position, Quaternion rotation)
{
if (navMeshData == null) throw new ArgumentNullException(nameof(navMeshData));
var handle = new NavMeshDataInstance();
handle.id = AddNavMeshDataTransformedInternal(navMeshData, position, rotation);
return handle;
}
public static void RemoveNavMeshData(NavMeshDataInstance handle)
{
RemoveNavMeshDataInternal(handle.id);
}
[StaticAccessor("GetNavMeshManager()")]
[NativeName("IsValidSurfaceID")]
internal static extern bool IsValidNavMeshDataHandle(int handle);
[StaticAccessor("GetNavMeshManager()")]
internal static extern bool IsValidLinkHandle(int handle);
internal static extern Object InternalGetOwner(int dataID);
[StaticAccessor("GetNavMeshManager()")]
[NativeName("SetSurfaceUserID")]
internal static extern bool InternalSetOwner(int dataID, int ownerID);
internal static extern Object InternalGetLinkOwner(int linkID);
[StaticAccessor("GetNavMeshManager()")]
[NativeName("SetLinkUserID")]
internal static extern bool InternalSetLinkOwner(int linkID, int ownerID);
[StaticAccessor("GetNavMeshManager()")]
[NativeName("LoadData")]
internal static extern int AddNavMeshDataInternal(NavMeshData navMeshData);
[StaticAccessor("GetNavMeshManager()")]
[NativeName("LoadData")]
internal static extern int AddNavMeshDataTransformedInternal(NavMeshData navMeshData, Vector3 position, Quaternion rotation);
[StaticAccessor("GetNavMeshManager()")]
[NativeName("UnloadData")]
internal static extern void RemoveNavMeshDataInternal(int handle);
public static NavMeshLinkInstance AddLink(NavMeshLinkData link)
{
var handle = new NavMeshLinkInstance();
handle.id = AddLinkInternal(link, Vector3.zero, Quaternion.identity);
return handle;
}
public static NavMeshLinkInstance AddLink(NavMeshLinkData link, Vector3 position, Quaternion rotation)
{
var handle = new NavMeshLinkInstance();
handle.id = AddLinkInternal(link, position, rotation);
return handle;
}
public static void RemoveLink(NavMeshLinkInstance handle)
{
RemoveLinkInternal(handle.id);
}
public static bool IsLinkActive(NavMeshLinkInstance handle)
{
return IsOffMeshConnectionActive(handle.id);
}
public static void SetLinkActive(NavMeshLinkInstance handle, bool value)
{
SetOffMeshConnectionActive(handle.id, value);
}
public static bool IsLinkOccupied(NavMeshLinkInstance handle)
{
return IsOffMeshConnectionOccupied(handle.id);
}
public static bool IsLinkValid(NavMeshLinkInstance handle)
{
return IsValidLinkHandle(handle.id);
}
public static Object GetLinkOwner(NavMeshLinkInstance handle)
{
return InternalGetLinkOwner(handle.id);
}
public static void SetLinkOwner(NavMeshLinkInstance handle, Object owner)
{
var ownerID = owner != null ? owner.GetInstanceID() : 0;
if (!InternalSetLinkOwner(handle.id, ownerID))
Debug.LogError("Cannot set 'owner' on an invalid NavMeshLinkInstance");
}
[StaticAccessor("GetNavMeshManager()")]
[NativeName("AddLink")]
internal static extern int AddLinkInternal(NavMeshLinkData link, Vector3 position, Quaternion rotation);
[StaticAccessor("GetNavMeshManager()")]
[NativeName("RemoveLink")]
internal static extern void RemoveLinkInternal(int handle);
[StaticAccessor("GetNavMeshManager()")]
internal static extern bool IsOffMeshConnectionOccupied(int handle);
[StaticAccessor("GetNavMeshManager()")]
internal static extern bool IsOffMeshConnectionActive(int linkHandle);
[StaticAccessor("GetNavMeshManager()")]
internal static extern void SetOffMeshConnectionActive(int linkHandle, bool activated);
public static bool SamplePosition(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, NavMeshQueryFilter filter)
{
return SamplePositionFilter(sourcePosition, out hit, maxDistance, filter.agentTypeID, filter.areaMask);
}
// a CUSTOM "SamplePosition" exists elsewhere. We need to pick unique name here to compile generated code in batch-builds
static extern bool SamplePositionFilter(Vector3 sourcePosition, out NavMeshHit hit, float maxDistance, int type, int mask);
public static bool FindClosestEdge(Vector3 sourcePosition, out NavMeshHit hit, NavMeshQueryFilter filter)
{
return FindClosestEdgeFilter(sourcePosition, out hit, filter.agentTypeID, filter.areaMask);
}
// a CUSTOM "FindClosestEdge" exists elsewhere. We need to pick unique name here to compile generated code in batch-builds
static extern bool FindClosestEdgeFilter(Vector3 sourcePosition, out NavMeshHit hit, int type, int mask);
public static bool Raycast(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, NavMeshQueryFilter filter)
{
return RaycastFilter(sourcePosition, targetPosition, out hit, filter.agentTypeID, filter.areaMask);
}
// a CUSTOM "Raycast" exists elsewhere. We need to pick unique name here to compile generated code in batch-builds
static extern bool RaycastFilter(Vector3 sourcePosition, Vector3 targetPosition, out NavMeshHit hit, int type, int mask);
public static bool CalculatePath(Vector3 sourcePosition, Vector3 targetPosition, NavMeshQueryFilter filter, NavMeshPath path)
{
path.ClearCorners();
return CalculatePathFilterInternal(sourcePosition, targetPosition, path, filter.agentTypeID, filter.areaMask, filter.costs);
}
static extern bool CalculatePathFilterInternal(Vector3 sourcePosition, Vector3 targetPosition, NavMeshPath path, int type, int mask, float[] costs);
[StaticAccessor("GetNavMeshProjectSettings()")]
public static extern NavMeshBuildSettings CreateSettings();
//[StaticAccessor("GetNavMeshProjectSettings()")]
//public static extern void UpdateSettings(NavMeshBuildSettings buildSettings);
[StaticAccessor("GetNavMeshProjectSettings()")]
public static extern void RemoveSettings(int agentTypeID);
public static extern NavMeshBuildSettings GetSettingsByID(int agentTypeID);
[StaticAccessor("GetNavMeshProjectSettings()")]
public static extern int GetSettingsCount();
public static extern NavMeshBuildSettings GetSettingsByIndex(int index);
public static extern string GetSettingsNameFromID(int agentTypeID);
[StaticAccessor("GetNavMeshManager()")]
[NativeName("CleanupAfterCarving")]
public static extern void RemoveAllNavMeshData();
}
}
| UnityCsReference/Modules/AI/NavMesh/NavMesh.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/AI/NavMesh/NavMesh.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 6599
} | 335 |
// 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.Accessibility
{
/// <summary>
/// Notifications that the app or the operating system can send.
/// </summary>
[NativeHeader("Modules/Accessibility/Native/AccessibilityNotificationContext.h")]
internal enum AccessibilityNotification
{
/// Default notification value that should not be sent.
None = 0,
/// A notification that an app sends when it needs to convey an
/// announcement to the screen reader.
Announcement = 1,
/// A notification that the operating system sends when the screen
/// reader finishes reading an announcement.
AnnouncementFinished = 2,
/// A notification that the operating system sends when the screen
/// reader is enabled or disabled.
ScreenReaderStatusChanged = 3,
/// A notification that an app sends when a new view appears that
/// occupies a major portion of the screen.
ScreenChanged = 4,
/// A notification that an app sends when the layout of a screen
/// changes.
LayoutChanged = 5,
/// A notification that an app sends when a scroll action completes.
PageScrolled = 6,
/// A notification that the operating system sends when an assistive
/// technology focuses on an accessibility node.
ElementFocused = 7,
/// A notification that the operating system sends when an assistive
/// technology removes focus from an accessibility node.
ElementUnfocused = 8,
/// A notification that the operating system sends when the user
/// changes the font scale in the system settings.
FontScaleChanged = 9,
/// A notification that the operating system sends when the bold
/// text setting changes.
BoldTextStatusChanged = 10,
/// A notification that the operating system sends when the closed
/// captioning setting changes.
ClosedCaptioningStatusChanged = 11,
}
/// <summary>
/// The context of an accessibility notification.
/// </summary>
[RequiredByNativeCode]
[StructLayout(LayoutKind.Sequential)]
[NativeType(CodegenOptions.Custom, "MonoAccessibilityNotificationContext")]
[NativeHeader("Modules/Accessibility/Native/AccessibilityNotificationContext.h")]
[NativeHeader("Modules/Accessibility/Bindings/AccessibilityNotificationContext.bindings.h")]
internal struct AccessibilityNotificationContext
{
/// <summary>
/// The accessibility notification that the app or the operating system
/// sends.
/// </summary>
public AccessibilityNotification notification { get; set; }
/// <summary>
/// Whether a screen reader is enabled.
/// <br/><br/>
/// Present for the following accessibility notifications:
/// <list type="bullet">
/// <item>
/// <description><see cref="AccessibilityNotification.ScreenReaderStatusChanged"/></description>
/// </item>
/// </list>
/// </summary>
public bool isScreenReaderEnabled { get; }
/// <summary>
/// The announcement or description of the new scroll position for the
/// screen reader to output.
/// <br/><br/>
/// Used with the following accessibility notifications:
/// <list type="bullet">
/// <item>
/// <description><see cref="AccessibilityNotification.Announcement"/></description>
/// </item>
/// <item>
/// <description><see cref="AccessibilityNotification.AnnouncementFinished"/></description>
/// </item>
/// <item>
/// <description><see cref="AccessibilityNotification.PageScrolled"/></description>
/// </item>
/// </list>
/// </summary>
public string announcement { get; set; }
/// <summary>
/// Whether the announcement was successful.
/// <br/><br/>
/// Present for the following accessibility notifications:
/// <list type="bullet">
/// <item>
/// <description><see cref="AccessibilityNotification.AnnouncementFinished"/></description>
/// </item>
/// </list>
/// </summary>
public bool wasAnnouncementSuccessful { get; }
/// <summary>
/// The accessibility node that is currently focused.
/// <br/><br/>
/// Present for the following accessibility notifications:
/// <list type="bullet">
/// <item>
/// <description><see cref="AccessibilityNotification.ElementFocused"/></description>
/// </item>
/// </list>
/// </summary>
public int currentNodeId { get; }
/// <summary>
/// The accessibility node for the screen reader to focus after
/// processing the notification.
/// <br/><br/>
/// Used with the following accessibility notifications:
/// <list type="bullet">
/// <item>
/// <description><see cref="AccessibilityNotification.ScreenChanged"/></description>
/// </item>
/// <item>
/// <description><see cref="AccessibilityNotification.LayoutChanged"/></description>
/// </item>
/// </list>
/// </summary>
public int nextNodeId { get; set; }
}
}
| UnityCsReference/Modules/Accessibility/Bindings/AccessibilityNotificationContext.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Accessibility/Bindings/AccessibilityNotificationContext.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2123
} | 336 |
// 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 Unity.Properties;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Accessibility
{
class SearchableLabel : VisualElement
{
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField] string text;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags text_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new SearchableLabel();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
if (ShouldWriteAttributeValue(text_UxmlAttributeFlags))
{
var e = (SearchableLabel)obj;
e.text = text;
}
}
}
private static readonly string s_UssClassName = "searchable-label";
private static readonly string s_LabelTextUssClassName = s_UssClassName + "__text";
private static readonly string s_HighlightUssClassName = s_UssClassName + "__highlight";
private readonly Label m_Label;
private readonly VisualElement m_Highlight;
[CreateProperty]
public string text
{
get => m_Label.text;
set => m_Label.text = value;
}
public SearchableLabel()
{
AddToClassList(s_UssClassName);
m_Label = new Label();
m_Label.AddToClassList(s_LabelTextUssClassName);
m_Highlight = new VisualElement();
m_Highlight.AddToClassList(s_HighlightUssClassName);
Add(m_Label);
Add(m_Highlight);
ClearHighlight();
}
public void ClearHighlight()
{
m_Highlight.style.display = DisplayStyle.None;
}
public void HighlightText(string query)
{
ClearHighlight();
if (string.IsNullOrEmpty(text) || string.IsNullOrEmpty(query))
return;
var indexOf = text.IndexOf(query, StringComparison.OrdinalIgnoreCase);
if (indexOf < 0)
return;
var startPos = m_Label.MeasureTextSize(text[..indexOf], 0, MeasureMode.Undefined, 0, MeasureMode.Undefined);
var endPos = m_Label.MeasureTextSize(text[..(indexOf + query.Length)], 0, MeasureMode.Undefined, 0, MeasureMode.Undefined);
m_Highlight.style.width = endPos.x - startPos.x;
m_Highlight.style.left = startPos.x;
m_Highlight.style.display = DisplayStyle.Flex;
}
}
}
| UnityCsReference/Modules/AccessibilityEditor/Managed/SearchableLabel.cs/0 | {
"file_path": "UnityCsReference/Modules/AccessibilityEditor/Managed/SearchableLabel.cs",
"repo_id": "UnityCsReference",
"token_count": 1305
} | 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 UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Playables;
namespace UnityEngine.Animations
{
public static class AnimationPlayableBinding
{
public static PlayableBinding Create(string name, UnityEngine.Object key)
{
return PlayableBinding.CreateInternal(name, key, typeof(Animator), CreateAnimationOutput);
}
private static PlayableOutput CreateAnimationOutput(PlayableGraph graph, string name)
{
return (PlayableOutput)AnimationPlayableOutput.Create(graph, name, null);
}
}
}
| UnityCsReference/Modules/Animation/Managed/AnimationPlayableBinding.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/Managed/AnimationPlayableBinding.cs",
"repo_id": "UnityCsReference",
"token_count": 257
} | 338 |
// 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 UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Animations
{
[MovedFrom("UnityEngine.Experimental.Animations")]
[NativeHeader("Modules/Animation/ScriptBindings/AnimationHumanStream.bindings.h")]
[NativeHeader("Modules/Animation/Director/AnimationHumanStream.h")]
[RequiredByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public struct AnimationHumanStream
{
private System.IntPtr stream;
public bool isValid
{
get { return stream != System.IntPtr.Zero; }
}
private void ThrowIfInvalid()
{
if (!isValid)
throw new InvalidOperationException("The AnimationHumanStream is invalid.");
}
public float humanScale { get { ThrowIfInvalid(); return GetHumanScale(); } }
public float leftFootHeight { get { ThrowIfInvalid(); return GetFootHeight(true); } }
public float rightFootHeight { get { ThrowIfInvalid(); return GetFootHeight(false); } }
public Vector3 bodyLocalPosition
{
get { ThrowIfInvalid(); return InternalGetBodyLocalPosition(); }
set { ThrowIfInvalid(); InternalSetBodyLocalPosition(value); }
}
public Quaternion bodyLocalRotation
{
get { ThrowIfInvalid(); return InternalGetBodyLocalRotation(); }
set { ThrowIfInvalid(); InternalSetBodyLocalRotation(value); }
}
public Vector3 bodyPosition
{
get { ThrowIfInvalid(); return InternalGetBodyPosition(); }
set { ThrowIfInvalid(); InternalSetBodyPosition(value); }
}
public Quaternion bodyRotation
{
get { ThrowIfInvalid(); return InternalGetBodyRotation(); }
set { ThrowIfInvalid(); InternalSetBodyRotation(value); }
}
public float GetMuscle(MuscleHandle muscle) { ThrowIfInvalid(); return InternalGetMuscle(muscle); }
public void SetMuscle(MuscleHandle muscle, float value) { ThrowIfInvalid(); InternalSetMuscle(muscle, value); }
public Vector3 leftFootVelocity { get { ThrowIfInvalid(); return GetLeftFootVelocity(); } }
public Vector3 rightFootVelocity { get { ThrowIfInvalid(); return GetRightFootVelocity(); } }
// IK goals
public void ResetToStancePose() { ThrowIfInvalid(); InternalResetToStancePose(); }
public Vector3 GetGoalPositionFromPose(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalPositionFromPose(index); }
public Quaternion GetGoalRotationFromPose(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalRotationFromPose(index); }
public Vector3 GetGoalLocalPosition(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalLocalPosition(index); }
public void SetGoalLocalPosition(AvatarIKGoal index, Vector3 pos) { ThrowIfInvalid(); InternalSetGoalLocalPosition(index, pos); }
public Quaternion GetGoalLocalRotation(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalLocalRotation(index); }
public void SetGoalLocalRotation(AvatarIKGoal index, Quaternion rot) { ThrowIfInvalid(); InternalSetGoalLocalRotation(index, rot); }
public Vector3 GetGoalPosition(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalPosition(index); }
public void SetGoalPosition(AvatarIKGoal index, Vector3 pos) { ThrowIfInvalid(); InternalSetGoalPosition(index, pos); }
public Quaternion GetGoalRotation(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalRotation(index); }
public void SetGoalRotation(AvatarIKGoal index, Quaternion rot) { ThrowIfInvalid(); InternalSetGoalRotation(index, rot); }
public void SetGoalWeightPosition(AvatarIKGoal index, float value) { ThrowIfInvalid(); InternalSetGoalWeightPosition(index, value); }
public void SetGoalWeightRotation(AvatarIKGoal index, float value) { ThrowIfInvalid(); InternalSetGoalWeightRotation(index, value); }
public float GetGoalWeightPosition(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalWeightPosition(index); }
public float GetGoalWeightRotation(AvatarIKGoal index) { ThrowIfInvalid(); return InternalGetGoalWeightRotation(index); }
// IK Hints
public Vector3 GetHintPosition(AvatarIKHint index) { ThrowIfInvalid(); return InternalGetHintPosition(index); }
public void SetHintPosition(AvatarIKHint index, Vector3 pos) { ThrowIfInvalid(); InternalSetHintPosition(index, pos); }
public void SetHintWeightPosition(AvatarIKHint index, float value) { ThrowIfInvalid(); InternalSetHintWeightPosition(index, value); }
public float GetHintWeightPosition(AvatarIKHint index) { ThrowIfInvalid(); return InternalGetHintWeightPosition(index); }
// Lookat
public void SetLookAtPosition(Vector3 lookAtPosition) { ThrowIfInvalid(); InternalSetLookAtPosition(lookAtPosition); }
public void SetLookAtClampWeight(float weight) { ThrowIfInvalid(); InternalSetLookAtClampWeight(weight); }
public void SetLookAtBodyWeight(float weight) { ThrowIfInvalid(); InternalSetLookAtBodyWeight(weight); }
public void SetLookAtHeadWeight(float weight) { ThrowIfInvalid(); InternalSetLookAtHeadWeight(weight); }
public void SetLookAtEyesWeight(float weight) { ThrowIfInvalid(); InternalSetLookAtEyesWeight(weight); }
public void SolveIK() { ThrowIfInvalid(); InternalSolveIK(); }
[NativeMethod(IsThreadSafe = true)]
private extern float GetHumanScale();
[NativeMethod(IsThreadSafe = true)]
private extern float GetFootHeight(bool left);
[NativeMethod(Name = "ResetToStancePose", IsThreadSafe = true)]
private extern void InternalResetToStancePose();
[NativeMethod(Name = "AnimationHumanStreamBindings::GetGoalPositionFromPose", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 InternalGetGoalPositionFromPose(AvatarIKGoal index);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetGoalRotationFromPose", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Quaternion InternalGetGoalRotationFromPose(AvatarIKGoal index);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetBodyLocalPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 InternalGetBodyLocalPosition();
[NativeMethod(Name = "AnimationHumanStreamBindings::SetBodyLocalPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetBodyLocalPosition(Vector3 value);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetBodyLocalRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Quaternion InternalGetBodyLocalRotation();
[NativeMethod(Name = "AnimationHumanStreamBindings::SetBodyLocalRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetBodyLocalRotation(Quaternion value);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetBodyPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 InternalGetBodyPosition();
[NativeMethod(Name = "AnimationHumanStreamBindings::SetBodyPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetBodyPosition(Vector3 value);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetBodyRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Quaternion InternalGetBodyRotation();
[NativeMethod(Name = "AnimationHumanStreamBindings::SetBodyRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetBodyRotation(Quaternion value);
[NativeMethod(Name = "GetMuscle", IsThreadSafe = true)]
private extern float InternalGetMuscle(MuscleHandle muscle);
[NativeMethod(Name = "SetMuscle", IsThreadSafe = true)]
private extern void InternalSetMuscle(MuscleHandle muscle, float value);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetLeftFootVelocity", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 GetLeftFootVelocity();
[NativeMethod(Name = "AnimationHumanStreamBindings::GetRightFootVelocity", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 GetRightFootVelocity();
[NativeMethod(Name = "AnimationHumanStreamBindings::GetGoalLocalPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 InternalGetGoalLocalPosition(AvatarIKGoal index);
[NativeMethod(Name = "AnimationHumanStreamBindings::SetGoalLocalPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetGoalLocalPosition(AvatarIKGoal index, Vector3 pos);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetGoalLocalRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Quaternion InternalGetGoalLocalRotation(AvatarIKGoal index);
[NativeMethod(Name = "AnimationHumanStreamBindings::SetGoalLocalRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetGoalLocalRotation(AvatarIKGoal index, Quaternion rot);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetGoalPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 InternalGetGoalPosition(AvatarIKGoal index);
[NativeMethod(Name = "AnimationHumanStreamBindings::SetGoalPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetGoalPosition(AvatarIKGoal index, Vector3 pos);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetGoalRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Quaternion InternalGetGoalRotation(AvatarIKGoal index);
[NativeMethod(Name = "AnimationHumanStreamBindings::SetGoalRotation", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetGoalRotation(AvatarIKGoal index, Quaternion rot);
[NativeMethod(Name = "SetGoalWeightPosition", IsThreadSafe = true)]
private extern void InternalSetGoalWeightPosition(AvatarIKGoal index, float value);
[NativeMethod(Name = "SetGoalWeightRotation", IsThreadSafe = true)]
private extern void InternalSetGoalWeightRotation(AvatarIKGoal index, float value);
[NativeMethod(Name = "GetGoalWeightPosition", IsThreadSafe = true)]
private extern float InternalGetGoalWeightPosition(AvatarIKGoal index);
[NativeMethod(Name = "GetGoalWeightRotation", IsThreadSafe = true)]
private extern float InternalGetGoalWeightRotation(AvatarIKGoal index);
[NativeMethod(Name = "AnimationHumanStreamBindings::GetHintPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern Vector3 InternalGetHintPosition(AvatarIKHint index);
[NativeMethod(Name = "AnimationHumanStreamBindings::SetHintPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetHintPosition(AvatarIKHint index, Vector3 pos);
[NativeMethod(Name = "SetHintWeightPosition", IsThreadSafe = true)]
private extern void InternalSetHintWeightPosition(AvatarIKHint index, float value);
[NativeMethod(Name = "GetHintWeightPosition", IsThreadSafe = true)]
private extern float InternalGetHintWeightPosition(AvatarIKHint index);
[NativeMethod(Name = "AnimationHumanStreamBindings::SetLookAtPosition", IsFreeFunction = true, IsThreadSafe = true, HasExplicitThis = true)]
private extern void InternalSetLookAtPosition(Vector3 lookAtPosition);
[NativeMethod(Name = "SetLookAtClampWeight", IsThreadSafe = true)]
private extern void InternalSetLookAtClampWeight(float weight);
[NativeMethod(Name = "SetLookAtBodyWeight", IsThreadSafe = true)]
private extern void InternalSetLookAtBodyWeight(float weight);
[NativeMethod(Name = "SetLookAtHeadWeight", IsThreadSafe = true)]
private extern void InternalSetLookAtHeadWeight(float weight);
[NativeMethod(Name = "SetLookAtEyesWeight", IsThreadSafe = true)]
private extern void InternalSetLookAtEyesWeight(float weight);
[NativeMethod(Name = "SolveIK", IsThreadSafe = true)]
private extern void InternalSolveIK();
}
}
| UnityCsReference/Modules/Animation/ScriptBindings/AnimationHumanStream.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimationHumanStream.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 4655
} | 339 |
// 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.Scripting;
using UnityEngine.Playables;
namespace UnityEngine.Animations
{
[NativeHeader("Modules/Animation/ScriptBindings/AnimatorControllerPlayable.bindings.h")]
[NativeHeader("Modules/Animation/ScriptBindings/Animator.bindings.h")]
[NativeHeader("Modules/Animation/Director/AnimatorControllerPlayable.h")]
[NativeHeader("Modules/Animation/RuntimeAnimatorController.h")]
[NativeHeader("Modules/Animation/AnimatorInfo.h")]
[StaticAccessor("AnimatorControllerPlayableBindings", StaticAccessorType.DoubleColon)]
[RequiredByNativeCode]
public partial struct AnimatorControllerPlayable : IPlayable, IEquatable<AnimatorControllerPlayable>
{
PlayableHandle m_Handle;
static readonly AnimatorControllerPlayable m_NullPlayable = new AnimatorControllerPlayable(PlayableHandle.Null);
public static AnimatorControllerPlayable Null { get { return m_NullPlayable; } }
public static AnimatorControllerPlayable Create(PlayableGraph graph, RuntimeAnimatorController controller)
{
var handle = CreateHandle(graph, controller);
return new AnimatorControllerPlayable(handle);
}
private static PlayableHandle CreateHandle(PlayableGraph graph, RuntimeAnimatorController controller)
{
PlayableHandle handle = PlayableHandle.Null;
if (!CreateHandleInternal(graph, controller, ref handle))
return PlayableHandle.Null;
return handle;
}
internal AnimatorControllerPlayable(PlayableHandle handle)
{
m_Handle = PlayableHandle.Null;
SetHandle(handle);
}
public PlayableHandle GetHandle()
{
return m_Handle;
}
public void SetHandle(PlayableHandle handle)
{
if (m_Handle.IsValid())
throw new InvalidOperationException("Cannot call IPlayable.SetHandle on an instance that already contains a valid handle.");
if (handle.IsValid())
{
if (!handle.IsPlayableOfType<AnimatorControllerPlayable>())
throw new InvalidCastException("Can't set handle: the playable is not an AnimatorControllerPlayable.");
}
m_Handle = handle;
}
public static implicit operator Playable(AnimatorControllerPlayable playable)
{
return new Playable(playable.GetHandle());
}
public static explicit operator AnimatorControllerPlayable(Playable playable)
{
return new AnimatorControllerPlayable(playable.GetHandle());
}
public bool Equals(AnimatorControllerPlayable other)
{
return GetHandle() == other.GetHandle();
}
// Gets the value of a float parameter
public float GetFloat(string name)
{
return GetFloatString(ref m_Handle, name);
}
// Gets the value of a float parameter
public float GetFloat(int id)
{
return GetFloatID(ref m_Handle, id);
}
// Sets the value of a float parameter
public void SetFloat(string name, float value)
{
SetFloatString(ref m_Handle, name, value);
}
// Sets the value of a float parameter
public void SetFloat(int id, float value)
{
SetFloatID(ref m_Handle, id, value);
}
// Gets the value of a bool parameter
public bool GetBool(string name)
{
return GetBoolString(ref m_Handle, name);
}
// Gets the value of a bool parameter
public bool GetBool(int id)
{
return GetBoolID(ref m_Handle, id);
}
// Sets the value of a bool parameter
public void SetBool(string name, bool value)
{
SetBoolString(ref m_Handle, name, value);
}
// Sets the value of a bool parameter
public void SetBool(int id, bool value)
{
SetBoolID(ref m_Handle, id, value);
}
// Gets the value of an integer parameter
public int GetInteger(string name)
{
return GetIntegerString(ref m_Handle, name);
}
// Gets the value of an integer parameter
public int GetInteger(int id)
{
return GetIntegerID(ref m_Handle, id);
}
// Sets the value of an integer parameter
public void SetInteger(string name, int value)
{
SetIntegerString(ref m_Handle, name, value);
}
// Sets the value of an integer parameter
public void SetInteger(int id, int value)
{
SetIntegerID(ref m_Handle, id, value);
}
// Sets the trigger parameter on
public void SetTrigger(string name)
{
SetTriggerString(ref m_Handle, name);
}
// Sets the trigger parameter at on
public void SetTrigger(int id)
{
SetTriggerID(ref m_Handle, id);
}
// Resets the trigger parameter at off
public void ResetTrigger(string name)
{
ResetTriggerString(ref m_Handle, name);
}
// Resets the trigger parameter at off
public void ResetTrigger(int id)
{
ResetTriggerID(ref m_Handle, id);
}
// Returns true if a parameter is controlled by an additional curve on an animation
public bool IsParameterControlledByCurve(string name)
{
return IsParameterControlledByCurveString(ref m_Handle, name);
}
// Returns true if a parameter is controlled by an additional curve on an animation
public bool IsParameterControlledByCurve(int id)
{
return IsParameterControlledByCurveID(ref m_Handle, id);
}
// The AnimatorController layer count
public int GetLayerCount()
{
return GetLayerCountInternal(ref m_Handle);
}
public string GetLayerName(int layerIndex)
{
return GetLayerNameInternal(ref m_Handle, layerIndex);
}
public int GetLayerIndex(string layerName)
{
return GetLayerIndexInternal(ref m_Handle, layerName);
}
public float GetLayerWeight(int layerIndex)
{
return GetLayerWeightInternal(ref m_Handle, layerIndex);
}
public void SetLayerWeight(int layerIndex, float weight)
{
SetLayerWeightInternal(ref m_Handle, layerIndex, weight);
}
public AnimatorStateInfo GetCurrentAnimatorStateInfo(int layerIndex)
{
return GetCurrentAnimatorStateInfoInternal(ref m_Handle, layerIndex);
}
public AnimatorStateInfo GetNextAnimatorStateInfo(int layerIndex)
{
return GetNextAnimatorStateInfoInternal(ref m_Handle, layerIndex);
}
// Gets the Transition information on a specified AnimatorController layer
public AnimatorTransitionInfo GetAnimatorTransitionInfo(int layerIndex)
{
return GetAnimatorTransitionInfoInternal(ref m_Handle, layerIndex);
}
public AnimatorClipInfo[] GetCurrentAnimatorClipInfo(int layerIndex)
{
return GetCurrentAnimatorClipInfoInternal(ref m_Handle, layerIndex);
}
// Gets the list of AnimatorClipInfo currently played by the current state
public void GetCurrentAnimatorClipInfo(int layerIndex, List<AnimatorClipInfo> clips)
{
if (clips == null) throw new ArgumentNullException("clips");
GetAnimatorClipInfoInternal(ref m_Handle, layerIndex, true, clips);
}
// Gets the list of AnimatorClipInfo currently played by the next state
public void GetNextAnimatorClipInfo(int layerIndex, List<AnimatorClipInfo> clips)
{
if (clips == null) throw new ArgumentNullException("clips");
GetAnimatorClipInfoInternal(ref m_Handle, layerIndex, false, clips);
}
[NativeThrows]
extern private static void GetAnimatorClipInfoInternal(ref PlayableHandle handle, int layerIndex, bool isCurrent, object clips);
// Gets the number of AnimatorClipInfo currently played by the current state
public int GetCurrentAnimatorClipInfoCount(int layerIndex)
{
return GetAnimatorClipInfoCountInternal(ref m_Handle, layerIndex, true);
}
// Gets the number of AnimatorClipInfo currently played by the next state
public int GetNextAnimatorClipInfoCount(int layerIndex)
{
return GetAnimatorClipInfoCountInternal(ref m_Handle, layerIndex, false);
}
public AnimatorClipInfo[] GetNextAnimatorClipInfo(int layerIndex)
{
return GetNextAnimatorClipInfoInternal(ref m_Handle, layerIndex);
}
public bool IsInTransition(int layerIndex)
{
return IsInTransitionInternal(ref m_Handle, layerIndex);
}
public int GetParameterCount()
{
return GetParameterCountInternal(ref m_Handle);
}
public AnimatorControllerParameter GetParameter(int index)
{
var parameter = GetParameterInternal(ref m_Handle, index);
if ((int)parameter.m_Type == AnimatorControllerParameterTypeConstants.InvalidType)
throw new IndexOutOfRangeException("Invalid parameter index.");
return parameter;
}
public void CrossFadeInFixedTime(string stateName, float transitionDuration)
{
CrossFadeInFixedTimeInternal(ref m_Handle, StringToHash(stateName), transitionDuration, -1, 0.0f);
}
public void CrossFadeInFixedTime(string stateName, float transitionDuration, int layer)
{
CrossFadeInFixedTimeInternal(ref m_Handle, StringToHash(stateName), transitionDuration, layer, 0.0f);
}
public void CrossFadeInFixedTime(string stateName, float transitionDuration, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("0.0f")] float fixedTime)
{
CrossFadeInFixedTimeInternal(ref m_Handle, StringToHash(stateName), transitionDuration, layer, fixedTime);
}
public void CrossFadeInFixedTime(int stateNameHash, float transitionDuration)
{
CrossFadeInFixedTimeInternal(ref m_Handle, stateNameHash, transitionDuration, -1, 0.0f);
}
public void CrossFadeInFixedTime(int stateNameHash, float transitionDuration, int layer)
{
CrossFadeInFixedTimeInternal(ref m_Handle, stateNameHash, transitionDuration, layer, 0.0f);
}
public void CrossFadeInFixedTime(int stateNameHash, float transitionDuration, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("0.0f")] float fixedTime)
{
CrossFadeInFixedTimeInternal(ref m_Handle, stateNameHash, transitionDuration, layer, fixedTime);
}
public void CrossFade(string stateName, float transitionDuration)
{
CrossFadeInternal(ref m_Handle, StringToHash(stateName), transitionDuration, -1, float.NegativeInfinity);
}
public void CrossFade(string stateName, float transitionDuration, int layer)
{
CrossFadeInternal(ref m_Handle, StringToHash(stateName), transitionDuration, layer, float.NegativeInfinity);
}
public void CrossFade(string stateName, float transitionDuration, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("float.NegativeInfinity")] float normalizedTime)
{
CrossFadeInternal(ref m_Handle, StringToHash(stateName), transitionDuration, layer, normalizedTime);
}
public void CrossFade(int stateNameHash, float transitionDuration)
{
CrossFadeInternal(ref m_Handle, stateNameHash, transitionDuration, -1, float.NegativeInfinity);
}
public void CrossFade(int stateNameHash, float transitionDuration, int layer)
{
CrossFadeInternal(ref m_Handle, stateNameHash, transitionDuration, layer, float.NegativeInfinity);
}
public void CrossFade(int stateNameHash, float transitionDuration, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("float.NegativeInfinity")] float normalizedTime)
{
CrossFadeInternal(ref m_Handle, stateNameHash, transitionDuration, layer, normalizedTime);
}
public void PlayInFixedTime(string stateName)
{
PlayInFixedTimeInternal(ref m_Handle, StringToHash(stateName), -1, float.NegativeInfinity);
}
public void PlayInFixedTime(string stateName, int layer)
{
PlayInFixedTimeInternal(ref m_Handle, StringToHash(stateName), layer, float.NegativeInfinity);
}
public void PlayInFixedTime(string stateName, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("float.NegativeInfinity")] float fixedTime)
{
PlayInFixedTimeInternal(ref m_Handle, StringToHash(stateName), layer, fixedTime);
}
public void PlayInFixedTime(int stateNameHash)
{
PlayInFixedTimeInternal(ref m_Handle, stateNameHash, -1, float.NegativeInfinity);
}
public void PlayInFixedTime(int stateNameHash, int layer)
{
PlayInFixedTimeInternal(ref m_Handle, stateNameHash, layer, float.NegativeInfinity);
}
public void PlayInFixedTime(int stateNameHash, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("float.NegativeInfinity")] float fixedTime)
{
PlayInFixedTimeInternal(ref m_Handle, stateNameHash, layer, fixedTime);
}
public void Play(string stateName)
{
PlayInternal(ref m_Handle, StringToHash(stateName), -1, float.NegativeInfinity);
}
public void Play(string stateName, int layer)
{
PlayInternal(ref m_Handle, StringToHash(stateName), layer, float.NegativeInfinity);
}
public void Play(string stateName, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("float.NegativeInfinity")] float normalizedTime)
{
PlayInternal(ref m_Handle, StringToHash(stateName), layer, normalizedTime);
}
public void Play(int stateNameHash)
{
PlayInternal(ref m_Handle, stateNameHash, -1, float.NegativeInfinity);
}
public void Play(int stateNameHash, int layer)
{
PlayInternal(ref m_Handle, stateNameHash, layer, float.NegativeInfinity);
}
public void Play(int stateNameHash, [UnityEngine.Internal.DefaultValue("-1")] int layer, [UnityEngine.Internal.DefaultValue("float.NegativeInfinity")] float normalizedTime)
{
PlayInternal(ref m_Handle, stateNameHash, layer, normalizedTime);
}
public bool HasState(int layerIndex, int stateID)
{
return HasStateInternal(ref m_Handle, layerIndex, stateID);
}
internal string ResolveHash(int hash)
{
return ResolveHashInternal(ref m_Handle, hash);
}
[NativeThrows]
extern private static bool CreateHandleInternal(PlayableGraph graph, RuntimeAnimatorController controller, ref PlayableHandle handle);
[NativeThrows]
extern private static RuntimeAnimatorController GetAnimatorControllerInternal(ref PlayableHandle handle);
[NativeThrows]
extern private static int GetLayerCountInternal(ref PlayableHandle handle);
[NativeThrows]
extern private static string GetLayerNameInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static int GetLayerIndexInternal(ref PlayableHandle handle, string layerName);
[NativeThrows]
extern private static float GetLayerWeightInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static void SetLayerWeightInternal(ref PlayableHandle handle, int layerIndex, float weight);
[NativeThrows]
extern private static AnimatorStateInfo GetCurrentAnimatorStateInfoInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static AnimatorStateInfo GetNextAnimatorStateInfoInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static AnimatorTransitionInfo GetAnimatorTransitionInfoInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static AnimatorClipInfo[] GetCurrentAnimatorClipInfoInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static int GetAnimatorClipInfoCountInternal(ref PlayableHandle handle, int layerIndex, bool current);
[NativeThrows]
extern private static AnimatorClipInfo[] GetNextAnimatorClipInfoInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static string ResolveHashInternal(ref PlayableHandle handle, int hash);
[NativeThrows]
extern private static bool IsInTransitionInternal(ref PlayableHandle handle, int layerIndex);
[NativeThrows]
extern private static AnimatorControllerParameter GetParameterInternal(ref PlayableHandle handle, int index);
[NativeThrows]
extern private static int GetParameterCountInternal(ref PlayableHandle handle);
[ThreadSafe]
extern private static int StringToHash(string name);
[NativeThrows]
extern private static void CrossFadeInFixedTimeInternal(ref PlayableHandle handle, int stateNameHash, float transitionDuration, int layer, float fixedTime);
[NativeThrows]
extern private static void CrossFadeInternal(ref PlayableHandle handle, int stateNameHash, float transitionDuration, int layer, float normalizedTime);
[NativeThrows]
extern private static void PlayInFixedTimeInternal(ref PlayableHandle handle, int stateNameHash, int layer, float fixedTime);
[NativeThrows]
extern private static void PlayInternal(ref PlayableHandle handle, int stateNameHash, int layer, float normalizedTime);
[NativeThrows]
extern private static bool HasStateInternal(ref PlayableHandle handle, int layerIndex, int stateID);
[NativeThrows]
extern private static void SetFloatString(ref PlayableHandle handle, string name, float value);
[NativeThrows]
extern private static void SetFloatID(ref PlayableHandle handle, int id, float value);
[NativeThrows]
extern private static float GetFloatString(ref PlayableHandle handle, string name);
[NativeThrows]
extern private static float GetFloatID(ref PlayableHandle handle, int id);
[NativeThrows]
extern private static void SetBoolString(ref PlayableHandle handle, string name, bool value);
[NativeThrows]
extern private static void SetBoolID(ref PlayableHandle handle, int id, bool value);
[NativeThrows]
extern private static bool GetBoolString(ref PlayableHandle handle, string name);
[NativeThrows]
extern private static bool GetBoolID(ref PlayableHandle handle, int id);
[NativeThrows]
extern private static void SetIntegerString(ref PlayableHandle handle, string name, int value);
[NativeThrows]
extern private static void SetIntegerID(ref PlayableHandle handle, int id, int value);
[NativeThrows]
extern private static int GetIntegerString(ref PlayableHandle handle, string name);
[NativeThrows]
extern private static int GetIntegerID(ref PlayableHandle handle, int id);
[NativeThrows]
extern private static void SetTriggerString(ref PlayableHandle handle, string name);
[NativeThrows]
extern private static void SetTriggerID(ref PlayableHandle handle, int id);
[NativeThrows]
extern private static void ResetTriggerString(ref PlayableHandle handle, string name);
[NativeThrows]
extern private static void ResetTriggerID(ref PlayableHandle handle, int id);
[NativeThrows]
extern private static bool IsParameterControlledByCurveString(ref PlayableHandle handle, string name);
[NativeThrows]
extern private static bool IsParameterControlledByCurveID(ref PlayableHandle handle, int id);
}
}
| UnityCsReference/Modules/Animation/ScriptBindings/AnimatorControllerPlayable.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimatorControllerPlayable.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 8038
} | 340 |
// 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.Scripting;
namespace UnityEngine
{
[NativeHeader("Modules/Animation/RuntimeAnimatorController.h")]
[UsedByNativeCode]
[ExcludeFromObjectFactory]
public partial class RuntimeAnimatorController : Object
{
protected RuntimeAnimatorController() {}
extern public AnimationClip[] animationClips { get; }
}
}
| UnityCsReference/Modules/Animation/ScriptBindings/RuntimeAnimatorController.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Animation/ScriptBindings/RuntimeAnimatorController.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 178
} | 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.Bindings;
namespace UnityEditor
{
[NativeHeader("Modules/AssetDatabase/Editor/ScriptBindings/CacheServer.bindings.h")]
[StaticAccessor("CacheServerBindings", StaticAccessorType.DoubleColon)]
public class CacheServer
{
private CacheServer() {}
[PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_ManagedException)]
extern public static void UploadArtifacts(GUID[] guids = null, bool uploadAllRevisions = false);
[PreventExecutionInState(AssetDatabasePreventExecution.kImportingAsset, PreventExecutionSeverity.PreventExecution_ManagedException)]
extern public static void UploadShaderCache();
}
}
| UnityCsReference/Modules/AssetDatabase/Editor/ScriptBindings/CacheServer.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetDatabase/Editor/ScriptBindings/CacheServer.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 286
} | 342 |
// 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 UnityEditorInternal;
using System.Collections.Generic;
using UnityEditor.AssetImporters;
using UnityEngine.Profiling;
using Object = UnityEngine.Object;
using System.Globalization;
using System.Linq;
namespace UnityEditor
{
internal class ModelImporterClipEditor : BaseAssetImporterTabUI
{
AnimationClipEditor m_AnimationClipEditor;
ModelImporter singleImporter { get { return targets[0] as ModelImporter; } }
internal const string ActiveClipIndex = "ModelImporterClipEditor.ActiveClipIndex";
public string selectedClipName
{
get
{
var clipInfo = GetSelectedClipInfo();
return clipInfo != null ? clipInfo.name : "";
}
}
private class ClipInformation
{
SerializedProperty prop;
public ClipInformation(SerializedProperty clipProperty)
{
prop = clipProperty;
animationClipProperty = clipProperty;
}
public SerializedProperty animationClipProperty { get; }
AnimationClipInfoProperties m_Property;
public AnimationClipInfoProperties property => m_Property ?? (m_Property = new AnimationClipInfoProperties(animationClipProperty));
public string name
{
get { return prop.FindPropertyRelative("name").stringValue; }
}
public string firstFrame
{
get { return prop.FindPropertyRelative("firstFrame").floatValue.ToString("0.0", CultureInfo.InvariantCulture.NumberFormat); }
}
public string lastFrame
{
get { return prop.FindPropertyRelative("lastFrame").floatValue.ToString("0.0", CultureInfo.InvariantCulture.NumberFormat); }
}
}
SerializedObject m_DefaultClipsSerializedObject = null;
#pragma warning disable 0649
[CacheProperty]
SerializedProperty m_AnimationType;
[CacheProperty]
SerializedProperty m_ImportAnimation;
[CacheProperty]
SerializedProperty m_ClipAnimations;
[CacheProperty]
SerializedProperty m_BakeSimulation;
[CacheProperty]
SerializedProperty m_ResampleCurves;
[CacheProperty]
SerializedProperty m_AnimationCompression;
[CacheProperty]
SerializedProperty m_AnimationRotationError;
[CacheProperty]
SerializedProperty m_AnimationPositionError;
[CacheProperty]
SerializedProperty m_AnimationScaleError;
[CacheProperty]
SerializedProperty m_AnimationWrapMode;
[CacheProperty]
SerializedProperty m_LegacyGenerateAnimations;
[CacheProperty]
SerializedProperty m_ImportAnimatedCustomProperties;
[CacheProperty]
SerializedProperty m_ImportConstraints;
[CacheProperty]
SerializedProperty m_MotionNodeName;
[CacheProperty]
SerializedProperty m_RemoveConstantScaleCurves;
[CacheProperty]
SerializedProperty m_ContainsAnimation;
#pragma warning restore 0649
public int motionNodeIndex { get; set; }
public int pivotNodeIndex { get; set; }
#pragma warning disable 0649
[CacheProperty]
private SerializedProperty m_AnimationImportErrors;
[CacheProperty]
private SerializedProperty m_AnimationImportWarnings;
[CacheProperty]
private SerializedProperty m_AnimationRetargetingWarnings;
[CacheProperty]
private SerializedProperty m_AnimationDoRetargetingWarnings;
#pragma warning restore 0649
string m_Errors;
string m_Warnings;
string m_RetargetWarnings;
GUIContent[] m_MotionNodeList;
private static bool s_MotionNodeFoldout = false;
private static bool s_ImportMessageFoldout = false;
//Prefix used to pick up errors concerning the rig importation
private const string k_RigErrorPrefix = "Rig Error: ";
ReorderableList m_ClipList;
private string[] referenceTransformPaths
{
get { return singleImporter.transformPaths; }
}
private ModelImporterAnimationType animationType
{
get { return (ModelImporterAnimationType)m_AnimationType.intValue; }
set { m_AnimationType.intValue = (int)value; }
}
private ModelImporterGenerateAnimations legacyGenerateAnimations
{
get { return (ModelImporterGenerateAnimations)m_LegacyGenerateAnimations.intValue; }
set { m_LegacyGenerateAnimations.intValue = (int)value; }
}
private class Styles
{
public GUIContent ErrorsFoundWhileImportingThisAnimation = EditorGUIUtility.TrTextContentWithIcon("Error(s) found while importing this animation file. Open \"Import Messages\" foldout below for more details.", MessageType.Error);
public GUIContent WarningsFoundWhileImportingRig = EditorGUIUtility.TrTextContentWithIcon("Warning(s) found while importing rig in this animation file. Open \"Rig\" tab for more details.", MessageType.Warning);
public GUIContent WarningsFoundWhileImportingThisAnimation = EditorGUIUtility.TrTextContentWithIcon("Warning(s) found while importing this animation file. Open \"Import Messages\" foldout below for more details.", MessageType.Warning);
public GUIContent ImportAnimations = EditorGUIUtility.TrTextContent("Import Animation", "Controls if animations are imported.");
public GUIStyle numberStyle = new GUIStyle(EditorStyles.label);
public GUIContent AnimWrapModeLabel = EditorGUIUtility.TrTextContent("Wrap Mode", "The default Wrap Mode for the animation in the mesh being imported.");
public GUIContent[] AnimWrapModeOpt =
{
EditorGUIUtility.TrTextContent("Default", "The animation plays as specified in the animation splitting options below."),
EditorGUIUtility.TrTextContent("Once", "The animation plays through to the end once and then stops."),
EditorGUIUtility.TrTextContent("Loop", "The animation plays through and then restarts when the end is reached."),
EditorGUIUtility.TrTextContent("PingPong", "The animation plays through and then plays in reverse from the end to the start, and so on."),
EditorGUIUtility.TrTextContent("ClampForever", "The animation plays through, but the last frame is repeated indefinitely. This is not the same as Once mode because playback does not technically stop at the last frame (which is useful when blending animations).")
};
public GUIContent BakeIK = EditorGUIUtility.TrTextContent("Bake Animations", "Enable this when using IK or simulation in your animation package. Unity will convert to forward kinematics on import. This option is available only for Maya, 3dsMax and Cinema4D files.");
public GUIContent ResampleCurves = EditorGUIUtility.TrTextContent("Resample Curves ", " Curves will be resampled on every frame. Use this if you're having issues with the interpolation between keys in your original animation. Disable this to keep curves as close as possible to how they were originally authored.");
public GUIContent AnimCompressionLabel = EditorGUIUtility.TrTextContent("Anim. Compression", "The type of compression that will be applied to this mesh's animation(s).");
public GUIContent[] AnimCompressionOptLegacy =
{
EditorGUIUtility.TrTextContent("Off", "Disables animation compression. This means that Unity doesn't reduce keyframe count on import, which leads to the highest precision animations, but slower performance and bigger file and runtime memory size. It is generally not advisable to use this option - if you need higher precision animation, you should enable keyframe reduction and lower allowed Animation Compression Error values instead."),
EditorGUIUtility.TrTextContent("Keyframe Reduction", "Reduces keyframes on import. If selected, the Animation Compression Errors options are displayed."),
EditorGUIUtility.TrTextContent("Keyframe Reduction and Compression", "Reduces keyframes on import and compresses keyframes when storing animations in files. This affects only file size - the runtime memory size is the same as Keyframe Reduction. If selected, the Animation Compression Errors options are displayed.")
};
public GUIContent[] AnimCompressionOpt =
{
EditorGUIUtility.TrTextContent("Off", "Disables animation compression. This means that Unity doesn't reduce keyframe count on import, which leads to the highest precision animations, but slower performance and bigger file and runtime memory size. It is generally not advisable to use this option - if you need higher precision animation, you should enable keyframe reduction and lower allowed Animation Compression Error values instead."),
EditorGUIUtility.TrTextContent("Keyframe Reduction", "Reduces keyframes on import. If selected, the Animation Compression Errors options are displayed."),
EditorGUIUtility.TrTextContent("Optimal", "Reduces keyframes on import and choose between different curve representations to reduce memory usage at runtime. This affects the runtime memory size and how curves are evaluated.")
};
public GUIContent AnimRotationErrorLabel = EditorGUIUtility.TrTextContent("Rotation Error", "Defines how much rotation curves should be reduced. The smaller value you use - the higher precision you get.");
public GUIContent AnimPositionErrorLabel = EditorGUIUtility.TrTextContent("Position Error", "Defines how much position curves should be reduced. The smaller value you use - the higher precision you get.");
public GUIContent AnimScaleErrorLabel = EditorGUIUtility.TrTextContent("Scale Error", "Defines how much scale curves should be reduced. The smaller value you use - the higher precision you get.");
public GUIContent AnimationCompressionHelp = EditorGUIUtility.TrTextContent("Rotation error is defined as maximum angle deviation allowed in degrees, for others it is defined as maximum distance/delta deviation allowed in percents");
public GUIContent clipMultiEditInfo = EditorGUIUtility.TrTextContent("Multi-object editing of clips not supported.");
public GUIContent updateMuscleDefinitionFromSource = EditorGUIUtility.TrTextContent("Update", "Update the copy of the muscle definition from the source.");
public GUIContent MotionSetting = EditorGUIUtility.TrTextContent("Motion", "Advanced setting for root motion and blending pivot");
public GUIContent MotionNode = EditorGUIUtility.TrTextContent("Root Motion Node", "Define a transform node that will be used to create root motion curves");
public GUIContent ImportMessages = EditorGUIUtility.TrTextContent("Import Messages");
public GUIContent GenerateRetargetingWarnings = EditorGUIUtility.TrTextContent("Generate Retargeting Quality Report");
public GUIContent RetargetingQualityCompares = EditorGUIUtility.TrTextContentWithIcon("Retargeting Quality compares retargeted with original animation. It reports average and maximum position/orientation difference for body parts. It may slow down import time of this file.", MessageType.Info);
public GUIContent AnimationDataWas = EditorGUIUtility.TrTextContentWithIcon("Animation data was imported using a deprecated Generation option in the Rig tab. Please switch to a non-deprecated import mode in the Rig tab to be able to edit the animation import settings.", MessageType.Info);
public GUIContent TheAnimationsSettingsCanBe = EditorGUIUtility.TrTextContentWithIcon("The animations settings can be edited after clicking Apply.", MessageType.Info);
public GUIContent ErrorsFoundWhileImporting = EditorGUIUtility.TrTextContentWithIcon("Error(s) found while importing rig in this animation file. Open \"Rig\" tab for more details.", MessageType.Error);
public GUIContent NoAnimationDataAvailable = EditorGUIUtility.TrTextContentWithIcon("No animation data available in this model.", MessageType.Info);
public GUIContent TheRigsOfTheSelectedModelsHave = EditorGUIUtility.TrTextContentWithIcon("The rigs of the selected models have different Animation Types.", MessageType.Info);
public GUIContent TheRigsOfTheSelectedModelsAre = EditorGUIUtility.TrTextContentWithIcon("The rigs of the selected models are not setup to handle animation. Change the Animation Type in the Rig tab and click Apply.", MessageType.Info);
public GUIContent Clips = EditorGUIUtility.TrTextContent("Clips");
public GUIContent Start = EditorGUIUtility.TrTextContent("Start");
public GUIContent End = EditorGUIUtility.TrTextContent("End");
public GUIContent MaskHasAPath = EditorGUIUtility.TrTextContent("Mask has a path that does not match the transform hierarchy. Animation may not import correctly.");
public GUIContent UpdateMask = EditorGUIUtility.TrTextContent("Update Mask");
public GUIContent SourceMaskHasChanged = EditorGUIUtility.TrTextContent("Source Mask has changed since last import and must be updated.");
public GUIContent SourceMaskHasAPath = EditorGUIUtility.TrTextContent("Source Mask has a path that does not match the transform hierarchy. Animation may not import correctly.");
public GUIContent Mask = EditorGUIUtility.TrTextContent("Mask", "Configure the mask for this clip to remove unnecessary curves.");
public GUIContent ImportAnimatedCustomProperties = EditorGUIUtility.TrTextContent("Import Animated Custom Properties", "Controls if animated custom properties are imported.");
public GUIContent ImportConstraints = EditorGUIUtility.TrTextContent("Import Constraints", "Controls if the constraints are imported.");
public GUIContent RemoveConstantScaleCurves = EditorGUIUtility.TrTextContent("Remove Constant Scale Curves", "Removes constant animation curves with values identical to the object initial scale value.");
public Styles()
{
numberStyle.alignment = TextAnchor.UpperRight;
}
}
static Styles styles;
public ModelImporterClipEditor(AssetImporterEditor panelContainer)
: base(panelContainer)
{
//Generate new Clip List
m_ClipList = new ReorderableList(new List<ClipInformation>(), typeof(string), false, true, true, true);
m_ClipList.onAddCallback = AddClipInList;
m_ClipList.onSelectCallback = SelectClipInList;
m_ClipList.onRemoveCallback = RemoveClipInList;
m_ClipList.drawElementCallback = DrawClipElement;
m_ClipList.drawHeaderCallback = DrawClipHeader;
m_ClipList.elementHeight = EditorGUI.kSingleLineHeight;
}
internal override void OnEnable()
{
Editor.AssignCachedProperties(this, serializedObject.GetIterator());
// caching errors values now as they can't change until next re-import that will triggers a new OnEnable
m_Errors = m_AnimationImportErrors.stringValue;
m_Warnings = m_AnimationImportWarnings.stringValue;
m_RetargetWarnings = m_AnimationRetargetingWarnings.stringValue;
RegisterListeners();
if (serializedObject.isEditingMultipleObjects)
return;
//Sometimes we dont want to start at the 0th index, this is where we're editing a clip - see
m_ClipList.index = EditorPrefs.GetInt(ActiveClipIndex, 0);
EditorPrefs.DeleteKey(ActiveClipIndex);
//Reset the Model Importer to its serialized copy
DeserializeClips();
string[] transformPaths = singleImporter.transformPaths;
m_MotionNodeList = new GUIContent[transformPaths.Length + 1];
m_MotionNodeList[0] = EditorGUIUtility.TrTextContent("<None>");
if (m_MotionNodeList.Length > 1)
m_MotionNodeList[1] = EditorGUIUtility.TrTextContent("<Root Transform>");
for (int i = 1; i < transformPaths.Length; i++)
m_MotionNodeList[i + 1] = new GUIContent(transformPaths[i]);
motionNodeIndex = ArrayUtility.FindIndex(m_MotionNodeList, delegate(GUIContent content) { return content.text == m_MotionNodeName.stringValue; });
motionNodeIndex = motionNodeIndex < 1 ? 0 : motionNodeIndex;
}
void SyncClipEditor(AnimationClipInfoProperties info)
{
if (m_AnimationClipEditor == null || m_MaskInspector == null)
return;
// It mandatory to set clip info into mask inspector first, this will update m_Mask.
m_MaskInspector.clipInfo = info;
m_AnimationClipEditor.ShowRange(info);
m_AnimationClipEditor.mask = m_Mask;
AnimationCurvePreviewCache.ClearCache();
}
private void SetupDefaultClips()
{
// Create dummy SerializedObject where we can add a clip for each
// take without making any properties show up as changed.
m_DefaultClipsSerializedObject = new SerializedObject(target);
m_ClipAnimations = m_DefaultClipsSerializedObject.FindProperty("m_ClipAnimations");
m_AnimationType = m_DefaultClipsSerializedObject.FindProperty("m_AnimationType");
m_ClipAnimations.ClearArray();
int clipListIndex = m_ClipList.index;
var allClipNames = new HashSet<string>();
m_ClipAnimations.arraySize = singleImporter.importedTakeInfos.Length;
var arrayElemProp = m_ClipAnimations.FindPropertyRelative("Array.size");
for (int i = 0; i < singleImporter.importedTakeInfos.Length; i++)
{
TakeInfo takeInfo = singleImporter.importedTakeInfos[i];
string uniqueName = MakeUniqueClipName(takeInfo.defaultClipName, allClipNames);
string uniqueIdentifier = MakeUniqueClipName(takeInfo.name, allClipNames);
allClipNames.Add(uniqueName);
arrayElemProp.Next(false);
AnimationClipInfoProperties info = new AnimationClipInfoProperties(arrayElemProp);
InitAnimationClipInfoProperties(info, takeInfo,uniqueName, uniqueIdentifier,0);
}
UpdateList();
//Attempt to maintain the previous clip index, now we've reverted to default clips
m_ClipList.index = Mathf.Min(clipListIndex, m_ClipList.list.Count);
}
// When switching to explicitly defined clips, we must fix up the internalID's to not lose AnimationClip references.
// When m_ClipAnimations is defined, the clips are identified by the clipName
// When m_ClipAnimations is not defined, the clips are identified by the takeName
void PatchDefaultClipTakeNamesToSplitClipNames()
{
foreach (TakeInfo takeInfo in singleImporter.importedTakeInfos)
{
UnityType animationClipType = UnityType.FindTypeByName("AnimationClip");
ImportSettingInternalID.Rename(serializedObject, animationClipType, takeInfo.name, takeInfo.defaultClipName);
}
}
// A dummy SerializedObject is created when there are no explicitly defined clips.
// When the user modifies any settings these clips must be transferred to the model importer.
private void TransferDefaultClipsToCustomClips()
{
if (m_DefaultClipsSerializedObject == null)
return;
bool wasEmpty = serializedObject.FindProperty("m_ClipAnimations").arraySize == 0;
if (!wasEmpty)
Debug.LogError("Transferring default clips failed, target already has clips");
// Transfer data to main SerializedObject
serializedObject.CopyFromSerializedProperty(m_ClipAnimations);
m_ClipAnimations = serializedObject.FindProperty("m_ClipAnimations");
m_DefaultClipsSerializedObject = null;
PatchDefaultClipTakeNamesToSplitClipNames();
UpdateList();
if (m_ClipList.index >= 0)
SyncClipEditor(((ClipInformation)m_ClipList.list[m_ClipList.index]).property);
}
internal override void OnDestroy()
{
DestroyEditorsAndData();
}
internal override void OnDisable()
{
UnregisterListeners();
DestroyEditorsAndData();
base.OnDisable();
}
internal override void ResetValues()
{
base.ResetValues();
DeserializeClips();
}
void AnimationClipGUI(ImportLog.ImportLogEntry[] importRigWarnings)
{
if (m_Errors.Length > 0)
{
EditorGUILayout.HelpBox(styles.ErrorsFoundWhileImportingThisAnimation);
}
else
{
if (importRigWarnings.Length > 0)
{
EditorGUILayout.HelpBox(styles.WarningsFoundWhileImportingRig);
}
if (m_Warnings.Length > 0)
{
EditorGUILayout.HelpBox(styles.WarningsFoundWhileImportingThisAnimation);
}
}
// Show general animation import settings
AnimationSettings();
if (serializedObject.isEditingMultipleObjects)
return;
Profiler.BeginSample("Clip inspector");
EditorGUILayout.Space();
// Show list of animations and inspector for individual animation
if (targets.Length == 1)
AnimationSplitTable();
else
GUILayout.Label(styles.clipMultiEditInfo, EditorStyles.helpBox);
Profiler.EndSample();
RootMotionNodeSettings();
s_ImportMessageFoldout = EditorGUILayout.Foldout(s_ImportMessageFoldout, styles.ImportMessages, true);
if (s_ImportMessageFoldout)
{
if (m_Errors.Length > 0)
EditorGUILayout.HelpBox(L10n.Tr(m_Errors), MessageType.Error);
if (m_Warnings.Length > 0)
EditorGUILayout.HelpBox(L10n.Tr(m_Warnings), MessageType.Warning);
if (animationType == ModelImporterAnimationType.Human)
{
EditorGUILayout.PropertyField(m_AnimationDoRetargetingWarnings, styles.GenerateRetargetingWarnings);
if (m_AnimationDoRetargetingWarnings.boolValue)
{
if (m_RetargetWarnings.Length > 0)
{
EditorGUILayout.HelpBox(L10n.Tr(m_RetargetWarnings), MessageType.Info);
}
}
else
{
EditorGUILayout.HelpBox(styles.RetargetingQualityCompares);
}
}
}
}
public override void OnInspectorGUI()
{
if (styles == null)
styles = new Styles();
EditorGUILayout.PropertyField(m_ImportConstraints, styles.ImportConstraints);
using (var check = new EditorGUI.ChangeCheckScope())
{
EditorGUILayout.PropertyField(m_ImportAnimation, styles.ImportAnimations);
if (check.changed)
DeserializeClips();
}
if (m_ImportAnimation.boolValue)
{
EditorGUILayout.PropertyField(m_ImportAnimatedCustomProperties, styles.ImportAnimatedCustomProperties);
}
if (m_ImportAnimation.boolValue && !m_ImportAnimation.hasMultipleDifferentValues)
{
ImportLog importLog = AssetImporter.GetImportLog(singleImporter.assetPath);
ImportLog.ImportLogEntry[] importRigErrors = importLog != null ? importLog.logEntries.Where(x => x.flags == ImportLogFlags.Error && x.message.StartsWith(k_RigErrorPrefix)).ToArray() : new ImportLog.ImportLogEntry[0];
ImportLog.ImportLogEntry[] importRigWarnings = importLog != null ? importLog.logEntries.Where(x => x.flags == ImportLogFlags.Warning && x.message.StartsWith(k_RigErrorPrefix)).ToArray() : new ImportLog.ImportLogEntry[0];
bool hasNoValidAnimationData = targets.Length == 1 && !m_ContainsAnimation.boolValue && singleImporter.animationType != ModelImporterAnimationType.None;
if (IsDeprecatedMultiAnimationRootImport())
EditorGUILayout.HelpBox(styles.AnimationDataWas);
else if (hasNoValidAnimationData)
{
if (serializedObject.hasModifiedProperties)
{
EditorGUILayout.HelpBox(styles.TheAnimationsSettingsCanBe);
}
else
{
if (importRigErrors.Length > 0)
{
EditorGUILayout.HelpBox(styles.ErrorsFoundWhileImporting);
}
else
{
EditorGUILayout.HelpBox(styles.NoAnimationDataAvailable);
}
}
}
else if (m_AnimationType.hasMultipleDifferentValues)
EditorGUILayout.HelpBox(styles.TheRigsOfTheSelectedModelsHave);
else if (animationType == ModelImporterAnimationType.None)
EditorGUILayout.HelpBox(styles.TheRigsOfTheSelectedModelsAre);
else if (singleImporter.importedTakeInfos.Length != 0)
{
AnimationClipGUI(importRigWarnings);
}
}
}
void AnimationSettings()
{
EditorGUILayout.Space();
// Bake IK
bool isBakeIKSupported = true;
foreach (ModelImporter importer in targets)
if (!importer.isBakeIKSupported)
isBakeIKSupported = false;
using (new EditorGUI.DisabledScope(!isBakeIKSupported))
{
EditorGUILayout.PropertyField(m_BakeSimulation, styles.BakeIK);
}
if (animationType == ModelImporterAnimationType.Generic)
{
EditorGUILayout.PropertyField(m_ResampleCurves, styles.ResampleCurves);
}
else
{
m_ResampleCurves.boolValue = true;
}
// Wrap mode
if (animationType == ModelImporterAnimationType.Legacy)
{
EditorGUI.showMixedValue = m_AnimationWrapMode.hasMultipleDifferentValues;
EditorGUILayout.Popup(m_AnimationWrapMode, styles.AnimWrapModeOpt, styles.AnimWrapModeLabel);
EditorGUI.showMixedValue = false;
// Compression
int[] kCompressionValues = { (int)ModelImporterAnimationCompression.Off, (int)ModelImporterAnimationCompression.KeyframeReduction, (int)ModelImporterAnimationCompression.KeyframeReductionAndCompression };
EditorGUILayout.IntPopup(m_AnimationCompression, styles.AnimCompressionOptLegacy, kCompressionValues, styles.AnimCompressionLabel);
}
else
{
// Compression
int[] kCompressionValues = { (int)ModelImporterAnimationCompression.Off, (int)ModelImporterAnimationCompression.KeyframeReduction, (int)ModelImporterAnimationCompression.Optimal };
EditorGUILayout.IntPopup(m_AnimationCompression, styles.AnimCompressionOpt, kCompressionValues, styles.AnimCompressionLabel);
}
if (m_AnimationCompression.intValue > (int)ModelImporterAnimationCompression.Off)
{
// keyframe reduction settings
EditorGUILayout.PropertyField(m_AnimationRotationError, styles.AnimRotationErrorLabel);
EditorGUILayout.PropertyField(m_AnimationPositionError, styles.AnimPositionErrorLabel);
EditorGUILayout.PropertyField(m_AnimationScaleError, styles.AnimScaleErrorLabel);
GUILayout.Label(styles.AnimationCompressionHelp, EditorStyles.helpBox);
}
EditorGUILayout.PropertyField(m_RemoveConstantScaleCurves, styles.RemoveConstantScaleCurves);
}
void RootMotionNodeSettings()
{
if (animationType == ModelImporterAnimationType.Human || animationType == ModelImporterAnimationType.Generic)
{
s_MotionNodeFoldout = EditorGUILayout.Foldout(s_MotionNodeFoldout, styles.MotionSetting, true);
if (s_MotionNodeFoldout)
{
EditorGUI.BeginChangeCheck();
motionNodeIndex = EditorGUILayout.Popup(styles.MotionNode, motionNodeIndex, m_MotionNodeList);
if (EditorGUI.EndChangeCheck())
{
if (motionNodeIndex > 0 && motionNodeIndex < m_MotionNodeList.Length)
{
m_MotionNodeName.stringValue = m_MotionNodeList[motionNodeIndex].text;
}
else
{
m_MotionNodeName.stringValue = "";
}
}
}
}
}
void DestroyEditorsAndData()
{
if (m_AnimationClipEditor != null)
{
Object.DestroyImmediate(m_AnimationClipEditor);
m_AnimationClipEditor = null;
}
if (m_MaskInspector)
{
DestroyImmediate(m_MaskInspector);
m_MaskInspector = null;
}
if (m_Mask)
{
DestroyImmediate(m_Mask);
m_Mask = null;
}
}
void SelectClip(int selected)
{
// If you were editing Clip Name (delayed text field had focus) and then selected a new clip from the clip list,
// the active string in the delayed text field would get applied to the new selected clip instead of the old.
// HACK: Calling EndGUI here on the recycled delayed text editor seems to fix this issue.
// Sometime we should reimplement delayed text field code to not be super confusing and then fix the issue more properly.
if (EditorGUI.s_DelayedTextEditor != null && Event.current != null)
EditorGUI.s_DelayedTextEditor.EndGUI(Event.current.type);
DestroyEditorsAndData();
m_ClipList.index = selected;
if (m_ClipList.index < 0)
return;
AnimationClipInfoProperties info = ((ClipInformation)m_ClipList.list[m_ClipList.index]).property;
AnimationClip clip = singleImporter.GetPreviewAnimationClipForTake(info.takeName);
if (clip != null)
{
m_AnimationClipEditor = (AnimationClipEditor)Editor.CreateEditor(clip, typeof(AnimationClipEditor));
InitMask(info);
SyncClipEditor(info);
m_AnimationClipEditor.InitClipTime();
}
}
void UpdateList()
{
List<ClipInformation> clipInfos = new List<ClipInformation>();
var prop = m_ClipAnimations.FindPropertyRelative("Array.size");
for (int i = 0; i < m_ClipAnimations.arraySize; i++)
{
prop.Next(false);
clipInfos.Add(new ClipInformation(prop.Copy()));
}
m_ClipList.list = clipInfos;
m_ClipList.index = Mathf.Clamp(m_ClipList.index, -1, m_ClipAnimations.arraySize - 1);
}
void AddClipInList(ReorderableList list)
{
if (m_DefaultClipsSerializedObject != null)
TransferDefaultClipsToCustomClips();
int takeIndex = 0;
if (0 < m_ClipList.index && m_ClipList.index < m_ClipAnimations.arraySize)
{
AnimationClipInfoProperties info = ((ClipInformation)m_ClipList.list[m_ClipList.index]).property;
for (int i = 0; i < singleImporter.importedTakeInfos.Length; i++)
{
if (singleImporter.importedTakeInfos[i].name == info.takeName)
{
takeIndex = i;
break;
}
}
}
AddClip(singleImporter.importedTakeInfos[takeIndex]);
SelectClip(list.list.Count - 1);
}
void RemoveClipInList(ReorderableList list)
{
TransferDefaultClipsToCustomClips();
RemoveClip(list.index);
SelectClip(Mathf.Min(list.index, list.count - 1));
}
void SelectClipInList(ReorderableList list)
{
SelectClip(list.index);
}
const int kFrameColumnWidth = 45;
private void DrawClipElement(Rect rect, int index, bool selected, bool focused)
{
ClipInformation info = (ClipInformation)m_ClipList.list[index];
rect.xMax -= kFrameColumnWidth * 2;
GUI.Label(rect, info.name, EditorStyles.label);
rect.x = rect.xMax;
rect.width = kFrameColumnWidth;
GUI.Label(rect, info.firstFrame, styles.numberStyle);
rect.x = rect.xMax;
GUI.Label(rect, info.lastFrame, styles.numberStyle);
}
private void DrawClipHeader(Rect rect)
{
rect.xMax -= kFrameColumnWidth * 2;
GUI.Label(rect, styles.Clips, EditorStyles.label);
rect.x = rect.xMax;
rect.width = kFrameColumnWidth;
GUI.Label(rect, styles.Start, styles.numberStyle);
rect.x = rect.xMax;
GUI.Label(rect, styles.End, styles.numberStyle);
}
void AnimationSplitTable()
{
if (m_ClipList.count != m_ClipAnimations.arraySize)
{
UpdateList();
SelectClipInList(m_ClipList);
}
if (singleImporter.importedTakeInfos.Length > 0)
{
m_ClipList.DoLayoutList();
EditorGUI.BeginChangeCheck();
// Show selected clip info
{
AnimationClipInfoProperties clip = GetSelectedClipInfo();
if (clip == null)
return;
if (m_AnimationClipEditor != null)
{
GUILayout.Space(5);
AnimationClip actualClip = m_AnimationClipEditor.target as AnimationClip;
if (!actualClip.legacy)
clip.AssignToPreviewClip(actualClip);
TakeInfo[] importedTakeInfos = singleImporter.importedTakeInfos;
string[] takeNames = new string[importedTakeInfos.Length];
for (int i = 0; i < importedTakeInfos.Length; i++)
takeNames[i] = importedTakeInfos[i].name;
EditorGUI.BeginChangeCheck();
string currentName = clip.name;
int takeIndex = ArrayUtility.IndexOf(takeNames, clip.takeName);
m_AnimationClipEditor.takeNames = takeNames;
m_AnimationClipEditor.takeIndex = ArrayUtility.IndexOf(takeNames, clip.takeName);
m_AnimationClipEditor.DrawHeader();
if (EditorGUI.EndChangeCheck())
{
clip.name = clip.name.Trim();
if (clip.name == String.Empty)
{
clip.name = currentName;
}
// We renamed the clip name, try to maintain the localIdentifierInFile so we don't lose any data.
if (clip.name != currentName)
{
var newName = clip.name;
clip.name = currentName;
clip.name = MakeUniqueClipName(newName);
TransferDefaultClipsToCustomClips();
UnityType animationClipType = UnityType.FindTypeByName("AnimationClip");
ImportSettingInternalID.Rename(serializedObject, animationClipType, currentName, clip.name);
}
int newTakeIndex = m_AnimationClipEditor.takeIndex;
if (newTakeIndex != -1 && newTakeIndex != takeIndex)
{
clip.name = MakeUniqueClipName(takeNames[newTakeIndex]);
SetupTakeNameAndFrames(clip, importedTakeInfos[newTakeIndex]);
GUIUtility.keyboardControl = 0;
SelectClip(m_ClipList.index);
// actualClip has been changed by SelectClip
actualClip = m_AnimationClipEditor.target as AnimationClip;
}
}
m_AnimationClipEditor.OnInspectorGUI();
AvatarMaskSettings(clip);
if (!actualClip.legacy)
clip.ExtractFromPreviewClip(actualClip);
if (EditorGUI.EndChangeCheck() || m_AnimationClipEditor.needsToGenerateClipInfo)
{
TransferDefaultClipsToCustomClips();
m_AnimationClipEditor.needsToGenerateClipInfo = false;
}
}
}
}
}
public override bool HasPreviewGUI()
{
return m_ImportAnimation.boolValue && m_AnimationClipEditor != null && m_AnimationClipEditor.HasPreviewGUI();
}
public override void OnPreviewSettings()
{
if (m_AnimationClipEditor != null)
m_AnimationClipEditor.OnPreviewSettings();
}
bool IsDeprecatedMultiAnimationRootImport()
{
if (animationType == ModelImporterAnimationType.Legacy)
return legacyGenerateAnimations == ModelImporterGenerateAnimations.InOriginalRoots || legacyGenerateAnimations == ModelImporterGenerateAnimations.InNodes;
else
return false;
}
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
m_AnimationClipEditor.OnInteractivePreviewGUI(r, background);
}
AnimationClipInfoProperties GetSelectedClipInfo()
{
//If it doesn't have a selected clip. return null - there is nothing to select!
return m_ClipList.index >= 0 && m_ClipList.index < m_ClipList.count ? ((ClipInformation)m_ClipList.list[m_ClipList.index]).property : null;
}
/// <summary>
/// Removes the duplicate brackets from a name.
/// </summary>
/// <returns>The name without the duplicate suffix.</returns>
/// <param name="name">Name.</param>
/// <param name="number">Number between the brackets (-1 if no brackets were found).</param>
string RemoveDuplicateSuffix(string name, out int number)
{
number = -1;
// The smallest format is " (1)".
int length = name.Length;
if (length < 4 || name[length - 1] != ')')
return name;
// Has an opening bracket.
int openingBracket = name.LastIndexOf('(', length - 2);
if (openingBracket == -1 || name[openingBracket - 1] != ' ')
return name;
// Brackets aren't empty.
int numberLength = length - openingBracket - 2;
if (numberLength == 0)
return name;
// Only has digits between the brackets.
int i = 0;
while (i < numberLength && char.IsDigit(name[openingBracket + 1 + i]))
++i;
if (i != numberLength)
return name;
// Get number.
string numberString = name.Substring(openingBracket + 1, numberLength);
number = int.Parse(numberString);
// Extract base name.
return name.Substring(0, openingBracket - 1);
}
string FindNextAvailableName(string baseName, HashSet<string> allClipNames)
{
string resultName = baseName;
int occurences = 0;
while (allClipNames.Contains(resultName))
{
occurences++;
resultName = baseName + " (" + occurences + ")";
}
return resultName;
}
string MakeUniqueClipName(string name, HashSet<string> allClipNames = null)
{
int dummy;
string baseName = RemoveDuplicateSuffix(name, out dummy);
if (allClipNames == null)
{
// If no collection was provided, the current list of clips is used.
allClipNames = new HashSet<string>();
for (int i = 0; i < m_ClipAnimations.arraySize; ++i)
{
AnimationClipInfoProperties clip = ((ClipInformation)m_ClipList.list[i]).property;
allClipNames.Add(clip.name);
}
}
return FindNextAvailableName(baseName, allClipNames);
}
void RemoveClip(int index)
{
m_ClipAnimations.DeleteArrayElementAtIndex(index);
if (m_ClipAnimations.arraySize == 0)
{
SetupDefaultClips();
m_ImportAnimation.boolValue = false;
}
UpdateList();
}
void SetupTakeNameAndFrames(AnimationClipInfoProperties info, TakeInfo takeInfo)
{
info.takeName = takeInfo.name;
info.firstFrame = (int)Mathf.Round(takeInfo.bakeStartTime * takeInfo.sampleRate);
info.lastFrame = (int)Mathf.Round(takeInfo.bakeStopTime * takeInfo.sampleRate);
}
void AddClip(TakeInfo takeInfo)
{
string uniqueName = MakeUniqueClipName(takeInfo.defaultClipName);
m_ClipAnimations.InsertArrayElementAtIndex(m_ClipAnimations.arraySize);
var property = m_ClipAnimations.GetArrayElementAtIndex(m_ClipAnimations.arraySize - 1);
AnimationClipInfoProperties info = new AnimationClipInfoProperties(property);
InitAnimationClipInfoProperties(info, takeInfo, uniqueName,uniqueName, m_ClipAnimations.arraySize - 1);
UpdateList();
}
void InitAnimationClipInfoProperties(AnimationClipInfoProperties info, TakeInfo takeInfo,string uniqueName,string uniqueIdentifier,int clipOffset)
{
SetupTakeNameAndFrames(info, takeInfo);
var animationClipType = UnityType.FindTypeByName("AnimationClip");
long id = ImportSettingInternalID.FindInternalID(serializedObject, animationClipType, uniqueIdentifier);
info.internalID = id == 0L
? AssetImporter.MakeLocalFileIDWithHash(animationClipType.persistentTypeID, uniqueIdentifier, clipOffset)
: id;
info.name = uniqueName;
info.wrapMode = (int)WrapMode.Default;
info.loop = false;
info.orientationOffsetY = 0;
info.level = 0;
info.cycleOffset = 0;
info.loopTime = false;
info.loopBlend = false;
info.loopBlendOrientation = false;
info.loopBlendPositionY = false;
info.loopBlendPositionXZ = false;
info.keepOriginalOrientation = false;
info.keepOriginalPositionY = true;
info.keepOriginalPositionXZ = false;
info.heightFromFeet = false;
info.mirror = false;
info.maskType = ClipAnimationMaskType.None;
SetBodyMaskDefaultValues(info);
info.ClearEvents();
info.ClearCurves();
}
private AvatarMask m_Mask = null;
private AvatarMaskInspector m_MaskInspector = null;
static private bool m_MaskFoldout = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////
///
private void AvatarMaskSettings(AnimationClipInfoProperties clipInfo)
{
if (clipInfo != null && m_AnimationClipEditor != null)
{
InitMask(clipInfo);
int prevIndent = EditorGUI.indentLevel;
// Don't make toggling foldout cause GUI.changed to be true (shouldn't cause undoable action etc.)
bool wasChanged = GUI.changed;
m_MaskFoldout = EditorGUILayout.Foldout(m_MaskFoldout, styles.Mask, true);
GUI.changed = wasChanged;
var maskType = clipInfo.maskType;
bool upToDate = true;
if (maskType == ClipAnimationMaskType.CreateFromThisModel || maskType == ClipAnimationMaskType.CopyFromOther)
{
upToDate = m_MaskInspector.IsMaskUpToDate();
}
if (maskType == ClipAnimationMaskType.CreateFromThisModel && !upToDate && !m_MaskInspector.IsMaskEmpty())
{
GUILayout.BeginHorizontal(EditorStyles.helpBox);
GUILayout.Label(styles.MaskHasAPath,
EditorStyles.wordWrappedMiniLabel);
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.Space(5);
if (GUILayout.Button(styles.UpdateMask))
{
SetTransformMaskFromReference(clipInfo);
m_MaskInspector.UpdateTransformInfos();
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
else if (maskType == ClipAnimationMaskType.CopyFromOther && clipInfo.MaskNeedsUpdating())
{
GUILayout.BeginHorizontal(EditorStyles.helpBox);
GUILayout.Label(styles.SourceMaskHasChanged,
EditorStyles.wordWrappedMiniLabel);
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.Space(5);
if (GUILayout.Button(styles.UpdateMask))
{
clipInfo.MaskToClip(clipInfo.maskSource);
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
else if (maskType == ClipAnimationMaskType.CopyFromOther && !upToDate)
{
GUILayout.BeginHorizontal(EditorStyles.helpBox);
GUILayout.Label(styles.SourceMaskHasAPath,
EditorStyles.wordWrappedMiniLabel);
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.Space(5);
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
if (m_MaskFoldout)
{
EditorGUI.indentLevel++;
m_MaskInspector.OnInspectorGUI();
}
EditorGUI.indentLevel = prevIndent;
}
}
private void InitMask(AnimationClipInfoProperties clipInfo)
{
if (m_Mask == null)
{
AnimationClip clip = m_AnimationClipEditor.target as AnimationClip;
m_Mask = new AvatarMask();
m_MaskInspector = (AvatarMaskInspector)Editor.CreateEditor(m_Mask, typeof(AvatarMaskInspector));
m_MaskInspector.canImport = false;
m_MaskInspector.showBody = clip.isHumanMotion;
m_MaskInspector.clipInfo = clipInfo;
}
}
private void SetTransformMaskFromReference(AnimationClipInfoProperties clipInfo)
{
string[] transformPaths = referenceTransformPaths;
string[] humanTransforms = animationType == ModelImporterAnimationType.Human ?
AvatarMaskUtility.GetAvatarHumanAndActiveExtraTransforms(serializedObject, clipInfo.transformMaskProperty, transformPaths) :
AvatarMaskUtility.GetAvatarInactiveTransformMaskPaths(clipInfo.transformMaskProperty);
AvatarMaskUtility.UpdateTransformMask(clipInfo.transformMaskProperty, transformPaths, humanTransforms, animationType == ModelImporterAnimationType.Human);
}
private void SetBodyMaskDefaultValues(AnimationClipInfoProperties clipInfo)
{
SerializedProperty bodyMask = clipInfo.bodyMaskProperty;
bodyMask.arraySize = (int)AvatarMaskBodyPart.LastBodyPart;
var prop = bodyMask.FindPropertyRelative("Array.size");
for (int i = 0; i < (int)AvatarMaskBodyPart.LastBodyPart; ++i)
{
prop.Next(false);
prop.intValue = 1;
}
}
void RegisterListeners()
{
//Ensures that the ClipList and the Serialized copy of the clip remain in sync when an Undo/Redo is performed.
if (!serializedObject.isEditingMultipleObjects)
Undo.undoRedoEvent += HandleUndo;
}
void UnregisterListeners()
{
//Ensures that the ClipList and the Serialized copy of the clip remain in sync when an Undo/Redo is performed.
if (!serializedObject.isEditingMultipleObjects)
Undo.undoRedoEvent -= HandleUndo;
}
void HandleUndo(in UndoRedoInfo info)
{
//Update animations serialization in-case something has changed
m_ClipAnimations.serializedObject.UpdateIfRequiredOrScript();
//Reset the cache to the serialized values
DeserializeClips();
}
void DeserializeClips()
{
//Clear the clip editors
DestroyEditorsAndData();
//Reload the clips
m_ClipAnimations = serializedObject.FindProperty("m_ClipAnimations");
m_AnimationType = serializedObject.FindProperty("m_AnimationType");
m_DefaultClipsSerializedObject = null;
if (m_ClipAnimations.arraySize == 0)
SetupDefaultClips();
UpdateList();
//Set the active clip within a valid range, -1 ONLY if there are no possible clips to select.
int selectedClip = m_ClipList.count > 0 ? Mathf.Clamp(m_ClipList.index, 0, m_ClipList.count) : -1;
SelectClip(selectedClip);
}
}
}
| UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterClipEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterClipEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 23202
} | 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 System.IO;
using UnityEditor.Utils;
using UnityEngine;
using UnityEngine.Bindings;
namespace UnityEditor
{
[NativeHeader("Editor/Src/ScriptCompilation/RoslynAnalyzers.bindings.h")]
[ExcludeFromPreset]
internal sealed class RoslynAdditionalFiles
{
[FreeFunction("GetAllCachedRoslynAdditionalFilePaths")] internal static extern string[] GetFilePaths();
[FreeFunction("GetAllRoslynAdditionalFilePaths")] internal static extern string[] GetAnalyzerAdditionalFilesForTargetAssembly(string analyzerPath, string targetAssemblyPath);
[FreeFunction("CacheRoslynAdditionalFiles")] internal static extern void AddAdditionalFiles(string[] additionalFiles);
}
}
| UnityCsReference/Modules/AssetPipelineEditor/Public/RoslynAdditionalFiles.binding.cs/0 | {
"file_path": "UnityCsReference/Modules/AssetPipelineEditor/Public/RoslynAdditionalFiles.binding.cs",
"repo_id": "UnityCsReference",
"token_count": 261
} | 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 UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Playables;
namespace UnityEngine.Audio
{
public static class AudioPlayableBinding
{
public static PlayableBinding Create(string name, UnityEngine.Object key)
{
return PlayableBinding.CreateInternal(name, key, typeof(AudioSource), CreateAudioOutput);
}
private static PlayableOutput CreateAudioOutput(PlayableGraph graph, string name)
{
return (PlayableOutput)AudioPlayableOutput.Create(graph, name, null);
}
}
}
| UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioPlayableBinding.cs/0 | {
"file_path": "UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioPlayableBinding.cs",
"repo_id": "UnityCsReference",
"token_count": 256
} | 345 |
// 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.Audio;
using UnityEngine.Bindings;
namespace UnityEditor.Audio
{
internal enum ParameterTransitionType
{
Lerp = 0,
Smoothstep = 1,
Squared = 2,
SquareRoot = 3,
BrickwallStart = 4,
BrickwallEnd = 5,
Attenuation = 6
}
[NativeHeader("Editor/Src/Audio/Mixer/AudioMixerSnapshotController.h")]
[NativeHeader("Modules/AudioEditor/ScriptBindings/AudioMixerSnapshotController.bindings.h")]
internal class AudioMixerSnapshotController : AudioMixerSnapshot
{
public AudioMixerSnapshotController(AudioMixer owner)
{
Internal_CreateAudioMixerSnapshotController(this, owner);
}
[FreeFunction("AudioMixerSnapshotControllerBindings::Internal_CreateAudioMixerSnapshotController")]
private static extern void Internal_CreateAudioMixerSnapshotController([Writable] AudioMixerSnapshotController mono, AudioMixer owner);
public extern GUID snapshotID { get; }
public extern void SetValue(GUID guid, float value);
public extern bool GetValue(GUID guid, out float value);
public extern void SetTransitionTypeOverride(GUID guid, ParameterTransitionType type);
public extern bool GetTransitionTypeOverride(GUID guid, out ParameterTransitionType type);
public extern void ClearTransitionTypeOverride(GUID guid);
}
}
| UnityCsReference/Modules/AudioEditor/ScriptBindings/AudioMixerSnapshotController.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/AudioEditor/ScriptBindings/AudioMixerSnapshotController.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 559
} | 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.Bindings;
using UnityEngine;
using UnityEngine.Scripting;
namespace UnityEditor.Build.Content
{
public enum ProfileEventType
{
Begin = 0,
End = 1,
Info = 2
}
public enum ProfileCaptureOptions
{
None = 0,
IgnoreShortEvents = 1
}
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public struct ContentBuildProfileEvent
{
public UInt64 TimeMicroseconds;
public string Name;
public string Metadata;
public ProfileEventType Type;
};
}
| UnityCsReference/Modules/BuildPipeline/Editor/Managed/ContentBuildInterfaceProfile.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/ContentBuildInterfaceProfile.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 291
} | 347 |
// 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.UIElements;
namespace UnityEditor.Build.Profile.Elements
{
/// <summary>
/// List item showing a build profile name and icon in the <see cref="BuildProfileWindow"/>
/// classic platform or build profile columns. It's possible to edit this label.
/// </summary>
internal class BuildProfileListEditableLabel : BuildProfileListLabel
{
protected override string k_Uxml => "BuildProfile/UXML/BuildProfileEditableLabelElement.uxml";
bool m_IsIndicatorActiveOnEdit;
TextField m_TextField;
Func<object, string, bool> m_OnNameChanged;
BuildProfileRenameOverlay m_RenameOverlay;
internal BuildProfileListEditableLabel(Func<object, string, bool> onNameChanged)
{
m_OnNameChanged = onNameChanged;
m_TextField = this.Q<TextField>("profile-list-text-field");
m_TextField.RegisterCallback<FocusOutEvent>(OnEditTextFinished);
m_TextField.RegisterValueChangedCallback(OnTextFieldValueChange);
m_TextField.Hide();
m_RenameOverlay = new BuildProfileRenameOverlay(m_TextField);
}
internal void UnbindItem()
{
m_TextField.UnregisterCallback<FocusOutEvent>(OnEditTextFinished);
m_TextField.UnregisterValueChangedCallback(OnTextFieldValueChange);
m_RenameOverlay.OnRenameEnd();
}
internal void EditName()
{
m_TextField.value = m_Text.text;
m_Text.Hide();
m_TextField.Show();
m_TextField.Focus();
m_IsIndicatorActiveOnEdit = m_ActiveIndicator.style.display != DisplayStyle.None;
if (m_IsIndicatorActiveOnEdit)
{
SetActiveIndicator(false);
}
}
void OnEditTextFinished(FocusOutEvent evt)
{
m_TextField.Hide();
if (m_OnNameChanged.Invoke(dataSource, m_TextField.value))
m_Text.text = m_TextField.value;
m_Text.Show();
if (m_IsIndicatorActiveOnEdit)
SetActiveIndicator(true);
m_RenameOverlay.OnRenameEnd();
}
void OnTextFieldValueChange(ChangeEvent<string> evt)
{
if (string.IsNullOrEmpty(evt.newValue))
return;
m_RenameOverlay.OnNameChanged(evt.previousValue, evt.newValue);
}
}
}
| UnityCsReference/Modules/BuildProfileEditor/Elements/BuildProfileListEditableLabel.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildProfileEditor/Elements/BuildProfileListEditableLabel.cs",
"repo_id": "UnityCsReference",
"token_count": 1150
} | 348 |
// 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.Build.Reporting
{
[NativeType(Header = "Modules/BuildReportingEditor/Public/BuildReport.h")]
public struct BuildStepMessage
{
public LogType type { get; }
public string content { get; }
}
}
| UnityCsReference/Modules/BuildReportingEditor/Managed/BuildStepMessage.cs/0 | {
"file_path": "UnityCsReference/Modules/BuildReportingEditor/Managed/BuildStepMessage.cs",
"repo_id": "UnityCsReference",
"token_count": 161
} | 349 |
// 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.Analytics
{
[NativeHeader("Modules/UnityConnect/PerformanceReporting/PerformanceReportingSettings.h")]
[StaticAccessor("GetPerformanceReportingSettings()", StaticAccessorType.Dot)]
public static partial class PerformanceReportingSettings
{
public static extern bool enabled
{
[ThreadSafe] get;
[ThreadSafe] set;
}
}
}
| UnityCsReference/Modules/CloudServicesSettingsEditor/PerformanceReporting/ScriptBindings/PerformanceReportingSettings.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/CloudServicesSettingsEditor/PerformanceReporting/ScriptBindings/PerformanceReportingSettings.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 208
} | 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.Linq;
using UnityEngine;
namespace UnityEditor.DeviceSimulation
{
internal class ScreenSimulation : ScreenShimBase
{
// Reasonable maximum resolution, tested on an Android device and game crashes when set beyond
private const int k_MaxResolution = 8192;
private int m_RequestedWidth;
private int m_RequestedHeight;
private ScreenOrientation m_RequestedOrientation;
private bool m_RequestedFullScreen;
private bool m_RequestDefaultResolution;
private bool m_RequestInsetUpdate;
private SimulationPlayerSettings m_PlayerSettings;
private DeviceInfo m_DeviceInfo;
private ScreenData m_Screen;
private bool m_AutoRotation;
public bool AutoRotation => m_AutoRotation;
private ScreenOrientation m_RenderedOrientation = ScreenOrientation.Portrait;
private Dictionary<ScreenOrientation, bool> m_AllowedAutoRotation;
private Dictionary<ScreenOrientation, OrientationData> m_SupportedOrientations;
private Rect m_CurrentSafeArea;
private Rect[] m_CurrentCutouts;
private bool m_WasResolutionSet;
private int m_CurrentWidth;
private int m_CurrentHeight;
private bool m_IsFullScreen;
public Vector4 Insets { get; private set; }
public Vector4 InsetsInCurrentOrientation
{
get
{
switch (m_RenderedOrientation)
{
case ScreenOrientation.Portrait:
return Insets;
case ScreenOrientation.PortraitUpsideDown:
return new Vector4(Insets.z, Insets.w, Insets.x, Insets.y);
case ScreenOrientation.LandscapeLeft:
return new Vector4(Insets.y, Insets.z, Insets.w, Insets.x);
case ScreenOrientation.LandscapeRight:
return new Vector4(Insets.w, Insets.x, Insets.y, Insets.z);
default:
return Insets;
}
}
}
private bool m_IsRenderingOutsideSafeArea;
public Rect ScreenSpaceSafeArea { get; private set; }
private ScreenOrientation m_DeviceOrientation;
public int DeviceRotation
{
set
{
m_DeviceOrientation = SimulatorUtilities.RotationToScreenOrientation(value);
ApplyAutoRotation();
}
}
public bool IsRenderingLandscape => SimulatorUtilities.IsLandscape(m_RenderedOrientation);
public event Action OnOrientationChanged;
public event Action OnAllowedOrientationChanged;
public event Action<int, int> OnResolutionChanged;
public event Action<bool> OnFullScreenChanged;
public event Action<Vector4> OnInsetsChanged;
public event Action<Rect> OnScreenSpaceSafeAreaChanged;
public ScreenSimulation(DeviceInfo device, SimulationPlayerSettings playerSettings, int screenIndex)
{
m_PlayerSettings = playerSettings;
m_DeviceInfo = device;
m_Screen = device.screens[screenIndex];
FindSupportedOrientations();
m_AllowedAutoRotation = new Dictionary<ScreenOrientation, bool>();
m_AllowedAutoRotation.Add(ScreenOrientation.Portrait, m_PlayerSettings.allowedPortrait);
m_AllowedAutoRotation.Add(ScreenOrientation.PortraitUpsideDown, m_PlayerSettings.allowedPortraitUpsideDown);
m_AllowedAutoRotation.Add(ScreenOrientation.LandscapeLeft, m_PlayerSettings.allowedLandscapeLeft);
m_AllowedAutoRotation.Add(ScreenOrientation.LandscapeRight, m_PlayerSettings.allowedLandscapeRight);
// Set the full screen mode.
m_IsFullScreen = !m_DeviceInfo.IsAndroidDevice() || m_PlayerSettings.androidStartInFullscreen;
m_RequestedFullScreen = m_IsFullScreen;
m_IsRenderingOutsideSafeArea = !m_DeviceInfo.IsAndroidDevice() || m_PlayerSettings.androidRenderOutsideSafeArea;
// Calculate the right orientation.
var settingOrientation = SimulatorUtilities.ToScreenOrientation(m_PlayerSettings.defaultOrientation);
if (settingOrientation == ScreenOrientation.AutoRotation)
{
m_AutoRotation = true;
SetFirstAvailableAutoOrientation();
}
else if (m_SupportedOrientations.ContainsKey(settingOrientation))
{
m_AutoRotation = false;
RequestOrientation(settingOrientation);
}
else
{
// The real iPhone X responds to this absolute corner case by crashing, we will not do that.
m_AutoRotation = false;
RequestOrientation(m_SupportedOrientations.Keys.ToArray()[0]);
}
m_RequestInsetUpdate = true;
m_RequestDefaultResolution = true;
ShimManager.UseShim(this);
}
public void ChangeScreen(int screenIndex)
{
m_Screen = m_DeviceInfo.screens[screenIndex];
FindSupportedOrientations();
if (!m_WasResolutionSet)
{
m_RequestDefaultResolution = true;
}
}
private void FindSupportedOrientations()
{
m_SupportedOrientations = new Dictionary<ScreenOrientation, OrientationData>();
foreach (var o in m_Screen.orientations)
{
m_SupportedOrientations.Add(o.orientation, o);
}
}
private void ApplyAutoRotation()
{
if (!m_AutoRotation) return;
if (m_DeviceOrientation != m_RequestedOrientation && m_SupportedOrientations.ContainsKey(m_DeviceOrientation) && m_AllowedAutoRotation[m_DeviceOrientation])
{
RequestOrientation(m_DeviceOrientation);
}
}
private void RequestOrientation(ScreenOrientation orientation)
{
m_RequestedOrientation = orientation;
}
private void SetAutoRotationOrientation(ScreenOrientation orientation, bool value)
{
m_AllowedAutoRotation[orientation] = value;
if (!m_AutoRotation)
{
OnAllowedOrientationChanged?.Invoke();
return;
}
// If the current auto rotation is disabled we need to rotate to another allowed orientation
if (!value && orientation == m_RequestedOrientation)
{
SetFirstAvailableAutoOrientation();
}
else if (value)
{
ApplyAutoRotation();
}
OnAllowedOrientationChanged?.Invoke();
}
private void SetFirstAvailableAutoOrientation()
{
foreach (var newOrientation in m_SupportedOrientations.Keys)
{
if (m_AllowedAutoRotation[newOrientation])
{
RequestOrientation(newOrientation);
return;
}
}
}
public void ApplyChanges()
{
var updateSafeArea = false;
var orientationEvent = false;
var resolutionEvent = false;
var fullScreenEvent = false;
var screenSpaceSafeAreaEvent = false;
var insetsEvent = false;
if (m_RequestedOrientation != m_RenderedOrientation)
{
if (m_RequestedOrientation.IsLandscape() != m_RenderedOrientation.IsLandscape())
{
// Swap resolution Width and Height if changing from Portrait to Landscape or vice versa
if(m_WasResolutionSet)
(m_RequestedHeight, m_RequestedWidth) = (m_RequestedWidth, m_RequestedHeight);
else
m_RequestDefaultResolution = true;
}
m_RenderedOrientation = m_RequestedOrientation;
orientationEvent = true;
m_RequestInsetUpdate = true;
updateSafeArea = true;
}
if(m_RequestedFullScreen != m_IsFullScreen)
{
m_IsFullScreen = m_RequestedFullScreen;
m_RequestInsetUpdate = true;
// We only change the resolution if we never set the resolution by calling Screen.SetResolution().
if (!m_WasResolutionSet)
{
m_RequestDefaultResolution = true;
}
updateSafeArea = true;
fullScreenEvent = true;
}
if (m_RequestInsetUpdate)
{
CalculateInsets();
insetsEvent = true;
}
if((m_RequestedWidth != m_CurrentWidth || m_RequestedHeight != m_CurrentHeight) && m_WasResolutionSet)
{
m_CurrentWidth = m_RequestedWidth;
m_CurrentHeight = m_RequestedHeight;
updateSafeArea = true;
resolutionEvent = true;
}
else if (m_RequestDefaultResolution)
{
CalculateResolutionWithInsets();
updateSafeArea = true;
resolutionEvent = true;
}
if (updateSafeArea)
{
CalculateSafeAreaAndCutouts();
screenSpaceSafeAreaEvent = true;
}
if(orientationEvent)
OnOrientationChanged?.Invoke();
if(resolutionEvent)
OnResolutionChanged?.Invoke(m_CurrentWidth, m_CurrentHeight);
if(fullScreenEvent)
OnFullScreenChanged?.Invoke(m_IsFullScreen);
if(screenSpaceSafeAreaEvent)
OnScreenSpaceSafeAreaChanged?.Invoke(ScreenSpaceSafeArea);
if(insetsEvent)
OnInsetsChanged?.Invoke(Insets);
m_RequestDefaultResolution = false;
m_RequestedOrientation = m_RenderedOrientation;
m_RequestedHeight = m_CurrentHeight;
m_RequestedWidth = m_CurrentWidth;
m_RequestInsetUpdate = false;
}
private void CalculateSafeAreaAndCutouts()
{
var orientationData = m_SupportedOrientations[m_RenderedOrientation];
var safeArea = orientationData.safeArea;
Rect onScreenSafeArea = new Rect();
// Calculating where on the screen to draw safe area
onScreenSafeArea = safeArea;
switch (m_RenderedOrientation)
{
case ScreenOrientation.Portrait:
onScreenSafeArea.y = m_Screen.height - safeArea.height - safeArea.y;
break;
case ScreenOrientation.PortraitUpsideDown:
break;
case ScreenOrientation.LandscapeLeft:
onScreenSafeArea.y = safeArea.x;
onScreenSafeArea.x = safeArea.y;
onScreenSafeArea.height = safeArea.width;
onScreenSafeArea.width = safeArea.height;
break;
case ScreenOrientation.LandscapeRight:
onScreenSafeArea.y = m_Screen.height - safeArea.width - safeArea.x;
onScreenSafeArea.x = m_Screen.width - safeArea.height - safeArea.y;
onScreenSafeArea.width = safeArea.height;
onScreenSafeArea.height = safeArea.width;
break;
}
if (!m_IsFullScreen)
{
switch (m_RenderedOrientation)
{
case ScreenOrientation.PortraitUpsideDown:
onScreenSafeArea.yMin += m_Screen.navigationBarHeight;
break;
case ScreenOrientation.LandscapeLeft:
case ScreenOrientation.LandscapeRight:
case ScreenOrientation.Portrait:
onScreenSafeArea.yMax -= m_Screen.navigationBarHeight;
break;
}
}
ScreenSpaceSafeArea = onScreenSafeArea;
var screenWidthInOrientation = IsRenderingLandscape ? m_Screen.height : m_Screen.width;
var screenHeightInOrientation = IsRenderingLandscape ? m_Screen.width : m_Screen.height;
// The inverse of safe area, that is the size of borders excluded from the safe area.
// It is more convenient to scale these borders to correct resolution than to scale safe area rect.
var unsafeBorders = new Vector4()
{
x = safeArea.x,
y = screenHeightInOrientation - safeArea.height - safeArea.y,
z = screenWidthInOrientation - safeArea.width - safeArea.x,
w = safeArea.y
};
// Need to exclude unsafe area hidden by insets. It is obscured by the inset and therefore disappears.
var insetsInOrientation = InsetsInCurrentOrientation;
unsafeBorders -= insetsInOrientation;
// A negative unsafe border can happen because inset encroaches on the safe area. In other words, unsafe border is smaller than the inset.
// In these cases the safe area will border the inset directly on that side of the screen, so unsafe border is clamped to 0.
unsafeBorders.x = Mathf.Clamp(unsafeBorders.x, 0, float.MaxValue);
unsafeBorders.y = Mathf.Clamp(unsafeBorders.y, 0, float.MaxValue);
unsafeBorders.z = Mathf.Clamp(unsafeBorders.z, 0, float.MaxValue);
unsafeBorders.w = Mathf.Clamp(unsafeBorders.w, 0, float.MaxValue);
// This is the resolution of the part of the screen where game rendering is occuring, it might be different than the actual rendering resolution.
var renderAreaWidth = screenWidthInOrientation - insetsInOrientation.x - insetsInOrientation.z;
var renderAreaHeight = screenHeightInOrientation - insetsInOrientation.y - insetsInOrientation.w;
var resolutionWidthScale = m_CurrentWidth / renderAreaWidth;
var resolutionHeightScale = m_CurrentHeight / renderAreaHeight;
unsafeBorders.x *= resolutionWidthScale;
unsafeBorders.y *= resolutionHeightScale;
unsafeBorders.z *= resolutionWidthScale;
unsafeBorders.w *= resolutionHeightScale;
m_CurrentSafeArea = new Rect(Mathf.Round(unsafeBorders.x), Mathf.Round(unsafeBorders.w), Mathf.Round(m_CurrentWidth - unsafeBorders.x - unsafeBorders.z), Mathf.Round(m_CurrentHeight - unsafeBorders.y - unsafeBorders.w));
if (orientationData.cutouts == null || orientationData.cutouts.Length == 0)
{
m_CurrentCutouts = new Rect[0];
}
else
{
// Calculating the cutouts and adding the ones that are inside the rendering area.
List<Rect> currentCutouts = new List<Rect>();
for (int i = 0; i < orientationData.cutouts.Length; ++i)
{
var cutout = orientationData.cutouts[i];
var currentCutout = new Rect(Mathf.Round((cutout.x - insetsInOrientation.x) * resolutionWidthScale), Mathf.Round((cutout.y - insetsInOrientation.w) * resolutionHeightScale), Mathf.Round(cutout.width * resolutionWidthScale), Mathf.Round(cutout.height * resolutionHeightScale));
// Negative coordinates can happen if the cutout overlaps the inset. In other words, if the cutout is outside the rendering area.
if (currentCutout.x >= 0 && currentCutout.y >= 0 && currentCutout.xMax <= m_CurrentWidth && currentCutout.yMax <= m_CurrentHeight)
{
currentCutouts.Add(currentCutout);
}
}
m_CurrentCutouts = currentCutouts.ToArray();
}
}
// Insets are parts of the screen that are outside of unity rendering area, like navigation bar in windowed mode. Insets are only possible on Android at the moment.
private void CalculateInsets()
{
if (!m_DeviceInfo.IsAndroidDevice())
return;
var safeArea = m_SupportedOrientations[ScreenOrientation.Portrait].safeArea;
var inset = Vector4.zero;
if (!m_IsRenderingOutsideSafeArea)
{
inset = new Vector4
{
x = safeArea.x,
y = m_Screen.height - safeArea.height - safeArea.y,
z = m_Screen.width - safeArea.width - safeArea.x,
w = safeArea.y
};
}
if (!m_IsFullScreen)
{
switch (m_RenderedOrientation)
{
case ScreenOrientation.Portrait:
case ScreenOrientation.LandscapeLeft:
case ScreenOrientation.LandscapeRight:
inset.w += m_Screen.navigationBarHeight;
break;
case ScreenOrientation.PortraitUpsideDown:
if (m_IsRenderingOutsideSafeArea)
{
inset.y = m_Screen.height - safeArea.height - safeArea.y;
}
inset.y += m_Screen.navigationBarHeight;
break;
}
}
Insets = inset;
}
private void CalculateResolutionWithInsets()
{
var screenWidthInOrientation = IsRenderingLandscape ? m_Screen.height : m_Screen.width;
var screenHeightInOrientation = IsRenderingLandscape ? m_Screen.width : m_Screen.height;
var insetsInOrientation = InsetsInCurrentOrientation;
var widthInOrientation = screenWidthInOrientation - insetsInOrientation.x - insetsInOrientation.z;
var heightInOrientation = screenHeightInOrientation - insetsInOrientation.y - insetsInOrientation.w;
var dpiRatio = 1f;
if (m_PlayerSettings.resolutionScalingMode == ResolutionScalingMode.FixedDpi && m_PlayerSettings.targetDpi < m_Screen.dpi)
dpiRatio = m_PlayerSettings.targetDpi / m_Screen.dpi;
m_CurrentWidth = Mathf.RoundToInt(widthInOrientation * dpiRatio);
m_CurrentHeight = Mathf.RoundToInt(heightInOrientation * dpiRatio);
}
public void Enable()
{
ShimManager.UseShim(this);
}
public void Disable()
{
ShimManager.RemoveShim(this);
}
public new void Dispose()
{
Disable();
}
#region ShimBase Overrides
public override int width => m_CurrentWidth;
public override int height => m_CurrentHeight;
public override Rect safeArea => m_CurrentSafeArea;
public override Rect[] cutouts => m_CurrentCutouts;
public override float dpi => m_Screen.dpi;
public override Resolution currentResolution => new Resolution() { width = m_CurrentWidth, height = m_CurrentHeight };
public override Resolution[] resolutions => new[] { currentResolution };
public override ScreenOrientation orientation
{
get => m_RenderedOrientation;
set
{
if (value == ScreenOrientation.AutoRotation)
{
m_AutoRotation = true;
ApplyAutoRotation();
}
else if (m_SupportedOrientations.ContainsKey(value))
{
m_AutoRotation = false;
RequestOrientation(value);
}
}
}
public override bool autorotateToPortrait
{
get => m_AllowedAutoRotation[ScreenOrientation.Portrait];
set => SetAutoRotationOrientation(ScreenOrientation.Portrait, value);
}
public override bool autorotateToPortraitUpsideDown
{
get => m_AllowedAutoRotation[ScreenOrientation.PortraitUpsideDown];
set => SetAutoRotationOrientation(ScreenOrientation.PortraitUpsideDown, value);
}
public override bool autorotateToLandscapeLeft
{
get => m_AllowedAutoRotation[ScreenOrientation.LandscapeLeft];
set => SetAutoRotationOrientation(ScreenOrientation.LandscapeLeft, value);
}
public override bool autorotateToLandscapeRight
{
get => m_AllowedAutoRotation[ScreenOrientation.LandscapeRight];
set => SetAutoRotationOrientation(ScreenOrientation.LandscapeRight, value);
}
public override void SetResolution(int width, int height, FullScreenMode fullScreenMode, RefreshRate refreshRate)
{
m_WasResolutionSet = true;
if (width > k_MaxResolution || height > k_MaxResolution || width < 0 || height < 0)
{
Debug.LogError($"Failed to change resolution. Make sure that both width and height are at least 0 and less than {k_MaxResolution}.");
return;
}
if (width == 0 && height == 0)
{
m_WasResolutionSet = false;
m_RequestDefaultResolution = true;
return;
}
if (width == 0)
width = 1;
else if (height == 0)
height = 1;
m_RequestedWidth = width;
m_RequestedHeight = height;
fullScreen = (fullScreenMode != FullScreenMode.Windowed); // Tested on Pixel 2 that all other three types go into full screen mode.
}
public override bool fullScreen
{
get => m_IsFullScreen;
set
{
if (!m_DeviceInfo.IsAndroidDevice() || m_IsFullScreen == value)
return;
m_RequestedFullScreen = value;
}
}
public override FullScreenMode fullScreenMode
{
get => fullScreen ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed;
set => fullScreen = (value != FullScreenMode.Windowed);
}
#endregion
}
}
| UnityCsReference/Modules/DeviceSimulatorEditor/Shims/ScreenSimulation.cs/0 | {
"file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/Shims/ScreenSimulation.cs",
"repo_id": "UnityCsReference",
"token_count": 10849
} | 351 |
// 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 interface IDataPlayer
{
/// <summary>
/// Called when a DataPlayableOutput is associated with the Player.
/// </summary>
/// Use this to provide the stream to the DataPlayableOutput.
/// <param name="output">The output associated with the Player.</param>
public void Bind(DataPlayableOutput output);
/// <summary>
/// Called when a DataPlayableOutput is dissociated from the Player.
/// </summary>
/// Use this to clean up any memory held by the player for the output.
/// <param name="output">The output associated with the Player.</param>
public void Release(DataPlayableOutput output);
}
}
| UnityCsReference/Modules/Director/ScriptBindings/IDataPlayer.cs/0 | {
"file_path": "UnityCsReference/Modules/Director/ScriptBindings/IDataPlayer.cs",
"repo_id": "UnityCsReference",
"token_count": 299
} | 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;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.EditorTools;
using UnityEngine.UIElements;
namespace UnityEditor.Toolbars
{
[EditorToolbarElement("Tools/Builtin Tools")]
sealed class BuiltinToolsStrip : VisualElement
{
// builtin, global, component
const int k_ToolbarSections = 3;
VisualElement[] m_Toolbars;
List<ToolEntry> m_AvailableTools = new List<ToolEntry>();
VisualElement defaultToolButtons => m_Toolbars[0];
VisualElement customGlobalToolButtons => m_Toolbars[1];
VisualElement componentToolButtons => m_Toolbars[2];
public BuiltinToolsStrip()
{
name = "BuiltinTools";
SceneViewToolbarStyles.AddStyleSheets(this);
EditorToolbarUtility.SetupChildrenAsButtonStrip(this);
// Only show the contexts dropdown if there are non-builtin contexts available
if (EditorToolUtility.toolContextsInProject > 1)
{
var contexts = new ToolContextButton();
contexts.AddToClassList(EditorToolbarUtility.aloneStripElementClassName);
Add(contexts);
}
m_Toolbars = new VisualElement[k_ToolbarSections]
{
new VisualElement() { name = "Builtin View and Transform Tools" },
new VisualElement() { name = "Custom Global Tools" },
new VisualElement()
};
for (int i = 0; i < k_ToolbarSections; ++i)
{
m_Toolbars[i].AddToClassList("toolbar-contents");
Add(m_Toolbars[i]);
}
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
RebuildAvailableTools();
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
EditorToolManager.availableToolsChanged += RebuildAvailableTools;
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
EditorToolManager.availableToolsChanged -= RebuildAvailableTools;
}
void RebuildAvailableTools()
{
EditorToolManager.GetAvailableTools(m_AvailableTools);
foreach (var toolbar in m_Toolbars)
toolbar.Clear();
m_AvailableTools = EditorToolManager.OrderAvailableTools(m_AvailableTools);
Type currentComponentHeaderType = null;
VisualElement componentTools = null;
foreach (var entry in m_AvailableTools)
{
switch (entry.scope)
{
case ToolEntry.Scope.BuiltinView:
case ToolEntry.Scope.BuiltinMove:
case ToolEntry.Scope.BuiltinRotate:
case ToolEntry.Scope.BuiltinScale:
case ToolEntry.Scope.BuiltinRect:
case ToolEntry.Scope.BuiltinTransform:
defaultToolButtons.Add(new ToolButton((Tool)entry.scope, entry.tools));
break;
case ToolEntry.Scope.BuiltinAdditional:
defaultToolButtons.Add(new ToolButton(entry.tools));
break;
case ToolEntry.Scope.CustomGlobal:
customGlobalToolButtons.Add(new ToolButton(entry.tools));
break;
case ToolEntry.Scope.Component:
if (currentComponentHeaderType == null || currentComponentHeaderType != entry.tools[0].target?.GetType())
{
currentComponentHeaderType = entry.tools[0].target?.GetType();
if (currentComponentHeaderType == null)
break;
if (componentTools != null)
EditorToolbarUtility.SetupChildrenAsButtonStrip(componentTools);
componentTools = new VisualElement() { name = "Component Tools" };
componentTools.AddToClassList("toolbar-contents");
var header = new EditorToolbarIcon();
if ((header.icon = EditorGUIUtility.FindTexture(currentComponentHeaderType)) == null)
header.textIcon = currentComponentHeaderType.Name;
componentToolButtons.Add(header);
componentToolButtons.Add(componentTools);
}
componentTools.Add(new ToolButton(entry.tools));
break;
}
}
if (componentTools != null)
EditorToolbarUtility.SetupChildrenAsButtonStrip(componentTools);
for (var i = 0; i < k_ToolbarSections - 1; i++)
EditorToolbarUtility.SetupChildrenAsButtonStrip(m_Toolbars[i]);
}
}
}
| UnityCsReference/Modules/EditorToolbar/ToolbarElements/EditorToolsToolbar.cs/0 | {
"file_path": "UnityCsReference/Modules/EditorToolbar/ToolbarElements/EditorToolsToolbar.cs",
"repo_id": "UnityCsReference",
"token_count": 2515
} | 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;
namespace UnityEditor.Experimental.GraphView
{
[Flags]
public enum Capabilities
{
Selectable = 1 << 0,
Collapsible = 1 << 1,
Resizable = 1 << 2,
Movable = 1 << 3,
Deletable = 1 << 4,
Droppable = 1 << 5,
Ascendable = 1 << 6,
Renamable = 1 << 7,
Copiable = 1 << 8,
Snappable = 1 << 9,
Groupable = 1 << 10,
Stackable = 1 << 11
}
internal enum ResizeRestriction
{
None,
FlexDirection
}
}
| UnityCsReference/Modules/GraphViewEditor/Capabilities.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Capabilities.cs",
"repo_id": "UnityCsReference",
"token_count": 315
} | 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;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public class MiniMap : GraphElement
{
public float maxHeight { get; set; }
public float maxWidth { get; set; }
float m_PreviousContainerWidth = -1;
float m_PreviousContainerHeight = -1;
readonly Label m_Label;
Dragger m_Dragger;
readonly Color m_ViewportColor = new Color(1.0f, 1.0f, 0.0f, 0.35f);
protected readonly Color m_SelectedChildrenColor = new Color(1.0f, 1.0f, 1.0f, 0.5f);
readonly Color m_PlacematBorderColor = new Color(0.23f, 0.23f, 0.23f);
// Various rects used by the MiniMap
Rect m_ViewportRect; // Rect that represents the current viewport
Rect m_ContentRect; // Rect that represents the rect needed to encompass all Graph Elements
Rect m_ContentRectLocal; // Rect that represents the rect needed to encompass all Graph Elements in local coords
int titleBarOffset { get { return (int)resolvedStyle.paddingTop; } }
public Action<string> zoomFactorTextChanged;
private bool m_Anchored;
public bool anchored
{
get { return m_Anchored; }
set
{
if (windowed || m_Anchored == value)
return;
m_Anchored = value;
if (m_Anchored)
{
capabilities &= ~Capabilities.Movable;
ResetPositionProperties();
AddToClassList("anchored");
}
else
{
capabilities |= Capabilities.Movable;
RemoveFromClassList("anchored");
}
Resize();
}
}
bool m_Windowed;
public bool windowed
{
get { return m_Windowed; }
set
{
if (m_Windowed == value) return;
if (value)
{
anchored = false; // Can't be anchored and windowed
capabilities &= ~Capabilities.Movable;
AddToClassList("windowed");
this.RemoveManipulator(m_Dragger);
}
else
{
capabilities |= Capabilities.Movable;
RemoveFromClassList("windowed");
this.AddManipulator(m_Dragger);
}
m_Windowed = value;
}
}
public MiniMap()
{
capabilities = Capabilities.Movable;
m_Dragger = new Dragger { clampToParentEdges = true };
this.AddManipulator(m_Dragger);
anchored = false;
maxWidth = 200;
maxHeight = 200;
m_Label = new Label("Floating Minimap");
Add(m_Label);
RegisterCallback<MouseDownEvent>(OnMouseDown);
m_Label.RegisterCallback<MouseDownEvent>(EatMouseDown);
this.AddManipulator(new ContextualMenuManipulator(BuildContextualMenu));
AddStyleSheetPath("StyleSheets/GraphView/Minimap.uss");
this.generateVisualContent += OnGenerateVisualContent;
}
private GraphView m_GraphView;
public GraphView graphView
{
get
{
if (!windowed && m_GraphView == null)
m_GraphView = GetFirstAncestorOfType<GraphView>();
return m_GraphView;
}
set
{
if (!windowed)
return;
m_GraphView = value;
}
}
void ToggleAnchorState(DropdownMenuAction a)
{
anchored = !anchored;
}
public virtual void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
if (!windowed)
evt.menu.AppendAction(anchored ? "Make floating" : "Anchor", ToggleAnchorState, DropdownMenuAction.AlwaysEnabled);
}
public void OnResized()
{
Resize();
}
void Resize()
{
if (windowed || parent == null)
return;
style.width = maxWidth;
style.height = maxHeight;
// Relocate if partially visible on bottom or right side (left/top not checked, only bottom/right affected by a size change)
if (resolvedStyle.left + resolvedStyle.width > parent.layout.x + parent.layout.width)
{
var newPosition = layout;
newPosition.x -= resolvedStyle.left + resolvedStyle.width - (parent.layout.x + parent.layout.width);
layout = newPosition;
}
if (resolvedStyle.top + resolvedStyle.height > parent.layout.y + parent.layout.height)
{
var newPosition = layout;
newPosition.y -= resolvedStyle.top + resolvedStyle.height - (parent.layout.y + parent.layout.height);
layout = newPosition;
}
var newMiniMapPos = layout;
newMiniMapPos.width = resolvedStyle.width;
newMiniMapPos.height = resolvedStyle.height;
newMiniMapPos.x = Mathf.Max(parent.layout.x, newMiniMapPos.x);
newMiniMapPos.y = Mathf.Max(parent.layout.y, newMiniMapPos.y);
layout = newMiniMapPos;
}
static void ChangeToMiniMapCoords(ref Rect rect, float factor, Vector3 translation)
{
// Apply factor
rect.width *= factor;
rect.height *= factor;
rect.x *= factor;
rect.y *= factor;
// Apply translation
rect.x += translation.x;
rect.y += translation.y;
}
void SetZoomFactorText(string zoomFactorText)
{
m_Label.text = "MiniMap " + zoomFactorText;
zoomFactorTextChanged?.Invoke(zoomFactorText);
}
void CalculateRects(VisualElement container)
{
if (graphView == null)
{
// Nothing to do in this case.
return;
}
m_ContentRect = graphView.CalculateRectToFitAll(container);
m_ContentRectLocal = m_ContentRect;
// Retrieve viewport rectangle as if zoom and pan were inactive
Matrix4x4 containerInvTransform = container.worldTransformInverse;
Vector4 containerInvTranslation = containerInvTransform.GetColumn(3);
var containerInvScale = new Vector2(containerInvTransform.m00, containerInvTransform.m11);
m_ViewportRect = graphView.rect;
// Bring back viewport coordinates to (0,0), scale 1:1
m_ViewportRect.x += containerInvTranslation.x;
m_ViewportRect.y += containerInvTranslation.y;
var graphViewWB = graphView.worldBound;
m_ViewportRect.x += graphViewWB.x * containerInvScale.x;
m_ViewportRect.y += graphViewWB.y * containerInvScale.y;
m_ViewportRect.width *= containerInvScale.x;
m_ViewportRect.height *= containerInvScale.y;
// Update label with new value
var containerZoomFactor = container.worldTransform.m00;
SetZoomFactorText(UnityString.Format("{0:F2}", containerZoomFactor) + "x");
// Adjust rects for MiniMap
float effectiveWidth = layout.width - 1;
float effectiveHeight = layout.height - 1;
// Encompass viewport rectangle (as if zoom and pan were inactive)
var totalRect = RectUtils.Encompass(m_ContentRect, m_ViewportRect);
var minimapFactor = effectiveWidth / totalRect.width;
// Transform each rect to MiniMap coordinates
ChangeToMiniMapCoords(ref totalRect, minimapFactor, Vector3.zero);
var minimapTranslation = new Vector3(-totalRect.x, titleBarOffset - totalRect.y);
ChangeToMiniMapCoords(ref m_ViewportRect, minimapFactor, minimapTranslation);
ChangeToMiniMapCoords(ref m_ContentRect, minimapFactor, minimapTranslation);
// Diminish and center everything to fit vertically
if (totalRect.height > (effectiveHeight - titleBarOffset))
{
float totalRectFactor = (effectiveHeight - titleBarOffset) / totalRect.height;
float totalRectOffsetX = (effectiveWidth - (totalRect.width * totalRectFactor)) / 2.0f;
float totalRectOffsetY = titleBarOffset - ((totalRect.y + minimapTranslation.y) * totalRectFactor);
m_ContentRect.width *= totalRectFactor;
m_ContentRect.height *= totalRectFactor;
m_ContentRect.x *= totalRectFactor;
m_ContentRect.y *= totalRectFactor;
m_ContentRect.x += totalRectOffsetX;
m_ContentRect.y += totalRectOffsetY;
m_ViewportRect.width *= totalRectFactor;
m_ViewportRect.height *= totalRectFactor;
m_ViewportRect.x *= totalRectFactor;
m_ViewportRect.y *= totalRectFactor;
m_ViewportRect.x += totalRectOffsetX;
m_ViewportRect.y += totalRectOffsetY;
}
}
Rect CalculateElementRect(GraphElement elem)
{
Rect rect = elem.ChangeCoordinatesTo(graphView.contentViewContainer, elem.rect);
rect.x = m_ContentRect.x + ((rect.x - m_ContentRectLocal.x) * m_ContentRect.width / m_ContentRectLocal.width);
rect.y = m_ContentRect.y + ((rect.y - m_ContentRectLocal.y) * m_ContentRect.height / m_ContentRectLocal.height);
rect.width *= m_ContentRect.width / m_ContentRectLocal.width;
rect.height *= m_ContentRect.height / m_ContentRectLocal.height;
// Clip using a minimal 2 pixel wide frame around edges
// (except yMin since we already have the titleBar offset which is enough for clipping)
var xMin = 2;
var yMin = windowed ? 2 : 0;
var xMax = layout.width - 2;
var yMax = layout.height - 2;
if (rect.x < xMin)
{
if (rect.x < xMin - rect.width)
return new Rect(0, 0, 0, 0);
rect.width -= xMin - rect.x;
rect.x = xMin;
}
if (rect.x + rect.width >= xMax)
{
if (rect.x >= xMax)
return new Rect(0, 0, 0, 0);
rect.width = rect.x - xMax;
}
if (rect.y < yMin + titleBarOffset)
{
if (rect.y < yMin + titleBarOffset - rect.height)
return new Rect(0, 0, 0, 0);
rect.height -= yMin + titleBarOffset - rect.y;
rect.y = yMin + titleBarOffset;
}
if (rect.y + rect.height >= yMax)
{
if (rect.y >= yMax)
return new Rect(0, 0, 0, 0);
rect.height = rect.y - yMax;
}
return rect;
}
private static Vector3[] s_CachedRect = new Vector3[4];
private void OnGenerateVisualContent(MeshGenerationContext mgc)
{
// This control begs to be fully rewritten and it shouldn't use immediate
// mode rendering at all. It should maintain its vertex/index lists and only
// update affected vertices when their respective elements are changed. This
// way the cost of GenerateVisualContent becomes effectively only two memcpys.
// The following call uses an internal UIToolkit API and should NOT be used here.
mgc.entryRecorder.DrawImmediate(mgc.parentEntry, DrawMinimapContent, true);
}
void DrawSolidRectangleWithOutline(ref Vector3[] cachedRect, Color faceColor, Color typeColor)
{
Handles.DrawSolidRectangleWithOutline(cachedRect, faceColor, typeColor);
}
static readonly Unity.Profiling.ProfilerMarker k_ImmediateRepaintMarker = new Unity.Profiling.ProfilerMarker("MiniMap.ImmediateRepaint");
void DrawMinimapContent()
{
Color currentColor = Handles.color;
if (graphView == null)
{
// Just need to draw the minimum rect.
Resize();
return;
}
k_ImmediateRepaintMarker.Begin();
VisualElement container = graphView.contentViewContainer;
// Retrieve all container relative information
Matrix4x4 containerTransform = graphView.viewTransform.matrix;
var containerScale = new Vector2(containerTransform.m00, containerTransform.m11);
float containerWidth = parent.layout.width / containerScale.x;
float containerHeight = parent.layout.height / containerScale.y;
if (Mathf.Abs(containerWidth - m_PreviousContainerWidth) > Mathf.Epsilon ||
Mathf.Abs(containerHeight - m_PreviousContainerHeight) > Mathf.Epsilon)
{
m_PreviousContainerWidth = containerWidth;
m_PreviousContainerHeight = containerHeight;
Resize();
}
// Refresh MiniMap rects
CalculateRects(container);
DrawElements();
// Draw viewport outline
DrawRectangleOutline(m_ViewportRect, m_ViewportColor);
Handles.color = currentColor;
k_ImmediateRepaintMarker.End();
}
void DrawElements()
{
// Draw placemats first ...
var placemats = graphView.placematContainer.Placemats;
foreach (var placemat in placemats.Where(p => p.showInMiniMap && p.visible))
{
var elemRect = CalculateElementRect(placemat);
s_CachedRect[0].Set(elemRect.xMin, elemRect.yMin, 0.0f);
s_CachedRect[1].Set(elemRect.xMax, elemRect.yMin, 0.0f);
s_CachedRect[2].Set(elemRect.xMax, elemRect.yMax, 0.0f);
s_CachedRect[3].Set(elemRect.xMin, elemRect.yMax, 0.0f);
Color fillColor = placemat.resolvedStyle.backgroundColor;
fillColor.a = 0.15f;
DrawSolidRectangleWithOutline(ref s_CachedRect, fillColor, m_PlacematBorderColor);
}
// ... then the other elements
Color darken = playModeTintColor;
graphView.graphElements.ForEach(elem =>
{
if (!elem.showInMiniMap || !elem.visible || elem is Placemat)
return;
var elemRect = CalculateElementRect(elem);
s_CachedRect[0].Set(elemRect.xMin, elemRect.yMin, 0.0f);
s_CachedRect[1].Set(elemRect.xMax, elemRect.yMin, 0.0f);
s_CachedRect[2].Set(elemRect.xMax, elemRect.yMax, 0.0f);
s_CachedRect[3].Set(elemRect.xMin, elemRect.yMax, 0.0f);
Handles.color = elem.elementTypeColor * darken;
DrawSolidRectangleWithOutline(ref s_CachedRect, elem.elementTypeColor, elem.elementTypeColor);
if (elem.selected)
DrawRectangleOutline(elemRect, m_SelectedChildrenColor);
});
}
void DrawRectangleOutline(Rect rect, Color color)
{
Color currentColor = Handles.color;
Handles.color = color;
// Draw viewport outline
Vector3[] points = new Vector3[5];
points[0] = new Vector3(rect.x, rect.y, 0.0f);
points[1] = new Vector3(rect.x + rect.width, rect.y, 0.0f);
points[2] = new Vector3(rect.x + rect.width, rect.y + rect.height, 0.0f);
points[3] = new Vector3(rect.x, rect.y + rect.height, 0.0f);
points[4] = new Vector3(rect.x, rect.y, 0.0f);
Handles.DrawPolyLine(points);
Handles.color = currentColor;
}
private void EatMouseDown(MouseDownEvent e)
{
// The minimap should not let any left mouse down go through when it's not movable.
if (e.button == (int)MouseButton.LeftMouse &&
(capabilities & Capabilities.Movable) == 0)
{
e.StopPropagation();
}
}
private void OnMouseDown(MouseDownEvent e)
{
if (graphView == null)
{
// Nothing to do if we're not attached to a GraphView!
return;
}
// Refresh MiniMap rects
CalculateRects(graphView.contentViewContainer);
var mousePosition = e.localMousePosition;
graphView.graphElements.ForEach(child =>
{
if (child == null)
return;
var selectable = child.GetFirstOfType<ISelectable>();
if (selectable == null || !selectable.IsSelectable())
return;
if (CalculateElementRect(child).Contains(mousePosition))
{
graphView.ClearSelection();
graphView.AddToSelection(selectable);
graphView.FrameSelection();
e.StopPropagation();
}
});
EatMouseDown(e);
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Elements/MiniMap.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/MiniMap.cs",
"repo_id": "UnityCsReference",
"token_count": 8654
} | 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.Collections.Generic;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public interface IDroppable
{
bool IsDroppable();
}
public interface IDropTarget
{
bool CanAcceptDrop(List<ISelectable> selection);
// evt.mousePosition will be in global coordinates.
bool DragUpdated(DragUpdatedEvent evt, IEnumerable<ISelectable> selection, IDropTarget dropTarget, ISelection dragSource);
bool DragPerform(DragPerformEvent evt, IEnumerable<ISelectable> selection, IDropTarget dropTarget, ISelection dragSource);
bool DragEnter(DragEnterEvent evt, IEnumerable<ISelectable> selection, IDropTarget enteredTarget, ISelection dragSource);
bool DragLeave(DragLeaveEvent evt, IEnumerable<ISelectable> selection, IDropTarget leftTarget, ISelection dragSource);
bool DragExited();
}
}
| UnityCsReference/Modules/GraphViewEditor/IDroppable.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/IDroppable.cs",
"repo_id": "UnityCsReference",
"token_count": 344
} | 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;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public class SelectionDragger : Dragger
{
IDropTarget m_PrevDropTarget;
bool m_ShiftClicked = false;
bool m_Dragging = false;
Snapper m_Snapper = new Snapper();
internal bool snapEnabled { get; set; }
// selectedElement is used to store a unique selection candidate for cases where user clicks on an item not to
// drag it but just to reset the selection -- we only know this after the manipulation has ended
GraphElement selectedElement { get; set; }
GraphElement clickedElement { get; set; }
private GraphViewChange m_GraphViewChange;
private List<GraphElement> m_MovedElements;
private List<VisualElement> m_DropTargetPickList = new List<VisualElement>();
IDropTarget GetDropTargetAt(Vector2 mousePosition, IEnumerable<VisualElement> exclusionList)
{
Vector2 pickPoint = mousePosition;
List<VisualElement> pickList = m_DropTargetPickList;
pickList.Clear();
target.panel.PickAll(pickPoint, pickList);
IDropTarget dropTarget = null;
for (int i = 0; i < pickList.Count; i++)
{
if (pickList[i] == target && target != m_GraphView)
continue;
VisualElement picked = pickList[i];
dropTarget = picked as IDropTarget;
if (dropTarget != null)
{
if (exclusionList.Contains(picked))
{
dropTarget = null;
}
else
break;
}
}
return dropTarget;
}
public SelectionDragger()
{
snapEnabled = EditorPrefs.GetBool("GraphSnapping", true);
activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse });
activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, modifiers = EventModifiers.Shift });
if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer)
{
activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, modifiers = EventModifiers.Command });
}
else
{
activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, modifiers = EventModifiers.Control });
}
panSpeed = new Vector2(1, 1);
clampToParentEdges = false;
m_MovedElements = new List<GraphElement>();
m_GraphViewChange.movedElements = m_MovedElements;
}
protected override void RegisterCallbacksOnTarget()
{
var selectionContainer = target as ISelection;
if (selectionContainer == null)
{
throw new InvalidOperationException("Manipulator can only be added to a control that supports selection");
}
target.RegisterCallback<MouseDownEvent>(OnMouseDown);
target.RegisterCallback<MouseMoveEvent>(OnMouseMove);
target.RegisterCallback<MouseUpEvent>(OnMouseUp);
target.RegisterCallback<KeyDownEvent>(OnKeyDown);
target.RegisterCallback<MouseCaptureOutEvent>(OnMouseCaptureOutEvent);
m_Dragging = false;
}
protected override void UnregisterCallbacksFromTarget()
{
target.UnregisterCallback<MouseDownEvent>(OnMouseDown);
target.UnregisterCallback<MouseMoveEvent>(OnMouseMove);
target.UnregisterCallback<MouseUpEvent>(OnMouseUp);
target.UnregisterCallback<KeyDownEvent>(OnKeyDown);
target.UnregisterCallback<MouseCaptureOutEvent>(OnMouseCaptureOutEvent);
}
private GraphView m_GraphView;
class OriginalPos
{
public Rect pos;
public Scope scope;
public StackNode stack;
public int stackIndex;
public bool dragStarted;
}
private Dictionary<GraphElement, OriginalPos> m_OriginalPos;
private Vector2 m_originalMouse;
static void SendDragAndDropEvent(IDragAndDropEvent evt, List<ISelectable> selection, IDropTarget dropTarget, ISelection dragSource)
{
if (dropTarget == null)
{
return;
}
EventBase e = evt as EventBase;
if (e.eventTypeId == DragExitedEvent.TypeId())
{
dropTarget.DragExited();
}
else if (e.eventTypeId == DragEnterEvent.TypeId())
{
dropTarget.DragEnter(evt as DragEnterEvent, selection, dropTarget, dragSource);
}
else if (e.eventTypeId == DragLeaveEvent.TypeId())
{
dropTarget.DragLeave(evt as DragLeaveEvent, selection, dropTarget, dragSource);
}
if (!dropTarget.CanAcceptDrop(selection))
{
return;
}
if (e.eventTypeId == DragPerformEvent.TypeId())
{
dropTarget.DragPerform(evt as DragPerformEvent, selection, dropTarget, dragSource);
}
else if (e.eventTypeId == DragUpdatedEvent.TypeId())
{
dropTarget.DragUpdated(evt as DragUpdatedEvent, selection, dropTarget, dragSource);
}
}
private void OnMouseCaptureOutEvent(MouseCaptureOutEvent e)
{
if (m_Active)
{
if (m_PrevDropTarget != null && m_GraphView != null)
{
if (m_PrevDropTarget.CanAcceptDrop(m_GraphView.selection))
{
m_PrevDropTarget.DragExited();
}
}
// Stop processing the event sequence if the target has lost focus, then.
selectedElement = null;
m_PrevDropTarget = null;
m_Active = false;
if (snapEnabled)
{
m_Snapper.EndSnap(m_GraphView);
}
}
}
protected new void OnMouseDown(MouseDownEvent e)
{
if (m_Active)
{
e.StopImmediatePropagation();
return;
}
if (CanStartManipulation(e))
{
m_GraphView = target as GraphView;
if (m_GraphView == null)
return;
// SGB-549: Prevent stealing capture from a child element. This shouldn't be necessary if children
// elements call StopPropagation when they capture the mouse, but we can't be sure of that and thus
// we are being a bit overprotective here.
if (target.panel?.GetCapturingElement(PointerId.mousePointerId) != null)
{
return;
}
selectedElement = null;
// avoid starting a manipulation on a non movable object
clickedElement = e.target as GraphElement;
if (clickedElement == null)
{
var ve = e.target as VisualElement;
clickedElement = ve.GetFirstAncestorOfType<GraphElement>();
if (clickedElement == null)
return;
}
// Only start manipulating if the clicked element is movable, selected and that the mouse is in its clickable region (it must be deselected otherwise).
if (!clickedElement.IsMovable() || !clickedElement.HitTest(clickedElement.WorldToLocal(e.mousePosition)))
return;
// If we hit this, this likely because the element has just been unselected
// It is important for this manipulator to receive the event so the previous one did not stop it
// but we shouldn't let it propagate to other manipulators to avoid a re-selection
if (!m_GraphView.selection.Contains(clickedElement))
{
e.StopImmediatePropagation();
return;
}
selectedElement = clickedElement;
m_OriginalPos = new Dictionary<GraphElement, OriginalPos>();
HashSet<GraphElement> elementsToMove = new HashSet<GraphElement>(m_GraphView.selection.OfType<GraphElement>());
var selectedPlacemats = new HashSet<Placemat>(elementsToMove.OfType<Placemat>());
foreach (var placemat in selectedPlacemats)
placemat.GetElementsToMove(e.shiftKey, elementsToMove);
foreach (GraphElement ce in elementsToMove)
{
if (ce == null || !ce.IsMovable())
continue;
StackNode stackNode = null;
if (ce.parent is StackNode)
{
stackNode = ce.parent as StackNode;
if (stackNode.IsSelected(m_GraphView))
continue;
}
Rect geometry = ce.GetPosition();
Rect geometryInContentViewSpace = ce.hierarchy.parent.ChangeCoordinatesTo(m_GraphView.contentViewContainer, geometry);
m_OriginalPos[ce] = new OriginalPos
{
pos = geometryInContentViewSpace,
scope = ce.GetContainingScope(),
stack = stackNode,
stackIndex = stackNode != null ? stackNode.IndexOf(ce) : -1
};
}
m_originalMouse = e.mousePosition;
m_ItemPanDiff = Vector3.zero;
if (m_PanSchedule == null)
{
m_PanSchedule = m_GraphView.schedule.Execute(Pan).Every(k_PanInterval).StartingIn(k_PanInterval);
m_PanSchedule.Pause();
}
// Checking if the Graph Element we are moving has the snappable Capability
if ((selectedElement.capabilities & Capabilities.Snappable) == 0)
{
snapEnabled = false;
}
else
{
snapEnabled = EditorPrefs.GetBool("GraphSnapping", true);
}
if (snapEnabled)
m_Snapper.BeginSnap(m_GraphView);
m_Active = true;
target.CaptureMouse(); // We want to receive events even when mouse is not over ourself.
e.StopImmediatePropagation();
}
}
internal const int k_PanAreaWidth = 100;
internal const int k_PanSpeed = 4;
internal const int k_PanInterval = 10;
internal const float k_MinSpeedFactor = 0.5f;
internal const float k_MaxSpeedFactor = 2.5f;
internal const float k_MaxPanSpeed = k_MaxSpeedFactor * k_PanSpeed;
private IVisualElementScheduledItem m_PanSchedule;
private Vector3 m_PanDiff = Vector3.zero;
private Vector3 m_ItemPanDiff = Vector3.zero;
private Vector2 m_MouseDiff = Vector2.zero;
float m_XScale;
internal Vector2 GetEffectivePanSpeed(Vector2 mousePos)
{
Vector2 effectiveSpeed = Vector2.zero;
if (mousePos.x <= k_PanAreaWidth)
effectiveSpeed.x = -(((k_PanAreaWidth - mousePos.x) / k_PanAreaWidth) + 0.5f) * k_PanSpeed;
else if (mousePos.x >= m_GraphView.contentContainer.layout.width - k_PanAreaWidth)
effectiveSpeed.x = (((mousePos.x - (m_GraphView.contentContainer.layout.width - k_PanAreaWidth)) / k_PanAreaWidth) + 0.5f) * k_PanSpeed;
if (mousePos.y <= k_PanAreaWidth)
effectiveSpeed.y = -(((k_PanAreaWidth - mousePos.y) / k_PanAreaWidth) + 0.5f) * k_PanSpeed;
else if (mousePos.y >= m_GraphView.contentContainer.layout.height - k_PanAreaWidth)
effectiveSpeed.y = (((mousePos.y - (m_GraphView.contentContainer.layout.height - k_PanAreaWidth)) / k_PanAreaWidth) + 0.5f) * k_PanSpeed;
effectiveSpeed = Vector2.ClampMagnitude(effectiveSpeed, k_MaxPanSpeed);
return effectiveSpeed;
}
void ComputeSnappedRect(ref Rect selectedElementProposedGeom, float scale)
{
// Let the snapper compute a snapped position using the precomputed position relatively to the geometries of all unselected
// GraphElements in the GraphView.contentViewContainer's space.
Rect geometryInContentViewContainerSpace = selectedElement.parent.ChangeCoordinatesTo(m_GraphView.contentViewContainer, selectedElementProposedGeom);
geometryInContentViewContainerSpace = m_Snapper.GetSnappedRect(geometryInContentViewContainerSpace, scale);
// Once the snapped position is computed in the GraphView.contentViewContainer's space then
// translate it into the local space of the parent of the selected element.
selectedElementProposedGeom = m_GraphView.contentViewContainer.ChangeCoordinatesTo(selectedElement.parent, geometryInContentViewContainerSpace);
}
protected new void OnMouseMove(MouseMoveEvent e)
{
if (!m_Active)
return;
if (m_GraphView == null)
return;
var ve = (VisualElement)e.target;
Vector2 gvMousePos = ve.ChangeCoordinatesTo(m_GraphView.contentContainer, e.localMousePosition);
m_PanDiff = GetEffectivePanSpeed(gvMousePos);
if (m_PanDiff != Vector3.zero)
{
m_PanSchedule.Resume();
}
else
{
m_PanSchedule.Pause();
}
// We need to monitor the mouse diff "by hand" because we stop positioning the graph elements once the
// mouse has gone out.
m_MouseDiff = m_originalMouse - e.mousePosition;
var groupElementsDraggedOut = e.shiftKey ? new Dictionary<Group, List<GraphElement>>() : null;
// Handle the selected element
Rect selectedElementGeom = GetSelectedElementGeom();
m_ShiftClicked = e.shiftKey;
if (snapEnabled && !m_ShiftClicked)
{
ComputeSnappedRect(ref selectedElementGeom, m_XScale);
}
if (snapEnabled && m_ShiftClicked)
{
m_Snapper.ClearSnapLines();
}
foreach (KeyValuePair<GraphElement, OriginalPos> v in m_OriginalPos)
{
GraphElement ce = v.Key;
// Protect against stale visual elements that have been deparented since the start of the manipulation
if (ce.hierarchy.parent == null)
continue;
if (!v.Value.dragStarted)
{
// TODO Would probably be a good idea to batch stack items as we do for group ones.
var stackParent = ce.GetFirstAncestorOfType<StackNode>();
if (stackParent != null)
stackParent.OnStartDragging(ce);
if (groupElementsDraggedOut != null)
{
var groupParent = ce.GetContainingScope() as Group;
if (groupParent != null)
{
if (!groupElementsDraggedOut.ContainsKey(groupParent))
{
groupElementsDraggedOut[groupParent] = new List<GraphElement>();
}
groupElementsDraggedOut[groupParent].Add(ce);
}
}
v.Value.dragStarted = true;
}
SnapOrMoveElement(v, selectedElementGeom);
}
// Needed to ensure nodes can be dragged out of multiple groups all at once.
if (groupElementsDraggedOut != null)
{
foreach (KeyValuePair<Group, List<GraphElement>> kvp in groupElementsDraggedOut)
{
kvp.Key.OnStartDragging(e, kvp.Value);
}
}
List<ISelectable> selection = m_GraphView.selection;
// TODO: Replace with a temp drawing or something...maybe manipulator could fake position
// all this to let operation know which element sits under cursor...or is there another way to draw stuff that is being dragged?
IDropTarget dropTarget = GetDropTargetAt(e.mousePosition, selection.OfType<VisualElement>());
if (m_PrevDropTarget != dropTarget)
{
if (m_PrevDropTarget != null)
{
using (DragLeaveEvent eexit = DragLeaveEvent.GetPooled(e))
{
SendDragAndDropEvent(eexit, selection, m_PrevDropTarget, m_GraphView);
}
}
using (DragEnterEvent eenter = DragEnterEvent.GetPooled(e))
{
SendDragAndDropEvent(eenter, selection, dropTarget, m_GraphView);
}
}
using (DragUpdatedEvent eupdated = DragUpdatedEvent.GetPooled(e))
{
SendDragAndDropEvent(eupdated, selection, dropTarget, m_GraphView);
}
m_PrevDropTarget = dropTarget;
m_Dragging = true;
e.StopPropagation();
}
private void Pan(TimerState ts)
{
m_GraphView.viewTransform.position -= m_PanDiff;
m_ItemPanDiff += m_PanDiff;
// Handle the selected element
Rect selectedElementGeom = GetSelectedElementGeom();
if (snapEnabled && !m_ShiftClicked)
{
ComputeSnappedRect(ref selectedElementGeom, m_XScale);
}
foreach (KeyValuePair<GraphElement, OriginalPos> v in m_OriginalPos)
{
SnapOrMoveElement(v, selectedElementGeom);
}
}
void SnapOrMoveElement(KeyValuePair<GraphElement, OriginalPos> v, Rect selectedElementGeom)
{
GraphElement ce = v.Key;
if (EditorPrefs.GetBool("GraphSnapping"))
{
Vector2 geomDiff = selectedElementGeom.position - m_OriginalPos[selectedElement].pos.position;
Rect ceLayout = ce.GetPosition();
ce.SetPosition(new Rect(v.Value.pos.x + geomDiff.x, v.Value.pos.y + geomDiff.y, ceLayout.width, ceLayout.height));
}
else
{
MoveElement(ce, v.Value.pos);
}
}
Rect GetSelectedElementGeom()
{
// Handle the selected element
Matrix4x4 g = selectedElement.worldTransform;
m_XScale = g.m00; //The scale on x is equal to the scale on y because the graphview is not distorted
Rect selectedElementGeom = m_OriginalPos[selectedElement].pos;
// Compute the new position of the selected element using the mouse delta position and panning info
selectedElementGeom.x = selectedElementGeom.x - (m_MouseDiff.x - m_ItemPanDiff.x) * panSpeed.x / m_XScale;
selectedElementGeom.y = selectedElementGeom.y - (m_MouseDiff.y - m_ItemPanDiff.y) * panSpeed.y / m_XScale;
return selectedElementGeom;
}
void MoveElement(GraphElement element, Rect originalPos)
{
Matrix4x4 g = element.worldTransform;
var scale = new Vector3(g.m00, g.m11, g.m22);
Rect newPos = new Rect(0, 0, originalPos.width, originalPos.height);
// Compute the new position of the selected element using the mouse delta position and panning info
newPos.x = originalPos.x - (m_MouseDiff.x - m_ItemPanDiff.x) * panSpeed.x / scale.x * element.transform.scale.x;
newPos.y = originalPos.y - (m_MouseDiff.y - m_ItemPanDiff.y) * panSpeed.y / scale.y * element.transform.scale.y;
element.SetPosition(m_GraphView.contentViewContainer.ChangeCoordinatesTo(element.hierarchy.parent, newPos));
}
protected new void OnMouseUp(MouseUpEvent evt)
{
if (m_GraphView == null)
{
if (m_Active)
{
target.ReleaseMouse();
selectedElement = null;
m_Active = false;
m_Dragging = false;
m_PrevDropTarget = null;
}
return;
}
List<ISelectable> selection = m_GraphView.selection;
if (CanStopManipulation(evt))
{
if (m_Active)
{
if (m_Dragging)
{
foreach (IGrouping<StackNode, GraphElement> grouping in m_OriginalPos.GroupBy(v => v.Value.stack, v => v.Key))
{
if (grouping.Key != null && m_GraphView.elementsRemovedFromStackNode != null)
m_GraphView.elementsRemovedFromStackNode(grouping.Key, grouping);
foreach (GraphElement ge in grouping)
ge.UpdatePresenterPosition();
m_MovedElements.AddRange(grouping);
}
var graphView = target as GraphView;
if (graphView != null && graphView.graphViewChanged != null)
{
KeyValuePair<GraphElement, OriginalPos> firstPos = m_OriginalPos.First();
m_GraphViewChange.moveDelta = firstPos.Key.GetPosition().position - firstPos.Value.pos.position;
graphView.graphViewChanged(m_GraphViewChange);
}
m_MovedElements.Clear();
}
m_PanSchedule.Pause();
if (m_ItemPanDiff != Vector3.zero)
{
Vector3 p = m_GraphView.contentViewContainer.transform.position;
Vector3 s = m_GraphView.contentViewContainer.transform.scale;
m_GraphView.UpdateViewTransform(p, s);
}
if (selection.Count > 0 && m_PrevDropTarget != null)
{
if (m_PrevDropTarget.CanAcceptDrop(selection))
{
using (DragPerformEvent drop = DragPerformEvent.GetPooled(evt))
{
SendDragAndDropEvent(drop, selection, m_PrevDropTarget, m_GraphView);
}
}
else
{
using (DragExitedEvent dexit = DragExitedEvent.GetPooled(evt))
{
SendDragAndDropEvent(dexit, selection, m_PrevDropTarget, m_GraphView);
}
}
}
if (snapEnabled)
m_Snapper.EndSnap(m_GraphView);
target.ReleaseMouse();
evt.StopPropagation();
}
selectedElement = null;
m_Active = false;
m_PrevDropTarget = null;
m_Dragging = false;
m_PrevDropTarget = null;
}
}
private void OnKeyDown(KeyDownEvent e)
{
if (e.keyCode != KeyCode.Escape || m_GraphView == null || !m_Active)
return;
// Reset the items to their original pos.
var groupsElementsToReset = new Dictionary<Scope, List<GraphElement>>();
foreach (KeyValuePair<GraphElement, OriginalPos> v in m_OriginalPos)
{
OriginalPos originalPos = v.Value;
if (originalPos.stack != null)
{
originalPos.stack.InsertElement(originalPos.stackIndex, v.Key);
}
else
{
if (originalPos.scope != null)
{
if (!groupsElementsToReset.ContainsKey(originalPos.scope))
{
groupsElementsToReset[originalPos.scope] = new List<GraphElement>();
}
groupsElementsToReset[originalPos.scope].Add(v.Key);
}
v.Key.SetPosition(originalPos.pos);
}
}
foreach (KeyValuePair<Scope, List<GraphElement>> toReset in groupsElementsToReset)
{
toReset.Key.AddElements(toReset.Value);
}
m_PanSchedule.Pause();
if (m_ItemPanDiff != Vector3.zero)
{
Vector3 p = m_GraphView.contentViewContainer.transform.position;
Vector3 s = m_GraphView.contentViewContainer.transform.scale;
m_GraphView.UpdateViewTransform(p, s);
}
using (DragExitedEvent dexit = DragExitedEvent.GetPooled())
{
List<ISelectable> selection = m_GraphView.selection;
SendDragAndDropEvent(dexit, selection, m_PrevDropTarget, m_GraphView);
}
target.ReleaseMouse();
e.StopPropagation();
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Manipulators/SelectionDragger.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Manipulators/SelectionDragger.cs",
"repo_id": "UnityCsReference",
"token_count": 13213
} | 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;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UnityEditor.Experimental.GraphView
{
public abstract class GraphViewToolWindow : EditorWindow
{
struct GraphViewChoice
{
public EditorWindow window;
public GraphView graphView;
public int idx;
public bool canUse;
}
const string k_DefaultSelectorName = "Select a panel";
UnityEditor.UIElements.Toolbar m_Toolbar;
protected VisualElement m_ToolbarContainer;
ToolbarMenu m_SelectorMenu;
[SerializeField]
EditorWindow m_SelectedWindow;
[SerializeField]
int m_SelectedGraphViewIdx;
protected GraphView m_SelectedGraphView;
List<GraphViewChoice> m_GraphViewChoices;
bool m_FirstUpdate;
protected abstract string ToolName { get; }
public override IEnumerable<Type> GetExtraPaneTypes()
{
return Assembly
.GetAssembly(typeof(GraphViewToolWindow))
.GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(GraphViewToolWindow)));
}
public void SelectGraphViewFromWindow(GraphViewEditorWindow window, GraphView graphView, int graphViewIndexInWindow = 0)
{
var gvChoice = new GraphViewChoice { window = window, graphView = graphView, idx = graphViewIndexInWindow };
SelectGraphView(gvChoice);
}
protected void OnEnable()
{
var root = rootVisualElement;
this.SetAntiAliasing(4);
m_Toolbar = new UnityEditor.UIElements.Toolbar();
// Register panel choice refresh on the toolbar so the event
// is received before the ToolbarPopup clickable handle it.
m_Toolbar.RegisterCallback<MouseDownEvent>(e =>
{
if (e.target == m_SelectorMenu)
RefreshPanelChoices();
}, TrickleDown.TrickleDown);
m_GraphViewChoices = new List<GraphViewChoice>();
m_SelectorMenu = new ToolbarMenu { name = "panelSelectPopup", text = "Select a panel" };
var menu = m_SelectorMenu.menu;
menu.AppendAction("None", OnSelectGraphView,
a => m_SelectedGraphView == null ?
DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal);
m_Toolbar.Add(m_SelectorMenu);
m_Toolbar.style.flexGrow = 1;
m_Toolbar.style.overflow = Overflow.Hidden;
m_ToolbarContainer = new VisualElement();
m_ToolbarContainer.style.flexDirection = FlexDirection.Row;
m_ToolbarContainer.Add(m_Toolbar);
root.Add(m_ToolbarContainer);
m_FirstUpdate = true;
titleContent.text = ToolName;
}
void Update()
{
// We need to wait until all the windows are created to re-assign a potential graphView.
if (m_FirstUpdate)
{
m_FirstUpdate = false;
if (m_SelectedWindow != null)
{
var graphViewEditor = m_SelectedWindow as GraphViewEditorWindow;
if (graphViewEditor != null && m_SelectedGraphViewIdx >= 0 && m_SelectedGraphView == null)
{
m_SelectedGraphView = graphViewEditor.graphViews.ElementAt(m_SelectedGraphViewIdx);
m_SelectorMenu.text = m_SelectedGraphView.name;
OnGraphViewChanged();
}
}
}
else
{
if (!m_SelectedWindow && m_SelectedGraphView != null)
SelectGraphView(null);
}
UpdateGraphViewName();
}
void RefreshPanelChoices()
{
m_GraphViewChoices.Clear();
var guiViews = new List<GUIView>();
GUIViewDebuggerHelper.GetViews(guiViews);
var usedGraphViews = new HashSet<GraphView>();
// Get all GraphViews used by existing tool windows of our type
using (var it = UIElementsUtility.GetPanelsIterator())
{
var currentWindowType = GetType();
while (it.MoveNext())
{
var dockArea = guiViews.FirstOrDefault(v => v.GetInstanceID() == it.Current.Key) as DockArea;
if (dockArea == null)
continue;
foreach (var graphViewTool in dockArea.m_Panes.Where(p => p.GetType() == currentWindowType).Cast<GraphViewToolWindow>())
{
if (graphViewTool.m_SelectedGraphView != null)
{
usedGraphViews.Add(graphViewTool.m_SelectedGraphView);
}
}
}
}
// Get all the existing GraphViewWindows we could use...
using (var it = UIElementsUtility.GetPanelsIterator())
{
while (it.MoveNext())
{
var dockArea = guiViews.FirstOrDefault(v => v.GetInstanceID() == it.Current.Key) as DockArea;
if (dockArea == null)
continue;
foreach (var graphViewWindow in dockArea.m_Panes.OfType<GraphViewEditorWindow>())
{
int idx = 0;
foreach (var graphView in graphViewWindow.graphViews.Where(IsGraphViewSupported))
{
m_GraphViewChoices.Add(new GraphViewChoice {window = graphViewWindow, idx = idx++, graphView = graphView, canUse = !usedGraphViews.Contains(graphView)});
}
}
}
}
var menu = m_SelectorMenu.menu;
var menuItemsCount = menu.MenuItems().Count;
// Clear previous items (but not the "none" one at the top of the list)
for (int i = menuItemsCount - 1; i > 0; i--)
menu.RemoveItemAt(i);
foreach (var graphView in m_GraphViewChoices)
{
menu.AppendAction(graphView.graphView.name, OnSelectGraphView,
a =>
{
var gvc = (GraphViewChoice)a.userData;
return (gvc.graphView == m_SelectedGraphView
? DropdownMenuAction.Status.Checked
: (gvc.canUse
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled));
},
graphView);
}
}
void OnSelectGraphView(DropdownMenuAction action)
{
var choice = (GraphViewChoice?)action.userData;
var newlySelectedGraphView = choice?.graphView;
if (newlySelectedGraphView == m_SelectedGraphView)
return;
SelectGraphView(choice);
}
void SelectGraphView(GraphViewChoice? choice)
{
OnGraphViewChanging();
m_SelectedGraphView = choice?.graphView;
m_SelectedWindow = choice?.window;
m_SelectedGraphViewIdx = choice?.idx ?? -1;
OnGraphViewChanged();
UpdateGraphViewName();
}
// Called just before the change.
protected abstract void OnGraphViewChanging();
// Called just after the change.
protected abstract void OnGraphViewChanged();
protected virtual bool IsGraphViewSupported(GraphView gv)
{
return false;
}
void UpdateGraphViewName()
{
string updatedName = k_DefaultSelectorName;
if (m_SelectedGraphView != null)
updatedName = m_SelectedGraphView.name;
if (m_SelectorMenu.text != updatedName)
m_SelectorMenu.text = updatedName;
}
}
}
| UnityCsReference/Modules/GraphViewEditor/Windows/GraphViewToolWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/GraphViewEditor/Windows/GraphViewToolWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 4209
} | 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 Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Internal;
namespace Unity.Hierarchy
{
/// <summary>
/// Provides strongly typed access to unmanaged property data.
/// </summary>
public readonly struct HierarchyPropertyUnmanaged<T> :
IEquatable<HierarchyPropertyUnmanaged<T>>,
IHierarchyProperty<T> where T : unmanaged
{
/// <summary>
/// The hierarchy this property belongs to.
/// </summary>
readonly Hierarchy m_Hierarchy;
/// <summary>
/// The internal property binding.
/// </summary>
internal readonly HierarchyPropertyId m_Property;
/// <summary>
/// Returns <see langword="true"/> if the native property is valid.
/// </summary>
public bool IsCreated => m_Property != HierarchyPropertyId.Null && m_Hierarchy is { IsCreated: true };
/// <summary>
/// Creates a new instance of <see cref="HierarchyPropertyUnmanaged{T}"/>.
/// </summary>
internal HierarchyPropertyUnmanaged(Hierarchy hierarchy, in HierarchyPropertyId property)
{
if (hierarchy == null)
throw new ArgumentNullException(nameof(hierarchy));
if (property == HierarchyPropertyId.Null)
throw new ArgumentException(nameof(property));
m_Hierarchy = hierarchy;
m_Property = property;
}
/// <summary>
/// Sets the property value for a <see cref="HierarchyNode"/>.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <param name="value">The value to set.</param>
public void SetValue(in HierarchyNode node, T value)
{
if (m_Hierarchy == null)
throw new NullReferenceException("Hierarchy reference has not been set.");
if (!m_Hierarchy.IsCreated)
throw new InvalidOperationException("Hierarchy has been disposed.");
unsafe
{
m_Hierarchy.SetPropertyRaw(in m_Property, in node, &value, sizeof(T));
}
}
/// <summary>
/// Gets the property value for the given <see cref="HierarchyNode"/>.
/// </summary>
/// <param name="node">The hierarchy node.</param>
/// <returns>The property value of the hierarchy node.</returns>
public T GetValue(in HierarchyNode node)
{
if (m_Hierarchy == null)
throw new NullReferenceException("Hierarchy reference has not been set.");
if (!m_Hierarchy.IsCreated)
throw new InvalidOperationException("Hierarchy has been disposed.");
unsafe
{
var ptr = m_Hierarchy.GetPropertyRaw(in m_Property, in node, out var size);
if (ptr == null || size != sizeof(T))
return default;
return UnsafeUtility.AsRef<T>(ptr);
}
}
/// <summary>
/// Removes the property value for a <see cref="HierarchyNode"/>.
/// </summary>
/// <param name="node">The hierarchy node.</param>
public void ClearValue(in HierarchyNode node)
{
if (m_Hierarchy == null)
throw new NullReferenceException("Hierarchy reference has not been set.");
if (!m_Hierarchy.IsCreated)
throw new InvalidOperationException("Hierarchy has been disposed.");
m_Hierarchy.ClearProperty(in m_Property, in node);
}
[ExcludeFromDocs]
public static bool operator ==(in HierarchyPropertyUnmanaged<T> lhs, in HierarchyPropertyUnmanaged<T> rhs) => lhs.m_Hierarchy == rhs.m_Hierarchy && lhs.m_Property == rhs.m_Property;
[ExcludeFromDocs]
public static bool operator !=(in HierarchyPropertyUnmanaged<T> lhs, in HierarchyPropertyUnmanaged<T> rhs) => !(lhs == rhs);
[ExcludeFromDocs]
public bool Equals(HierarchyPropertyUnmanaged<T> other) => m_Hierarchy == other.m_Hierarchy && m_Property == other.m_Property;
[ExcludeFromDocs]
public override string ToString() => m_Property.ToString();
[ExcludeFromDocs]
public override bool Equals(object obj) => obj is HierarchyPropertyUnmanaged<T> property && Equals(property);
[ExcludeFromDocs]
public override int GetHashCode() => m_Property.GetHashCode();
}
}
| UnityCsReference/Modules/HierarchyCore/Managed/HierarchyPropertyUnmanaged.cs/0 | {
"file_path": "UnityCsReference/Modules/HierarchyCore/Managed/HierarchyPropertyUnmanaged.cs",
"repo_id": "UnityCsReference",
"token_count": 1921
} | 359 |
// 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 Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Bindings;
namespace Unity.Hierarchy
{
[NativeType(Header = "Modules/HierarchyCore/HierarchyTestsHelper.h")]
internal static class HierarchyTestsHelper
{
[Flags]
internal enum Capabilities
{
None = 0,
Initialize = 1 << 0,
Dispose = 1 << 1,
GetNodeTypeName = 1 << 2,
GetDefaultNodeFlags = 1 << 3,
ChangesPending = 1 << 4,
IntegrateChanges = 1 << 5,
SearchMatch = 1 << 6,
SearchEnd = 1 << 7
}
[NativeType(Header = "Modules/HierarchyCore/HierarchyTestsHelper.h")]
internal enum SortOrder
{
Ascending,
Descending
}
internal delegate void ForEachDelegate(in HierarchyNode node, int index);
/// <summary>
/// Generate a tree of nodes with the specified <paramref name="width"/> and <paramref name="depth"/>, up to a maximum of <paramref name="maxCount"/> nodes.
/// </summary>
/// <param name="hierarchy">The hierarchy.</param>
/// <param name="root">The root node to add nodes to.</param>
/// <param name="width">The number of nodes added per depth level.</param>
/// <param name="depth">The maximum depth.</param>
/// <param name="maxCount">The maximum node count to add.</param>
/// <returns>The number of nodes added.</returns>
[NativeMethod(IsThreadSafe = true)]
internal static extern int GenerateNodesTree(Hierarchy hierarchy, in HierarchyNode root, int width, int depth, int maxCount = 0);
/// <summary>
/// Generate a fixed count of nodes by repeatedly generating trees of nodes with the specified <paramref name="width"/> and <paramref name="depth"/>.
/// </summary>
/// <param name="hierarchy">The hierarchy.</param>
/// <param name="root">The root node to add nodes to.</param>
/// <param name="count">The number of nodes to add.</param>
/// <param name="width">The number of nodes added per depth level.</param>
/// <param name="depth">The maximum depth.</param>
[NativeMethod(IsThreadSafe = true)]
internal static extern void GenerateNodesCount(Hierarchy hierarchy, in HierarchyNode root, int count, int width, int depth);
[NativeMethod(IsThreadSafe = true)]
internal static extern void GenerateSortIndex(Hierarchy hierarchy, in HierarchyNode root, SortOrder order);
internal static void ForEach(Hierarchy hierarchy, in HierarchyNode root, ForEachDelegate func)
{
var stack = new Stack<HierarchyNode>();
stack.Push(root);
// Since we do not have NativeList, use the hierarchy count as the capacity
using var buffer = new NativeArray<HierarchyNode>(hierarchy.Count, Allocator.Temp);
while (stack.Count > 0)
{
var node = stack.Pop();
unsafe
{
// Can't use EnumerateChildren here, because the function may modify the hierarchy
var childrenCount = hierarchy.GetChildrenCount(in node);
var children = new Span<HierarchyNode>(buffer.GetUnsafePtr(), childrenCount);
var count = hierarchy.GetChildren(node, children);
if (count != childrenCount)
throw new InvalidOperationException($"Expected GetChildren to return {childrenCount}, but was {count}.");
for (int i = 0, c = children.Length; i < c; ++i)
{
var child = children[i];
func(in child, i);
stack.Push(child);
}
}
}
}
[NativeMethod(IsThreadSafe = true)]
internal static extern void SetNextHierarchyNodeId(Hierarchy hierarchy, int id);
internal static int GetNodeType<T>() where T : HierarchyNodeTypeHandlerBase => GetNodeType(typeof(T));
[NativeMethod(IsThreadSafe = true)]
static extern int GetNodeType(Type type);
[NativeMethod(IsThreadSafe = true)]
internal static extern int[] GetRegisteredNodeTypes(Hierarchy hierarchy);
[NativeMethod(IsThreadSafe = true)]
internal static extern int GetCapacity(Hierarchy hierarchy);
[NativeMethod(IsThreadSafe = true)]
internal static extern int GetVersion(Hierarchy hierarchy);
[NativeMethod(IsThreadSafe = true)]
internal static extern int GetChildrenCapacity(Hierarchy hierarchy, in HierarchyNode node);
internal static bool SearchMatch(HierarchyViewModel model, in HierarchyNode node)
{
var handler = model.Hierarchy.GetNodeTypeHandlerBase(in node);
return handler?.Internal_SearchMatch(in node) ?? false;
}
[NativeMethod(IsThreadSafe = true)]
internal static extern void SetCapabilitiesScriptingHandler(Hierarchy hierarchy, string nodeTypeName, int cap);
[NativeMethod(IsThreadSafe = true)]
internal static extern void SetCapabilitiesNativeHandler(Hierarchy hierarchy, string nodeTypeName, int cap);
[NativeMethod(IsThreadSafe = true)]
internal static extern int GetCapabilitiesScriptingHandler(Hierarchy hierarchy, string nodeTypeName);
[NativeMethod(IsThreadSafe = true)]
internal static extern int GetCapabilitiesNativeHandler(Hierarchy hierarchy, string nodeTypeName);
[NativeMethod(IsThreadSafe = true)]
internal static extern object GetHierarchyScriptingObject(Hierarchy hierarchy);
[NativeMethod(IsThreadSafe = true)]
internal static extern object GetHierarchyFlattenedScriptingObject(HierarchyFlattened hierarchyFlattened);
[NativeMethod(IsThreadSafe = true)]
internal static extern object GetHierarchyViewModelScriptingObject(HierarchyViewModel viewModel);
[NativeMethod(IsThreadSafe = true)]
internal static extern object GetHierarchyCommandListScriptingObject(HierarchyCommandList cmdList);
}
}
| UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyTestsHelper.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/HierarchyCore/ScriptBindings/HierarchyTestsHelper.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2496
} | 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;
namespace UnityEngine
{
// Scaling mode to draw textures with
public enum ScaleMode
{
// Stretches the texture to fill the complete rectangle passed in to GUI.DrawTexture
StretchToFill = 0,
// Scales the texture, maintaining aspect ratio, so it completely covers the /position/ rectangle passed to GUI.DrawTexture. If the texture is being draw to a rectangle with a different aspect ratio than the original, the image is cropped.
ScaleAndCrop = 1,
// Scales the texture, maintaining aspect ratio, so it completely fits withing the /position/ rectangle passed to GUI.DrawTexture.
ScaleToFit = 2
}
// Used by GUIUtility.GetcontrolID to inform the UnityGUI system if a given control can get keyboard focus.
public enum FocusType
{
[Obsolete("FocusType.Native now behaves the same as FocusType.Passive in all OS cases. (UnityUpgradable) -> Passive", false)]
Native = 0,
// This is a proper keyboard control. It can have input focus on all platforms. Used for TextField and TextArea controls
Keyboard = 1,
// This control can never receive keyboard focus.
Passive = 2
}
}
| UnityCsReference/Modules/IMGUI/GUIEnums.cs/0 | {
"file_path": "UnityCsReference/Modules/IMGUI/GUIEnums.cs",
"repo_id": "UnityCsReference",
"token_count": 424
} | 361 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.