text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEditor.Scripting.ScriptCompilation { internal struct SemVersion : IVersion<SemVersion> { public bool IsInitialized { get; } public int Major { get; } public int Minor { get; } public int Patch { get; } public string Prerelease { get; } public string Build { get; } public SemVersion(int major, int minor = 0, int patch = 0, string prerelease = "", string build = "") { Major = major; Minor = minor; Patch = patch; Prerelease = prerelease ?? ""; Build = build ?? ""; IsInitialized = true; } public static int Compare(SemVersion versionA, SemVersion versionB) { return versionA.CompareTo(versionB); } public static bool operator==(SemVersion left, SemVersion right) { return Equals(left, right); } public static bool operator!=(SemVersion left, SemVersion right) { return !Equals(left, right); } public static bool operator>(SemVersion left, SemVersion right) { return Compare(left, right) > 0; } public static bool operator>=(SemVersion left, SemVersion right) { return left == right || left > right; } public static bool operator<(SemVersion left, SemVersion right) { return Compare(left, right) < 0; } public static bool operator<=(SemVersion left, SemVersion right) { return left == right || left < right; } public int CompareTo(object obj) { return CompareTo((SemVersion)obj); } public int CompareTo(SemVersion other) { var result = Major.CompareTo(other.Major); if (result != 0) { return result; } result = Minor.CompareTo(other.Minor); if (result != 0) { return result; } result = Patch.CompareTo(other.Patch); if (result != 0) { return result; } result = CompareExtension(Prerelease, other.Prerelease, true); if (result != 0) { return result; } return 0; } private static int CompareExtension(string current, string other, bool lower = false) { var currentIsEmpty = string.IsNullOrEmpty(current); var otherIsEmpty = string.IsNullOrEmpty(other); if (currentIsEmpty && otherIsEmpty) return 0; if (currentIsEmpty) return lower ? 1 : -1; if (otherIsEmpty) return lower ? -1 : 1; var currentParts = current.Split('.'); var otherParts = other.Split('.'); for (var i = 0; i < Math.Min(currentParts.Length, otherParts.Length); i++) { var currentPart = currentParts[i]; var otherPart = otherParts[i]; int currentNumber; int otherNumber; var currentPartIsNumber = int.TryParse(currentPart, out currentNumber); var otherPartIsNumber = int.TryParse(otherPart, out otherNumber); int result; if (currentPartIsNumber && otherPartIsNumber) { result = currentNumber.CompareTo(otherNumber); if (result != 0) { return result; } } else { if (currentPartIsNumber) { return -1; } if (otherPartIsNumber) { return 1; } result = string.CompareOrdinal(currentPart, otherPart); if (result != 0) { return result; } } } return currentParts.Length.CompareTo(otherParts.Length); } public bool Equals(SemVersion other) { // We do not compare the Build return Major == other.Major && Minor == other.Minor && Patch == other.Patch && string.Equals(Prerelease, other.Prerelease, StringComparison.Ordinal); } public override bool Equals(object other) { if (ReferenceEquals(other, null)) return false; return other.GetType() == GetType() && Equals((SemVersion)other); } public override string ToString() { var version = $"{Major}.{Minor}.{Patch}"; if (!string.IsNullOrEmpty(Prerelease)) { version += $"-{Prerelease}"; } if (!string.IsNullOrEmpty(Build)) { version += $"+{Build}"; } return version; } public override int GetHashCode() { unchecked { int result = Major.GetHashCode(); result = result * 31 + Minor.GetHashCode(); result = result * 31 + Patch.GetHashCode(); result = result * 31 + Prerelease.GetHashCode(); result = result * 31 + Build.GetHashCode(); return result; } } public SemVersion Parse(string version, bool strict = false) { return SemVersionParser.Parse(version, strict); } public static SemVersionTypeTraits VersionTypeTraits { get; } = new SemVersionTypeTraits(); public IVersionTypeTraits GetVersionTypeTraits() { return VersionTypeTraits; } } internal class SemVersionTypeTraits : IVersionTypeTraits { public bool IsAllowedFirstCharacter(char c, bool strict = false) { return VersionTypeTraitsUtils.IsCharDigit(c); } public bool IsAllowedLastCharacter(char c, bool strict = false) { return VersionTypeTraitsUtils.IsCharDigit(c) || VersionTypeTraitsUtils.IsCharLetter(c); } public bool IsAllowedCharacter(char c) { return VersionTypeTraitsUtils.IsCharDigit(c) || c == '.' || c == '-' || VersionTypeTraitsUtils.IsCharLetter(c); } } internal static class SemVersionParser { public static SemVersion Parse(string version, bool strict = false) { if (TryParse(version, out var result) && result.HasValue) { return result.Value; } throw new ArgumentException($"{version} is not valid Semantic Version"); } public static bool TryParse(string version, out SemVersion? result) { if (string.IsNullOrEmpty(version)) { result = null; return false; } int cursor = 0; int major = 0; int minor = 0; int patch = 0; string prerelease = null; string build = null; //Doing this instead because RegEx is impressively slow try { if (!VersionUtils.TryConsumeIntVersionComponentFromString(version, ref cursor, x => !char.IsDigit(x), out major)) { result = null; return false; } if (cursor < version.Length && version[cursor] == '.') { cursor++; VersionUtils.TryConsumeIntVersionComponentFromString(version, ref cursor, x => !char.IsDigit(x), out minor, zeroIfEmpty: true); } if (cursor < version.Length && version[cursor] == '.') { cursor++; VersionUtils.TryConsumeIntVersionComponentFromString(version, ref cursor, x => !char.IsDigit(x), out patch, zeroIfEmpty: true); } if (cursor < version.Length && version[cursor] == '-') { cursor++; prerelease = VersionUtils.ConsumeVersionComponentFromString(version, ref cursor, x => x == '+'); } if (cursor < version.Length && version[cursor] == '+') { cursor++; build = VersionUtils.ConsumeVersionComponentFromString(version, ref cursor, x => x == '\0'); } } catch (Exception) { result = null; return false; } result = new SemVersion(major, minor, patch, prerelease, build); return true; } } }
UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/SemVersion.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Scripting/ScriptCompilation/SemVersion.cs", "repo_id": "UnityCsReference", "token_count": 4735 }
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 Object = UnityEngine.Object; namespace UnityEditor.SearchService { [Obsolete("ObjectSelector has been deprecated. Use ObjectSelectorSearch instead (UnityUpgradable) -> ObjectSelectorSearch", error: true)] public static class ObjectSelector { public const SearchEngineScope EngineScope = SearchEngineScope.ObjectSelector; public static void RegisterEngine(IObjectSelectorEngine engine) { ObjectSelectorSearch.RegisterEngine(engine); } public static void UnregisterEngine(IObjectSelectorEngine engine) { ObjectSelectorSearch.UnregisterEngine(engine); } } [Obsolete("ObjectSelectorHandlerAttribute has been deprecated. Use SearchContextAttribute instead.", error: true)] [AttributeUsage(AttributeTargets.Method)] public class ObjectSelectorHandlerAttribute : Attribute { public Type attributeType { get; } public ObjectSelectorHandlerAttribute(Type attributeType) { this.attributeType = attributeType; } } [Obsolete("ObjectSelectorTargetInfo has been deprecated.", error: true)] public struct ObjectSelectorTargetInfo { public GlobalObjectId globalObjectId { get; } public Object targetObject { get; } public Type type { get; } public ObjectSelectorTargetInfo(GlobalObjectId globalObjectId, Object targetObject = null, Type type = null) { this.globalObjectId = globalObjectId; this.targetObject = targetObject; this.type = type; } public Object LoadObject() { return targetObject ?? GlobalObjectId.GlobalObjectIdentifierToObjectSlow(globalObjectId); } } public partial class ObjectSelectorSearchContext : ISearchContext { [Obsolete("selectorConstraint has been deprecated.", error: true)] public Func<ObjectSelectorTargetInfo, Object[], ObjectSelectorSearchContext, bool> selectorConstraint { get; set; } } }
UnityCsReference/Editor/Mono/Search/ObjectSelector.Deprecated.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Search/ObjectSelector.Deprecated.cs", "repo_id": "UnityCsReference", "token_count": 771 }
348
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine; namespace UnityEditor { internal class SerializedPropertyFilters { internal interface IFilter { bool Active(); // returns true if filter is active, false otherwise bool Filter(SerializedProperty prop); // returns true if filtering passes void OnGUI(Rect r); // draws the filter control string SerializeState(); // returns null if there's nothing to serialize void DeserializeState(string state); // state must not be null } internal abstract class SerializableFilter : IFilter { public abstract bool Active(); // returns true if filter is active, false otherwise public abstract bool Filter(SerializedProperty prop); // returns true if filtering passes public abstract void OnGUI(Rect r); // draws the filter control public string SerializeState() { return JsonUtility.ToJson(this); } public void DeserializeState(string state) { JsonUtility.FromJsonOverwrite(state, this); } } internal class String : SerializableFilter { static class Styles { public static readonly GUIStyle searchField = "SearchTextField"; public static readonly GUIStyle searchFieldCancelButton = "SearchCancelButton"; public static readonly GUIStyle searchFieldCancelButtonEmpty = "SearchCancelButtonEmpty"; } [SerializeField] protected string m_Text = ""; public override bool Active() { return !string.IsNullOrEmpty(m_Text); } public override bool Filter(SerializedProperty prop) { return prop.stringValue.IndexOf(m_Text, 0, System.StringComparison.OrdinalIgnoreCase) >= 0; } public override void OnGUI(Rect r) { bool empty = string.IsNullOrEmpty(m_Text); Rect buttonRect = r; buttonRect.x += (r.width - 15); buttonRect.width = 15; GUIStyle buttonStyle = empty ? Styles.searchFieldCancelButtonEmpty : Styles.searchFieldCancelButton; if (GUI.Button(buttonRect, GUIContent.none, buttonStyle) && !empty) { m_Text = ""; GUIUtility.keyboardControl = 0; } m_Text = EditorGUI.TextField(r, GUIContent.none, m_Text, Styles.searchField); GUI.Button(buttonRect, GUIContent.none, buttonStyle); } } internal sealed class Name : String { public bool Filter(string str) { return str.IndexOf(m_Text, 0, System.StringComparison.OrdinalIgnoreCase) >= 0; } } internal sealed class None : IFilter { public bool Active() { return false; } public bool Filter(SerializedProperty prop) { return true; } public void OnGUI(Rect r) {} public string SerializeState() { return null; } public void DeserializeState(string state) {} } internal static readonly None s_FilterNone = new None(); } }
UnityCsReference/Editor/Mono/SerializedProperty/SerializedPropertyFilters.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/SerializedProperty/SerializedPropertyFilters.cs", "repo_id": "UnityCsReference", "token_count": 1474 }
349
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Bindings; using ShaderPropertyFlags = UnityEngine.Rendering.ShaderPropertyFlags; using TextureDimension = UnityEngine.Rendering.TextureDimension; namespace UnityEditor { [NativeHeader("Editor/Mono/ShaderUtil.bindings.h")] public partial class ShaderUtil { [Obsolete("ClearShaderErrors has been deprecated. Use ClearShaderMessages instead (UnityUpgradable) -> ClearShaderMessages(*)")] [NativeName("ClearShaderMessages")] extern public static void ClearShaderErrors([NotNull] Shader s); [Obsolete("Use UnityEngine.Rendering.TextureDimension instead.")] public enum ShaderPropertyTexDim { TexDimNone = 0, // no texture TexDim2D = 2, TexDim3D = 3, TexDimCUBE = 4, TexDimAny = 6, } // We can't deprecate them yet (Sept 2019): Some integration tests expect no compile warning/error from built-in packages but TextMeshPro uses // these APIs and emits deprecation warnings. We'll land the new APIs without deprecation first and then see if we can upgrade TextMeshPro afterwards. //[Obsolete("Use UnityEngine.ShaderPropertyType instead.", false)] public enum ShaderPropertyType { Color, Vector, Float, Range, TexEnv, Int, } //[Obsolete("Use Shader.GetPropertyCount instead.", false)] public static int GetPropertyCount(Shader s) { if (s == null) throw new ArgumentNullException("s"); return s.GetPropertyCount(); } //[Obsolete("Use Shader.GetPropertyName instead.", false)] public static string GetPropertyName(Shader s, int propertyIdx) { if (s == null) throw new ArgumentNullException("s"); return s.GetPropertyName(propertyIdx); } //[Obsolete("Use Shader.GetPropertyType instead.", false)] public static ShaderPropertyType GetPropertyType(Shader s, int propertyIdx) { if (s == null) throw new ArgumentNullException("s"); return (ShaderPropertyType)s.GetPropertyType(propertyIdx); } //[Obsolete("Use Shader.GetPropertyDescription instead.", false)] public static string GetPropertyDescription(Shader s, int propertyIdx) { if (s == null) throw new ArgumentNullException("s"); return s.GetPropertyDescription(propertyIdx); } //[Obsolete("Use Shader.GetPropertyRangeLimits and Shader.GetDefaultValue instead.", false)] public static float GetRangeLimits(Shader s, int propertyIdx, int defminmax) { if (s == null) throw new ArgumentNullException("s"); else if (defminmax < 0 || defminmax > 2) throw new ArgumentException("defminmax should be one of 0,1,2."); return defminmax > 0 ? s.GetPropertyRangeLimits(propertyIdx)[defminmax - 1] : s.GetPropertyDefaultFloatValue(propertyIdx); } //[Obsolete("Use Shader.GetPropertyTextureDimension instead.", false)] public static TextureDimension GetTexDim(Shader s, int propertyIdx) { if (s == null) throw new ArgumentNullException("s"); return s.GetPropertyTextureDimension(propertyIdx); } //[Obsolete("Use Shader.GetPropertyFlags and test against ShaderPropertyFlags.HideInInspector instead.", false)] public static bool IsShaderPropertyHidden(Shader s, int propertyIdx) { if (s == null) throw new ArgumentNullException("s"); return (s.GetPropertyFlags(propertyIdx) & ShaderPropertyFlags.HideInInspector) != 0; } //[Obsolete("Use Shader.GetPropertyFlags and test against ShaderPropertyFlags.NonModifiableTextureData instead.", false)] public static bool IsShaderPropertyNonModifiableTexureProperty(Shader s, int propertyIdx) { if (s == null) throw new ArgumentNullException("s"); return (s.GetPropertyFlags(propertyIdx) & ShaderPropertyFlags.NonModifiableTextureData) != 0; } } }
UnityCsReference/Editor/Mono/ShaderUtil.bindings.deprecated.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/ShaderUtil.bindings.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 1870 }
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 UnityEngine; using UnityEngine.Bindings; using Object = UnityEngine.Object; namespace UnityEditor { // StaticOcclusionCulling lets you perform static occlusion culling operations [NativeHeader("Runtime/Camera/OcclusionCullingSettings.h")] [NativeHeader("Runtime/Camera/RendererScene.h")] [NativeHeader("Editor/Src/OcclusionCulling.h")] public static class StaticOcclusionCulling { // Used to generate static occlusion culling data. This function will not return until occlusion data is generated. [NativeName("GenerateTome")] public static extern bool Compute(); // Used to compute static occlusion culling data asynchronously. [NativeName("GenerateTomeInBackground")] public static extern bool GenerateInBackground(); [NativeName("RemoveTempFolder")] public static extern void RemoveCacheFolder(); // Used to invalidate preVisualistion debug data. internal static extern void InvalidatePrevisualisationData(); // Used to cancel asynchronous generation of static occlusion culling data. public static extern void Cancel(); // Used to check if asynchronous generation of static occlusion culling data is still running. public static extern bool isRunning { [NativeName("IsRunning")] get; } // Clears the Tome of the opened scene [NativeName("ClearUmbraTome")] public static extern void Clear(); // Get the OcclusionCullingSettings internal static extern Object occlusionCullingSettings { [FreeFunction] get; } [StaticAccessor("GetOcclusionCullingSettings()", StaticAccessorType.Dot)] [NativeProperty(TargetType = TargetType.Field)] public static extern float smallestOccluder { [NativeName("GetOcclusionBakeSettings().smallestOccluder")] get; [NativeName("GetOcclusionBakeSettingsSetDirty().smallestOccluder")] set; } [StaticAccessor("GetOcclusionCullingSettings()", StaticAccessorType.Dot)] [NativeProperty(TargetType = TargetType.Field)] public static extern float smallestHole { [NativeName("GetOcclusionBakeSettings().smallestHole")] get; [NativeName("GetOcclusionBakeSettingsSetDirty().smallestHole")] set; } [StaticAccessor("GetOcclusionCullingSettings()", StaticAccessorType.Dot)] [NativeProperty(TargetType = TargetType.Field)] public static extern float backfaceThreshold { [NativeName("GetOcclusionBakeSettings().backfaceThreshold")] get; [NativeName("GetOcclusionBakeSettingsSetDirty().backfaceThreshold")] set; } public static extern bool doesSceneHaveManualPortals { [NativeName("DoesSceneHaveManualPortals")] get; } // Returns the size in bytes that the Tome data is currently taking up in this scene on disk [StaticAccessor("GetRendererScene()", StaticAccessorType.Dot)] public static extern int umbraDataSize { get; } [StaticAccessor("GetOcclusionCullingSettings()", StaticAccessorType.Dot)] public static extern void SetDefaultOcclusionBakeSettings(); } // Used to visualize static occlusion culling at development time in scene view. [StaticAccessor("GetOcclusionCullingVisualization()", StaticAccessorType.Arrow)] [NativeHeader("Editor/Src/OcclusionCullingVisualizationState.h")] [NativeHeader("Runtime/Camera/Camera.h")] public static class StaticOcclusionCullingVisualization { // If set to true, visualization of target volumes is enabled. public static extern bool showOcclusionCulling { get; set; } // If set to true, the visualization lines of the PVS volumes will show all cells rather than cells after culling. [NativeName("ShowPreVis")] public static extern bool showPreVisualization { get; set; } // If set to true, visualization of view volumes is enabled. public static extern bool showViewVolumes { get; set; } public static extern bool showDynamicObjectBounds { get; set; } // If set to true, visualization of portals is enabled. public static extern bool showPortals { get; set; } // If set to true, visualization of portals is enabled. public static extern bool showVisibilityLines { get; set; } // If set to true, culling of geometry is enabled. public static extern bool showGeometryCulling { get; set; } public static extern bool isPreviewOcclusionCullingCameraInPVS { [FreeFunction("IsPreviewOcclusionCullingCameraInPVS")] get; } public static extern Camera previewOcclusionCamera { [FreeFunction("FindPreviewOcclusionCamera")] get; } //*undoc* // This is here because it was released on 3.0 (this is a typo) public static extern Camera previewOcclucionCamera { [FreeFunction("FindPreviewOcclusionCamera")] get; } } }
UnityCsReference/Editor/Mono/StaticOcclusionCulling.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/StaticOcclusionCulling.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2116 }
351
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityObject = UnityEngine.Object; using System.Collections.Generic; namespace UnityEditor.EditorTools { // Specific to tool editors. interface IEditor { // Should be implemented publicly UnityObject target { get; } IEnumerable<UnityObject> targets { get; } // Should be implemented explicitly void SetTarget(UnityObject value); void SetTargets(UnityObject[] value); } }
UnityCsReference/Editor/Mono/Tools/IEditor.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Tools/IEditor.cs", "repo_id": "UnityCsReference", "token_count": 200 }
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.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.UIElements { class AssetTracking<T> where T : ScriptableObject { public T m_Asset; public string m_AssetPath; public int m_LastDirtyCount; public int m_LastElementCount; public int m_LastInlinePropertiesCount; public int m_LastAttributePropertiesDirtyCount; public int m_ReferenceCount; } internal abstract class BaseLiveReloadAssetTracker<T> : ILiveReloadAssetTracker<T> where T : ScriptableObject { protected Dictionary<int, AssetTracking<T>> m_TrackedAssets = new Dictionary<int, AssetTracking<T>>(); protected List<int> m_RemovedAssets = new List<int>(); public int StartTrackingAsset(T asset) { int assetId = asset.GetInstanceID(); if (m_TrackedAssets.TryGetValue(assetId, out var tracking)) { tracking.m_ReferenceCount++; } else { tracking = new AssetTracking<T>() { m_Asset = asset, m_AssetPath = AssetDatabase.GetAssetPath(asset), m_LastDirtyCount = EditorUtility.GetDirtyCount(asset), m_ReferenceCount = 1 }; m_TrackedAssets[assetId] = tracking; } return tracking.m_LastDirtyCount; } public void StopTrackingAsset(T asset) { int assetId = asset.GetInstanceID(); if (!m_TrackedAssets.ContainsKey(assetId)) { return; } if (m_TrackedAssets[assetId].m_ReferenceCount <= 1) { m_TrackedAssets.Remove(assetId); } else { m_TrackedAssets[assetId].m_ReferenceCount--; } } public bool IsTrackingAsset(T asset) { return m_TrackedAssets.ContainsKey(asset.GetInstanceID()); } public bool IsTrackingAssets() { return m_TrackedAssets.Count > 0; } public bool CheckTrackedAssetsDirty() { // Early out: no assets being tracked. if (m_TrackedAssets.Count == 0) { return false; } bool isTrackedAssetDirty = false; foreach (var styleSheetAssetEntry in m_TrackedAssets) { var tracking = styleSheetAssetEntry.Value; int currentDirtyCount = EditorUtility.GetDirtyCount(tracking.m_Asset); if (tracking.m_LastDirtyCount != currentDirtyCount) { tracking.m_LastDirtyCount = currentDirtyCount; isTrackedAssetDirty = true; } } return isTrackedAssetDirty; } public void UpdateAssetTrackerCounts(T asset, int newDirtyCount, int newElementCount, int newInlinePropertiesCount, int newAttributePropertiesDirtyCount) { if (m_TrackedAssets.TryGetValue(asset.GetInstanceID(), out var assetTracking)) { assetTracking.m_LastDirtyCount = newDirtyCount; assetTracking.m_LastElementCount = newElementCount; assetTracking.m_LastInlinePropertiesCount = newInlinePropertiesCount; assetTracking.m_LastAttributePropertiesDirtyCount = newAttributePropertiesDirtyCount; assetTracking.m_LastDirtyCount = newDirtyCount; } } public abstract bool OnAssetsImported(HashSet<T> changedAssets, HashSet<string> deletedAssets); public virtual void OnTrackedAssetChanged() {} protected virtual bool ProcessChangedAssets(HashSet<T> changedAssets) { return false; } protected virtual bool ProcessDeletedAssets(HashSet<string> deletedAssets) { // Early out: nothing to be checked if (deletedAssets.Count == 0) { return false; } // We have the path to the deleted assets, but the dictionary uses the asset instance IDs as keys // so we need to look into the related paths and then delete the entries outside of the loop. foreach (var trackingPair in m_TrackedAssets) { var tracking = trackingPair.Value; if (deletedAssets.Contains(tracking.m_AssetPath)) { m_RemovedAssets.Add(trackingPair.Key); } } return m_RemovedAssets.Count > 0; } } internal abstract class BaseLiveReloadVisualTreeAssetTracker : BaseLiveReloadAssetTracker<VisualTreeAsset> { internal abstract void OnVisualTreeAssetChanged(); public override void OnTrackedAssetChanged() { OnVisualTreeAssetChanged(); } public override bool OnAssetsImported(HashSet<VisualTreeAsset> changedAssets, HashSet<string> deletedAssets) { // Early out: no asset being tracked. if (m_TrackedAssets.Count == 0) { return false; } bool shouldReload = ProcessChangedAssets(changedAssets); if (ProcessDeletedAssets(deletedAssets) || shouldReload) { shouldReload = true; if (m_RemovedAssets.Count > 0) { foreach (var removedAsset in m_RemovedAssets) { m_TrackedAssets.Remove(removedAsset); } m_RemovedAssets.Clear(); } } return shouldReload; } protected override bool ProcessChangedAssets(HashSet<VisualTreeAsset> changedAssets) { // Early out: nothing to be checked. if (changedAssets == null) { return false; } foreach (var changedAsset in changedAssets) { int assetId = changedAsset.GetInstanceID(); if (m_TrackedAssets.ContainsKey(assetId)) { return true; } } return false; } } internal class LiveReloadStyleSheetAssetTracker : BaseLiveReloadAssetTracker<StyleSheet> { public override bool OnAssetsImported(HashSet<StyleSheet> changedAssets, HashSet<string> deletedAssets) { // Early out: no assets being tracked. if (m_TrackedAssets.Count == 0) { return false; } if (ProcessDeletedAssets(deletedAssets)) { foreach (var removedAsset in m_RemovedAssets) { m_TrackedAssets.Remove(removedAsset); } m_RemovedAssets.Clear(); } return true; } } }
UnityCsReference/Editor/Mono/UIElements/BaseLiveReloadAssetTracker.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/BaseLiveReloadAssetTracker.cs", "repo_id": "UnityCsReference", "token_count": 3641 }
353
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.UIElements { /// <summary> /// A toolbar for tool windows. For more information, refer to [[wiki:UIE-uxml-element-Toolbar|UXML element Toolbar]]. /// </summary> public class Toolbar : VisualElement { private static readonly string s_ToolbarDarkStyleSheetPath = "StyleSheets/Generated/ToolbarDark.uss.asset"; private static readonly string s_ToolbarLightStyleSheetPath = "StyleSheets/Generated/ToolbarLight.uss.asset"; private static readonly StyleSheet s_ToolbarDarkStyleSheet; private static readonly StyleSheet s_ToolbarLightStyleSheet; [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new Toolbar(); } /// <summary> /// Instantiates a <see cref="Toolbar"/> 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<Toolbar> {} static Toolbar() { if (Application.isBuildingEditorResources) return; s_ToolbarDarkStyleSheet = EditorGUIUtility.Load(UIElementsEditorUtility.GetStyleSheetPathForCurrentFont(s_ToolbarDarkStyleSheetPath)) as StyleSheet; s_ToolbarDarkStyleSheet.isDefaultStyleSheet = true; s_ToolbarLightStyleSheet = EditorGUIUtility.Load(UIElementsEditorUtility.GetStyleSheetPathForCurrentFont(s_ToolbarLightStyleSheetPath)) as StyleSheet; s_ToolbarLightStyleSheet.isDefaultStyleSheet = true; } internal static void SetToolbarStyleSheet(VisualElement ve) { if (EditorGUIUtility.isProSkin) { ve.styleSheets.Add(s_ToolbarDarkStyleSheet); } else { ve.styleSheets.Add(s_ToolbarLightStyleSheet); } } /// <summary> /// USS class name of elements of this type. /// </summary> public static readonly string ussClassName = "unity-toolbar"; /// <summary> /// Constructor. /// </summary> public Toolbar() { AddToClassList(ussClassName); SetToolbarStyleSheet(this); } } }
UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/Toolbar.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/Controls/Toolbar/Toolbar.cs", "repo_id": "UnityCsReference", "token_count": 1091 }
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.Collections; using System.Collections.Generic; using System.Linq; using UnityEditorInternal; using UnityEngine; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace UnityEditor.UIElements { internal class EditorElement : VisualElement, IEditorElement { // Local method use only -- created here to reduce garbage collection. Collection must be cleared before use static readonly List<VisualElement> s_Decorators = new List<VisualElement>(); static readonly EditorElementDecoratorCollection s_EditorDecoratorCollection = new EditorElementDecoratorCollection(); /// <summary> /// Adds the given editor decorator. /// </summary> /// <param name="editorDecorator">The editor decorator instance to be added.</param> internal static void AddDecorator(IEditorElementDecorator editorDecorator) => s_EditorDecoratorCollection.Add(editorDecorator); /// <summary> /// Removes the given editor decorator. /// </summary> /// <param name="editorDecorator">The editor decorator instance to be removed.</param> internal static void RemoveDecorator(IEditorElementDecorator editorDecorator) => s_EditorDecoratorCollection.Remove(editorDecorator); readonly IPropertyView inspectorWindow; Editor[] m_EditorCache; // getting activeEditors is costly, so pass in the previously retrieved editor array where possible private Editor[] PopulateCache(Editor[] editors = null) { if (editors == null) editors = inspectorWindow.tracker.activeEditors; m_EditorCache = editors; return m_EditorCache; } Editor[] m_Editors { get { if (m_EditorCache == null || m_EditorIndex >= m_EditorCache.Length || !m_EditorCache[m_EditorIndex]) { PopulateCache(); } return m_EditorCache; } } public IEnumerable<Editor> Editors => m_Editors.AsEnumerable(); Object m_EditorTarget; Editor m_EditorUsedInDecorators; int m_EditorIndex; public Editor editor { get { if (m_EditorIndex < m_Editors.Length) { return m_Editors[m_EditorIndex]; } return null; } } private bool IsEditorValid() { if (m_EditorIndex < m_Editors.Length) { return m_Editors[m_EditorIndex]; } return false; } Rect m_DragRect; Rect m_ContentRect; VisualElement m_PrefabElement; IMGUIContainer m_Header; InspectorElement m_InspectorElement; VisualElement m_DecoratorsElement; IMGUIContainer m_Footer; bool m_WasVisible; bool m_IsCulled; static class Styles { public static GUIStyle importedObjectsHeaderStyle = new GUIStyle("IN BigTitle"); static Styles() { importedObjectsHeaderStyle.font = EditorStyles.label.font; importedObjectsHeaderStyle.fontSize = EditorStyles.label.fontSize; importedObjectsHeaderStyle.alignment = TextAnchor.UpperLeft; } } internal EditorElement(int editorIndex, IPropertyView iw, Editor[] editors, bool isCulled = false) { m_EditorIndex = editorIndex; inspectorWindow = iw; m_IsCulled = isCulled; pickingMode = PickingMode.Ignore; var editor = editors == null || editors.Length == 0 || m_EditorIndex < 0 || m_EditorIndex >= editors.Length ? null : editors[m_EditorIndex]; name = GetNameFromEditor(editor); // Register ui callbacks RegisterCallback<AttachToPanelEvent>(OnAttachToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); if (isCulled) { InitCulled(editors); return; } Init(editors); } void InitCulled(Editor[] editors) { PopulateCache(editors); var container = inspectorWindow.CreateIMGUIContainer(() => { if (editor != null) { // Reset dirtiness when repainting, just like in EditorElement.HeaderOnGUI. if (Event.current.type == EventType.Repaint) { editor.isInspectorDirty = false; } } }, name); Add(container); } void Init(Editor[] editors) { PopulateCache(editors); m_EditorTarget = editor.targets[0]; var editorTitle = ObjectNames.GetInspectorTitle(m_EditorTarget, editor.targets.Length > 1); m_Header = BuildHeaderElement(editorTitle); m_Footer = BuildFooterElement(editorTitle); Add(m_Header); Add(m_Footer); // For GameObjects we want to ensure the first component's title bar is flush with the header, // so we apply a small offset to the margin. (UUM-16138) if (m_EditorTarget is GameObject) { AddToClassList("game-object-inspector"); } if (InspectorElement.disabledThrottling) CreateInspectorElement(); } InspectorElement BuildInspectorElement() { var editors = PopulateCache(); var editorTitle = ObjectNames.GetInspectorTitle(m_EditorTarget); var inspectorElement = new InspectorElement(editor) { focusable = false, name = editorTitle + "Inspector", style = { paddingBottom = PropertyEditor.kEditorElementPaddingBottom } }; if (EditorNeedsVerticalOffset(editors, m_EditorTarget)) { inspectorElement.style.overflow = Overflow.Hidden; } return inspectorElement; } void OnAttachToPanel(AttachToPanelEvent evt) { s_EditorDecoratorCollection.OnAdd += OnEditorDecoratorAdded; s_EditorDecoratorCollection.OnRemove += OnEditorDecoratorRemoved; } void OnDetachFromPanel(DetachFromPanelEvent evt) { s_EditorDecoratorCollection.OnAdd -= OnEditorDecoratorAdded; s_EditorDecoratorCollection.OnRemove -= OnEditorDecoratorRemoved; } public void ReinitCulled(int editorIndex, Editor[] editors) { if (m_Header != null) { m_EditorIndex = editorIndex; m_Header = m_Footer = null; m_EditorUsedInDecorators = null; m_DecoratorsElement = null; m_IsCulled = true; Clear(); InitCulled(editors); return; } PopulateCache(editors); } public void Reinit(int editorIndex, Editor[] editors) { if (m_Header == null) { m_EditorIndex = editorIndex; m_EditorUsedInDecorators = null; m_IsCulled = false; Clear(); Init(editors); return; } PopulateCache(editors); Object editorTarget = editor.targets[0]; name = GetNameFromEditor(editor); string editorTitle = ObjectNames.GetInspectorTitle(editorTarget); // If the target change we need to invalidate IMGUI container cached measurements // See https://fogbugz.unity3d.com/f/cases/1279830/ if (m_EditorTarget != editorTarget) { m_Header.MarkDirtyLayout(); m_Footer.MarkDirtyLayout(); } m_EditorTarget = editorTarget; m_EditorIndex = editorIndex; m_Header.onGUIHandler = HeaderOnGUI; m_Footer.onGUIHandler = FooterOnGUI; m_Header.name = editorTitle + "Header"; m_Footer.name = editorTitle + "Footer"; if (m_InspectorElement != null) { m_InspectorElement.SetEditor(editor); m_InspectorElement.name = editorTitle + "Inspector"; // InspectorElement should be enabled only if the Editor is open for edit. m_InspectorElement.SetEnabled(editor.IsOpenForEdit()); // Update decorators if (m_EditorUsedInDecorators != editor) { m_EditorUsedInDecorators = editor; UpdateDecoratorsElement(m_EditorUsedInDecorators, editorTitle); } } UpdateInspectorVisibility(); } public void CreateInspectorElement() { if (null == editor || null != m_InspectorElement || m_IsCulled) return; //set the current PropertyHandlerCache to the current editor ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache; // Need to update the cache for multi-object edit detection. if (editor.targets.Length != Selection.objects.Length) { // Cannot force rebuild if locked, otherwise we get an infinite update loop. var tracker = inspectorWindow.tracker; if (tracker.isLocked) tracker.RebuildIfNecessary(); else tracker.ForceRebuild(); } var updateInspectorVisibility = false; // If the editor targets contain many targets and multi editing is not supported, we should not add this inspector. if (null != editor && (editor.targets.Length <= 1 || PropertyEditor.IsMultiEditingSupported(editor, editor.target, inspectorWindow.inspectorMode))) { m_InspectorElement = BuildInspectorElement(); Insert(IndexOf(m_Header) + 1, m_InspectorElement); SetElementVisible(m_InspectorElement, m_WasVisible); updateInspectorVisibility = true; } // Create decorators if (m_InspectorElement != null && m_EditorUsedInDecorators != editor) { m_EditorUsedInDecorators = editor; UpdateDecoratorsElement(m_EditorUsedInDecorators); updateInspectorVisibility = true; } if (updateInspectorVisibility) UpdateInspectorVisibility(); } string GetNameFromEditor(Editor editor) { return editor == null ? "Nothing Selected" : $"{editor.GetType().Name}_{editor.targets[0].GetType().Name}_{editor.targets[0].GetInstanceID()}"; } void UpdateInspectorVisibility() { if (editor.CanBeExpandedViaAFoldoutWithoutUpdate()) { if (m_Footer != null) m_Footer.style.marginTop = m_WasVisible ? 0 : -kFooterDefaultHeight; if (m_DecoratorsElement != null) { if (m_InspectorElement != null) m_InspectorElement.style.paddingBottom = 0; m_DecoratorsElement.style.paddingBottom = PropertyEditor.kEditorElementPaddingBottom; } else { if (m_InspectorElement != null) m_InspectorElement.style.paddingBottom = PropertyEditor.kEditorElementPaddingBottom; } } else { if (m_DecoratorsElement != null) { if (m_Footer != null) m_Footer.style.marginTop = m_WasVisible ? 0 : -kFooterDefaultHeight; m_DecoratorsElement.style.paddingBottom = PropertyEditor.kEditorElementPaddingBottom; } else { if (m_Footer != null) m_Footer.style.marginTop = -kFooterDefaultHeight; } if (m_InspectorElement != null) m_InspectorElement.style.paddingBottom = 0; } } public void AddPrefabComponent(VisualElement comp) { if (m_PrefabElement != null) { m_PrefabElement.RemoveFromHierarchy(); m_PrefabElement = null; } if (comp != null) { m_PrefabElement = comp; Insert(0, m_PrefabElement); } } #region Header IMGUIContainer BuildHeaderElement(string editorTitle) { //Create and IMGUIContainer to enclose the header // This also needs to validate the state of the editor tracker (stuff that was already done in the original DrawEditors var headerElement = inspectorWindow.CreateIMGUIContainer(HeaderOnGUI, editorTitle + "Header"); return headerElement; } private static UQueryState<IMGUIContainer> ImguiContainersQuery = new UQueryBuilder<IMGUIContainer>(null).SingleBaseType().Build(); internal static void InvalidateIMGUILayouts(VisualElement element) { if (element != null) { var q = ImguiContainersQuery.RebuildOn(element); q.ForEach(e => e.MarkDirtyLayout()); } } private bool m_LastOpenForEdit; void HeaderOnGUI() { var editors = PopulateCache(); if (!IsEditorValid()) { if (m_InspectorElement != null) { SetElementVisible(m_InspectorElement, false); } if (m_DecoratorsElement != null) { SetElementVisible(m_DecoratorsElement, false); } return; } // Avoid drawing editor if native target object is not alive, unless it's a MonoBehaviour/ScriptableObject // We want to draw the generic editor with a warning about missing/invalid script // Case 891450: // - ActiveEditorTracker will automatically create editors for materials of components on tracked game objects // - UnityEngine.UI.Mask will destroy this material in OnDisable (e.g. disabling it with the checkbox) causing problems when drawing the material editor var target = editor.target; if (target == null && !NativeClassExtensionUtilities.ExtendsANativeType(target)) { if (m_InspectorElement != null) { SetElementVisible(m_InspectorElement, false); } if (m_DecoratorsElement != null) { SetElementVisible(m_DecoratorsElement, false); } return; } // Active polling of "open for edit" changes. // If the header is moving to UI Toolkit, we may have to rely on a scheduler instead. if (editor != null) { bool openForEdit = editor.IsOpenForEdit(); if (openForEdit != m_LastOpenForEdit) { m_LastOpenForEdit = openForEdit; m_InspectorElement?.SetEnabled(openForEdit); } } m_WasVisible = inspectorWindow.WasEditorVisible(editors, m_EditorIndex, target); GUIUtility.GetControlID(target.GetInstanceID(), FocusType.Passive); EditorGUIUtility.ResetGUIState(); GUI.color = playModeTintColor; if (editor.target is AssetImporter) inspectorWindow.editorsWithImportedObjectLabel.Add(m_EditorIndex + 1); //set the current PropertyHandlerCache to the current editor ScriptAttributeUtility.propertyHandlerCache = editor.propertyHandlerCache; using (new InspectorWindowUtils.LayoutGroupChecker()) { m_DragRect = DrawEditorHeader(editors, target, ref m_WasVisible); } if (GUI.changed) { // If the header changed something, we must trigger a layout calculating on imgui children // Fixes Material editor toggling layout issues (case 1148706) InvalidateIMGUILayouts(this); } if (m_InspectorElement != null && m_WasVisible != IsElementVisible(m_InspectorElement)) { SetElementVisible(m_InspectorElement, m_WasVisible); } if (m_DecoratorsElement != null && m_WasVisible != IsElementVisible(m_DecoratorsElement)) { SetElementVisible(m_DecoratorsElement, m_WasVisible); } UpdateInspectorVisibility(); var multiEditingSupported = PropertyEditor.IsMultiEditingSupported(editor, target, inspectorWindow.inspectorMode); if (!multiEditingSupported && m_WasVisible) { GUILayout.Label("Multi-object editing not supported.", EditorStyles.helpBox); return; } InspectorWindowUtils.DisplayDeprecationMessageIfNecessary(editor); // Reset dirtiness when repainting if (Event.current.type == EventType.Repaint) { editor.isInspectorDirty = false; } // Case 1359247: // Object might have been unloaded. Calling into native code down here will crash the editor. if (editor.target != null) { bool excludedClass = InspectorWindowUtils.IsExcludedClass(target); if (excludedClass) EditorGUILayout.HelpBox( "The module which implements this component type has been force excluded in player settings. This object will be removed in play mode and from any builds you make.", MessageType.Warning); } if (m_WasVisible) { m_ContentRect = m_InspectorElement?.layout ?? Rect.zero; } else { Rect r = m_Header.layout; r.y = r.y + r.height - 1; r.height = kFooterDefaultHeight; m_ContentRect = r; } } Rect DrawEditorHeader(Editor[] editors, Object target, ref bool wasVisible) { var largeHeader = DrawEditorLargeHeader(editors, ref wasVisible); // Dragging handle used for editor reordering var dragRect = largeHeader ? new Rect() : DrawEditorSmallHeader(editors, target, wasVisible); return dragRect; } bool DrawEditorLargeHeader(Editor[] editors, ref bool wasVisible) { if (!IsEditorValid()) { return true; } bool largeHeader = InspectorWindow.EditorHasLargeHeader(m_EditorIndex, editors); // Draw large headers before we do the culling of unsupported editors below, // so the large header is always shown even when the editor can't be. if (largeHeader) { bool IsOpenForEdit = editor.IsOpenForEdit(); wasVisible = true; if (inspectorWindow.editorsWithImportedObjectLabel.Contains(m_EditorIndex)) { var importedObjectBarRect = GUILayoutUtility.GetRect(16, 20); importedObjectBarRect.height = 21; var headerText = "Imported Object"; if (editors.Length > 1) { if (editors[0] is PrefabImporterEditor && editors[1] is GameObjectInspector) headerText = "Root in Prefab Asset (Open for full editing support)"; } GUILayout.Label(headerText, Styles.importedObjectsHeaderStyle, GUILayout.ExpandWidth(true)); GUILayout.Space(-7f); // Ensures no spacing between this header and the next header } // Header using (new EditorGUI.DisabledScope(!IsOpenForEdit)) // Only disable the entire header if the asset is locked by VCS { editor.DrawHeader(); } } return largeHeader; } // Draw small headers (the header above each component) after the culling above // so we don't draw a component header for all the components that can't be shown. Rect DrawEditorSmallHeader(Editor[] editors, Object target, bool wasVisible) { var currentEditor = editor; if (currentEditor == null) return GUILayoutUtility.GetLastRect(); using (new EditorGUI.DisabledScope(!currentEditor.IsEnabled())) { bool isVisible = EditorGUILayout.InspectorTitlebar(wasVisible, currentEditor); if (wasVisible != isVisible) { inspectorWindow.tracker.SetVisible(m_EditorIndex, isVisible ? 1 : 0); InternalEditorUtility.SetIsInspectorExpanded(target, isVisible); if (isVisible) { inspectorWindow.lastInteractedEditor = currentEditor; } else if (inspectorWindow.lastInteractedEditor == currentEditor) { inspectorWindow.lastInteractedEditor = null; } } } return GUILayoutUtility.GetLastRect(); } private bool IsElementVisible(VisualElement ve) { return (ve.resolvedStyle.display == DisplayStyle.Flex); } internal static void SetElementVisible(VisualElement ve, bool visible) { if (visible) { ve.style.display = DisplayStyle.Flex; SetInspectorElementChildIMGUIContainerFocusable(ve, true); } else { ve.style.display = DisplayStyle.None; SetInspectorElementChildIMGUIContainerFocusable(ve, false); } } static void SetInspectorElementChildIMGUIContainerFocusable(VisualElement ve, bool focusable) { var childCount = ve.childCount; for (int i = 0; i < childCount; ++i) { var child = ve[i]; if (child.isIMGUIContainer) { var imguiContainer = (IMGUIContainer)child; imguiContainer.focusable = focusable; } } } #endregion Header #region Footer const float kFooterDefaultHeight = 5; IMGUIContainer BuildFooterElement(string editorTitle) { IMGUIContainer footerElement = inspectorWindow.CreateIMGUIContainer(FooterOnGUI, editorTitle + "Footer"); footerElement.style.height = kFooterDefaultHeight; return footerElement; } void FooterOnGUI() { var editors = m_EditorCache; var ed = editor; if (ed == null) { return; } m_ContentRect.y = -m_ContentRect.height; inspectorWindow.editorDragging.HandleDraggingToEditor(editors, m_EditorIndex, m_DragRect, m_ContentRect); HandleComponentScreenshot(m_ContentRect, ed); var target = ed.target; var comp = target as Component; if (EditorGUI.ShouldDrawOverrideBackground(ed.targets, Event.current, comp)) { var rect = GUILayoutUtility.kDummyRect; bool wasVisible = inspectorWindow.WasEditorVisible(editors, m_EditorIndex, target); // if the inspector is currently visible then the override background drawn by the footer needs to be slightly larger than if the inspector is collapsed if (wasVisible) { rect.y -= 1; rect.height += 1; } else { rect.y += 1; rect.height -= 1; } EditorGUI.DrawOverrideBackgroundApplicable(rect, true); } } void HandleComponentScreenshot(Rect content, Editor editor) { if (ScreenShots.s_TakeComponentScreenshot) { content.yMin -= 16; if (content.Contains(Event.current.mousePosition)) { Rect globalComponentRect = GUIClip.Unclip(content); globalComponentRect.position = globalComponentRect.position + inspectorWindow.parent.screenPosition.position; ScreenShots.ScreenShotComponent(globalComponentRect, editor.target); } } } #endregion Footer #region Decorator private class EditorElementDecoratorCollection : IEnumerable<IEditorElementDecorator> { readonly List<IEditorElementDecorator> m_EditorDecorators = new List<IEditorElementDecorator>(); internal Action<IEditorElementDecorator> OnAdd; internal Action<IEditorElementDecorator> OnRemove; internal int Count => m_EditorDecorators.Count; internal void Add(IEditorElementDecorator editorDecorator) { if (m_EditorDecorators.Contains(editorDecorator)) return; m_EditorDecorators.Add(editorDecorator); OnAdd?.Invoke(editorDecorator); } internal void Remove(IEditorElementDecorator editorDecorator) { if (!m_EditorDecorators.Contains(editorDecorator)) return; m_EditorDecorators.Remove(editorDecorator); OnRemove?.Invoke(editorDecorator); } IEnumerator<IEditorElementDecorator> IEnumerable<IEditorElementDecorator>.GetEnumerator() => m_EditorDecorators.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => m_EditorDecorators.GetEnumerator(); } static bool TryGetDecorators(Editor editor, List<VisualElement> decorators) { if (null == editor || editor.inspectorMode != InspectorMode.Normal) return false; decorators.Clear(); foreach (var editorDecorator in s_EditorDecoratorCollection) { var decorator = editorDecorator.OnCreateFooter(editor); if (decorator != null) decorators.Add(decorator); } return decorators.Count != 0; } void OnEditorDecoratorAdded(IEditorElementDecorator editorDecorator) { if (null == editor || null == m_InspectorElement || m_IsCulled) return; m_EditorUsedInDecorators = editor; UpdateDecoratorsElement(m_EditorUsedInDecorators); UpdateInspectorVisibility(); } void OnEditorDecoratorRemoved(IEditorElementDecorator editorDecorator) { if (null == editor || null == m_InspectorElement || m_IsCulled) return; m_EditorUsedInDecorators = editor; UpdateDecoratorsElement(m_EditorUsedInDecorators); UpdateInspectorVisibility(); } void UpdateDecoratorsElement(Editor editor, string editorTitle = null) { if (s_EditorDecoratorCollection.Count != 0 && TryGetDecorators(editor, s_Decorators)) { editorTitle ??= ObjectNames.GetInspectorTitle(editor.targets[0], editor.targets.Length > 1); CreateDecoratorsElement(editorTitle, s_Decorators); SetElementVisible(m_DecoratorsElement, m_WasVisible); } else if (m_DecoratorsElement != null) { m_DecoratorsElement.Clear(); m_DecoratorsElement.RemoveFromHierarchy(); m_DecoratorsElement = null; } } void CreateDecoratorsElement(string editorTitle, List<VisualElement> children) { if (m_DecoratorsElement == null) { m_DecoratorsElement = BuildDecoratorsElement(editorTitle); } else { m_DecoratorsElement.Clear(); m_DecoratorsElement.RemoveFromClassList(InspectorElement.uIEInspectorVariantUssClassName); m_DecoratorsElement.name = editorTitle + "Decorators"; } if (editor.UseDefaultMargins()) { m_DecoratorsElement.AddToClassList(InspectorElement.uIEInspectorVariantUssClassName); m_DecoratorsElement.style.paddingTop = 0; } foreach (var child in children) m_DecoratorsElement.Add(child); if (m_DecoratorsElement.parent != this) Insert(IndexOf(m_Footer), m_DecoratorsElement); } VisualElement BuildDecoratorsElement(string editorTitle) { var decoratorsParent = new VisualElement() { name = editorTitle + "Decorators" }; decoratorsParent.AddToClassList(PropertyField.decoratorDrawersContainerClassName); return decoratorsParent; } #endregion Decorator internal bool EditorNeedsVerticalOffset(Editor[] editors, Object target) { return m_EditorIndex > 0 && IsEditorValid() && editors[m_EditorIndex - 1]?.target is GameObject && target is Component; } internal InspectorElement GetInspectorElementInternal() { return m_InspectorElement; } } }
UnityCsReference/Editor/Mono/UIElements/Inspector/EditorElement.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/UIElements/Inspector/EditorElement.cs", "repo_id": "UnityCsReference", "token_count": 15100 }
355
// 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 RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; namespace UnityEditor { public partial class Undo { internal enum UndoRedoType { Undo, Redo } [RequiredByNativeCode] static void OnSelectionUndo(bool redo) { if (selectionUndoRedoPerformed != null) selectionUndoRedoPerformed(redo ? UndoRedoType.Redo : UndoRedoType.Undo); } internal static event Action<UndoRedoType> selectionUndoRedoPerformed; } }
UnityCsReference/Editor/Mono/Undo.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Undo.cs", "repo_id": "UnityCsReference", "token_count": 272 }
356
// 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; using System.Collections.Generic; namespace UnityEditor { internal static class EditorExtensionMethods { // Use this method when checking if user hit Space or Return in order to activate the main action // for a control, such as opening a popup menu or color picker. internal static bool MainActionKeyForControl(this UnityEngine.Event evt, int controlId) { if (EditorGUIUtility.keyboardControl != controlId) return false; bool anyModifiers = (evt.alt || evt.shift || evt.command || evt.control); // Space or return is action key return evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter) && !anyModifiers; } internal static bool IsArrayOrList(this Type listType) { if (listType.IsArray) { return true; } else if (listType.IsGenericType && listType.GetGenericTypeDefinition() == typeof(List<>)) { return true; } return false; } internal static Type GetArrayOrListElementType(this Type listType) { if (listType.IsArray) { return listType.GetElementType(); } else if (listType.IsGenericType) { return listType.GetGenericArguments()[0]; } return null; } internal static List<Enum> EnumGetNonObsoleteValues(this Type type) { // each enum value has the same position in both values and names arrays string[] names = Enum.GetNames(type); Enum[] values = Enum.GetValues(type).Cast<Enum>().ToArray(); var result = new List<Enum>(); for (int i = 0; i < names.Length; i++) { var info = type.GetMember(names[i]); var attrs = info[0].GetCustomAttributes(typeof(ObsoleteAttribute), false); var isObsolete = false; foreach (var attr in attrs) { if (attr is ObsoleteAttribute) isObsolete = true; } if (!isObsolete) result.Add(values[i]); } return result; } } }
UnityCsReference/Editor/Mono/Utils/EditorExtensionMethods.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/EditorExtensionMethods.cs", "repo_id": "UnityCsReference", "token_count": 1278 }
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 Bee.BeeDriver; using NiceIO; using UnityEditor.Scripting; using UnityEditor.Scripting.Compilers; using UnityEditor.Utils; namespace UnityEditor.Mono.Utils { internal enum PramLogLevel { Quiet, Verbose, VeryVerbose, Trace, } /// <summary> /// Invocation wrapper for Pram /// (Platform Runtime Application Manager - https://github.cds.internal.unity3d.com/unity/pram) /// </summary> internal class Pram { private NPath pramDll; public PramLogLevel LogLevel { get; set; } = PramLogLevel.Verbose; public Dictionary<string, string> EnvironmentVariables { get; } = new Dictionary<string, string>(); public NPath[] ProviderLoadPaths { get; set; } public static readonly NPath PramDataDirectory = "Library/PramData"; public Pram(NPath pramDll, params NPath[] providerLoadPaths) { PramDataDirectory.EnsureDirectoryExists(); this.pramDll = pramDll; this.EnvironmentVariables.Add("PRAM_DIRECTORY", PramDataDirectory.ToString()); this.ProviderLoadPaths = providerLoadPaths; } public Program CreateProgram(IEnumerable<string> arguments) { var logLevelArgument = LogLevel switch { PramLogLevel.Quiet => "--quiet", PramLogLevel.Verbose => "--verbose", PramLogLevel.VeryVerbose => "--very-verbose", PramLogLevel.Trace => "--trace", _ => throw new ArgumentOutOfRangeException() }; var providerLoadPathArguments = ProviderLoadPaths.Select(p => $"--provider-load-path={p.InQuotes()}"); return new NetCoreProgram(pramDll.ToString(SlashMode.Native), providerLoadPathArguments .Append(logLevelArgument) .Concat(arguments) .SeparateWith(" "), info => { foreach (var envVar in EnvironmentVariables) info.EnvironmentVariables[envVar.Key] = envVar.Value; }); } public Program AppKill(string provider, string applicationId, string environment) => CreateProgram(new[] {"app-kill", "--environment", environment, provider, applicationId }); public Program AppDeploy(string provider, string applicationId, string environment, NPath applicationPath) => CreateProgram(new[] {"app-deploy", "--environment", environment, provider, applicationId, CommandLineFormatter.PrepareFileName(applicationPath.ToString()) }); public Program AppStartDetached(string provider, string applicationId, string environment, params string[] arguments) => CreateProgram(new[] {"app-start-detached", "--environment", environment, provider, applicationId, "--"}.Concat(arguments)); public Program DetectEnvironment(string provider) => CreateProgram(new[] {"env-detect", provider }); public Program EnvironmentProperties(string provider, string environment) => CreateProgram(new[] {"env-props", "--environment", environment, provider }); } }
UnityCsReference/Editor/Mono/Utils/Pram.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/Utils/Pram.cs", "repo_id": "UnityCsReference", "token_count": 1382 }
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; namespace UnityEditor.VersionControl { public partial class Asset { internal static bool IsState(Asset.States isThisState, Asset.States partOfThisState) { return (isThisState & partOfThisState) != 0; } public bool IsState(Asset.States state) { return IsState(this.state, state); } public bool IsOneOfStates(Asset.States[] states) { var localState = this.state; foreach (Asset.States st in states) { if ((localState & st) != 0) return true; } return false; } internal bool IsUnderVersionControl { get { return IsState(Asset.States.Synced) || IsState(Asset.States.OutOfSync) || IsState(Asset.States.AddedLocal); } } public void Edit() { UnityEngine.Object load = Load(); if (load != null) AssetDatabase.OpenAsset(load); } public UnityEngine.Object Load() { if (state == States.DeletedLocal || isMeta) { return null; } // Standard asset loading return AssetDatabase.LoadAssetAtPath(path, typeof(UnityEngine.Object)); } internal static string StateToString(States state) { if (IsState(state, States.AddedLocal)) return "Added Local"; if (IsState(state, States.AddedRemote)) return "Added Remote"; if (IsState(state, States.DeletedRemote)) return "Deleted Remote"; if (IsState(state, States.CheckedOutLocal) && !IsState(state, States.LockedLocal)) return "Checked Out Local"; if (IsState(state, States.CheckedOutRemote) && !IsState(state, States.LockedRemote)) return "Checked Out Remote"; if (IsState(state, States.Conflicted)) return "Conflicted"; if (IsState(state, States.DeletedLocal)) return "Deleted Local"; if (IsState(state, States.Local) && !(IsState(state, States.OutOfSync) || IsState(state, States.Synced))) return "Local"; if (IsState(state, States.LockedLocal)) return "Locked Local"; if (IsState(state, States.LockedRemote)) return "Locked Remote"; if (IsState(state, States.OutOfSync)) return "Out Of Sync"; if (IsState(state, States.Updating)) return "Updating Status"; return ""; } internal static string AllStateToString(States state) { var sb = new System.Text.StringBuilder(); if (IsState(state, States.AddedLocal)) sb.Append("Added Local, "); if (IsState(state, States.AddedRemote)) sb.Append("Added Remote, "); if (IsState(state, States.CheckedOutLocal)) sb.Append("Checked Out Local, "); if (IsState(state, States.CheckedOutRemote)) sb.Append("Checked Out Remote, "); if (IsState(state, States.Conflicted)) sb.Append("Conflicted, "); if (IsState(state, States.DeletedLocal)) sb.Append("Deleted Local, "); if (IsState(state, States.DeletedRemote)) sb.Append("Deleted Remote, "); if (IsState(state, States.Local)) sb.Append("Local, "); if (IsState(state, States.LockedLocal)) sb.Append("Locked Local, "); if (IsState(state, States.LockedRemote)) sb.Append("Locked Remote, "); if (IsState(state, States.OutOfSync)) sb.Append("Out Of Sync, "); if (IsState(state, States.Synced)) sb.Append("Synced, "); if (IsState(state, States.Missing)) sb.Append("Missing, "); if (IsState(state, States.ReadOnly)) sb.Append("ReadOnly, "); if (IsState(state, States.Unversioned)) sb.Append("Unversioned, "); if (IsState(state, States.Exclusive)) sb.Append("Exclusive, "); // remove trailing ", " if had any if (sb.Length > 2) sb.Remove(sb.Length - 2, 2); return sb.ToString(); } internal string StateToString() { if (isFolder && !isMeta && !Provider.isVersioningFolders) return string.Empty; return StateToString(this.state); } public string prettyPath { get { return path; } } } }
UnityCsReference/Editor/Mono/VersionControl/Common/VCAsset.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/Common/VCAsset.cs", "repo_id": "UnityCsReference", "token_count": 2518 }
359
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor; using UnityEditor.VersionControl; namespace UnityEditorInternal.VersionControl { // Change list window menu; set up and invoked from native code when VCS integration is turned on class PendingWindowContextMenu { //[MenuItem("CONTEXT/Pending/Submit...", true, 100)] static bool SubmitTest(int userData) { return Provider.SubmitIsValid(null, ListControl.FromID(userData).SelectedAssets); } //[MenuItem ("CONTEXT/Pending/Submit...", false, 100)] static void Submit(int userData) { WindowChange.Open(ListControl.FromID(userData).SelectedAssets, true); } //[MenuItem("CONTEXT/Pending/Revert...", true, 200)] static bool RevertTest(int userData) { return Provider.RevertIsValid(ListControl.FromID(userData).SelectedAssets, RevertMode.Normal); } //[MenuItem ("CONTEXT/Pending/Revert...", false, 200)] static void Revert(int userData) { WindowRevert.Open(ListControl.FromID(userData).SelectedAssets); } //[MenuItem ("CONTEXT/Pending/Revert Unchanged", true, 201)] static bool RevertUnchangedTest(int userData) { return Provider.RevertIsValid(ListControl.FromID(userData).SelectedAssets, RevertMode.Unchanged); } //[MenuItem ("CONTEXT/Pending/Revert Unchanged", false, 201)] static void RevertUnchanged(int userData) { AssetList list = ListControl.FromID(userData).SelectedAssets; Provider.Revert(list, RevertMode.Unchanged).SetCompletionAction(CompletionAction.UpdatePendingWindow); Provider.Status(list); } //[MenuItem("CONTEXT/Pending/Resolve Conflicts...", true, 202)] static bool ResolveTest(int userData) { return Provider.ResolveIsValid(ListControl.FromID(userData).SelectedAssets); } //[MenuItem ("CONTEXT/Pending/Resolve Conflicts...", false, 202)] static void Resolve(int userData) { WindowResolve.Open(ListControl.FromID(userData).SelectedAssets); } //[MenuItem("CONTEXT/Pending/Lock", true, 300)] static bool LockTest(int userData) { return Provider.LockIsValid(ListControl.FromID(userData).SelectedAssets); } //[MenuItem ("CONTEXT/Pending/Lock", false, 300)] static void Lock(int userData) { AssetList list = ListControl.FromID(userData).SelectedAssets; Provider.Lock(list, true).SetCompletionAction(CompletionAction.UpdatePendingWindow); } //[MenuItem("CONTEXT/Pending/Unlock", true, 301)] static bool UnlockTest(int userData) { return Provider.UnlockIsValid(ListControl.FromID(userData).SelectedAssets); } //[MenuItem ("CONTEXT/Pending/Unlock", false, 301)] static void Unlock(int userData) { AssetList list = ListControl.FromID(userData).SelectedAssets; Provider.Lock(list, false).SetCompletionAction(CompletionAction.UpdatePendingWindow); } //[MenuItem("CONTEXT/Pending/Diff/Against Head...", true, 400)] static bool DiffHeadTest(int userData) { return Provider.DiffIsValid(ListControl.FromID(userData).SelectedAssets); } //[MenuItem ("CONTEXT/Pending/Diff/Against Head...", false, 400)] static void DiffHead(int userData) { Provider.DiffHead(ListControl.FromID(userData).SelectedAssets, false); } //[MenuItem("CONTEXT/Pending/Diff/Against Head with .meta...", true, 401)] static bool DiffHeadWithMetaTest(int userData) { return Provider.DiffIsValid(ListControl.FromID(userData).SelectedAssets); } //[MenuItem ("CONTEXT/Pending/Diff/Against Head with .meta...", false, 401)] static void DiffHeadWithMeta(int userData) { Provider.DiffHead(ListControl.FromID(userData).SelectedAssets, true); } //[MenuItem("CONTEXT/Pending/Reveal in Finder", true, 402)] static bool ShowInExplorerTest(int userData) { return (ListControl.FromID(userData)).SelectedAssets.Count > 0; } //[MenuItem ("CONTEXT/Pending/Reveal in Finder", false, 402)] static void ShowInExplorer(int userData) { if (System.Environment.OSVersion.Platform == System.PlatformID.MacOSX || System.Environment.OSVersion.Platform == System.PlatformID.Unix) { EditorApplication.ExecuteMenuItem("Assets/Reveal in Finder"); } else { EditorApplication.ExecuteMenuItem("Assets/Show in Explorer"); } } //[MenuItem("CONTEXT/Pending/New Changeset...", true, 501)] static bool NewChangeSetTest(int userData) { return Provider.isActive; } //[MenuItem ("CONTEXT/Pending/New Changeset...", false, 501)] static void NewChangeSet(int userData) { WindowChange.Open(ListControl.FromID(userData).SelectedAssets, false); } } }
UnityCsReference/Editor/Mono/VersionControl/UI/VCMenuPending.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/UI/VCMenuPending.cs", "repo_id": "UnityCsReference", "token_count": 2318 }
360
// 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.VersionControl { [NativeHeader("Editor/Src/VersionControl/VCManager.h")] [StaticAccessor("GetVCManager()")] partial class VersionControlManager { static extern ScriptableObject GetActiveObject(); static extern void SetActiveObject(ScriptableObject vco); } }
UnityCsReference/Editor/Mono/VersionControl/VersionControlManager.bindings.cs/0
{ "file_path": "UnityCsReference/Editor/Mono/VersionControl/VersionControlManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 167 }
361
namespace Unity.Baselib { internal static class BaselibNativeLibrary { // TODO: pinvoke interface not yet supported/used outside of baselib testing. //public const string DllName = "__Internal"; } }
UnityCsReference/External/baselib/baselib/CSharp/BaselibNativeLibrary.cs/0
{ "file_path": "UnityCsReference/External/baselib/baselib/CSharp/BaselibNativeLibrary.cs", "repo_id": "UnityCsReference", "token_count": 82 }
362
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Unity.Baselib.LowLevel; namespace Unity.Baselib { internal struct ErrorState { // Can't use CallerFilePath/CallerLineNumber because UnityEngine.dll is still linking against an old .Net framework. //public void ThrowIfFailed([CallerFilePath] string file = "", [CallerLineNumber] int line = 0) public void ThrowIfFailed() { if (ErrorCode != Binding.Baselib_ErrorCode.Success) throw new BaselibException(this); } public Binding.Baselib_ErrorCode ErrorCode => nativeErrorState.code; /// <summary> /// Native error state object, should only be written by native code. /// </summary> private Binding.Baselib_ErrorState nativeErrorState; public unsafe Binding.Baselib_ErrorState* NativeErrorStatePtr { get { fixed (Binding.Baselib_ErrorState* ptr = &nativeErrorState) return ptr; } } /// <summary> /// Retrieves a (potentially) platform specific explanation string from the error state. /// </summary> /// <param name="verbose"> /// If false, only writes error code type and value. /// If true, adds source location if available and error explanation if available (similar to strerror). /// </param> public string Explain(Binding.Baselib_ErrorState_ExplainVerbosity verbosity = Binding.Baselib_ErrorState_ExplainVerbosity.ErrorType_SourceLocation_Explanation) { unsafe { fixed (Binding.Baselib_ErrorState* nativeErrorStatePtr = &nativeErrorState) { // Add 1 because querying the length does not contain nullterminator. var length = Binding.Baselib_ErrorState_Explain(nativeErrorStatePtr, null, 0, verbosity) + 1; var nativeExplanationString = Binding.Baselib_Memory_Allocate(new UIntPtr(length)); try { Binding.Baselib_ErrorState_Explain(nativeErrorStatePtr, (byte*)nativeExplanationString, length, verbosity); return Marshal.PtrToStringAnsi(nativeExplanationString); // System.Text.Encoding.UTF8.GetString is not supported in DOTS as of writing. } finally { Binding.Baselib_Memory_Free(nativeExplanationString); } } } } } /// <summary> /// Exception thrown when a critical Baselib error was raised. /// </summary> internal class BaselibException : Exception { internal BaselibException(ErrorState errorState) : base(errorState.Explain()) { this.errorState = errorState; } public Binding.Baselib_ErrorCode ErrorCode => errorState.ErrorCode; private readonly ErrorState errorState; } }
UnityCsReference/External/baselib/baselib/CSharp/Error.cs/0
{ "file_path": "UnityCsReference/External/baselib/baselib/CSharp/Error.cs", "repo_id": "UnityCsReference", "token_count": 1343 }
363
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.AI { // Keep this enum in sync with the one defined in "NavMeshBindingTypes.h" // Status of path. [MovedFrom("UnityEngine")] public enum NavMeshPathStatus { PathComplete = 0, // The path terminates at the destination. PathPartial = 1, // The path cannot reach the destination. PathInvalid = 2 // The path is invalid. } // Path navigation. [NativeHeader("Modules/AI/NavMeshPath.bindings.h")] [StructLayout(LayoutKind.Sequential)] [MovedFrom("UnityEngine")] public sealed class NavMeshPath { internal IntPtr m_Ptr; internal Vector3[] m_Corners; public NavMeshPath() { m_Ptr = InitializeNavMeshPath(); } ~NavMeshPath() { DestroyNavMeshPath(m_Ptr); m_Ptr = IntPtr.Zero; } [FreeFunction("NavMeshPathScriptBindings::InitializeNavMeshPath")] static extern IntPtr InitializeNavMeshPath(); [FreeFunction("NavMeshPathScriptBindings::DestroyNavMeshPath", IsThreadSafe = true)] static extern void DestroyNavMeshPath(IntPtr ptr); [FreeFunction("NavMeshPathScriptBindings::GetCornersNonAlloc", HasExplicitThis = true)] public extern int GetCornersNonAlloc([Out] Vector3[] results); [FreeFunction("NavMeshPathScriptBindings::CalculateCornersInternal", HasExplicitThis = true)] extern Vector3[] CalculateCornersInternal(); [FreeFunction("NavMeshPathScriptBindings::ClearCornersInternal", HasExplicitThis = true)] extern void ClearCornersInternal(); // Erase all corner points from path. public void ClearCorners() { ClearCornersInternal(); m_Corners = null; } void CalculateCorners() { if (m_Corners == null) m_Corners = CalculateCornersInternal(); } // Corner points of path. (RO) public Vector3[] corners { get { CalculateCorners(); return m_Corners; } } // Status of the path. (RO) public extern NavMeshPathStatus status { get; } internal static class BindingsMarshaller { public static IntPtr ConvertToNative(NavMeshPath navMeshPath) => navMeshPath.m_Ptr; } } }
UnityCsReference/Modules/AI/NavMeshPath.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AI/NavMeshPath.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1036 }
364
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; namespace UnityEngine.Accessibility { /// <summary> /// Access point to assistive technology support APIs. /// </summary> /// <remarks> /// The currently supported platforms are: /// ///- <see cref="RuntimePlatform.Android"/> ///- <see cref="RuntimePlatform.IPhonePlayer"/> /// /// This class contains static methods that allow users to support assistive technologies in the operating /// system (for example, the screen reader). /// </remarks> public static class AssistiveSupport { internal class NotificationDispatcher : IAccessibilityNotificationDispatcher { /// <summary> /// Sends the given notification to the operating system. /// </summary> /// <param name="context">The accessibility notification to be sent.</param> static void Send(in AccessibilityNotificationContext context) { AccessibilityManager.SendAccessibilityNotification(context); } public void SendAnnouncement(string announcement) { var notification = new AccessibilityNotificationContext { notification = AccessibilityNotification.Announcement, announcement = announcement }; Send(notification); } /// <summary> /// Sends a notification to the screen reader conveying that a page was scrolled. /// </summary> /// <param name="announcement">The string containing a description of the new scroll position (for example, /// @@"Tab 3 of 5"@@ or @@"Page 19 of 27"@@).</param> public void SendPageScrolledAnnouncement(string announcement) { var notification = new AccessibilityNotificationContext { notification = AccessibilityNotification.PageScrolled, announcement = announcement }; Send(notification); } public void SendScreenChanged(AccessibilityNode nodeToFocus = null) { var notification = new AccessibilityNotificationContext { notification = AccessibilityNotification.ScreenChanged, nextNodeId = nodeToFocus == null ? -1 : nodeToFocus.id }; Send(notification); } public void SendLayoutChanged(AccessibilityNode nodeToFocus = null) { var notification = new AccessibilityNotificationContext { notification = AccessibilityNotification.LayoutChanged, nextNodeId = nodeToFocus == null ? -1 : nodeToFocus.id }; Send(notification); } } /// <summary> /// Event that is invoked on the main thread when the screen reader focus changes. /// <para>For all the supported platforms, refer to <see cref="AssistiveSupport"/>.</para> /// </summary> public static event Action<AccessibilityNode> nodeFocusChanged; /// <summary> /// Event that is invoked on the main thread when the screen reader is enabled or disabled. /// <para>For all the supported platforms, refer to <see cref="AssistiveSupport"/>.</para> /// </summary> public static event Action<bool> screenReaderStatusChanged; /// <summary> /// Whether the screen reader is enabled on the operating system. /// <para>For all the supported platforms, refer to <see cref="AssistiveSupport"/>.</para> /// </summary> public static bool isScreenReaderEnabled { get; private set; } /// <summary> /// Service used to send accessibility notifications to the screen reader. /// <para>For all the supported platforms, refer to <see cref="AssistiveSupport"/>.</para> /// </summary> public static IAccessibilityNotificationDispatcher notificationDispatcher { get; } = new NotificationDispatcher(); static ServiceManager s_ServiceManager; internal static void Initialize() { isScreenReaderEnabled = AccessibilityManager.IsScreenReaderEnabled(); AccessibilityManager.screenReaderStatusChanged += ScreenReaderStatusChanged; AccessibilityManager.nodeFocusChanged += NodeFocusChanged; s_ServiceManager = new ServiceManager(); } internal static T GetService<T>() where T : IService { if (s_ServiceManager == null) { return default; } return s_ServiceManager.GetService<T>(); } internal static bool IsServiceRunning<T>() where T : IService { IService service = GetService<T>(); return service != null; } internal static void SetApplicationAccessibilityLanguage(SystemLanguage language) { AccessibilityManager.SetApplicationAccessibilityLanguage(language); } static void ScreenReaderStatusChanged(bool screenReaderEnabled) { if (isScreenReaderEnabled == screenReaderEnabled) { return; } isScreenReaderEnabled = screenReaderEnabled; screenReaderStatusChanged?.Invoke(isScreenReaderEnabled); } static void NodeFocusChanged(AccessibilityNode currentNode) { nodeFocusChanged?.Invoke(currentNode); } /// <summary> /// The active AccessibilityHierarchy for the screen reader. May be @@null@@ if no hierarchy is active. /// <para>You need an active accessibility hierarchy to present any content to the user through the screen reader.</para> /// <para>If the screen reader is off, there is no active hierarchy. If the screen reader is turned off on the device /// while an active hierarchy is set, the active hierarchy is automatically set to @@null@@.</para> /// <para>For all the supported platforms, refer to <see cref="AssistiveSupport"/>.</para> /// </summary> /// <remarks> /// Throws @@PlatformNotSupportedException@@ if the screen reader support is not implemented for the /// platform and the code is not running in the Unity Editor. /// </remarks> /// <remarks> /// When the active hierarchy is assigned, a notification is sent to the operating system that the screen changed /// considerably. The notification is sent by calling <see /// cref="IAccessibilityNotificationDispatcher.SendScreenChanged"/> (with a @@null@@ parameter). /// </remarks> public static AccessibilityHierarchy activeHierarchy { set { CheckPlatformSupported(); using var amlock = AccessibilityManager.GetExclusiveLock(); var hierarchyService = GetService<AccessibilityHierarchyService>(); if (hierarchyService != null) { hierarchyService.hierarchy = value; s_ActiveHierarchyChanged?.Invoke(value); } } get => GetService<AccessibilityHierarchyService>()?.hierarchy; } private static event Action<AccessibilityHierarchy> s_ActiveHierarchyChanged; /// <summary> /// Event sent when the active hierarchy is changed. /// </summary> internal static event Action<AccessibilityHierarchy> activeHierarchyChanged { [VisibleToOtherModules("UnityEditor.AccessibilityModule")] add { s_ActiveHierarchyChanged += value; } [VisibleToOtherModules("UnityEditor.AccessibilityModule")] remove { s_ActiveHierarchyChanged -= value; } } internal static void OnHierarchyNodeFramesRefreshed(AccessibilityHierarchy hierarchy) { if (activeHierarchy == hierarchy) { notificationDispatcher.SendLayoutChanged(); } } static void CheckPlatformSupported() { // We accept Editor platform even though it is not actually supported yet in order to be able to debug // Accessibility hierarchy using the Accessibility Hierarchy Viewer. if (!Application.isEditor && !AccessibilityManager.isSupportedPlatform) { throw new PlatformNotSupportedException($"This API is not supported for platform {Application.platform}"); } } } }
UnityCsReference/Modules/Accessibility/Managed/AssistiveSupport.cs/0
{ "file_path": "UnityCsReference/Modules/Accessibility/Managed/AssistiveSupport.cs", "repo_id": "UnityCsReference", "token_count": 3582 }
365
// 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; namespace UnityEngine.Android { [NativeHeader("Modules/AndroidJNI/Public/AndroidApp.bindings.h")] [StaticAccessor("AndroidApp", StaticAccessorType.DoubleColon)] [NativeConditional("PLATFORM_ANDROID")] internal static class AndroidApp { private static AndroidJavaObject m_Context; private static AndroidJavaObject m_Activity; public static AndroidJavaObject Context { get { AcquireContextAndActivity(); return m_Context; } } public static AndroidJavaObject Activity { get { AcquireContextAndActivity(); return m_Activity; // can be null if context is not an activity } } private static void AcquireContextAndActivity() { if (m_Context != null) return; using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { m_Context = unityPlayer.GetStatic<AndroidJavaObject>("currentContext"); m_Activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); } } public static extern IntPtr UnityPlayerRaw { [ThreadSafe] get; } private static AndroidJavaObject m_UnityPlayer; public static AndroidJavaObject UnityPlayer { get { if (m_UnityPlayer != null) return m_UnityPlayer; m_UnityPlayer = new AndroidJavaObject(UnityPlayerRaw); return m_UnityPlayer; } } } }
UnityCsReference/Modules/AndroidJNI/AndroidApp.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/AndroidJNI/AndroidApp.bindings.cs", "repo_id": "UnityCsReference", "token_count": 844 }
366
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Scripting; namespace UnityEngine.Animations { [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field)] public class DiscreteEvaluationAttribute : Attribute { } internal static class DiscreteEvaluationAttributeUtilities { public static int ConvertFloatToDiscreteInt(float f) { unsafe { float* fp = &f; int* i = (int*)fp; return *i; } } public static float ConvertDiscreteIntToFloat(int f) { unsafe { int* fp = &f; float* i = (float*)fp; return *i; } } } }
UnityCsReference/Modules/Animation/Managed/DiscreteEvaluationAttribute.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/Managed/DiscreteEvaluationAttribute.cs", "repo_id": "UnityCsReference", "token_count": 444 }
367
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEngine.Playables; namespace UnityEngine.Animations { [NativeHeader("Modules/Animation/ScriptBindings/AnimationMotionXToDeltaPlayable.bindings.h")] [StaticAccessor("AnimationMotionXToDeltaPlayableBindings", StaticAccessorType.DoubleColon)] [RequiredByNativeCode] internal struct AnimationMotionXToDeltaPlayable : IPlayable, IEquatable<AnimationMotionXToDeltaPlayable> { PlayableHandle m_Handle; static readonly AnimationMotionXToDeltaPlayable m_NullPlayable = new AnimationMotionXToDeltaPlayable(PlayableHandle.Null); public static AnimationMotionXToDeltaPlayable Null { get { return m_NullPlayable; } } public static AnimationMotionXToDeltaPlayable Create(PlayableGraph graph) { var handle = CreateHandle(graph); return new AnimationMotionXToDeltaPlayable(handle); } private static PlayableHandle CreateHandle(PlayableGraph graph) { PlayableHandle handle = PlayableHandle.Null; if (!CreateHandleInternal(graph, ref handle)) return PlayableHandle.Null; handle.SetInputCount(1); return handle; } private AnimationMotionXToDeltaPlayable(PlayableHandle handle) { if (handle.IsValid()) { if (!handle.IsPlayableOfType<AnimationMotionXToDeltaPlayable>()) throw new InvalidCastException("Can't set handle: the playable is not an AnimationMotionXToDeltaPlayable."); } m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public static implicit operator Playable(AnimationMotionXToDeltaPlayable playable) { return new Playable(playable.GetHandle()); } public static explicit operator AnimationMotionXToDeltaPlayable(Playable playable) { return new AnimationMotionXToDeltaPlayable(playable.GetHandle()); } public bool Equals(AnimationMotionXToDeltaPlayable other) { return GetHandle() == other.GetHandle(); } public bool IsAbsoluteMotion() { return IsAbsoluteMotionInternal(ref m_Handle); } public void SetAbsoluteMotion(bool value) { SetAbsoluteMotionInternal(ref m_Handle, value); } // Bindings methods. [NativeThrows] extern private static bool CreateHandleInternal(PlayableGraph graph, ref PlayableHandle handle); [NativeThrows] extern static private bool IsAbsoluteMotionInternal(ref PlayableHandle handle); [NativeThrows] extern static private void SetAbsoluteMotionInternal(ref PlayableHandle handle, bool value); } }
UnityCsReference/Modules/Animation/ScriptBindings/AnimationMotionXToDeltaPlayable.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimationMotionXToDeltaPlayable.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1194 }
368
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine { [NativeHeader("Modules/Animation/OptimizeTransformHierarchy.h")] public class AnimatorUtility { [FreeFunction] extern public static void OptimizeTransformHierarchy([NotNull] GameObject go, string[] exposedTransforms); [FreeFunction] extern public static void DeoptimizeTransformHierarchy([NotNull] GameObject go); } }
UnityCsReference/Modules/Animation/ScriptBindings/AnimatorUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Animation/ScriptBindings/AnimatorUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 203 }
369
// 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 { partial class AssetBundle { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method CreateFromFile has been renamed to LoadFromFile (UnityUpgradable) -> LoadFromFile(*)", true)] public static AssetBundle CreateFromFile(string path) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method CreateFromMemory has been renamed to LoadFromMemoryAsync (UnityUpgradable) -> LoadFromMemoryAsync(*)", true)] public static AssetBundleCreateRequest CreateFromMemory(byte[] binary) { return null; } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [Obsolete("Method CreateFromMemoryImmediate has been renamed to LoadFromMemory (UnityUpgradable) -> LoadFromMemory(*)", true)] public static AssetBundle CreateFromMemoryImmediate(byte[] binary) { return null; } } }
UnityCsReference/Modules/AssetBundle/Managed/AssetBundle.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/AssetBundle/Managed/AssetBundle.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 372 }
370
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.CodeDom; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text.RegularExpressions; namespace UnityEditor.AssetImporters { internal class StaticFieldCollector { private static IReadOnlyList<FieldInfo> GetAllStaticFieldsInPostProcessorsAndScriptedImporters(IList<Type> specificAssetPostProcessors = null, IList<Type> specificScriptedImporters = null) { List<FieldInfo> staticFields = new List<FieldInfo>(); try { var ignoreFieldsHashSet = new HashSet<FieldInfo>(TypeCache.GetFieldsWithAttribute<AssetPostprocessorStaticVariableIgnoreAttribute>()); // Get all types in the assembly IList<Type> assetPostProcessors = specificAssetPostProcessors ?? TypeCache.GetTypesDerivedFrom<AssetPostprocessor>(); CollectOffendingFields(assetPostProcessors, staticFields, ignoreFieldsHashSet); IList<Type> scriptedImporters = specificScriptedImporters ?? TypeCache.GetTypesDerivedFrom<ScriptedImporter>(); CollectOffendingFields(scriptedImporters, staticFields, ignoreFieldsHashSet); } catch (ReflectionTypeLoadException ex) { UnityEngine.Debug.LogException(ex); } return staticFields; } private static void CollectOffendingFields(IList<Type> extractedTypes, List<FieldInfo> staticFieldsToReport, HashSet<FieldInfo> ignoreFieldsHashSet) { foreach (var type in extractedTypes) { // Get all static fields in the type FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); // Add the fields to the list foreach (FieldInfo curField in fields) { if (!ignoreFieldsHashSet.Contains(curField)) staticFieldsToReport.Add(curField); } } } private static void BruteForceFindClassInProject(string containingClassFullName, ref string[] paths, out string additionalWarning) { additionalWarning = string.Empty; var allMatchGUIDs = new List<string>(); var allScripts = AssetDatabase.FindAssets("t:Script"); foreach (var curScriptGUID in allScripts) { MonoScript monoScript = AssetDatabase.LoadAssetAtPath<MonoScript>(AssetDatabase.GUIDToAssetPath(curScriptGUID)); // This is the case when there are no classes inside the Script, // such as, a C# file with only enums in it if (monoScript == null) continue; Type scriptClass = monoScript.GetClass(); if (scriptClass != null && (scriptClass.IsSubclassOf(typeof(AssetPostprocessor)) || scriptClass.IsSubclassOf(typeof(ScriptedImporter))) && scriptClass.FullName == containingClassFullName) { allMatchGUIDs.Add(curScriptGUID); } } paths = allMatchGUIDs.ToArray(); if (paths.Length == 0) additionalWarning = L10n.Tr("Unable to locate a corresponding file for this type. Check your project for instances where multiple classes are defined in a single file, with one class sharing the file name."); } private static void TryExtractInfoForWarningMessage(string[] foundGUIDs, string containingClassFullName, Regex regEx, FieldInfo curField, out string scriptPath, out int lineNumber, out int columnNumber) { //Initialize to default values scriptPath = string.Empty; lineNumber = 0; columnNumber = 0; foreach (var curGUID in foundGUIDs) { var curPath = AssetDatabase.GUIDToAssetPath(curGUID); var importer = AssetImporter.GetAtPath(curPath) as MonoImporter; if (importer == null || importer.GetScript().GetClass().FullName != containingClassFullName) continue; // We have found the script that corresponds // to where the class it. Store it here // in case we don't find the line or column numbers scriptPath = curPath; var scriptContents = importer.GetScript().text; // Line numbers begin at 1 int lineCount = 1; // Use StringReader to read line by line, so that we can // keep count of where the line number is using (StringReader reader = new StringReader(scriptContents)) { string line; while ((line = reader.ReadLine()) != null) { // We have a match, now we need // to extract the column number from it if (regEx.IsMatch(line)) { lineNumber = lineCount; // We add 1 because column numbers start at 1 columnNumber = line.IndexOf(curField.Name, StringComparison.Ordinal) + 1; break; } lineCount++; } } // No need to process any more paths, we found the // class which contains our static variable return; } } // Usage: If specificAssetPostProcessors or specificScriptedImporters are specified, // only those will be used and the TypeCache will be side-stepped. // These were added mostly for testing, but can also be used when this API becomes // more widely used. internal static ImportActivityWindow.PostProcessorStaticFieldWarningMessage[] FindStaticVariablesInPostProcessorsAndScriptedImporters(IList<Type> specificAssetPostProcessors = null, IList<Type> specificScriptedImporters = null) { var warnings = new List<ImportActivityWindow.PostProcessorStaticFieldWarningMessage>(); var applicationContentsPath = Path.GetFullPath(EditorApplication.applicationContentsPath); // There should only be a few postprocessors in a project, so the // staticFields list won't be too long var staticFields = GetAllStaticFieldsInPostProcessorsAndScriptedImporters(specificAssetPostProcessors, specificScriptedImporters); foreach (var curField in staticFields) { // We're not interested in readonly fields, as their value // is always initialized in the MonoDomain // We also filter out constant fields, as their value is implicitly // static and their value is also initialized when being declared if (curField == null || curField.DeclaringType == null || curField.IsInitOnly || curField.IsLiteral) continue; var assemblyLocation = Path.GetFullPath(curField.DeclaringType.Assembly.Location); // Ignore Editor Assemblies since we can't get source for them if (assemblyLocation.StartsWith(applicationContentsPath, StringComparison.Ordinal)) continue; var containingClassName = curField.DeclaringType.Name; var containingClassFullName = curField.DeclaringType.FullName; // Types can be nested, so we need to make sure we can extract nested types var declaringType = curField.DeclaringType; while (declaringType != null && (declaringType.Attributes.HasFlag(TypeAttributes.NestedPrivate) || declaringType.Attributes.HasFlag(TypeAttributes.NestedPublic) || declaringType.Attributes.HasFlag(TypeAttributes.NestedFamORAssem) || declaringType.Attributes.HasFlag(TypeAttributes.NestedFamily))) { containingClassName = declaringType.DeclaringType.Name; containingClassFullName = declaringType.DeclaringType.FullName; declaringType = declaringType.DeclaringType; } if (string.IsNullOrEmpty(containingClassName)) continue; string scriptPath = string.Empty; int lineNumber = 0; int columnNumber = 0; // This regex pattern matches the word "static" followed by any number of // characters that are not parentheses, braces, or brackets, and then // matches the full word for the field name, // ensuring that the field name is not a part of a longer word. // Note: '([^\\(\\[\\{{])*' -> This part matches zero or more characters // that are not parentheses, braces, or brackets. var regEx = new Regex($"static ([^\\(\\[\\{{])*\\b{curField.Name}\\b", RegexOptions.Compiled); var foundGUIDs = AssetDatabase.FindAssets($"{containingClassName}"); var additionalWarning = string.Empty; // This should be quite rare, but can still happen in case // we have a C# file with a class that does not have the same name // as the file. In that case, we fallback to getting all scripts, // then only going through AssetPostprocessors (or ScriptedImporters) // and then check if the class names match. // If there's a match, we add it to paths if (foundGUIDs.Length == 0) BruteForceFindClassInProject(containingClassFullName, ref foundGUIDs, out additionalWarning); // Getting the scriptPath should happen most of the time // but getting the line number and columnNumber may not always be possible TryExtractInfoForWarningMessage(foundGUIDs, containingClassFullName, regEx, curField, out scriptPath, out lineNumber, out columnNumber); string warningMessage = $"{curField.DeclaringType.FullName} contains static variable: {curField.Name}."; const string additionalInfo = "Using static variables can cause hard to detect bugs when performing parallel imports. This warning can be disabled by placing the [AssetPostprocessorStaticVariableIgnore] attribute over the reported variable."; warnings.Add(new ImportActivityWindow.PostProcessorStaticFieldWarningMessage() { message = warningMessage, additionalInfo = additionalInfo, additionalWarning = additionalWarning, filePath = scriptPath, lineNumber = lineNumber, columnNumber = columnNumber }); } return warnings.ToArray(); } } }
UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/AssetImportWorkerPostProcessorHelper.cs/0
{ "file_path": "UnityCsReference/Modules/AssetDatabase/Editor/V2/Managed/AssetImportWorkerPostProcessorHelper.cs", "repo_id": "UnityCsReference", "token_count": 4974 }
371
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEditor.AssetImporters; namespace UnityEditor { internal class ModelImporterModelEditor : BaseAssetImporterTabUI { #pragma warning disable 0649 // Scene [CacheProperty] SerializedProperty m_GlobalScale; [CacheProperty] SerializedProperty m_UseFileScale; [CacheProperty] SerializedProperty m_FileScale; [CacheProperty] SerializedProperty m_FileScaleUnit; [CacheProperty] SerializedProperty m_FileScaleFactor; [CacheProperty] SerializedProperty m_ImportBlendShapes; [CacheProperty] SerializedProperty m_ImportBlendShapeDeformPercent; [CacheProperty] SerializedProperty m_ImportVisibility; [CacheProperty] protected SerializedProperty m_ImportCameras; [CacheProperty] SerializedProperty m_ImportLights; // Meshes [CacheProperty] SerializedProperty m_MeshCompression; [CacheProperty] SerializedProperty m_IsReadable; [CacheProperty("meshOptimizationFlags")] SerializedProperty m_MeshOptimizationFlags; // Geometry [CacheProperty("keepQuads")] SerializedProperty m_KeepQuads; [CacheProperty("weldVertices")] SerializedProperty m_WeldVertices; [CacheProperty("indexFormat")] protected SerializedProperty m_IndexFormat; [CacheProperty("swapUVChannels")] SerializedProperty m_SwapUVChannels; [CacheProperty("generateSecondaryUV")] SerializedProperty m_GenerateSecondaryUV; bool m_SecondaryUVAdvancedOptions = false; [CacheProperty("secondaryUVAngleDistortion")] SerializedProperty m_SecondaryUVAngleDistortion; [CacheProperty("secondaryUVAreaDistortion")] SerializedProperty m_SecondaryUVAreaDistortion; [CacheProperty("secondaryUVHardAngle")] SerializedProperty m_SecondaryUVHardAngle; [CacheProperty("secondaryUVMarginMethod")] SerializedProperty m_SecondaryUVMarginMethod; [CacheProperty("secondaryUVPackMargin")] SerializedProperty m_SecondaryUVPackMargin; [CacheProperty("secondaryUVMinLightmapResolution")] SerializedProperty m_SecondaryUVMinLightmapResolution; [CacheProperty("secondaryUVMinObjectScale")] SerializedProperty m_SecondaryUVMinObjectScale; [CacheProperty("normalImportMode")] protected SerializedProperty m_NormalImportMode; [CacheProperty("normalCalculationMode")] protected SerializedProperty m_NormalCalculationMode; [CacheProperty("blendShapeNormalImportMode")] SerializedProperty m_BlendShapeNormalCalculationMode; [CacheProperty("legacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes")] SerializedProperty m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes; [CacheProperty("normalSmoothingSource")] SerializedProperty m_NormalSmoothingSource; [CacheProperty("normalSmoothAngle")] protected SerializedProperty m_NormalSmoothAngle; [CacheProperty("tangentImportMode")] protected SerializedProperty m_TangentImportMode; // Prefab [CacheProperty] SerializedProperty m_PreserveHierarchy; [CacheProperty] SerializedProperty m_SortHierarchyByName; [CacheProperty] SerializedProperty m_AddColliders; [CacheProperty("bakeAxisConversion")] SerializedProperty m_BakeAxisConversion; [CacheProperty] SerializedProperty m_StrictVertexDataChecks; #pragma warning restore 0649 public ModelImporterModelEditor(AssetImporterEditor panelContainer) : base(panelContainer) { } internal override void OnEnable() { Editor.AssignCachedProperties(this, serializedObject.GetIterator()); } protected static class Styles { public static GUIContent Scene = EditorGUIUtility.TrTextContent("Scene", "FBX Scene import settings"); public static GUIContent ScaleFactor = EditorGUIUtility.TrTextContent("Scale Factor", "How much to scale the models compared to what is in the source file."); public static GUIContent UseFileScale = EditorGUIUtility.TrTextContent("Convert Units", "Convert file units to Unity ones."); public static GUIContent ImportBlendShapes = EditorGUIUtility.TrTextContent("Import BlendShapes", "Should Unity import BlendShapes."); public static GUIContent ImportBlendShapesDeformPercent = EditorGUIUtility.TrTextContent("Import Deform Percent", "Import BlendShapes deform percent. If disabled, all values will be set to 0."); public static GUIContent ImportVisibility = EditorGUIUtility.TrTextContent("Import Visibility", "Use visibility properties to enable or disable MeshRenderer components."); public static GUIContent ImportCameras = EditorGUIUtility.TrTextContent("Import Cameras"); public static GUIContent ImportLights = EditorGUIUtility.TrTextContent("Import Lights"); public static GUIContent PreserveHierarchy = EditorGUIUtility.TrTextContent("Preserve Hierarchy", "Always create an explicit prefab root, even if the model only has a single root."); public static GUIContent SortHierarchyByName = EditorGUIUtility.TrTextContent("Sort Hierarchy By Name", "Sort game objects children by name."); public static GUIContent StrictVertexDataChecks = EditorGUIUtility.TrTextContent("Strict Vertex Data Checks", "Enables strict checks on Vertex data. If enabled, checks discard invalid data, this may result in missing vertex data but ensures that import results are consistent and can prevent crashes."); public static GUIContent Meshes = EditorGUIUtility.TrTextContent("Meshes", "Global settings for generated meshes"); public static GUIContent MeshCompressionLabel = EditorGUIUtility.TrTextContent("Mesh Compression" , "Higher compression ratio means lower mesh precision. If enabled, the mesh bounds and a lower bit depth per component are used to compress the mesh data."); public static GUIContent IsReadable = EditorGUIUtility.TrTextContent("Read/Write", "Allow vertices and indices to be accessed from script."); public static GUIContent OptimizationFlags = EditorGUIUtility.TrTextContent("Optimize Mesh", "Reorder vertices and/or polygons for better GPU performance."); public static GUIContent GenerateColliders = EditorGUIUtility.TrTextContent("Generate Colliders", "Should Unity generate mesh colliders for all meshes."); public static GUIContent Geometry = EditorGUIUtility.TrTextContent("Geometry", "Detailed mesh data"); public static GUIContent KeepQuads = EditorGUIUtility.TrTextContent("Keep Quads", "If model contains quad faces, they are kept for DX11 tessellation."); public static GUIContent WeldVertices = EditorGUIUtility.TrTextContent("Weld Vertices", "Combine vertices that share the same position in space."); public static GUIContent IndexFormatLabel = EditorGUIUtility.TrTextContent("Index Format", "Format of mesh index buffer. Auto mode picks 16 or 32 bit depending on mesh vertex count."); public static GUIContent NormalsLabel = EditorGUIUtility.TrTextContent("Normals", "Source of mesh normals. If Import is selected and a mesh has no normals, they will be calculated instead."); public static GUIContent RecalculateNormalsLabel = EditorGUIUtility.TrTextContent("Normals Mode", "How to weight faces when calculating normals."); public static GUIContent SmoothingAngle = EditorGUIUtility.TrTextContent("Smoothing Angle", "When calculating normals on a mesh that doesn't have smoothing groups, edges between faces will be smooth if this value is greater than the angle between the faces."); public static GUIContent TangentsLabel = EditorGUIUtility.TrTextContent("Tangents", "Source of mesh tangents. If Import is selected and a mesh has no tangents, they will be calculated instead."); public static GUIContent BlendShapeNormalsLabel = EditorGUIUtility.TrTextContent("Blend Shape Normals", "Source of blend shape normals. If Import is selected and a blend shape has no normals, they will be calculated instead."); public static GUIContent NormalSmoothingSourceLabel = EditorGUIUtility.TrTextContent("Smoothness Source", "How to determine which edges should be smooth and which should be sharp."); public static GUIContent SwapUVChannels = EditorGUIUtility.TrTextContent("Swap UVs", "Swaps the 2 UV channels in meshes. Use if your diffuse texture uses UVs from the lightmap."); public static GUIContent GenerateSecondaryUV = EditorGUIUtility.TrTextContent("Generate Lightmap UVs", "Generate lightmap UVs into UV2."); public static GUIContent GenerateSecondaryUVAdvanced = EditorGUIUtility.TrTextContent("Lightmap UVs settings", "Advanced settings for Lightmap UVs generation"); public static GUIContent secondaryUVAngleDistortion = EditorGUIUtility.TrTextContent("Angle Error", "Measured in percents. Angle error measures deviation of UV angles from geometry angles. Area error measures deviation of UV triangles area from geometry triangles if they were uniformly scaled."); public static GUIContent secondaryUVAreaDistortion = EditorGUIUtility.TrTextContent("Area Error"); public static GUIContent secondaryUVHardAngle = EditorGUIUtility.TrTextContent("Hard Angle", "Angle between neighbor triangles that will generate seam."); public static GUIContent secondaryUVMarginMethod = EditorGUIUtility.TrTextContent("Margin Method", "Method to handle margins between UV charts."); public static GUIContent secondaryUVPackMargin = EditorGUIUtility.TrTextContent("Pack Margin", "Measured in pixels, assuming mesh will cover an entire 1024x1024 lightmap."); public static GUIContent secondaryUVMinLightmapResolution = EditorGUIUtility.TrTextContent("Min Lightmap Resolution", "The minimum lightmap resolution at which this object will be used. Used to determine a packing which ensures no texel bleeding."); public static GUIContent secondaryUVMinObjectScale = EditorGUIUtility.TrTextContent("Min Object Scale", "The smallest scale at which this mesh will be used. Used to determine a packing which ensures no texel bleeding."); public static GUIContent secondaryUVMinLightmapResolutionNotice = EditorGUIUtility.TrTextContent("The active scene's Lightmap Resolution is less than the specified Min Lightmap Resolution.", EditorGUIUtility.GetHelpIcon(MessageType.Info)); public static GUIContent LegacyComputeNormalsFromSmoothingGroupsWhenMeshHasBlendShapes = EditorGUIUtility.TrTextContent("Legacy Blend Shape Normals", "Compute normals from smoothing groups when the mesh has BlendShapes."); public static GUIContent BakeAxisConversion = EditorGUIUtility.TrTextContent("Bake Axis Conversion", "Perform axis conversion on all content for models defined in an axis system that differs from Unity's (left handed, Z forward, Y-up)."); } public override void OnInspectorGUI() { SceneGUI(); MeshesGUI(); GeometryGUI(); } protected void MeshesGUI() { EditorGUILayout.LabelField(Styles.Meshes, EditorStyles.boldLabel); using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var prop = new EditorGUI.PropertyScope(horizontal.rect, Styles.MeshCompressionLabel, m_MeshCompression)) { EditorGUI.BeginChangeCheck(); var newValue = (int)(ModelImporterMeshCompression)EditorGUILayout.EnumPopup(prop.content, (ModelImporterMeshCompression)m_MeshCompression.intValue); if (EditorGUI.EndChangeCheck()) { m_MeshCompression.intValue = newValue; } } } EditorGUILayout.PropertyField(m_IsReadable, Styles.IsReadable); m_MeshOptimizationFlags.intValue = (int)(MeshOptimizationFlags)EditorGUILayout.EnumFlagsField(Styles.OptimizationFlags, (MeshOptimizationFlags)m_MeshOptimizationFlags.intValue); EditorGUILayout.PropertyField(m_AddColliders, Styles.GenerateColliders); } void SceneGUI() { GUILayout.Label(Styles.Scene, EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_GlobalScale, Styles.ScaleFactor); using (var horizontalScope = new EditorGUILayout.HorizontalScope()) { using (var propertyField = new EditorGUI.PropertyScope(horizontalScope.rect, Styles.UseFileScale, m_UseFileScale)) { EditorGUI.showMixedValue = m_UseFileScale.hasMultipleDifferentValues; using (var changed = new EditorGUI.ChangeCheckScope()) { var result = EditorGUILayout.Toggle(propertyField.content, m_UseFileScale.boolValue); if (changed.changed) m_UseFileScale.boolValue = result; } // Put the unit convertion description on a second line if the Inspector is too small. if (!EditorGUIUtility.wideMode) { EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); } using (new EditorGUI.DisabledScope(!m_UseFileScale.boolValue)) { if (!string.IsNullOrEmpty(m_FileScaleUnit.stringValue)) { GUIContent content = m_FileScaleUnit.hasMultipleDifferentValues ? EditorGUI.mixedValueContent : GUIContent.Temp(UnityString.Format(L10n.Tr("1{0} (File) to {1}m (Unity)"), m_FileScaleUnit.stringValue, m_FileScaleFactor.floatValue)); EditorGUILayout.LabelField(content, GUILayout.ExpandWidth(true)); } else { GUIContent content = m_FileScaleUnit.hasMultipleDifferentValues ? EditorGUI.mixedValueContent : GUIContent.Temp(UnityString.Format(L10n.Tr("1 unit (File) to {0}m (Unity)"), m_FileScale.floatValue)); EditorGUILayout.LabelField(content); } } } } EditorGUILayout.PropertyField(m_BakeAxisConversion, Styles.BakeAxisConversion); EditorGUILayout.PropertyField(m_ImportBlendShapes, Styles.ImportBlendShapes); if(m_ImportBlendShapes.boolValue) EditorGUILayout.PropertyField(m_ImportBlendShapeDeformPercent, Styles.ImportBlendShapesDeformPercent); EditorGUILayout.PropertyField(m_ImportVisibility, Styles.ImportVisibility); EditorGUILayout.PropertyField(m_ImportCameras, Styles.ImportCameras); EditorGUILayout.PropertyField(m_ImportLights, Styles.ImportLights); EditorGUILayout.PropertyField(m_PreserveHierarchy, Styles.PreserveHierarchy); EditorGUILayout.PropertyField(m_SortHierarchyByName, Styles.SortHierarchyByName); } protected void GeometryGUI() { GUILayout.Label(Styles.Geometry, EditorStyles.boldLabel); EditorGUILayout.PropertyField(m_KeepQuads, Styles.KeepQuads); EditorGUILayout.PropertyField(m_WeldVertices, Styles.WeldVertices); using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var prop = new EditorGUI.PropertyScope(horizontal.rect, Styles.IndexFormatLabel, m_IndexFormat)) { EditorGUI.BeginChangeCheck(); var newValue = (int)(ModelImporterIndexFormat)EditorGUILayout.EnumPopup(prop.content, (ModelImporterIndexFormat)m_IndexFormat.intValue); if (EditorGUI.EndChangeCheck()) { m_IndexFormat.intValue = newValue; } } } NormalsTangentsGUI(); UvsGUI(); EditorGUILayout.PropertyField(m_StrictVertexDataChecks, Styles.StrictVertexDataChecks); } void NormalsTangentsGUI() { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes.hasMultipleDifferentValues; var legacyComputeFromSmoothingGroups = EditorGUILayout.Toggle(Styles.LegacyComputeNormalsFromSmoothingGroupsWhenMeshHasBlendShapes, m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes.boolValue); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes.boolValue = legacyComputeFromSmoothingGroups; } using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var property = new EditorGUI.PropertyScope(horizontal.rect, Styles.NormalsLabel, m_NormalImportMode)) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = m_NormalImportMode.hasMultipleDifferentValues; var newValue = (int)(ModelImporterNormals)EditorGUILayout.EnumPopup(property.content, (ModelImporterNormals)m_NormalImportMode.intValue); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { m_NormalImportMode.intValue = newValue; // This check is made in CheckConsistency, but because AssetImporterEditor does not serialize the object each update, // We need to double check here for UI consistency. if (m_NormalImportMode.intValue == (int)ModelImporterNormals.None) m_TangentImportMode.intValue = (int)ModelImporterTangents.None; else if (m_NormalImportMode.intValue == (int)ModelImporterNormals.Calculate && m_TangentImportMode.intValue == (int)ModelImporterTangents.Import) m_TangentImportMode.intValue = (int)ModelImporterTangents.CalculateMikk; // Also make the blendshape normal mode follow normal mode, with the exception that we never // select Import automatically (since we can't trust imported normals to be correct, and we // also can't detect when they're not). if (m_NormalImportMode.intValue == (int)ModelImporterNormals.None) m_BlendShapeNormalCalculationMode.intValue = (int)ModelImporterNormals.None; else m_BlendShapeNormalCalculationMode.intValue = (int)ModelImporterNormals.Calculate; } } } if (!m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes.boolValue && m_ImportBlendShapes.boolValue && !m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes.hasMultipleDifferentValues) { using (new EditorGUI.DisabledScope(m_NormalImportMode.intValue == (int)ModelImporterNormals.None)) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = m_BlendShapeNormalCalculationMode.hasMultipleDifferentValues; var blendShapeNormalCalculationMode = (int)(ModelImporterNormals)EditorGUILayout.EnumPopup(Styles.BlendShapeNormalsLabel, (ModelImporterNormals)m_BlendShapeNormalCalculationMode.intValue); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { m_BlendShapeNormalCalculationMode.intValue = blendShapeNormalCalculationMode; } } } if (m_NormalImportMode.intValue != (int)ModelImporterNormals.None || m_BlendShapeNormalCalculationMode.intValue != (int)ModelImporterNormals.None) { // Normal calculation mode using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var property = new EditorGUI.PropertyScope(horizontal.rect, Styles.RecalculateNormalsLabel, m_NormalCalculationMode)) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = m_NormalCalculationMode.hasMultipleDifferentValues; var normalCalculationMode = (int)(ModelImporterNormalCalculationMode)EditorGUILayout.EnumPopup(property.content, (ModelImporterNormalCalculationMode)m_NormalCalculationMode.intValue); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { m_NormalCalculationMode.intValue = normalCalculationMode; } } } // Normal smoothness if (!m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes.boolValue) { using (var horizontal = new EditorGUILayout.HorizontalScope()) using (var property = new EditorGUI.PropertyScope(horizontal.rect, Styles.NormalSmoothingSourceLabel, m_NormalSmoothingSource)) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = m_NormalSmoothingSource.hasMultipleDifferentValues; var normalSmoothingSource = (int)(ModelImporterNormalSmoothingSource)EditorGUILayout.EnumPopup(property.content, (ModelImporterNormalSmoothingSource)m_NormalSmoothingSource.intValue); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { m_NormalSmoothingSource.intValue = normalSmoothingSource; } } } // Normal split angle if (m_LegacyComputeAllNormalsFromSmoothingGroupsWhenMeshHasBlendShapes.boolValue || m_NormalSmoothingSource.intValue == (int)ModelImporterNormalSmoothingSource.PreferSmoothingGroups || m_NormalSmoothingSource.intValue == (int)ModelImporterNormalSmoothingSource.FromAngle) { EditorGUI.BeginChangeCheck(); EditorGUILayout.Slider(m_NormalSmoothAngle, 0, 180, Styles.SmoothingAngle); // Property is serialized as float but we want to show it as an int so we round the value when changed if (EditorGUI.EndChangeCheck()) m_NormalSmoothAngle.floatValue = Mathf.Round(m_NormalSmoothAngle.floatValue); } } // Choose the option values and labels based on what the NormalImportMode is if (m_NormalImportMode.intValue != (int)ModelImporterNormals.None) { using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var property = new EditorGUI.PropertyScope(horizontal.rect, Styles.TangentsLabel, m_TangentImportMode)) { EditorGUI.BeginChangeCheck(); var newValue = (int)(ModelImporterTangents)EditorGUILayout.EnumPopup(property.content, (ModelImporterTangents)m_TangentImportMode.intValue, TangentModeAvailabilityCheck, false); if (EditorGUI.EndChangeCheck()) { m_TangentImportMode.intValue = newValue; } } } } } protected bool TangentModeAvailabilityCheck(Enum value) { return (int)(ModelImporterTangents)value >= m_NormalImportMode.intValue; } protected void UvsGUI() { EditorGUILayout.PropertyField(m_SwapUVChannels, Styles.SwapUVChannels); EditorGUILayout.PropertyField(m_GenerateSecondaryUV, Styles.GenerateSecondaryUV); if (m_GenerateSecondaryUV.boolValue) { m_SecondaryUVAdvancedOptions = EditorGUILayout.Foldout(m_SecondaryUVAdvancedOptions, Styles.GenerateSecondaryUVAdvanced, true, EditorStyles.foldout); if (m_SecondaryUVAdvancedOptions) { using (new EditorGUI.IndentLevelScope()) { EditorGUI.BeginChangeCheck(); EditorGUILayout.Slider(m_SecondaryUVHardAngle, 0, 180, Styles.secondaryUVHardAngle); EditorGUILayout.Slider(m_SecondaryUVAngleDistortion, 1, 75, Styles.secondaryUVAngleDistortion); EditorGUILayout.Slider(m_SecondaryUVAreaDistortion, 1, 75, Styles.secondaryUVAreaDistortion); using (var horizontal = new EditorGUILayout.HorizontalScope()) { using (var prop = new EditorGUI.PropertyScope(horizontal.rect, Styles.secondaryUVMarginMethod, m_SecondaryUVMarginMethod)) { EditorGUI.BeginChangeCheck(); var newValue = (int)(ModelImporterSecondaryUVMarginMethod)EditorGUILayout.EnumPopup(prop.content, (ModelImporterSecondaryUVMarginMethod)m_SecondaryUVMarginMethod.intValue); if (EditorGUI.EndChangeCheck()) { m_SecondaryUVMarginMethod.intValue = newValue; } } } if (m_SecondaryUVMarginMethod.intValue == (int)ModelImporterSecondaryUVMarginMethod.Calculate) { EditorGUILayout.PropertyField(m_SecondaryUVMinLightmapResolution, Styles.secondaryUVMinLightmapResolution); if (Lightmapping.GetLightingSettingsOrDefaultsFallback().lightmapResolution < m_SecondaryUVMinLightmapResolution.floatValue) { EditorGUILayout.HelpBox(Styles.secondaryUVMinLightmapResolutionNotice); } EditorGUILayout.PropertyField(m_SecondaryUVMinObjectScale, Styles.secondaryUVMinObjectScale); } else { EditorGUILayout.Slider(m_SecondaryUVPackMargin, 1, 64, Styles.secondaryUVPackMargin); } if (EditorGUI.EndChangeCheck()) { m_SecondaryUVHardAngle.floatValue = Mathf.Round(m_SecondaryUVHardAngle.floatValue); m_SecondaryUVPackMargin.floatValue = Mathf.Round(m_SecondaryUVPackMargin.floatValue); m_SecondaryUVMinLightmapResolution.floatValue = Mathf.Round(m_SecondaryUVMinLightmapResolution.floatValue); m_SecondaryUVMinObjectScale.floatValue = m_SecondaryUVMinObjectScale.floatValue; m_SecondaryUVAngleDistortion.floatValue = Mathf.Round(m_SecondaryUVAngleDistortion.floatValue); m_SecondaryUVAreaDistortion.floatValue = Mathf.Round(m_SecondaryUVAreaDistortion.floatValue); } } } } } } }
UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterModelEditor.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/ImportSettings/ModelImporterModelEditor.cs", "repo_id": "UnityCsReference", "token_count": 12421 }
372
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; using UnityEngine.Scripting.APIUpdating; namespace UnityEditor.AssetImporters { // Class Concept: Root, abstract class for all Asset importers implemented in C#. [ExtensionOfNativeClass] [Preserve] [UsedByNativeCode] [MovedFrom("UnityEditor.Experimental.AssetImporters")] [NativeHeader("Modules/AssetPipelineEditor/Public/ScriptedImporter.h")] public abstract class ScriptedImporter : AssetImporter { // Called by native code to invoke the import handling code of the specialized scripted importer class. // Marshals the data between the two models (native / managed) [RequiredByNativeCode] void GenerateAssetData(AssetImportContext ctx) { OnImportAsset(ctx); } public abstract void OnImportAsset(AssetImportContext ctx); public new virtual bool SupportsRemappedAssetType(Type type) { return false; } [RequiredByNativeCode] private static bool SupportsRemappedAssetTypeProxy(ScriptedImporter importer, Type type) { return importer.SupportsRemappedAssetType(type); } static bool IsStaticMethodInClassOrParent(Type type, string methodName) { var baseClass = typeof(ScriptedImporter); while (type != null && type != baseClass) { // we have to look for each parent on by one because BindingFlags.FlattenHierarchy cannot find private methods in parent classes. if (type.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) != null) return true; type = type.BaseType; } return false; } [RequiredByNativeCode] internal static void RegisterScriptedImporters() { //Find the types with the 'ScriptedImporter' attribute which also derive from 'ScriptedImporter' var importers = new List<Type>(); foreach (var type in TypeCache.GetTypesWithAttribute<ScriptedImporterAttribute>()) if (type.IsSubclassOf(typeof(ScriptedImporter))) importers.Add(type); else Debug.LogError(String.Format("{0} has a 'ScriptedImporter' Attribute but is not a subclass of 'ScriptedImporter'.", type.ToString())); ScriptedImporterAttribute[] scriptedImporterAttributes = new ScriptedImporterAttribute[importers.Count]; SortedDictionary<string, bool>[] handledExtensions = new SortedDictionary<string, bool>[importers.Count]; Dictionary<string, List<int>> importersByExtension = new Dictionary<string, List<int>>(); // Build a dictionary of which importers are trying to register each extension that we can use to quickly find conflicts // (i.e. if an entry in the extension-keyed dictionary has a list of importers with more than one entry) for (var importerIndex = 0; importerIndex < importers.Count; importerIndex++) { Type importer = importers[importerIndex]; scriptedImporterAttributes[importerIndex] = Attribute.GetCustomAttribute(importer, typeof(ScriptedImporterAttribute)) as ScriptedImporterAttribute; handledExtensions[importerIndex] = GetHandledExtensionsByImporter(scriptedImporterAttributes[importerIndex]); if (handledExtensions[importerIndex].Count == 0) Debug.LogError($"The ScriptedImporter {importer.FullName} does not provide any non-null file extension."); foreach (KeyValuePair<string, bool> handledExtension in handledExtensions[importerIndex]) { // Only consider AutoSelected ones if (handledExtension.Value) { // Add this importer to the dictionary entry for this file extension, creating it if not already present if (!importersByExtension.TryGetValue(handledExtension.Key, out List<int> importerIndicesForThisExtension)) { importerIndicesForThisExtension = new List<int>(); importersByExtension.Add(handledExtension.Key, importerIndicesForThisExtension); } importerIndicesForThisExtension.Add(importerIndex); } } } // Check each AutoSelected extension we found, any of them that have more than one importer associated with them are rejected (i.e. removed from all importers that provided them) foreach (KeyValuePair<string, List<int>> importerExtension in importersByExtension) { if (importerExtension.Value.Count > 1) { string rejectedImporters = ""; foreach (int importerIndex in importerExtension.Value) { handledExtensions[importerIndex].Remove(importerExtension.Key); if (rejectedImporters.Length != 0) rejectedImporters = $"{rejectedImporters}, "; rejectedImporters = $"{rejectedImporters}{importers[importerIndex].FullName} (assembly: {importers[importerIndex].Module.FullyQualifiedName})"; } Debug.LogError(String.Format("Multiple scripted importers are targeting the extension '{0}' and have all been rejected: {1} ", importerExtension.Key, rejectedImporters)); } } for (var index = 0; index < importers.Count; index++) { var importer = importers[index]; var attribute = scriptedImporterAttributes[index]; var handledExts = handledExtensions[index]; if (handledExts.Count > 0) { var supportsImportDependencyHinting = (importer.GetMethod("GetHashOfImportedAssetDependencyHintsForTesting", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static) != null) || IsStaticMethodInClassOrParent(importer, "GatherDependenciesFromSourceFile"); // Register the importer foreach (var ext in handledExts) AssetImporter.RegisterImporter(importer, attribute.version, attribute.importQueuePriority, ext.Key, supportsImportDependencyHinting, ext.Value, attribute.AllowCaching); } } } static SortedDictionary<string, bool> GetHandledExtensionsByImporter(ScriptedImporterAttribute attribute) { var handledExts = new SortedDictionary<string, bool>(); if (attribute.fileExtensions != null) { var fileExtensions = attribute.fileExtensions.Distinct(StringComparer.OrdinalIgnoreCase); foreach (var fileExtension in fileExtensions) { var cleanExt = fileExtension.Trim('.'); if (!string.IsNullOrEmpty(cleanExt)) handledExts.Add(cleanExt, true); } } if (attribute.overrideFileExtensions != null) { var overrideFileExtensions = attribute.overrideFileExtensions.Distinct(StringComparer.OrdinalIgnoreCase); foreach (var fileExtension in overrideFileExtensions) { var cleanExt = fileExtension.Trim('.'); if (!string.IsNullOrEmpty(cleanExt) && !handledExts.ContainsKey(cleanExt)) handledExts.Add(cleanExt, false); } } return handledExts; } internal extern static void UnregisterScriptedImporters(); } // Class Concept: Class attribute that describes Scriptable importers and their static characteristics. [AttributeUsage(AttributeTargets.Class, Inherited = false)] [MovedFrom("UnityEditor.Experimental.AssetImporters")] public class ScriptedImporterAttribute : Attribute { public int version { get; private set; } // Gives control over when the asset is imported with regards to assets of other types. // Positive values delay the processing of source asset files while Negative values place them earlier in the import process. public int importQueuePriority { get; private set; } public string[] fileExtensions { get; private set; } public string[] overrideFileExtensions { get; private set; } [Obsolete("Use overrideFileExtensions instead to specify this importer is an override for those file extensions",true)] public bool AutoSelect = true; public bool AllowCaching = false; public ScriptedImporterAttribute(int version, string ext) { Init(version, new[] { ext }, null, 0); } public ScriptedImporterAttribute(int version, string ext, int importQueueOffset) { Init(version, new[] { ext }, null, importQueueOffset); } public ScriptedImporterAttribute(int version, string[] exts) { Init(version, exts, null, 0); } public ScriptedImporterAttribute(int version, string[] exts, string[] overrideExts) { Init(version, exts, overrideExts, 0); } public ScriptedImporterAttribute(int version, string[] exts, int importQueueOffset) { Init(version, exts, null, importQueueOffset); } public ScriptedImporterAttribute(int version, string[] exts, string[] overrideExts, int importQueueOffset) { Init(version, exts, overrideExts, importQueueOffset); } private void Init(int version, string[] exts, string[] overrideExts, int importQueueOffset) { this.version = version; this.importQueuePriority = importQueueOffset; fileExtensions = exts; this.overrideFileExtensions = overrideExts; } } } // The following block is to make sure scripts with unnecessary using directive of Experimental.AssetImporters compile // Should be removed after API updater addresses this kind of migration. namespace UnityEditor.Experimental.AssetImporters { class PlaceholderEmptyClassForDeprecatedExperimentalAssetImporters {} }
UnityCsReference/Modules/AssetPipelineEditor/Public/ScriptedImporter.cs/0
{ "file_path": "UnityCsReference/Modules/AssetPipelineEditor/Public/ScriptedImporter.cs", "repo_id": "UnityCsReference", "token_count": 4517 }
373
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.Bindings; namespace UnityEngine.Audio; enum AudioRandomContainerTriggerMode { Manual = 0, Automatic = 1 } enum AudioRandomContainerPlaybackMode { Sequential = 0, Shuffle = 1, Random = 2 } enum AudioRandomContainerAutomaticTriggerMode { Pulse = 0, Offset = 1 } enum AudioRandomContainerLoopMode { Infinite = 0, Clips = 1, Cycles = 2 } [NativeHeader("Modules/Audio/Public/AudioContainerElement.h")] sealed class AudioContainerElement : Object { internal AudioContainerElement() { Internal_Create(this); } internal extern AudioClip audioClip { get; set; } internal extern float volume { get; set; } internal extern bool enabled { get; set; } static extern void Internal_Create([Writable] AudioContainerElement self); } [NativeHeader("Modules/Audio/Public/AudioRandomContainer.h")] [ExcludeFromPreset] sealed class AudioRandomContainer : AudioResource { internal enum ChangeEventType { Volume, Pitch, List }; internal AudioRandomContainer() { Internal_Create(this); } internal extern float volume { get; set; } internal extern Vector2 volumeRandomizationRange { get; set; } internal extern bool volumeRandomizationEnabled { get; set; } internal extern float pitch { get; set; } internal extern Vector2 pitchRandomizationRange { get; set; } internal extern bool pitchRandomizationEnabled { get; set; } // Note: list changes will implicitly stop and reset playback internal extern AudioContainerElement[] elements { get; set; } internal extern AudioRandomContainerTriggerMode triggerMode { get; set; } internal extern AudioRandomContainerPlaybackMode playbackMode { get; set; } internal extern int avoidRepeatingLast { get; set; } internal extern AudioRandomContainerAutomaticTriggerMode automaticTriggerMode { get; set; } internal extern float automaticTriggerTime { get; set; } internal extern Vector2 automaticTriggerTimeRandomizationRange { get; set; } internal extern bool automaticTriggerTimeRandomizationEnabled { get; set; } internal extern AudioRandomContainerLoopMode loopMode { get; set; } internal extern int loopCount { get; set; } internal extern Vector2 loopCountRandomizationRange { get; set; } internal extern bool loopCountRandomizationEnabled { get; set; } // Note: list changes will implicitly stop and reset playback internal extern void NotifyObservers(ChangeEventType eventType); static extern void Internal_Create([Writable] AudioRandomContainer self); }
UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioRandomContainer.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Audio/Public/ScriptBindings/AudioRandomContainer.bindings.cs", "repo_id": "UnityCsReference", "token_count": 868 }
374
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor; using UnityEngine; using UnityEngine.Scripting; using System.Collections.Generic; namespace UnityEditor.Build { internal delegate void GetScriptCompilationDefinesDelegate(BuildTarget target, HashSet<string> defines); [RequiredByNativeCode] internal class BuildDefines { public static event GetScriptCompilationDefinesDelegate getScriptCompilationDefinesDelegates; [RequiredByNativeCode] public static string[] GetScriptCompilationDefines(BuildTarget target, string[] defines) { var hashSet = new HashSet<string>(defines); if (getScriptCompilationDefinesDelegates != null) getScriptCompilationDefinesDelegates(target, hashSet); var array = new string[hashSet.Count]; hashSet.CopyTo(array); return array; } } }
UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildDefines.cs/0
{ "file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/BuildDefines.cs", "repo_id": "UnityCsReference", "token_count": 365 }
375
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; using System.Collections.Generic; namespace UnityEditor.Build.Player { public enum ScriptCompilationOptions { None = 0, DevelopmentBuild = 1 << 0, Assertions = 1 << 1 } [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] public struct ScriptCompilationSettings { [NativeName("subtarget")] internal int m_Subtarget; public int subtarget { get { return m_Subtarget; } set { m_Subtarget = value; } } [NativeName("target")] internal BuildTarget m_Target; public BuildTarget target { get { return m_Target; } set { m_Target = value; } } [NativeName("group")] internal BuildTargetGroup m_Group; public BuildTargetGroup group { get { return m_Group; } set { m_Group = value; } } [NativeName("options")] internal ScriptCompilationOptions m_Options; public ScriptCompilationOptions options { get { return m_Options; } set { m_Options = value; } } [NativeName("resultTypeDB")] internal TypeDB m_ResultTypeDB; [NativeName("extraScriptingDefines")] internal string[] m_ExtraScriptingDefines; public string[] extraScriptingDefines { get { return m_ExtraScriptingDefines; } set { m_ExtraScriptingDefines = value; } } } [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] public struct ScriptCompilationResult { [NativeName("assemblies")] internal string[] m_Assemblies; public ReadOnlyCollection<string> assemblies { get { return Array.AsReadOnly(m_Assemblies); } } [Ignore] internal TypeDB m_TypeDB; public TypeDB typeDB { get { return m_TypeDB; } } } [NativeHeader("Modules/BuildPipeline/Editor/Public/PlayerBuildInterface.h")] public static class PlayerBuildInterface { public static Func<IEnumerable<string>> ExtraTypesProvider; [FreeFunction(Name = "BuildPipeline::CompilePlayerScripts")] extern private static ScriptCompilationResult CompilePlayerScriptsNative(ScriptCompilationSettings input, string outputFolder, bool editorScripts); public static ScriptCompilationResult CompilePlayerScripts(ScriptCompilationSettings input, string outputFolder) { return CompilePlayerScriptsInternal(input, outputFolder, false); } internal static ScriptCompilationResult CompilePlayerScriptsInternal(ScriptCompilationSettings input, string outputFolder, bool editorScripts) { input.m_ResultTypeDB = new TypeDB(); ScriptCompilationResult result = CompilePlayerScriptsNative(input, outputFolder, editorScripts); result.m_TypeDB = result.m_Assemblies.Length != 0 ? input.m_ResultTypeDB : null; return result; } } }
UnityCsReference/Modules/BuildPipeline/Editor/Managed/PlayerBuildInterface.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/BuildPipeline/Editor/Managed/PlayerBuildInterface.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1339 }
376
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Build.Profile.Elements { /// <summary> /// Dropdown Button exported from <see cref="BuildPlayerWindow"/>, /// as UIToolkit does not support DropdownButton. /// </summary> internal class DropdownButton : VisualElement { const int k_ButtonWidth = 120; readonly GenericMenu m_Menu; readonly GUIContent m_BuildButton; readonly Action m_DefaultClicked; public DropdownButton(string text, Action defaultClicked, GenericMenu menu) { this.m_Menu = menu; m_BuildButton = new GUIContent(text); m_DefaultClicked = defaultClicked; Add(new IMGUIContainer(RenderIMGUI)); } public void SetText(string text) { m_BuildButton.text = text; } void RenderIMGUI() { Rect buildRect = GUILayoutUtility.GetRect(m_BuildButton, BuildProfileModuleUtil.dropDownToggleButton, GUILayout.Width(k_ButtonWidth)); Rect buildRectPopupButton = buildRect; buildRectPopupButton.x += buildRect.width - 16; buildRectPopupButton.width = 16; if (m_Menu != null && EditorGUI.DropdownButton(buildRectPopupButton, GUIContent.none, FocusType.Passive, GUIStyle.none)) { m_Menu.DropDown(buildRect); } else { GUIStyle style = m_Menu == null ? GUI.skin.button : BuildProfileModuleUtil.dropDownToggleButton; if (GUI.Button(buildRect, m_BuildButton, style)) { m_DefaultClicked(); } } } } }
UnityCsReference/Modules/BuildProfileEditor/Elements/DropdownButton.cs/0
{ "file_path": "UnityCsReference/Modules/BuildProfileEditor/Elements/DropdownButton.cs", "repo_id": "UnityCsReference", "token_count": 870 }
377
// 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 { namespace Build.Reporting { [NativeType(Header = "Modules/BuildReportingEditor/Public/CommonRoles.h")] public static class CommonRoles { [NativeProperty("BuildReporting::CommonRoles::scene", true, TargetType.Field)] public static extern string scene { get; } [NativeProperty("BuildReporting::CommonRoles::sharedAssets", true, TargetType.Field)] public static extern string sharedAssets { get; } [NativeProperty("BuildReporting::CommonRoles::resourcesFile", true, TargetType.Field)] public static extern string resourcesFile { get; } [NativeProperty("BuildReporting::CommonRoles::assetBundle", true, TargetType.Field)] public static extern string assetBundle { get; } [NativeProperty("BuildReporting::CommonRoles::manifestAssetBundle", true, TargetType.Field)] public static extern string manifestAssetBundle { get; } [NativeProperty("BuildReporting::CommonRoles::assetBundleTextManifest", true, TargetType.Field)] public static extern string assetBundleTextManifest { get; } [NativeProperty("BuildReporting::CommonRoles::managedLibrary", true, TargetType.Field)] public static extern string managedLibrary { get; } [NativeProperty("BuildReporting::CommonRoles::dependentManagedLibrary", true, TargetType.Field)] public static extern string dependentManagedLibrary { get; } [NativeProperty("BuildReporting::CommonRoles::executable", true, TargetType.Field)] public static extern string executable { get; } [NativeProperty("BuildReporting::CommonRoles::streamingResourceFile", true, TargetType.Field)] public static extern string streamingResourceFile { get; } [NativeProperty("BuildReporting::CommonRoles::streamingAsset", true, TargetType.Field)] public static extern string streamingAsset { get; } [NativeProperty("BuildReporting::CommonRoles::bootConfig", true, TargetType.Field)] public static extern string bootConfig { get; } [NativeProperty("BuildReporting::CommonRoles::builtInResources", true, TargetType.Field)] public static extern string builtInResources { get; } [NativeProperty("BuildReporting::CommonRoles::builtInShaders", true, TargetType.Field)] public static extern string builtInShaders { get; } [NativeProperty("BuildReporting::CommonRoles::appInfo", true, TargetType.Field)] public static extern string appInfo { get; } [NativeProperty("BuildReporting::CommonRoles::managedEngineAPI", true, TargetType.Field)] public static extern string managedEngineApi { get; } [NativeProperty("BuildReporting::CommonRoles::monoRuntime", true, TargetType.Field)] public static extern string monoRuntime { get; } [NativeProperty("BuildReporting::CommonRoles::monoConfig", true, TargetType.Field)] public static extern string monoConfig { get; } [NativeProperty("BuildReporting::CommonRoles::debugInfo", true, TargetType.Field)] public static extern string debugInfo { get; } [NativeProperty("BuildReporting::CommonRoles::globalGameManagers", true, TargetType.Field)] public static extern string globalGameManagers { get; } [NativeProperty("BuildReporting::CommonRoles::crashHandler", true, TargetType.Field)] public static extern string crashHandler { get; } [NativeProperty("BuildReporting::CommonRoles::engineLibrary", true, TargetType.Field)] public static extern string engineLibrary { get; } } } }
UnityCsReference/Modules/BuildReportingEditor/Managed/CommonRoles.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/BuildReportingEditor/Managed/CommonRoles.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1416 }
378
// 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; namespace UnityEngine { [NativeHeader("Modules/ClusterRenderer/ClusterNetwork.h")] public class ClusterNetwork { public static extern bool isMasterOfCluster { get; } public static extern bool isDisconnected { get; } public static extern int nodeIndex { get; set; } } }
UnityCsReference/Modules/ClusterRenderer/ClusterRenderer.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ClusterRenderer/ClusterRenderer.bindings.cs", "repo_id": "UnityCsReference", "token_count": 172 }
379
// 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.Serialization.Json; using System.Text; using System.Xml; using System.Xml.Linq; using UnityEditor.AssetImporters; using UnityEngine; using UnityEngine.Rendering; namespace UnityEditor.DeviceSimulation { [ScriptedImporter(1, "device")] internal class DeviceInfoImporter : ScriptedImporter { public override void OnImportAsset(AssetImportContext ctx) { SimulatorWindow.MarkAllDeviceListsDirty(); var asset = ScriptableObject.CreateInstance<DeviceInfoAsset>(); var deviceJson = File.ReadAllText(ctx.assetPath); asset.deviceInfo = ParseDeviceInfo(deviceJson, out var errors, out var systemInfoElement, out var graphicsDataElement); if (errors.Length > 0) { asset.parseErrors = errors; } else { FindOptionalFieldAvailability(asset, systemInfoElement, graphicsDataElement); AddOptionalFields(asset.deviceInfo); // Saving asset path in order to find overlay relatively to it asset.directory = Path.GetDirectoryName(ctx.assetPath); ctx.DependsOnSourceAsset(ctx.assetPath); } ctx.AddObjectToAsset("main obj", asset); ctx.SetMainObject(asset); } internal struct GraphicsTypeElement { public GraphicsDeviceType type; public XElement element; } internal static DeviceInfo ParseDeviceInfo(string deviceJsonText, out string[] errors, out XElement systemInfoElement, out List<GraphicsTypeElement> graphicsTypeElements) { var errorList = new List<string>(); graphicsTypeElements = new List<GraphicsTypeElement>(); XElement root; DeviceInfo deviceInfo; try { root = XElement.Load(JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(deviceJsonText), new XmlDictionaryReaderQuotas())); deviceInfo = JsonUtility.FromJson<DeviceInfo>(deviceJsonText); } catch (Exception) { errorList.Add("Failed parsing JSON. Make sure this is a valid JSON file."); errors = errorList.ToArray(); systemInfoElement = null; return null; } var versionElement = root.Element("version"); if (versionElement == null) errorList.Add("Mandatory field [version] is missing"); else if (versionElement.Value != "1") errorList.Add("[version] field is set to an unknown value. The newest version is 1"); var friendlyNameElement = root.Element("friendlyName"); if (friendlyNameElement == null) errorList.Add("Mandatory field [friendlyName] is missing"); else if (string.IsNullOrEmpty(friendlyNameElement.Value)) errorList.Add("[friendlyName] field is empty, which is not allowed"); systemInfoElement = root.Element("systemInfo"); if (systemInfoElement == null) errorList.Add("Mandatory field [systemInfo] is missing"); else { var operatingSystemElement = systemInfoElement.Element("operatingSystem"); if (operatingSystemElement == null) errorList.Add("Mandatory field [systemInfo -> operatingSystem] is missing. [operatingSystem] must be set to a string containing either <android> or <ios>"); else if (!operatingSystemElement.Value.ToLower().Contains("android") && !operatingSystemElement.Value.ToLower().Contains("ios")) errorList.Add("[systemInfo -> operatingSystem] field must be set to a string containing either <android> or <ios>, other platforms are not supported at the moment"); var graphicsSystemInfoArray = systemInfoElement.Element("graphicsDependentData"); if (graphicsSystemInfoArray != null) { var graphicsSystemInfo = graphicsSystemInfoArray.Elements("item").ToArray(); var graphicsTypes = new HashSet<GraphicsDeviceType>(); for (int i = 0; i < graphicsSystemInfo.Length; i++) { var graphicsDeviceElement = graphicsSystemInfo[i].Element("graphicsDeviceType"); if (graphicsDeviceElement == null) errorList.Add($"Mandatory field [systemInfo -> graphicsDependentData[{i}] -> graphicsDeviceType] is missing. [graphicsDependentData] must contain [graphicsDeviceType]"); else if (!int.TryParse(graphicsDeviceElement.Value, out var typeInt) || !Enum.IsDefined(typeof(GraphicsDeviceType), typeInt)) errorList.Add($"[systemInfo -> graphicsDependentData[{i}] -> graphicsDeviceType] is set to a value that could not be parsed as GraphicsDeviceType"); else { var type = deviceInfo.systemInfo.graphicsDependentData[i].graphicsDeviceType; if (graphicsTypes.Contains(type)) errorList.Add($"Multiple [systemInfo -> graphicsDependentData] fields have the same GraphicsDeviceType {type}."); else graphicsTypes.Add(type); graphicsTypeElements.Add(new GraphicsTypeElement {element = graphicsSystemInfo[i], type = type}); } } } } var screensElement = root.Element("screens"); if (screensElement == null) errorList.Add("Mandatory field [screens] is missing. [screens] array must contain at least one screen"); else { var screenElements = screensElement.Elements("item").ToArray(); if (!screenElements.Any()) { errorList.Add("[screens] array must contain at least one screen"); } else { for (var i = 0; i < screenElements.Length; i++) { var screen = deviceInfo.screens[i]; if (screenElements[i].Element("width") == null) errorList.Add($"Mandatory field [screens[{i}] -> width] is missing"); else if (screen.width < 4 || screen.width > 8192) errorList.Add($"[screens[{i}] -> width] field is set to an incorrect value {screen.width}. Screen width must be larger than 4 and smaller than 8192."); if (screenElements[i].Element("height") == null) errorList.Add($"Mandatory field [screens[{i}] -> height] is missing"); else if (screen.height < 4 || screen.height > 8192) errorList.Add($"[screens[{i}] -> height] field is set to an incorrect value {screen.height}. Screen height must be larger than 4 and smaller than 8192."); if (screenElements[i].Element("dpi") == null) errorList.Add($"Mandatory field [screens[{i}] -> dpi] is missing"); else if (screen.dpi < 0.0001f || screen.dpi > 10000f) errorList.Add($"[screens[{i}] -> dpi] field is set to an incorrect value {screen.dpi}. Screen dpi must be larger than 0 and smaller than 10000."); } } } errors = errorList.ToArray(); return errors.Length == 0 ? deviceInfo : null; } internal static void AddOptionalFields(DeviceInfo deviceInfo) { foreach (var screen in deviceInfo.screens) { if (screen.orientations == null || screen.orientations.Length == 0) { screen.orientations = new[] { new OrientationData {orientation = ScreenOrientation.Portrait}, new OrientationData {orientation = ScreenOrientation.PortraitUpsideDown}, new OrientationData {orientation = ScreenOrientation.LandscapeLeft}, new OrientationData {orientation = ScreenOrientation.LandscapeRight} }; } foreach (var orientation in screen.orientations) { if (orientation.safeArea == Rect.zero) orientation.safeArea = SimulatorUtilities.IsLandscape(orientation.orientation) ? new Rect(0, 0, screen.height, screen.width) : new Rect(0, 0, screen.width, screen.height); } } } internal static void FindOptionalFieldAvailability(DeviceInfoAsset asset, XElement systemInfoElement, List<GraphicsTypeElement> graphicsDataElements) { string[] systemInfoFields = { "deviceModel", "deviceType", "operatingSystemFamily", "processorCount", "processorFrequency", "processorType", "processorModel", "processorManufacturer", "supportsAccelerometer", "supportsAudio", "supportsGyroscope", "supportsLocationService", "supportsVibration", "systemMemorySize" }; string[] graphicsSystemInfoFields = { "graphicsMemorySize", "graphicsDeviceName", "graphicsDeviceVendor", "graphicsDeviceID", "graphicsDeviceVendorID", "graphicsUVStartsAtTop", "graphicsDeviceVersion", "graphicsShaderLevel", "graphicsMultiThreaded", "renderingThreadingMode", "foveatedRenderingCaps", "hasHiddenSurfaceRemovalOnGPU", "hasDynamicUniformArrayIndexingInFragmentShaders", "supportsShadows", "supportsRawShadowDepthSampling", "supportsMotionVectors", "supports3DTextures", "supports2DArrayTextures", "supports3DRenderTextures", "supportsCubemapArrayTextures", "copyTextureSupport", "supportsComputeShaders", "supportsGeometryShaders", "supportsTessellationShaders", "supportsInstancing", "supportsHardwareQuadTopology", "supports32bitsIndexBuffer", "supportsSparseTextures", "supportedRenderTargetCount", "supportsSeparatedRenderTargetsBlend", "supportedRandomWriteTargetCount", "supportsMultisampledTextures", "supportsMultisampleAutoResolve", "supportsTextureWrapMirrorOnce", "usesReversedZBuffer", "npotSupport", "maxTextureSize", "maxCubemapSize", "maxComputeBufferInputsVertex", "maxComputeBufferInputsFragment", "maxComputeBufferInputsGeometry", "maxComputeBufferInputsDomain", "maxComputeBufferInputsHull", "maxComputeBufferInputsCompute", "maxComputeWorkGroupSize", "maxComputeWorkGroupSizeX", "maxComputeWorkGroupSizeY", "maxComputeWorkGroupSizeZ", "supportsAsyncCompute", "supportsGraphicsFence", "supportsAsyncGPUReadback", "supportsRayTracing", "supportsRayTracingShaders", "supportsInlineRayTracing", "supportsIndirectDispatchRays", "supportsSetConstantBuffer", "hasMipMaxLevel", "supportsMipStreaming", "usesLoadStoreActions" }; foreach (var field in systemInfoFields) { if (systemInfoElement.Element(field) != null) asset.availableSystemInfoFields.Add(field); } foreach (var graphicsDataElement in graphicsDataElements) { var availableFields = new HashSet<string>(); asset.availableGraphicsSystemInfoFields.Add(graphicsDataElement.type, availableFields); foreach (var field in graphicsSystemInfoFields) { if (graphicsDataElement.element.Element(field) != null) availableFields.Add(field); } } } } }
UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfoImporter.cs/0
{ "file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/DeviceInfo/DeviceInfoImporter.cs", "repo_id": "UnityCsReference", "token_count": 6465 }
380
// 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.DeviceSimulation { [Serializable] internal class SimulatorState : ISerializationCallbackReceiver { public bool controlPanelVisible; public float controlPanelWidth; public Dictionary<string, bool> controlPanelFoldouts = new Dictionary<string, bool>(); [SerializeField] private List<string> controlPanelFoldoutKeys = new List<string>(); [SerializeField] private List<bool> controlPanelFoldoutValues = new List<bool>(); public Dictionary<string, string> plugins = new Dictionary<string, string>(); [SerializeField] private List<string> pluginNames = new List<string>(); [SerializeField] private List<string> pluginStates = new List<string>(); public int scale; public bool fitToScreenEnabled = true; public int rotationDegree; public bool highlightSafeAreaEnabled; public string friendlyName = string.Empty; public int screenIndex = 0; public NetworkReachability networkReachability = NetworkReachability.ReachableViaCarrierDataNetwork; public SystemLanguage systemLanguage = SystemLanguage.English; public void OnBeforeSerialize() { foreach (var plugin in plugins) { pluginNames.Add(plugin.Key); pluginStates.Add(plugin.Value); } foreach (var foldout in controlPanelFoldouts) { controlPanelFoldoutKeys.Add(foldout.Key); controlPanelFoldoutValues.Add(foldout.Value); } } public void OnAfterDeserialize() { for (int index = 0; index < pluginNames.Count; ++index) { plugins.Add(pluginNames[index], pluginStates[index]); } for (int index = 0; index < controlPanelFoldoutKeys.Count; ++index) { controlPanelFoldouts.Add(controlPanelFoldoutKeys[index], controlPanelFoldoutValues[index]); } } } }
UnityCsReference/Modules/DeviceSimulatorEditor/SimulatorState.cs/0
{ "file_path": "UnityCsReference/Modules/DeviceSimulatorEditor/SimulatorState.cs", "repo_id": "UnityCsReference", "token_count": 910 }
381
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.EditorTools; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Toolbars { sealed class EditorToolContextButton<T> : EditorToolbarToggle where T : EditorToolContext { T m_Context; public EditorToolContextButton(T ctx) { m_Context = ctx; GUIContent content = EditorToolUtility.GetToolbarIcon(m_Context); tooltip = content.tooltip; icon = content.image as Texture2D; this.RegisterValueChangedCallback(evt => { EditorToolManager.activeToolContext = evt.newValue ? m_Context : null; }); RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); UpdateState(); } void UpdateState() { SetValueWithoutNotify(ToolManager.IsActiveContext(m_Context)); } void OnAttachedToPanel(AttachToPanelEvent evt) => ToolManager.activeContextChanged += UpdateState; void OnDetachFromPanel(DetachFromPanelEvent evt) => ToolManager.activeContextChanged -= UpdateState; } }
UnityCsReference/Modules/EditorToolbar/Controls/ComponentToolContextButton.cs/0
{ "file_path": "UnityCsReference/Modules/EditorToolbar/Controls/ComponentToolContextButton.cs", "repo_id": "UnityCsReference", "token_count": 533 }
382
// 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.Toolbars { [EditorToolbarElement("Editor Utility/Modes", typeof(DefaultMainToolbar))] sealed class ModesDropdown : EditorToolbarDropdown { public ModesDropdown() { name = "ModesDropdown"; clicked += OpenModesDropdown; style.display = DisplayStyle.None; RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); EditorApplication.delayCall += CheckAvailability; //Immediately after a domain reload, calling check availability sometimes returns the wrong value } void OnAttachedToPanel(AttachToPanelEvent evt) { ModeService.modeChanged += OnModeChanged; } void OnDetachFromPanel(DetachFromPanelEvent evt) { ModeService.modeChanged -= OnModeChanged; } void CheckAvailability() { style.display = Unsupported.IsDeveloperBuild() && ModeService.hasSwitchableModes ? DisplayStyle.Flex : DisplayStyle.None; UpdateContent(); } void OnModeChanged(ModeService.ModeChangedArgs args) { CheckAvailability(); UpdateContent(); } void UpdateContent() { text = ModeService.modeNames[ModeService.currentIndex]; } void OpenModesDropdown() { GenericMenu menu = new GenericMenu(); var modes = ModeService.modeNames; for (var i = 0; i < modes.Length; i++) { var modeName = ModeService.modeNames[i]; int selected = i; menu.AddItem( new GUIContent(modeName), ModeService.currentIndex == i, () => { EditorApplication.delayCall += () => ModeService.ChangeModeByIndex(selected); }); } menu.DropDown(worldBound, true); } } }
UnityCsReference/Modules/EditorToolbar/ToolbarElements/ModesDropdown.cs/0
{ "file_path": "UnityCsReference/Modules/EditorToolbar/ToolbarElements/ModesDropdown.cs", "repo_id": "UnityCsReference", "token_count": 1056 }
383
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; using System.Collections.Generic; using UnityEngine.Profiling; namespace UnityEditor.Experimental.GraphView { public class EdgeControl : VisualElement { private struct EdgeCornerSweepValues { public Vector2 circleCenter; public double sweepAngle; public double startAngle; public double endAngle; public Vector2 crossPoint1; public Vector2 crossPoint2; public float radius; } private VisualElement m_FromCap; private VisualElement m_ToCap; private GraphView m_GraphView; private static Stack<VisualElement> capPool = new Stack<VisualElement>(); private static VisualElement GetCap() { VisualElement result = null; if (capPool.Count > 0) { result = capPool.Pop(); } else { result = new VisualElement(); result.AddToClassList("edgeCap"); } return result; } private static void RecycleCap(VisualElement cap) { capPool.Push(cap); } public EdgeControl() { RegisterCallback<DetachFromPanelEvent>(OnLeavePanel); m_FromCap = null; m_ToCap = null; pickingMode = PickingMode.Ignore; generateVisualContent += OnGenerateVisualContent; RegisterCallback<AttachToPanelEvent>(OnAttachToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); } void MarkDirtyOnTransformChanged(GraphView gv) { MarkDirtyRepaint(); } void OnAttachToPanel(AttachToPanelEvent e) { if (m_GraphView == null) m_GraphView = GetFirstAncestorOfType<GraphView>(); m_GraphView.viewTransformChanged += MarkDirtyOnTransformChanged; } void OnDetachFromPanel(DetachFromPanelEvent e) { m_GraphView.viewTransformChanged -= MarkDirtyOnTransformChanged; } private bool m_ControlPointsDirty = true; private bool m_RenderPointsDirty = true; Mesh m_Mesh; public const float k_MinEdgeWidth = 1.75f; private const float k_EdgeLengthFromPort = 12.0f; private const float k_EdgeTurnDiameter = 16.0f; private const float k_EdgeSweepResampleRatio = 4.0f; private const int k_EdgeStraightLineSegmentDivisor = 5; static readonly Gradient k_Gradient = new Gradient(); private Orientation m_InputOrientation; public Orientation inputOrientation { get { return m_InputOrientation; } set { if (m_InputOrientation == value) return; m_InputOrientation = value; MarkDirtyRepaint(); } } private Orientation m_OutputOrientation; public Orientation outputOrientation { get { return m_OutputOrientation; } set { if (m_OutputOrientation == value) return; m_OutputOrientation = value; MarkDirtyRepaint(); } } [Obsolete("Use inputColor and/or outputColor")] public Color edgeColor { get { return m_InputColor; } set { if (m_InputColor == value && m_OutputColor == value) return; m_InputColor = value; m_OutputColor = value; MarkDirtyRepaint(); } } Color m_InputColor = Color.grey; public Color inputColor { get { return m_InputColor; } set { if (m_InputColor != value) { m_InputColor = value; MarkDirtyRepaint(); } } } Color m_OutputColor = Color.grey; public Color outputColor { get { return m_OutputColor; } set { if (m_OutputColor != value) { m_OutputColor = value; MarkDirtyRepaint(); } } } private Color m_FromCapColor; public Color fromCapColor { get { return m_FromCapColor; } set { if (m_FromCapColor == value) return; m_FromCapColor = value; if (m_FromCap != null) { m_FromCap.style.backgroundColor = m_FromCapColor; } MarkDirtyRepaint(); } } private Color m_ToCapColor; public Color toCapColor { get { return m_ToCapColor; } set { if (m_ToCapColor == value) return; m_ToCapColor = value; if (m_ToCap != null) { m_ToCap.style.backgroundColor = m_ToCapColor; } MarkDirtyRepaint(); } } private float m_CapRadius = 5; public float capRadius { get { return m_CapRadius; } set { if (m_CapRadius == value) return; m_CapRadius = value; MarkDirtyRepaint(); } } private int m_EdgeWidth = 2; public int edgeWidth { get { return m_EdgeWidth; } set { if (m_EdgeWidth == value) return; m_EdgeWidth = value; UpdateLayout(); // The layout depends on the edges width MarkDirtyRepaint(); } } private float m_InterceptWidth = 5; public float interceptWidth { get { return m_InterceptWidth; } set { m_InterceptWidth = value; } } // The start of the edge in graph coordinates. private Vector2 m_From; public Vector2 from { get { return m_From; } set { if ((m_From - value).sqrMagnitude > 0.25f) { m_From = value; PointsChanged(); } } } // The end of the edge in graph coordinates. private Vector2 m_To; public Vector2 to { get { return m_To; } set { if ((m_To - value).sqrMagnitude > 0.25f) { m_To = value; PointsChanged(); } } } // The control points in graph coordinates. private Vector2[] m_ControlPoints; public Vector2[] controlPoints { get { return m_ControlPoints; } } public bool drawFromCap { get { return m_FromCap != null; } set { if (!value) { if (m_FromCap != null) { m_FromCap.RemoveFromHierarchy(); RecycleCap(m_FromCap); m_FromCap = null; } } else { if (m_FromCap == null) { m_FromCap = GetCap(); m_FromCap.style.backgroundColor = m_FromCapColor; Add(m_FromCap); } } } } public bool drawToCap { get { return m_ToCap != null; } set { if (!value) { if (m_ToCap != null) { m_ToCap.RemoveFromHierarchy(); RecycleCap(m_ToCap); m_ToCap = null; } } else { if (m_ToCap == null) { m_ToCap = GetCap(); m_ToCap.style.backgroundColor = m_ToCapColor; Add(m_ToCap); } } } } void UpdateEdgeCaps() { if (m_FromCap != null) { Vector2 size = m_FromCap.layout.size; if ((size.x > 0) && (size.y > 0)) m_FromCap.layout = new Rect(parent.ChangeCoordinatesTo(this, m_From) - (size / 2), size); } if (m_ToCap != null) { Vector2 size = m_ToCap.layout.size; if ((size.x > 0) && (size.y > 0)) m_ToCap.layout = new Rect(parent.ChangeCoordinatesTo(this, m_To) - (size / 2), size); } } private void OnGenerateVisualContent(MeshGenerationContext mgc) { UnityEngine.Profiling.Profiler.BeginSample("DrawEdge"); DrawEdge(mgc); UnityEngine.Profiling.Profiler.EndSample(); } public override bool ContainsPoint(Vector2 localPoint) { Profiler.BeginSample("EdgeControl.ContainsPoint"); if (!base.ContainsPoint(localPoint)) { Profiler.EndSample(); return false; } // bounding box check succeeded, do more fine grained check by measuring distance to bezier points // exclude endpoints float capMaxDist = 4 * capRadius * capRadius; //(2 * CapRadius)^2 if ((from - localPoint).sqrMagnitude <= capMaxDist || (to - localPoint).sqrMagnitude <= capMaxDist) { Profiler.EndSample(); return false; } var allPoints = m_RenderPoints; if (allPoints.Count > 0) { //we use squareDistance to avoid sqrts float distance = (allPoints[0] - localPoint).sqrMagnitude; float interceptWidth2 = interceptWidth * interceptWidth; for (var i = 0; i < allPoints.Count - 1; i++) { Vector2 currentPoint = allPoints[i]; Vector2 nextPoint = allPoints[i + 1]; Vector2 next2Current = nextPoint - currentPoint; float distanceNext = (nextPoint - localPoint).sqrMagnitude; float distanceLine = next2Current.sqrMagnitude; // if the point is somewhere between the two points if (distance < distanceLine && distanceNext < distanceLine) { //https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line var d = next2Current.y * localPoint.x - next2Current.x * localPoint.y + nextPoint.x * currentPoint.y - nextPoint.y * currentPoint.x; if (d * d < interceptWidth2 * distanceLine) { Profiler.EndSample(); return true; } } distance = distanceNext; } } Profiler.EndSample(); return false; } public override bool Overlaps(Rect rect) { if (base.Overlaps(rect)) { for (int a = 0; a < m_RenderPoints.Count - 1; a++) { if (RectUtils.IntersectsSegment(rect, m_RenderPoints[a], m_RenderPoints[a + 1])) return true; } } return false; } protected virtual void PointsChanged() { m_ControlPointsDirty = true; MarkDirtyRepaint(); } // The points that will be rendered. Expressed in coordinates local to the element. List<Vector2> m_RenderPoints = new List<Vector2>(); static bool Approximately(Vector2 v1, Vector2 v2) { return Mathf.Approximately(v1.x, v2.x) && Mathf.Approximately(v1.y, v2.y); } public virtual void UpdateLayout() { if (parent == null) return; if (m_ControlPointsDirty) { ComputeControlPoints(); // Computes the control points in parent ( graph ) coordinates ComputeLayout(); // Update the element layout based on the control points. m_ControlPointsDirty = false; } UpdateEdgeCaps(); MarkDirtyRepaint(); } private List<Vector2> lastLocalControlPoints = new List<Vector2>(); void RenderStraightLines(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) { float safeSpan = outputOrientation == Orientation.Horizontal ? Mathf.Abs((p1.x + k_EdgeLengthFromPort) - (p4.x - k_EdgeLengthFromPort)) : Mathf.Abs((p1.y + k_EdgeLengthFromPort) - (p4.y - k_EdgeLengthFromPort)); float safeSpan3 = safeSpan / k_EdgeStraightLineSegmentDivisor; float nodeToP2Dist = Mathf.Min(safeSpan3, k_EdgeTurnDiameter); nodeToP2Dist = Mathf.Max(0, nodeToP2Dist); var offset = outputOrientation == Orientation.Horizontal ? new Vector2(k_EdgeTurnDiameter - nodeToP2Dist, 0) : new Vector2(0, k_EdgeTurnDiameter - nodeToP2Dist); m_RenderPoints.Add(p1); m_RenderPoints.Add(p2 - offset); m_RenderPoints.Add(p3 + offset); m_RenderPoints.Add(p4); } protected virtual void UpdateRenderPoints() { ComputeControlPoints(); // This should have been updated before : make sure anyway. if (m_RenderPointsDirty == false && m_ControlPoints != null) { return; } Vector2 p1 = parent.ChangeCoordinatesTo(this, m_ControlPoints[0]); Vector2 p2 = parent.ChangeCoordinatesTo(this, m_ControlPoints[1]); Vector2 p3 = parent.ChangeCoordinatesTo(this, m_ControlPoints[2]); Vector2 p4 = parent.ChangeCoordinatesTo(this, m_ControlPoints[3]); // Only compute this when the "local" points have actually changed if (lastLocalControlPoints.Count == 4) { if (Approximately(p1, lastLocalControlPoints[0]) && Approximately(p2, lastLocalControlPoints[1]) && Approximately(p3, lastLocalControlPoints[2]) && Approximately(p4, lastLocalControlPoints[3])) { m_RenderPointsDirty = false; return; } } Profiler.BeginSample("EdgeControl.UpdateRenderPoints"); lastLocalControlPoints.Clear(); lastLocalControlPoints.Add(p1); lastLocalControlPoints.Add(p2); lastLocalControlPoints.Add(p3); lastLocalControlPoints.Add(p4); m_RenderPointsDirty = false; m_RenderPoints.Clear(); float diameter = k_EdgeTurnDiameter; // We have to handle a special case of the edge when it is a straight line, but not // when going backwards in space (where the start point is in front in y to the end point). // We do this by turning the line into 3 linear segments with no curves. This also // avoids possible NANs in later angle calculations. bool sameOrientations = outputOrientation == inputOrientation; if (sameOrientations && ((outputOrientation == Orientation.Horizontal && Mathf.Abs(p1.y - p4.y) < 2 && p1.x + k_EdgeLengthFromPort < p4.x - k_EdgeLengthFromPort) || (outputOrientation == Orientation.Vertical && Mathf.Abs(p1.x - p4.x) < 2 && p1.y + k_EdgeLengthFromPort < p4.y - k_EdgeLengthFromPort))) { RenderStraightLines(p1, p2, p3, p4); Profiler.EndSample(); return; } bool renderBothCorners = true; EdgeCornerSweepValues corner1 = GetCornerSweepValues(p1, p2, p3, diameter, Direction.Output); EdgeCornerSweepValues corner2 = GetCornerSweepValues(p2, p3, p4, diameter, Direction.Input); if (!ValidateCornerSweepValues(ref corner1, ref corner2)) { if (sameOrientations) { RenderStraightLines(p1, p2, p3, p4); Profiler.EndSample(); return; } renderBothCorners = false; //we try to do it with a single corner instead Vector2 px = (outputOrientation == Orientation.Horizontal) ? new Vector2(p4.x, p1.y) : new Vector2(p1.x, p4.y); corner1 = GetCornerSweepValues(p1, px, p4, diameter, Direction.Output); } m_RenderPoints.Add(p1); if (!sameOrientations && renderBothCorners) { //if the 2 corners or endpoints are too close, the corner sweep angle calculations can't handle different orientations float minDistance = 2 * diameter * diameter; if ((p3 - p2).sqrMagnitude < minDistance || (p4 - p1).sqrMagnitude < minDistance) { Vector2 px = (p2 + p3) * 0.5f; corner1 = GetCornerSweepValues(p1, px, p4, diameter, Direction.Output); renderBothCorners = false; } } GetRoundedCornerPoints(m_RenderPoints, corner1, Direction.Output); if (renderBothCorners) GetRoundedCornerPoints(m_RenderPoints, corner2, Direction.Input); m_RenderPoints.Add(p4); Profiler.EndSample(); } private bool ValidateCornerSweepValues(ref EdgeCornerSweepValues corner1, ref EdgeCornerSweepValues corner2) { // Get the midpoint between the two corner circle centers. Vector2 circlesMidpoint = (corner1.circleCenter + corner2.circleCenter) / 2; // Find the angle to the corner circles midpoint so we can compare it to the sweep angles of each corner. Vector2 p2CenterToCross1 = corner1.circleCenter - corner1.crossPoint1; Vector2 p2CenterToCirclesMid = corner1.circleCenter - circlesMidpoint; double angleToCirclesMid = outputOrientation == Orientation.Horizontal ? Math.Atan2(p2CenterToCross1.y, p2CenterToCross1.x) - Math.Atan2(p2CenterToCirclesMid.y, p2CenterToCirclesMid.x) : Math.Atan2(p2CenterToCross1.x, p2CenterToCross1.y) - Math.Atan2(p2CenterToCirclesMid.x, p2CenterToCirclesMid.y); if (double.IsNaN(angleToCirclesMid)) return false; // We need the angle to the circles midpoint to match the turn direction of the first corner's sweep angle. angleToCirclesMid = Math.Sign(angleToCirclesMid) * 2 * Mathf.PI - angleToCirclesMid; if (Mathf.Abs((float)angleToCirclesMid) > 1.5 * Mathf.PI) angleToCirclesMid = -1 * Math.Sign(angleToCirclesMid) * 2 * Mathf.PI + angleToCirclesMid; // Calculate the maximum sweep angle so that both corner sweeps and with the tangents of the 2 circles meeting each other. float h = p2CenterToCirclesMid.magnitude; float p2AngleToMidTangent = Mathf.Acos(corner1.radius / h); if (double.IsNaN(p2AngleToMidTangent)) return false; float maxSweepAngle = Mathf.Abs((float)corner1.sweepAngle) - p2AngleToMidTangent * 2; // If the angle to the circles midpoint is within the sweep angle, we need to apply our maximum sweep angle // calculated above, otherwise the maximum sweep angle is irrelevant. if (Mathf.Abs((float)angleToCirclesMid) < Mathf.Abs((float)corner1.sweepAngle)) { corner1.sweepAngle = Math.Sign(corner1.sweepAngle) * Mathf.Min(maxSweepAngle, Mathf.Abs((float)corner1.sweepAngle)); corner2.sweepAngle = Math.Sign(corner2.sweepAngle) * Mathf.Min(maxSweepAngle, Mathf.Abs((float)corner2.sweepAngle)); } return true; } private EdgeCornerSweepValues GetCornerSweepValues( Vector2 p1, Vector2 cornerPoint, Vector2 p2, float diameter, Direction closestPortDirection) { EdgeCornerSweepValues corner = new EdgeCornerSweepValues(); // Calculate initial radius. This radius can change depending on the sharpness of the corner. corner.radius = diameter / 2; // Calculate vectors from p1 to cornerPoint. Vector2 d1Corner = (cornerPoint - p1).normalized; Vector2 d1 = d1Corner * diameter; float dx1 = d1.x; float dy1 = d1.y; // Calculate vectors from p2 to cornerPoint. Vector2 d2Corner = (cornerPoint - p2).normalized; Vector2 d2 = d2Corner * diameter; float dx2 = d2.x; float dy2 = d2.y; // Calculate the angle of the corner (divided by 2). float angle = (float)(Math.Atan2(dy1, dx1) - Math.Atan2(dy2, dx2)) / 2; // Calculate the length of the segment between the cornerPoint and where // the corner circle with given radius meets the line. float tan = (float)Math.Abs(Math.Tan(angle)); float segment = corner.radius / tan; // If the segment is larger than the diameter, we need to cap the segment // to the diameter and reduce the radius to match the segment. This is what // makes the corner turn radii get smaller as the edge corners get tighter. if (segment > diameter) { segment = diameter; corner.radius = diameter * tan; } // Calculate both cross points (where the circle touches the p1-cornerPoint line // and the p2-cornerPoint line). corner.crossPoint1 = cornerPoint - (d1Corner * segment); corner.crossPoint2 = cornerPoint - (d2Corner * segment); // Calculation of the coordinates of the circle center. corner.circleCenter = GetCornerCircleCenter(cornerPoint, corner.crossPoint1, corner.crossPoint2, segment, corner.radius); // Calculate the starting and ending angles. corner.startAngle = Math.Atan2(corner.crossPoint1.y - corner.circleCenter.y, corner.crossPoint1.x - corner.circleCenter.x); corner.endAngle = Math.Atan2(corner.crossPoint2.y - corner.circleCenter.y, corner.crossPoint2.x - corner.circleCenter.x); // Get the full sweep angle from the starting and ending angles. corner.sweepAngle = corner.endAngle - corner.startAngle; // If we are computing the second corner (into the input port), we want to start // the sweep going backwards. if (closestPortDirection == Direction.Input) { double endAngle = corner.endAngle; corner.endAngle = corner.startAngle; corner.startAngle = endAngle; } // Validate the sweep angle so it turns into the correct direction. if (corner.sweepAngle > Math.PI) corner.sweepAngle = -2 * Math.PI + corner.sweepAngle; else if (corner.sweepAngle < -Math.PI) corner.sweepAngle = 2 * Math.PI + corner.sweepAngle; return corner; } private Vector2 GetCornerCircleCenter(Vector2 cornerPoint, Vector2 crossPoint1, Vector2 crossPoint2, float segment, float radius) { float dx = cornerPoint.x * 2 - crossPoint1.x - crossPoint2.x; float dy = cornerPoint.y * 2 - crossPoint1.y - crossPoint2.y; var cornerToCenterVector = new Vector2(dx, dy); float L = cornerToCenterVector.magnitude; if (Mathf.Approximately(L, 0)) { return cornerPoint; } float d = new Vector2(segment, radius).magnitude; float factor = d / L; return new Vector2(cornerPoint.x - cornerToCenterVector.x * factor, cornerPoint.y - cornerToCenterVector.y * factor); } private void GetRoundedCornerPoints(List<Vector2> points, EdgeCornerSweepValues corner, Direction closestPortDirection) { // Calculate the number of points that will sample the arc from the sweep angle. int pointsCount = Mathf.CeilToInt((float)Math.Abs(corner.sweepAngle * k_EdgeSweepResampleRatio)); int sign = Math.Sign(corner.sweepAngle); bool backwards = (closestPortDirection == Direction.Input); for (int i = 0; i < pointsCount; ++i) { // If we are computing the second corner (into the input port), the sweep is going backwards // but we still need to add the points to the list in the correct order. float sweepIndex = backwards ? i - pointsCount : i; double sweepedAngle = corner.startAngle + sign * sweepIndex / k_EdgeSweepResampleRatio; var pointX = (float)(corner.circleCenter.x + Math.Cos(sweepedAngle) * corner.radius); var pointY = (float)(corner.circleCenter.y + Math.Sin(sweepedAngle) * corner.radius); // Check if we overlap the previous point. If we do, we skip this point so that we // don't cause the edge polygons to twist. if (i == 0 && backwards) { if (outputOrientation == Orientation.Horizontal) { if (corner.sweepAngle < 0 && points[points.Count - 1].y > pointY) continue; else if (corner.sweepAngle >= 0 && points[points.Count - 1].y < pointY) continue; } else { if (corner.sweepAngle < 0 && points[points.Count - 1].x < pointX) continue; else if (corner.sweepAngle >= 0 && points[points.Count - 1].x > pointX) continue; } } points.Add(new Vector2(pointX, pointY)); } } private void AssignControlPoint(ref Vector2 destination, Vector2 newValue) { if (!Approximately(destination, newValue)) { destination = newValue; m_RenderPointsDirty = true; } } protected virtual void ComputeControlPoints() { if (m_ControlPointsDirty == false) return; Profiler.BeginSample("EdgeControl.ComputeControlPoints"); float offset = k_EdgeLengthFromPort + k_EdgeTurnDiameter; // This is to ensure we don't have the edge extending // left and right by the offset right when the `from` // and `to` are on top of each other. float fromToDistance = (to - from).magnitude; offset = Mathf.Min(offset, fromToDistance * 2); offset = Mathf.Max(offset, k_EdgeTurnDiameter); if (m_ControlPoints == null || m_ControlPoints.Length != 4) m_ControlPoints = new Vector2[4]; AssignControlPoint(ref m_ControlPoints[0], from); if (outputOrientation == Orientation.Horizontal) AssignControlPoint(ref m_ControlPoints[1], new Vector2(from.x + offset, from.y)); else AssignControlPoint(ref m_ControlPoints[1], new Vector2(from.x, from.y + offset)); if (inputOrientation == Orientation.Horizontal) AssignControlPoint(ref m_ControlPoints[2], new Vector2(to.x - offset, to.y)); else AssignControlPoint(ref m_ControlPoints[2], new Vector2(to.x, to.y - offset)); AssignControlPoint(ref m_ControlPoints[3], to); Profiler.EndSample(); } void ComputeLayout() { Profiler.BeginSample("EdgeControl.ComputeLayout"); Vector2 to = m_ControlPoints[m_ControlPoints.Length - 1]; Vector2 from = m_ControlPoints[0]; Rect rect = new Rect(Vector2.Min(to, from), new Vector2(Mathf.Abs(from.x - to.x), Mathf.Abs(from.y - to.y))); // Make sure any control points (including tangents, are included in the rect) for (int i = 1; i < m_ControlPoints.Length - 1; ++i) { if (!rect.Contains(m_ControlPoints[i])) { Vector2 pt = m_ControlPoints[i]; rect.xMin = Math.Min(rect.xMin, pt.x); rect.yMin = Math.Min(rect.yMin, pt.y); rect.xMax = Math.Max(rect.xMax, pt.x); rect.yMax = Math.Max(rect.yMax, pt.y); } } if (m_GraphView == null) { m_GraphView = GetFirstAncestorOfType<GraphView>(); } //Make sure that we have the place to display Edges with EdgeControl.k_MinEdgeWidth at the lowest level of zoom. float margin = Mathf.Max(edgeWidth * 0.5f + 1, EdgeControl.k_MinEdgeWidth / m_GraphView.minScale); rect.xMin -= margin; rect.yMin -= margin; rect.width += margin; rect.height += margin; if (layout != rect) { layout = rect; m_RenderPointsDirty = true; } Profiler.EndSample(); } void DrawEdge(MeshGenerationContext mgc) { if (edgeWidth <= 0) return; UpdateRenderPoints(); if (m_RenderPoints.Count == 0) return; // Don't draw anything Color inColor = this.inputColor; Color outColor = this.outputColor; inColor *= playModeTintColor; outColor *= playModeTintColor; uint cpt = (uint)m_RenderPoints.Count; var painter2D = mgc.painter2D; float width = edgeWidth; float alpha = 1.0f; float zoom = m_GraphView?.scale ?? 1.0f; if (edgeWidth * zoom < k_MinEdgeWidth) { alpha = edgeWidth * zoom / k_MinEdgeWidth; width = k_MinEdgeWidth / zoom; } k_Gradient.SetKeys(new[]{ new GradientColorKey(outColor, 0),new GradientColorKey(inColor, 1)},new []{new GradientAlphaKey(alpha, 0)}); painter2D.BeginPath(); painter2D.strokeGradient = k_Gradient; painter2D.lineWidth = width; painter2D.MoveTo(m_RenderPoints[0]); for(int i = 1 ; i < cpt ; ++i) painter2D.LineTo(m_RenderPoints[i]); painter2D.Stroke(); } void OnLeavePanel(DetachFromPanelEvent e) { if (m_Mesh != null) { UnityEngine.Object.DestroyImmediate(m_Mesh); m_Mesh = null; } } } }
UnityCsReference/Modules/GraphViewEditor/EdgeControl.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/EdgeControl.cs", "repo_id": "UnityCsReference", "token_count": 16506 }
384
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Experimental.GraphView { public class Placemat : GraphElement { internal static readonly Vector2 k_DefaultCollapsedSize = new Vector2(200, 42); static readonly Color k_DefaultColor = new Color(0.15f, 0.19f, 0.19f); static readonly int k_SelectRectOffset = 3; protected GraphView m_GraphView; TextField m_TitleField; ResizableElement m_Resizer; Button m_CollapseButton; internal void Init(GraphView graphView) { m_GraphView = graphView; var template = EditorGUIUtility.Load("UXML/GraphView/PlacematElement.uxml") as VisualTreeAsset; if (template != null) template.CloneTree(this); AddStyleSheetPath("StyleSheets/GraphView/Placemat.uss"); AddToClassList("placemat"); AddToClassList("selectable"); pickingMode = PickingMode.Position; capabilities |= Capabilities.Deletable | Capabilities.Movable | Capabilities.Selectable | Capabilities.Copiable; capabilities &= ~Capabilities.Ascendable; focusable = true; RegisterCallback<AttachToPanelEvent>(OnAttachToPanel); RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel); m_TitleField = this.Q<TextField>(); m_TitleField.isDelayed = true; this.AddManipulator(new ContextualMenuManipulator(BuildContextualMenu)); m_CollapseButton = this.Q<Button>(); m_CollapseButton.clicked += () => Collapsed = !Collapsed; m_CollapseButton.AddToClassList("placematCollapse"); m_Resizer = this.Q<ResizableElement>(); if (Collapsed) { m_Resizer.style.visibility = Visibility.Hidden; m_CollapseButton.RemoveFromClassList("icon-expanded"); } else { m_Resizer.style.visibility = StyleKeyword.Null; m_CollapseButton.AddToClassList("icon-expanded"); } } string m_Title; public override string title { get { return m_Title; } set { m_Title = value; if (m_TitleField != null) m_TitleField.value = m_Title; } } public virtual int ZOrder { get; set; } Color m_Color = k_DefaultColor; public virtual Color Color { get { return m_Color; } set { m_Color = value; style.backgroundColor = value; } } public Vector2 UncollapsedSize { get; private set; } public Vector2 CollapsedSize { get { var actualCollapsedSize = k_DefaultCollapsedSize; if (UncollapsedSize.x < k_DefaultCollapsedSize.x) actualCollapsedSize.x = UncollapsedSize.x; return actualCollapsedSize; } } public Rect ExpandedPosition => Collapsed ? new Rect(layout.position, UncollapsedSize) : GetPosition(); public override void SetPosition(Rect newPos) { if (!Collapsed) UncollapsedSize = newPos.size; else newPos.size = CollapsedSize; base.SetPosition(newPos); } PlacematContainer m_PlacematContainer; PlacematContainer Container => m_PlacematContainer ?? (m_PlacematContainer = GetFirstAncestorOfType<PlacematContainer>()); HashSet<GraphElement> m_CollapsedElements = new HashSet<GraphElement>(); public IEnumerable<GraphElement> CollapsedElements => m_CollapsedElements; protected internal void SetCollapsedElements(IEnumerable<GraphElement> collapsedElements) { if (!Collapsed) return; foreach (var collapsedElement in m_CollapsedElements) collapsedElement.style.visibility = StyleKeyword.Null; m_CollapsedElements.Clear(); if (collapsedElements == null) return; foreach (var collapsedElement in collapsedElements) { collapsedElement.style.visibility = Visibility.Hidden; m_CollapsedElements.Add(collapsedElement); } } internal void HideCollapsedEdges() { var nodes = new HashSet<Node>(AllCollapsedElements.OfType<Node>()); foreach (var edge in m_GraphView.edges.ToList()) if (AnyNodeIsConnectedToPort(nodes, edge.input) && AnyNodeIsConnectedToPort(nodes, edge.output)) { if (edge.style.visibility != Visibility.Hidden) { edge.style.visibility = Visibility.Hidden; m_CollapsedElements.Add(edge); } } } IEnumerable<GraphElement> AllCollapsedElements { get { foreach (var graphElement in CollapsedElements) { var placemat = graphElement as Placemat; if (placemat != null && placemat.Collapsed) foreach (var subElement in placemat.AllCollapsedElements) yield return subElement; yield return graphElement; } } } bool m_Collapsed; public virtual bool Collapsed { get { return m_Collapsed; } set { if (m_Collapsed != value) { m_Collapsed = value; CollapseSelf(); ShowHideCollapsedElements(); } } } void CollapseSelf() { if (Collapsed) { layout = new Rect(layout.position, CollapsedSize); if (m_Resizer != null) m_Resizer.style.visibility = Visibility.Hidden; } else { layout = new Rect(layout.position, UncollapsedSize); if (m_Resizer != null) m_Resizer.style.visibility = StyleKeyword.Null; } m_CollapseButton?.EnableInClassList("icon-expanded", !Collapsed); EnableInClassList("collapsed", Collapsed); } void RebuildCollapsedElements() { m_CollapsedElements.Clear(); var graphElements = m_GraphView.graphElements.ToList() .Where(e => !(e is Edge) && (e.parent is GraphView.Layer) && (e.capabilities & Capabilities.Selectable) != 0) .ToList(); var collapsedElementsElsewhere = new List<GraphElement>(); RecurseRebuildCollapsedElements_LocalFunc(this, graphElements, collapsedElementsElsewhere); var nodes = new HashSet<Node>(AllCollapsedElements.OfType<Node>()); foreach (var edge in m_GraphView.edges.ToList()) if (AnyNodeIsConnectedToPort(nodes, edge.input) && AnyNodeIsConnectedToPort(nodes, edge.output)) m_CollapsedElements.Add(edge); foreach (var ge in collapsedElementsElsewhere) m_CollapsedElements.Remove(ge); } // TODO: Move to local function of Collapse once we move to C# 7.0 or higher. void RecurseRebuildCollapsedElements_LocalFunc(Placemat currentPlacemat, IList<GraphElement> graphElements, List<GraphElement> collapsedElementsElsewhere) { var currRect = currentPlacemat.ExpandedPosition; var currentActivePlacematRect = new Rect( currRect.x + k_SelectRectOffset, currRect.y + k_SelectRectOffset, currRect.width - 2 * k_SelectRectOffset, currRect.height - 2 * k_SelectRectOffset); foreach (var elem in graphElements) { if (elem.layout.Overlaps(currentActivePlacematRect)) { var placemat = elem as Placemat; if (placemat != null && placemat.ZOrder > currentPlacemat.ZOrder) { if (placemat.Collapsed) foreach (var cge in placemat.CollapsedElements) collapsedElementsElsewhere.Add(cge); else RecurseRebuildCollapsedElements_LocalFunc(placemat, graphElements, collapsedElementsElsewhere); } if (placemat == null || placemat.ZOrder > currentPlacemat.ZOrder) if (elem.resolvedStyle.visibility == Visibility.Visible) m_CollapsedElements.Add(elem); } } } void ShowHideCollapsedElements() { if (m_GraphView == null) return; if (Collapsed) { RebuildCollapsedElements(); foreach (var ge in m_CollapsedElements) ge.style.visibility = Visibility.Hidden; UpdateCollapsedNodeEdges(); } else { foreach (var ge in m_CollapsedElements) ge.style.visibility = StyleKeyword.Null; UpdateCollapsedNodeEdges(); //Update edges just before clearing list m_CollapsedElements.Clear(); } } static bool AnyNodeIsConnectedToPort(IEnumerable<Node> nodes, Port port) { foreach (var node in nodes) { var stackNode = node as StackNode; if (stackNode != null && stackNode.contentContainer.Children().Any(n => n == port.node)) return true; if (node == port.node) return true; } return false; } void UpdateCollapsedNodeEdges() { if (m_GraphView == null) return; //We need to update all the edges whose either port is in the placemat var touchedEdges = new HashSet<Edge>(); var nodes = new HashSet<Node>(AllCollapsedElements.OfType<Node>()); foreach (var edge in m_GraphView.edges.ToList()) if (AnyNodeIsConnectedToPort(nodes, edge.input) || AnyNodeIsConnectedToPort(nodes, edge.output)) touchedEdges.Add(edge); foreach (var edge in touchedEdges) edge.ForceUpdateEdgeControl(); } void OnTitleFieldChange(ChangeEvent<string> evt) { // Call setter in derived class, if any. title = evt.newValue; } [EventInterest(typeof(PointerDownEvent))] protected override void HandleEventBubbleUp(EventBase evt) { base.HandleEventBubbleUp(evt); if (evt is PointerDownEvent mde && evt.currentTarget == evt.target && mde.clickCount == 2 && mde.button == (int)MouseButton.LeftMouse) { SelectGraphElementsOver(); } } [EventInterest(EventInterestOptions.Inherit)] [Obsolete("ExecuteDefaultActionAtTarget override has been removed because default event handling was migrated to HandleEventBubbleUp. Please use HandleEventBubbleUp.", false)] protected override void ExecuteDefaultActionAtTarget(EventBase evt) { } void ActOnGraphElementsOver(Action<GraphElement> act) { var graphElements = m_GraphView.graphElements.ToList() .Where(e => !(e is Edge) && (e.parent is GraphView.Layer) && (e.capabilities & Capabilities.Selectable) != 0); foreach (var elem in graphElements) { if (elem.layout.Overlaps(layout)) act(elem); } } internal bool ActOnGraphElementsOver(Func<GraphElement, bool> act, bool includePlacemats) { var graphElements = m_GraphView.graphElements.ToList() .Where(e => !(e is Edge) && e.parent is GraphView.Layer && (e.capabilities & Capabilities.Selectable) != 0).ToList(); return RecurseActOnGraphElementsOver_LocalFunc(this, graphElements, act, includePlacemats); } // TODO: Move to local function of ActOnGraphElementsOver once we move to C# 7.0 or higher. static bool RecurseActOnGraphElementsOver_LocalFunc(Placemat currentPlacemat, List<GraphElement> graphElements, Func<GraphElement, bool> act, bool includePlacemats) { if (currentPlacemat.Collapsed) { foreach (var elem in currentPlacemat.CollapsedElements) { var placemat = elem as Placemat; if (placemat != null && placemat.ZOrder > currentPlacemat.ZOrder) if (RecurseActOnGraphElementsOver_LocalFunc(placemat, graphElements, act, includePlacemats)) return true; if (placemat == null || (includePlacemats && placemat.ZOrder > currentPlacemat.ZOrder)) if (act(elem)) return true; } } else { var currRect = currentPlacemat.ExpandedPosition; var currentActivePlacematRect = new Rect( currRect.x + k_SelectRectOffset, currRect.y + k_SelectRectOffset, currRect.width - 2 * k_SelectRectOffset, currRect.height - 2 * k_SelectRectOffset); foreach (var elem in graphElements) { if (elem.layout.Overlaps(currentActivePlacematRect)) { var placemat = elem as Placemat; if (placemat != null && placemat.ZOrder > currentPlacemat.ZOrder) if (RecurseActOnGraphElementsOver_LocalFunc(placemat, graphElements, act, includePlacemats)) return true; if (placemat == null || (includePlacemats && placemat.ZOrder > currentPlacemat.ZOrder)) if (elem.resolvedStyle.visibility != Visibility.Hidden) if (act(elem)) return true; } } } return false; } void SelectGraphElementsOver() { ActOnGraphElementsOver(e => m_GraphView.AddToSelection(e)); } internal bool WillDragNode(Node node) { if (Collapsed) return AllCollapsedElements.Contains(node); return ActOnGraphElementsOver(t => node == t, true); } internal void GrowToFitElements(List<GraphElement> elements) { if (elements == null) elements = GetHoveringNodes(); var pos = new Rect(); if (elements.Count > 0 && ComputeElementBounds(ref pos, elements, MinSizePolicy.DoNotEnsureMinSize)) { // We don't resize to be snug. In other words: we don't ever decrease in size. Rect currentRect = GetPosition(); if (pos.xMin > currentRect.xMin) pos.xMin = currentRect.xMin; if (pos.xMax < currentRect.xMax) pos.xMax = currentRect.xMax; if (pos.yMin > currentRect.yMin) pos.yMin = currentRect.yMin; if (pos.yMax < currentRect.yMax) pos.yMax = currentRect.yMax; MakeRectAtLeastMinimalSize(ref pos); SetPosition(pos); } } internal void ShrinkToFitElements(List<GraphElement> elements) { if (elements == null) elements = GetHoveringNodes(); var pos = new Rect(); if (elements.Count > 0 && ComputeElementBounds(ref pos, elements)) SetPosition(pos); } void ResizeToIncludeSelectedNodes() { List<GraphElement> nodes = m_GraphView.selection.OfType<GraphElement>().Where(e => e is Node).ToList(); // Now include the selected nodes var pos = new Rect(); if (ComputeElementBounds(ref pos, nodes, MinSizePolicy.DoNotEnsureMinSize)) { // We don't resize to be snug: we only resize enough to contain the selected nodes. var currentRect = GetPosition(); if (pos.xMin > currentRect.xMin) pos.xMin = currentRect.xMin; if (pos.xMax < currentRect.xMax) pos.xMax = currentRect.xMax; if (pos.yMin > currentRect.yMin) pos.yMin = currentRect.yMin; if (pos.yMax < currentRect.yMax) pos.yMax = currentRect.yMax; MakeRectAtLeastMinimalSize(ref pos); SetPosition(pos); } } internal void GetElementsToMove(bool moveOnlyPlacemat, HashSet<GraphElement> collectedElementsToMove) { if (Collapsed) { foreach (var ge in AllCollapsedElements) if (!(ge is Edge)) collectedElementsToMove.Add(ge); } else if (!moveOnlyPlacemat) { ActOnGraphElementsOver(e => { collectedElementsToMove.Add(e); return false; }, true); } } protected virtual void BuildContextualMenu(ContextualMenuPopulateEvent evt) { var placemat = evt.target as Placemat; if (placemat != null) { evt.menu.AppendAction("Edit Title", a => placemat.StartEditTitle()); evt.menu.AppendSeparator(); evt.menu.AppendAction("Change Color...", a => { ColorPicker.Show(c => placemat.Color = c, placemat.Color, showAlpha: false); }); // Resizing section evt.menu.AppendSeparator(); evt.menu.AppendAction(placemat.Collapsed ? "Expand" : "Collapse", a => placemat.Collapsed = !placemat.Collapsed); // Gather nodes here so that we don't recycle this code in the resize functions. List<GraphElement> hoveringNodes = placemat.GetHoveringNodes(); evt.menu.AppendAction("Resize/Grow To Fit", a => placemat.GrowToFitElements(hoveringNodes), hoveringNodes.Count > 0 ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); evt.menu.AppendAction("Resize/Shrink To Fit", a => placemat.ShrinkToFitElements(hoveringNodes), hoveringNodes.Count > 0 ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); evt.menu.AppendAction("Resize/Grow To Fit Selection", a => placemat.ResizeToIncludeSelectedNodes(), s => { foreach (ISelectable sel in placemat.m_GraphView.selection) { var node = sel as Node; if (node != null && !hoveringNodes.Contains(node)) return DropdownMenuAction.Status.Normal; } return DropdownMenuAction.Status.Disabled; }); var status = placemat.Container.Placemats.Any() ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled; evt.menu.AppendAction("Order/Bring To Front", a => Container.BringToFront(placemat), status); evt.menu.AppendAction("Order/Bring Forward", a => Container.CyclePlacemat(placemat, PlacematContainer.CycleDirection.Up), status); evt.menu.AppendAction("Order/Send Backward", a => Container.CyclePlacemat(placemat, PlacematContainer.CycleDirection.Down), status); evt.menu.AppendAction("Order/Send To Back", a => Container.SendToBack(placemat), status); } } List<GraphElement> GetHoveringNodes() { var potentialElements = new List<GraphElement>(); ActOnGraphElementsOver(e => potentialElements.Add(e)); return potentialElements.Where(e => e is Node).ToList(); } public void StartEditTitle() { // Focus field and select text (spare the user from having to type enter before editing text). m_TitleField?.Q(TextField.textInputUssName)?.Focus(); } void OnAttachToPanel(AttachToPanelEvent evt) { m_TitleField.RegisterCallback<ChangeEvent<string>>(OnTitleFieldChange); } void OnDetachFromPanel(DetachFromPanelEvent evt) { m_TitleField.UnregisterCallback<ChangeEvent<string>>(OnTitleFieldChange); } internal bool GetPortCenterOverride(Port port, out Vector2 overriddenPosition) { if (!Collapsed || parent == null) { overriddenPosition = Vector2.zero; return false; } const int xOffset = 6; const int yOffset = 3; var halfSize = CollapsedSize * 0.5f; var offset = port.orientation == Orientation.Horizontal ? new Vector2(port.direction == Direction.Input ? -halfSize.x + xOffset : halfSize.x - xOffset, 0) : new Vector2(0, port.direction == Direction.Input ? -halfSize.y + yOffset : halfSize.y - yOffset); overriddenPosition = parent.LocalToWorld(layout.center + offset); return true; } // Helper method that calculates how big a Placemat should be to fit the nodes on top of it currently. internal const float k_Bounds = 9.0f; internal const float k_BoundTop = 29.0f; // Current height of Title public enum MinSizePolicy { EnsureMinSize, DoNotEnsureMinSize } // Returns false if bounds could not be computed. public static bool ComputeElementBounds(ref Rect pos, List<GraphElement> elements, MinSizePolicy ensureMinSize = MinSizePolicy.EnsureMinSize) { if (elements == null || elements.Count == 0) return false; float minX = Mathf.Infinity; float maxX = -Mathf.Infinity; float minY = Mathf.Infinity; float maxY = -Mathf.Infinity; foreach (var r in elements.Select(n => n.GetPosition())) { if (r.xMin < minX) minX = r.xMin; if (r.xMax > maxX) maxX = r.xMax; if (r.yMin < minY) minY = r.yMin; if (r.yMax > maxY) maxY = r.yMax; } var width = maxX - minX + k_Bounds * 2.0f; var height = maxY - minY + k_Bounds * 2.0f + k_BoundTop; pos = new Rect( minX - k_Bounds, minY - (k_BoundTop + k_Bounds), width, height); if (ensureMinSize == MinSizePolicy.EnsureMinSize) MakeRectAtLeastMinimalSize(ref pos); return true; } // The next two values need to be the same as USS... however, we can't get the values from there as we need them in a static // methods used to create new placemats const float k_MinWidth = 200; const float k_MinHeight = 100; static void MakeRectAtLeastMinimalSize(ref Rect r) { if (r.width < k_MinWidth) r.width = k_MinWidth; if (r.height < k_MinHeight) r.height = k_MinHeight; } } }
UnityCsReference/Modules/GraphViewEditor/Elements/Placemat/Placemat.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Elements/Placemat/Placemat.cs", "repo_id": "UnityCsReference", "token_count": 12599 }
385
// 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.Experimental.GraphView { public interface ISelection { List<ISelectable> selection { get; } void AddToSelection(ISelectable selectable); void RemoveFromSelection(ISelectable selectable); void ClearSelection(); } }
UnityCsReference/Modules/GraphViewEditor/ISelection.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/ISelection.cs", "repo_id": "UnityCsReference", "token_count": 160 }
386
// 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.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; using UnityEditor.Experimental.GraphView; namespace UnityEditor.UIElements.GraphView { enum SnapReference { LeftEdge, HorizontalCenter, RightEdge, TopEdge, VerticalCenter, BottomEdge } class SnapResult { public Rect sourceRect { get; set; } public SnapReference sourceReference { get; set; } public Rect snappableRect { get; set; } public SnapReference snappableReference { get; set; } public float offset { get; set; } public float distance { get { return Math.Abs(offset); } } public Line2 indicatorLine; public SnapResult() { } } class SnapService { const float k_DefaultSnapDistance = 8.0f; float m_CurrentScale = 1.0f; List<Rect> m_SnappableRects = new List<Rect>(); public bool active { get; private set; } public float snapDistance { get; set; } public SnapService() { snapDistance = k_DefaultSnapDistance; } internal static float GetPos(Rect rect, SnapReference reference) { switch (reference) { case SnapReference.LeftEdge: return rect.x; case SnapReference.HorizontalCenter: return rect.center.x; case SnapReference.RightEdge: return rect.xMax; case SnapReference.TopEdge: return rect.y; case SnapReference.VerticalCenter: return rect.center.y; case SnapReference.BottomEdge: return rect.yMax; default: return 0; } } virtual public void BeginSnap(List<Rect> snappableRects) { if (active) { throw new InvalidOperationException("SnapService.BeginSnap: Already active. Call EndSnap() first."); } active = true; m_SnappableRects = new List<Rect>(snappableRects); } public void UpdateSnapRects(List<Rect> snappableRects) { m_SnappableRects = snappableRects; } public Rect GetSnappedRect(Rect sourceRect, out List<SnapResult> results, float scale = 1.0f) { if (!active) { throw new InvalidOperationException("SnapService.GetSnappedRect: Already active. Call BeginSnap() first."); } Rect snappedRect = sourceRect; m_CurrentScale = scale; results = GetClosestSnapElements(sourceRect); foreach (SnapResult result in results) { ApplyResult(sourceRect, ref snappedRect, result); } foreach (SnapResult result in results) { result.indicatorLine = GetSnapLine(snappedRect, result.sourceReference, result.snappableRect, result.snappableReference); } return snappedRect; } virtual public void EndSnap() { if (!active) { throw new InvalidOperationException("SnapService.End: Already active. Call BeginSnap() first."); } m_SnappableRects.Clear(); active = false; } SnapResult GetClosestSnapElement(Rect sourceRect, SnapReference sourceRef, Rect snappableRect, SnapReference startReference, SnapReference centerReference, SnapReference endReference) { float sourcePos = GetPos(sourceRect, sourceRef); float offsetStart = sourcePos - GetPos(snappableRect, startReference); float offsetEnd = sourcePos - GetPos(snappableRect, endReference); float minOffset = offsetStart; SnapReference minSnappableReference = startReference; if (Math.Abs(minOffset) > Math.Abs(offsetEnd)) { minOffset = offsetEnd; minSnappableReference = endReference; } SnapResult minResult = new SnapResult { sourceRect = sourceRect, sourceReference = sourceRef, snappableRect = snappableRect, snappableReference = minSnappableReference, offset = minOffset }; if (minResult.distance <= snapDistance * 1 / m_CurrentScale) return minResult; else return null; } SnapResult GetClosestSnapElement(Rect sourceRect, SnapReference sourceRef, SnapReference startReference, SnapReference centerReference, SnapReference endReference) { SnapResult minResult = null; float minDistance = float.MaxValue; foreach (Rect snappableRect in m_SnappableRects) { SnapResult result = GetClosestSnapElement(sourceRect, sourceRef, snappableRect, startReference, centerReference, endReference); if (result != null && minDistance > result.distance) { minDistance = result.distance; minResult = result; } } return minResult; } List<SnapResult> GetClosestSnapElements(Rect sourceRect, Orientation orientation) { SnapReference startReference = orientation == Orientation.Horizontal ? SnapReference.LeftEdge : SnapReference.TopEdge; SnapReference centerReference = orientation == Orientation.Horizontal ? SnapReference.HorizontalCenter : SnapReference.VerticalCenter; SnapReference endReference = orientation == Orientation.Horizontal ? SnapReference.RightEdge : SnapReference.BottomEdge; List<SnapResult> results = new List<SnapResult>(3); SnapResult result = GetClosestSnapElement(sourceRect, startReference, startReference, centerReference, endReference); if (result != null) results.Add(result); result = GetClosestSnapElement(sourceRect, centerReference, startReference, centerReference, endReference); if (result != null) results.Add(result); result = GetClosestSnapElement(sourceRect, endReference, startReference, centerReference, endReference); if (result != null) results.Add(result); // Look for the minimum if (results.Count > 0) { results.Sort((a, b) => a.distance.CompareTo(b.distance)); float minDistance = results[0].distance; results.RemoveAll(r => Math.Abs(r.distance - minDistance) > 0.01f); } return results; } List<SnapResult> GetClosestSnapElements(Rect sourceRect) { List<SnapResult> snapResults = GetClosestSnapElements(sourceRect, Orientation.Horizontal); return snapResults.Union(GetClosestSnapElements(sourceRect, Orientation.Vertical)).ToList(); } Line2 GetSnapLine(Rect r, SnapReference reference) { Vector2 start = Vector2.zero, end = Vector2.zero; switch (reference) { case SnapReference.LeftEdge: start = r.position; end = new Vector2(r.x, r.yMax); break; case SnapReference.HorizontalCenter: start = r.center; end = start; break; case SnapReference.RightEdge: start = new Vector2(r.xMax, r.yMin); end = new Vector2(r.xMax, r.yMax); break; case SnapReference.TopEdge: start = r.position; end = new Vector2(r.xMax, r.yMin); break; case SnapReference.VerticalCenter: start = r.center; end = start; break; default: // case SnapReference.BottomEdge: start = new Vector2(r.x, r.yMax); end = new Vector2(r.xMax, r.yMax); break; } return new Line2(start, end); } Line2 GetSnapLine(Rect r1, SnapReference reference1, Rect r2, SnapReference reference2) { bool horizontal = reference1 <= SnapReference.RightEdge; Line2 line1 = GetSnapLine(r1, reference1); Line2 line2 = GetSnapLine(r2, reference2); Vector2 p11 = line1.start , p12 = line1.end , p21 = line2.start , p22 = line2.end , start = Vector2.zero , end = Vector2.zero; if (horizontal) { float x = p21.x; float yMin = Math.Min(p22.y, Math.Min(p21.y, Math.Min(p11.y, p12.y))); float yMax = Math.Max(p22.y, Math.Max(p21.y, Math.Max(p11.y, p12.y))); start = new Vector2(x, yMin); end = new Vector2(x, yMax); } else { float y = p22.y; float xMin = Math.Min(p22.x, Math.Min(p21.x, Math.Min(p11.x, p12.x))); float xMax = Math.Max(p22.x, Math.Max(p21.x, Math.Max(p11.x, p12.x))); start = new Vector2(xMin, y); end = new Vector2(xMax, y); } return new Line2(start, end); } void ApplyResult(Rect sourceRect, ref Rect r1, SnapResult result) { if (result.snappableReference <= SnapReference.RightEdge) r1.x = sourceRect.x - result.offset; else r1.y = sourceRect.y - result.offset; } } }
UnityCsReference/Modules/GraphViewEditor/Manipulators/SnapService.cs/0
{ "file_path": "UnityCsReference/Modules/GraphViewEditor/Manipulators/SnapService.cs", "repo_id": "UnityCsReference", "token_count": 4968 }
387
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; using UnityEngine.Bindings; namespace UnityEngine { [RequireComponent(typeof(Transform))] [NativeHeader("Modules/Grid/Public/GridMarshalling.h")] [NativeType(Header = "Modules/Grid/Public/Grid.h")] public partial class GridLayout : Behaviour { // Enums. public enum CellLayout { Rectangle = 0, Hexagon = 1, Isometric = 2, IsometricZAsY = 3, } public enum CellSwizzle { XYZ = 0, XZY = 1, YXZ = 2, YZX = 3, ZXY = 4, ZYX = 5 } public extern Vector3 cellSize { [FreeFunction("GridLayoutBindings::GetCellSize", HasExplicitThis = true)] get; } public extern Vector3 cellGap { [FreeFunction("GridLayoutBindings::GetCellGap", HasExplicitThis = true)] get; } public extern CellLayout cellLayout { get; } public extern CellSwizzle cellSwizzle { get; } [FreeFunction("GridLayoutBindings::GetBoundsLocal", HasExplicitThis = true)] public extern Bounds GetBoundsLocal(Vector3Int cellPosition); public Bounds GetBoundsLocal(Vector3 origin, Vector3 size) { return GetBoundsLocalOriginSize(origin, size); } [FreeFunction("GridLayoutBindings::GetBoundsLocalOriginSize", HasExplicitThis = true)] private extern Bounds GetBoundsLocalOriginSize(Vector3 origin, Vector3 size); [FreeFunction("GridLayoutBindings::CellToLocal", HasExplicitThis = true)] public extern Vector3 CellToLocal(Vector3Int cellPosition); [FreeFunction("GridLayoutBindings::LocalToCell", HasExplicitThis = true)] public extern Vector3Int LocalToCell(Vector3 localPosition); [FreeFunction("GridLayoutBindings::CellToLocalInterpolated", HasExplicitThis = true)] public extern Vector3 CellToLocalInterpolated(Vector3 cellPosition); [FreeFunction("GridLayoutBindings::LocalToCellInterpolated", HasExplicitThis = true)] public extern Vector3 LocalToCellInterpolated(Vector3 localPosition); [FreeFunction("GridLayoutBindings::CellToWorld", HasExplicitThis = true)] public extern Vector3 CellToWorld(Vector3Int cellPosition); [FreeFunction("GridLayoutBindings::WorldToCell", HasExplicitThis = true)] public extern Vector3Int WorldToCell(Vector3 worldPosition); [FreeFunction("GridLayoutBindings::LocalToWorld", HasExplicitThis = true)] public extern Vector3 LocalToWorld(Vector3 localPosition); [FreeFunction("GridLayoutBindings::WorldToLocal", HasExplicitThis = true)] public extern Vector3 WorldToLocal(Vector3 worldPosition); [FreeFunction("GridLayoutBindings::GetLayoutCellCenter", HasExplicitThis = true)] public extern Vector3 GetLayoutCellCenter(); [RequiredByNativeCode] private void DoNothing() {} } }
UnityCsReference/Modules/Grid/ScriptBindings/GridLayout.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Grid/ScriptBindings/GridLayout.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1339 }
388
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace Unity.Hierarchy { /// <summary> /// An interface that is used to access strongly typed node data. /// </summary> public interface IHierarchyProperty<T> { /// <summary> /// Returns <see langword="true"/> if the native property is valid. /// </summary> public bool IsCreated { get; } /// <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> T GetValue(in HierarchyNode node); /// <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> void SetValue(in HierarchyNode node, T value); /// <summary> /// Removes the property value for a <see cref="HierarchyNode"/>. /// </summary> /// <param name="node">The hierarchy node.</param> void ClearValue(in HierarchyNode node); } }
UnityCsReference/Modules/HierarchyCore/Managed/IHierarchyProperty.cs/0
{ "file_path": "UnityCsReference/Modules/HierarchyCore/Managed/IHierarchyProperty.cs", "repo_id": "UnityCsReference", "token_count": 496 }
389
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEngine { internal delegate bool DrawHandler(GUIStyle style, Rect rect, GUIContent content, DrawStates states); internal readonly struct DrawStates { public DrawStates(bool isHover, bool isActive, bool on, bool hasKeyboardFocus) : this(-1, isHover, isActive, on, hasKeyboardFocus) { } public DrawStates(int controlId, bool isHover, bool isActive, bool on, bool hasKeyboardFocus) { this.controlId = controlId; this.isHover = isHover; this.isActive = isActive; this.on = on; this.hasKeyboardFocus = hasKeyboardFocus; hasTextInput = false; drawSelectionAsComposition = false; cursorFirstPosition = cursorLastPosition = Vector2.zero; selectionColor = cursorColor = Color.red; } public DrawStates(int controlId, bool isHover, bool isActive, bool on, bool hasKeyboardFocus, bool drawSelectionAsComposition, Vector2 cursorFirstPosition, Vector2 cursorLastPosition, Color cursorColor, Color selectionColor) : this(controlId, isHover, isActive, on, hasKeyboardFocus) { hasTextInput = true; this.drawSelectionAsComposition = drawSelectionAsComposition; this.cursorFirstPosition = cursorFirstPosition; this.cursorLastPosition = cursorLastPosition; this.cursorColor = cursorColor; this.selectionColor = selectionColor; } public readonly int controlId; public readonly bool isHover; public readonly bool isActive; public readonly bool on; public readonly bool hasKeyboardFocus; public readonly bool hasTextInput; public readonly bool drawSelectionAsComposition; public readonly Vector2 cursorFirstPosition; public readonly Vector2 cursorLastPosition; public readonly Color cursorColor; public readonly Color selectionColor; } }
UnityCsReference/Modules/IMGUI/DrawStates.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/DrawStates.cs", "repo_id": "UnityCsReference", "token_count": 884 }
390
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; namespace UnityEngine { // Class internally used to pass layout options into [[GUILayout]] functions. You don't use these directly, but construct them with the layouting functions in the [[GUILayout]] class. public sealed class GUILayoutOption { internal enum Type { fixedWidth, fixedHeight, minWidth, maxWidth, minHeight, maxHeight, stretchWidth, stretchHeight, // These are just for the spacing variables alignStart, alignMiddle, alignEnd, alignJustify, equalSize, spacing } // *undocumented* internal Type type; // *undocumented* internal object value; // *undocumented* internal GUILayoutOption(Type type, object value) { this.type = type; this.value = value; } } }
UnityCsReference/Modules/IMGUI/GUILayoutOption.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/GUILayoutOption.cs", "repo_id": "UnityCsReference", "token_count": 379 }
391
// 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.TextCore.Text; namespace UnityEngine { /// <summary> /// Represents text rendering settings for IMGUI runtime /// </summary> internal class RuntimeTextSettings : TextSettings { private static RuntimeTextSettings s_DefaultTextSettings; internal static RuntimeTextSettings defaultTextSettings { get { if (s_DefaultTextSettings == null) { s_DefaultTextSettings = ScriptableObject.CreateInstance<RuntimeTextSettings>(); } return s_DefaultTextSettings; } } } }
UnityCsReference/Modules/IMGUI/RuntimeTextSettings.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/RuntimeTextSettings.cs", "repo_id": "UnityCsReference", "token_count": 343 }
392
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Unity.Collections.LowLevel.Unsafe; using Unity.IntegerTime; using UnityEngine; using UnityEngine.Bindings; namespace UnityEngine.InputForUI { // Keyboard key event [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal struct KeyEvent : IEventProperties { public enum Type { /// <summary> /// Button was pressed. /// </summary> KeyPressed = 1, /// <summary> /// Button was held and press was repeated. /// </summary> KeyRepeated = 2, /// <summary> /// Button was released. /// </summary> KeyReleased = 3, /// <summary> /// No changes since last event. /// Used when code requested current state of devices for polling purposes. /// </summary> State = 4 } public Type type; public KeyCode keyCode; public ButtonsState buttonsState; public DiscreteTime timestamp { get; set; } public EventSource eventSource { get; set; } public uint playerId { get; set; } public EventModifiers eventModifiers { get; set; } public override string ToString() { switch (type) { case Type.KeyPressed: case Type.KeyRepeated: case Type.KeyReleased: return $"{type} {keyCode}"; case Type.State: return $"{type} Pressed:{buttonsState}"; default: throw new ArgumentOutOfRangeException(); } } public struct ButtonsState { // ignore everything above KeyCode.Menu as it only contains mouse and joysticks // TODO do we need to map to a more tight bit packing? private const uint kMaxIndex = (int)KeyCode.Menu; private const uint kSizeInBytes = (kMaxIndex + 7) / 8; private unsafe fixed byte buttons[(int)kSizeInBytes]; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool ShouldBeProcessed(KeyCode keyCode) { var index = (uint)keyCode; return index <= kMaxIndex; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe bool GetUnchecked(uint index) { return (buttons[index >> 3] & (byte)(1U << (int)(index & 7))) != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe void SetUnchecked(uint index) { buttons[index >> 3] |= (byte)(1U << (int)(index & 7)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe void ClearUnchecked(uint index) { buttons[index >> 3] &= (byte)~(1U << (int)(index & 7)); } public bool IsPressed(KeyCode keyCode) { return ShouldBeProcessed(keyCode) && GetUnchecked((uint)keyCode); } public IEnumerable<KeyCode> GetAllPressed() { for (var index = 0U; index <= kMaxIndex; ++index) if (GetUnchecked(index)) yield return (KeyCode)index; } public void SetPressed(KeyCode keyCode, bool pressed) { if (!ShouldBeProcessed(keyCode)) return; if (pressed) SetUnchecked((uint)keyCode); else ClearUnchecked((uint)keyCode); } public unsafe void Reset() { for (var i = 0; i < kSizeInBytes; ++i) buttons[i] = 0; } public override string ToString() { return string.Join(",", GetAllPressed()); } } } }
UnityCsReference/Modules/InputForUI/Events/KeyEvent.cs/0
{ "file_path": "UnityCsReference/Modules/InputForUI/Events/KeyEvent.cs", "repo_id": "UnityCsReference", "token_count": 2111 }
393
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Runtime.InteropServices; using System.Collections.Generic; using UnityEditor.Experimental.Licensing; using UnityEngine; using UnityEngine.Bindings; using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; namespace UnityEditor.Experimental.Licensing { [Serializable] [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeAsStruct] public class EntitlementGroupInfo { [SerializeField] private string m_Expiration_ts; public string Expiration_ts { get { return m_Expiration_ts; } } [SerializeField] string m_EntitlementGroupId; public string EntitlementGroupId { get { return m_EntitlementGroupId; } } [SerializeField] string m_ProductName; public string ProductName { get { return m_ProductName; } } [SerializeField] string m_LicenseType; public string LicenseType { get { return m_LicenseType; } } } public enum EntitlementStatus { Unknown, Granted, NotGranted, Free } [Serializable] [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeAsStruct] public class EntitlementInfo { [SerializeField] string m_EntitlementId; public string EntitlementId { get { return m_EntitlementId; } } [SerializeField] EntitlementStatus m_Status; public EntitlementStatus Status { get { return m_Status; } } [SerializeField] bool m_IsPackage; public bool IsPackage { get { return m_IsPackage; } } [SerializeField] int m_Count; public int Count { get { return m_Count; } } [SerializeField] string m_CustomData; public string CustomData { get { return m_CustomData; } } [SerializeField] EntitlementGroupInfo[] m_EntitlementGroupsData; public EntitlementGroupInfo[] EntitlementGroupsData { get { return m_EntitlementGroupsData; } } } [NativeHeader("Modules/Licensing/Public/LicensingUtility.bindings.h")] public static class LicensingUtility { [NativeMethod("HasEntitlement")] public extern static bool HasEntitlement(string entitlement); [NativeMethod("HasEntitlements")] public extern static string[] HasEntitlements(string[] entitlements); [NativeMethod("IsOnPremiseLicensingEnabled")] internal extern static bool IsOnPremiseLicensingEnabled(); [NativeMethod("HasEntitlementsExtended")] public extern static EntitlementInfo[] HasEntitlementsExtended(string[] entitlements, bool includeCustomData); public static extern void InvokeLicenseUpdateCallbacks(); public static extern bool UpdateLicense(); } }
UnityCsReference/Modules/Licensing/Public/LicensingUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/Public/LicensingUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1128 }
394
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEditor.Licensing.UI.Events.Text; namespace UnityEditor.Licensing.UI.Events.Buttons; sealed class SaveAndQuitButton : TemplateEventsButton { INativeApiWrapper m_NativeApiWrapper; Action m_CloseAction; public SaveAndQuitButton(Action closeAction, Action additionalClickAction, INativeApiWrapper nativeApiWrapper) : base(LicenseTrStrings.BtnSaveAndQuit, additionalClickAction) { m_NativeApiWrapper = nativeApiWrapper; m_CloseAction = closeAction; } protected override void Click() { m_CloseAction?.Invoke(); var _ = m_NativeApiWrapper.SaveUnsavedChanges(); m_NativeApiWrapper.ExitEditor(); } }
UnityCsReference/Modules/Licensing/UI/Events/Buttons/SaveAndQuitButton.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Buttons/SaveAndQuitButton.cs", "repo_id": "UnityCsReference", "token_count": 313 }
395
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.Licensing.UI.Data.Events; using UnityEditor.Licensing.UI.Events.Buttons; using UnityEditor.Licensing.UI.Events.Text; using UnityEditor.Licensing.UI.Helper; using UnityEngine; namespace UnityEditor.Licensing.UI.Events.Windows; class LicenseOfflineValidityEndedWindow : TemplateLicenseEventWindow { public static void ShowWindow(INativeApiWrapper nativeApiWrapper, ILicenseLogger licenseLogger, object notification) { s_NativeApiWrapper = nativeApiWrapper; s_Notification = notification as LicenseExpiredNotification; s_LicenseLogger = licenseLogger; TemplateLicenseEventWindow.ShowWindow<LicenseOfflineValidityEndedWindow>(LicenseTrStrings.OfflineValidityEndedWindowTitle, true); } public void CreateGUI() { s_Root = new LicenseOfflineValidityEndedWindowContents( (LicenseExpiredNotification)s_Notification, new EventsButtonFactory(s_NativeApiWrapper, Close), s_LicenseLogger); rootVisualElement.Add(s_Root); } }
UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseOfflineValidityEndedWindow.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Windows/LicenseOfflineValidityEndedWindow.cs", "repo_id": "UnityCsReference", "token_count": 412 }
396
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine.SceneManagement; namespace UnityEditor.Licensing.UI; interface INativeApiWrapper { T CreateObjectFromJson<T>(string jsonString); void ExitEditor(); bool HasUiEntitlement(); bool SaveUnsavedChanges(); Scene[] GetAllScenes(); bool HasUnsavedScenes(); void InvokeLicenseUpdateCallbacks(); void OpenHubLicenseManagementWindow(); bool UpdateLicense(); bool IsHumanControllingUs(); }
UnityCsReference/Modules/Licensing/UI/INativeApiWrapper.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/INativeApiWrapper.cs", "repo_id": "UnityCsReference", "token_count": 200 }
397
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.UIElements; using UnityEngine.UIElements; using UnityEditor.Toolbars; namespace UnityEditor.Multiplayer.Internal { [EditorToolbarElement("Multiplayer/MultiplayerRole", typeof(DefaultMainToolbar))] class MultiplayerRoleDropdown : EditorToolbarDropdown { public MultiplayerRoleDropdown() { EditorMultiplayerManager.CreateMultiplayerRoleDropdown(this); } } }
UnityCsReference/Modules/MultiplayerEditor/Managed/MultiplayerRoleDropdown.cs/0
{ "file_path": "UnityCsReference/Modules/MultiplayerEditor/Managed/MultiplayerRoleDropdown.cs", "repo_id": "UnityCsReference", "token_count": 195 }
398
// 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.Bindings; using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; namespace UnityEditor.PackageManager { [Serializable] [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeAsStruct] public class RegistryInfo { [SerializeField] [NativeName("id")] private string m_Id; [SerializeField] [NativeName("name")] private string m_Name; [SerializeField] [NativeName("url")] private string m_Url; [SerializeField] [NativeName("scopes")] private string[] m_Scopes; [SerializeField] [NativeName("isDefault")] private bool m_IsDefault; [SerializeField] [NativeName("capabilities")] private SearchCapabilities m_Capabilities; [SerializeField] [NativeName("configSource")] private ConfigSource m_ConfigSource; internal RegistryInfo(string id = "", string name = "", string url = "", string[] scopes = null, bool isDefault = false, SearchCapabilities capabilities = SearchCapabilities.None, ConfigSource configSource = ConfigSource.Unknown) { m_Id = id; m_Name = name; m_Url = url; m_Scopes = scopes ?? Array.Empty<string>(); m_IsDefault = isDefault; m_Capabilities = capabilities; m_ConfigSource = configSource; } internal string id { get { return m_Id; } } public string name { get { return m_Name; } } public string url { get { return m_Url; } } internal string[] scopes { get { return m_Scopes; } } public bool isDefault { get { return m_IsDefault; } } internal SearchCapabilities capabilities { get { return m_Capabilities; } } internal ConfigSource configSource { get { return m_ConfigSource; } } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/RegistryInfo.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/RegistryInfo.cs", "repo_id": "UnityCsReference", "token_count": 850 }
399
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager { public enum StatusCode { InProgress, Success, Failure } }
UnityCsReference/Modules/PackageManager/Editor/Managed/StatusCode.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/StatusCode.cs", "repo_id": "UnityCsReference", "token_count": 105 }
400
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager.UI { /// <summary> /// Interface for handlers for the PackageSelectionChanged event /// </summary> internal interface IPackageSelectionChangedHandler { /// <summary> /// Called when the package selection is changed in the Package Manager window. /// </summary> /// <param name="args">The arguments for the selection changed event.</param> void OnPackageSelectionChanged(PackageSelectionArgs args); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IPackageSelectionChangedHandler.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IPackageSelectionChangedHandler.cs", "repo_id": "UnityCsReference", "token_count": 205 }
401
// 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.Analytics; namespace UnityEditor.PackageManager.UI.Internal { [AnalyticInfo(eventName: k_EventName, vendorKey: k_VendorKey)] internal class PackageManagerOperationErrorAnalytics : IAnalytic { private const string k_EventName = "packageManagerWindowOperationError"; private const string k_VendorKey = "unity.package-manager-ui"; [Serializable] private class Data : IAnalytic.IData { public string operation_type; public string message; public string error_type; public int status_code; public string[] attributes; public string read_more_url; } private Data m_Data; private PackageManagerOperationErrorAnalytics(string operationType, UIError error) { m_Data = new Data { operation_type = operationType, message = error.message, error_type = error.errorCode.ToString(), status_code = error.operationErrorCode, attributes = error.attribute == UIError.Attribute.None ? Array.Empty<string>() : error.attribute.ToString().Split(','), read_more_url = error.readMoreURL ?? string.Empty }; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { error = null; data = m_Data; return data != null; } public static void SendEvent(string operationType, UIError error) { var editorAnalyticsProxy = ServicesContainer.instance.Resolve<IEditorAnalyticsProxy>(); editorAnalyticsProxy.SendAnalytic(new PackageManagerOperationErrorAnalytics(operationType, error)); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerOperationErrorAnalytics.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageManagerOperationErrorAnalytics.cs", "repo_id": "UnityCsReference", "token_count": 812 }
402
// 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.Scripting.ScriptCompilation; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class AssetStoreProductInfo { public long productId; public long versionId; public string packageName; public string description; public string publisherName; public string category; public string versionString; public string publishedDate; public string displayName; public string state; public string publishNotes; public string firstPublishedDate; public string assetStoreProductUrl; public string assetStorePublisherUrl; public string publisherWebsiteUrl; public string publisherSupportUrl; public List<string> supportedVersions; public List<PackageImage> images; public List<PackageSizeInfo> sizeInfos; public bool Equals(AssetStoreProductInfo other) { return other != null && other.productId == productId && other.versionId == versionId && other.versionString == versionString; } } internal partial class JsonParser { private List<PackageImage> GetImagesFromProductDetails(IDictionary<string, object> productDetail) { int imageLimit = 4; int imagesLoaded = 0; var result = new List<PackageImage>(); var mainImageDictionary = productDetail.GetDictionary("mainImage"); var mainImageThumbnailUrl = mainImageDictionary?.GetString("url"); if (!string.IsNullOrEmpty(mainImageThumbnailUrl)) { mainImageThumbnailUrl = mainImageThumbnailUrl.Replace("//d2ujflorbtfzji.cloudfront.net/", "//assetstorev1-prd-cdn.unity3d.com/"); var imageUrl = "http:" + mainImageDictionary.GetString("big"); result.Add(new PackageImage { type = PackageImage.ImageType.Main, thumbnailUrl = "http:" + mainImageThumbnailUrl, url = imageUrl }); ++imagesLoaded; } var images = productDetail.GetList<IDictionary<string, object>>("images") ?? Enumerable.Empty<IDictionary<string, object>>(); foreach (var image in images) { if (imagesLoaded >= imageLimit) break; var type = image?.GetString("type"); if (string.IsNullOrEmpty(type)) continue; var imageType = PackageImage.ImageType.Screenshot; var thumbnailUrl = image.GetString("thumbnailUrl"); thumbnailUrl = thumbnailUrl.Replace("//d2ujflorbtfzji.cloudfront.net/", "//assetstorev1-prd-cdn.unity3d.com/"); if (type == "sketchfab") imageType = PackageImage.ImageType.Sketchfab; else if (type == "youtube") imageType = PackageImage.ImageType.Youtube; else if (type == "vimeo") imageType = PackageImage.ImageType.Vimeo; // for now we only use screenshot types var imageUrl = image.GetString("imageUrl"); if (imageType == PackageImage.ImageType.Screenshot) { imageUrl = "http:" + imageUrl; result.Add(new PackageImage { type = imageType, thumbnailUrl = "http:" + thumbnailUrl, url = imageUrl }); ++imagesLoaded; } } return result; } private List<PackageSizeInfo> GetSizeInfoFromProductDetails(IDictionary<string, object> productDetail) { var result = new List<PackageSizeInfo>(); var uploads = productDetail.GetDictionary("uploads"); if (uploads != null) { foreach (var key in uploads.Keys) { var simpleVersion = Regex.Replace(key, @"(?<major>\d+)\.(?<minor>\d+).(?<patch>\d+)[abfp].+", "${major}.${minor}.${patch}"); SemVersion? version; bool isVersionParsed = SemVersionParser.TryParse(simpleVersion.Trim(), out version); if (isVersionParsed) { var info = uploads.GetDictionary(key); var assetCount = info?.GetString("assetCount") ?? string.Empty; var downloadSize = info?.GetString("downloadSize") ?? string.Empty; result.Add(new PackageSizeInfo { supportedUnityVersion = (SemVersion)version, assetCount = string.IsNullOrEmpty(assetCount) ? 0 : ulong.Parse(assetCount), downloadSize = string.IsNullOrEmpty(downloadSize) ? 0 : ulong.Parse(downloadSize) }); } } } return result; } public AssetStoreProductInfo ParseProductInfo(string assetStoreUrl, long productId, IDictionary<string, object> productDetail) { if (productId <= 0 || productDetail == null || !productDetail.Any()) return null; var productInfo = new AssetStoreProductInfo(); productInfo.productId = productId; productInfo.description = CleanUpHtml(productDetail.GetString("description")) ?? string.Empty; var publisher = productDetail.GetDictionary("productPublisher"); var publisherId = string.Empty; productInfo.publisherName = string.Empty; if (publisher != null) { if (publisher.GetString("url") == "http://unity3d.com") productInfo.publisherName = "Unity Technologies Inc."; else productInfo.publisherName = publisher.GetString("name") ?? L10n.Tr("Unknown publisher"); publisherId = publisher.GetString("externalRef") ?? string.Empty; } if (!string.IsNullOrEmpty(publisherId)) productInfo.assetStorePublisherUrl = $"{assetStoreUrl}/publishers/{publisherId}"; productInfo.packageName = productDetail.GetString("packageName") ?? string.Empty; productInfo.category = productDetail.GetDictionary("category")?.GetString("name") ?? string.Empty; productInfo.publishNotes = CleanUpHtml(productDetail.GetString("publishNotes") ?? string.Empty, false); productInfo.firstPublishedDate = productDetail.GetDictionary("properties")?.GetString("firstPublishedDate"); var versionInfo = productDetail.GetDictionary("version"); if (versionInfo != null) { productInfo.versionString = versionInfo.GetString("name"); productInfo.versionId = versionInfo.GetStringAsLong("id"); productInfo.publishedDate = versionInfo.GetString("publishedDate"); } productInfo.displayName = productDetail.GetString("displayName"); productInfo.supportedVersions = productDetail.GetList<string>("supportedUnityVersions")?.ToList(); productInfo.state = productDetail.GetString("state"); productInfo.images = GetImagesFromProductDetails(productDetail); productInfo.sizeInfos = GetSizeInfoFromProductDetails(productDetail); productInfo.assetStoreProductUrl = GetProductUrlFromProductDetails(assetStoreUrl, productDetail); productInfo.publisherWebsiteUrl = GetPublisherWebsiteUrlFromProductDetails(assetStoreUrl, productDetail); productInfo.publisherSupportUrl = GetPublisherSupportUrlFromProductDetails(assetStoreUrl, productDetail); return productInfo; } private string GetProductUrlFromProductDetails(string assetStoreUrl, IDictionary<string, object> productDetail) { var slug = productDetail.GetString("slug") ?? productDetail.GetString("id"); return $"{assetStoreUrl}/packages/p/{slug}"; } private string GetPublisherWebsiteUrlFromProductDetails(string assetStoreUrl, IDictionary<string, object> productDetail) { var url = productDetail.GetDictionary("productPublisher")?.GetString("url"); return BuildUrl(assetStoreUrl, url); } private string GetPublisherSupportUrlFromProductDetails(string assetStoreUrl, IDictionary<string, object> productDetail) { var supportUrl = productDetail.GetDictionary("productPublisher")?.GetString("supportUrl"); return BuildUrl(assetStoreUrl, supportUrl); } private string BuildUrl(string assetStoreUrl, string url) { if (string.IsNullOrEmpty(url) || !Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute)) return string.Empty; if (!url.StartsWith("http:", StringComparison.InvariantCulture) && !url.StartsWith("https:", StringComparison.InvariantCulture)) return assetStoreUrl + url; return url; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreProductInfo.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStoreProductInfo.cs", "repo_id": "UnityCsReference", "token_count": 4270 }
403
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Diagnostics.CodeAnalysis; namespace UnityEditor.PackageManager.UI.Internal; internal interface IOperationFactory : IService { void ResolveDependenciesForOperation(AssetStoreListOperation operation); AssetStoreListOperation CreateAssetStoreListOperation(); } internal class OperationFactory : BaseService<IOperationFactory>, IOperationFactory { private readonly IUnityConnectProxy m_UnityConnect; private readonly IAssetStoreRestAPI m_AssetStoreRestAPI; private readonly IAssetStoreCache m_AssetStoreCache; public OperationFactory(IUnityConnectProxy unityConnect, IAssetStoreRestAPI assetStoreRestAPI, IAssetStoreCache assetStoreCache) { m_UnityConnect = RegisterDependency(unityConnect); m_AssetStoreRestAPI = RegisterDependency(assetStoreRestAPI); m_AssetStoreCache = RegisterDependency(assetStoreCache); } [ExcludeFromCodeCoverage] public void ResolveDependenciesForOperation(AssetStoreListOperation operation) { operation?.ResolveDependencies(m_UnityConnect, m_AssetStoreRestAPI, m_AssetStoreCache); } public AssetStoreListOperation CreateAssetStoreListOperation() { return new AssetStoreListOperation(m_UnityConnect, m_AssetStoreRestAPI, m_AssetStoreCache); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/OperationFactory.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/OperationFactory.cs", "repo_id": "UnityCsReference", "token_count": 441 }
404
// 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.Scripting.ScriptCompilation; namespace UnityEditor.PackageManager.UI { internal interface IPackageVersion { string name { get; } string displayName { get; } // versionString and versionId are the same for UpmPackage but difference for in the case Asset Store packages: // versionString - something that looks like `1.0.2` or `1.0a` // versionId - the unique numeric id that is used in the Asset Store backend that looks like `12345` // to avoid confusing external developers, we only expose `versionString` in the public API and not `versionId` string versionString { get; } string uniqueId { get; } string packageId { get; } IPackage package { get; } bool isInstalled { get; } } } namespace UnityEditor.PackageManager.UI.Internal { internal interface IPackageVersion : UI.IPackageVersion { new IPackage package { get; set; } string author { get; } // Note that localReleaseNotes here is different from IPackage.latestReleaseNotes // localReleaseNotes is always from the locally downloaded .unitypackage, while // latestReleaseNotes is always from the productInfo we fetch from the server. string localReleaseNotes { get; } // Note that description here is different from IPackage.productDescription // description here is the description for this specific package version (from PackageInfo) // productDescription is the product description we fetch from the Asset Store server string description { get; } string category { get; } IEnumerable<UIError> errors { get; } bool hasEntitlements { get; } bool hasEntitlementsError { get; } SemVersion? version { get; } string versionInManifest { get; } bool isInvalidSemVerInManifest { get; } long uploadId { get; } DateTime? publishedDate { get; } DependencyInfo[] dependencies { get; } DependencyInfo[] resolvedDependencies { get; } IEnumerable<Asset> importedAssets { get; } bool HasTag(PackageTag tag); string GetAnalyticsTags(); RegistryType availableRegistry { get; } // A version is fully fetched when the information isn't derived from another version (therefore may be inaccurate) bool isFullyFetched { get; } bool isDirectDependency { get; } string localPath { get; } SemVersion? supportedVersion { get; } IEnumerable<SemVersion> supportedVersions { get; } IEnumerable<PackageSizeInfo> sizes { get; } EntitlementsInfo entitlements { get; } bool IsDifferentVersionThanRequested { get; } bool IsRequestedButOverriddenVersion { get; } string deprecationMessage { get; } string GetDescriptor(bool isFirstLetterCapitalized = false); bool MatchesSearchText(string searchText); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IPackageVersion.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Interfaces/IPackageVersion.cs", "repo_id": "UnityCsReference", "token_count": 1103 }
405
// 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; namespace UnityEditor.PackageManager.UI.Internal; [Flags] internal enum PackageActionState : uint { None = 0, Visible = 1 << 0, DisabledTemporarily = 1 << 1, DisabledForPackage = 1 << 2, InProgress = 1 << 3, Disabled = DisabledTemporarily | DisabledForPackage } internal abstract class PackageAction { protected static readonly string k_InProgressGenericTooltip = L10n.Tr("This action is currently in progress."); public Action onActionTriggered; // For now, this is only used for LegacyFormat dropdown button. public virtual bool isRecommended => false; public virtual Icon icon => Icon.None; public virtual PackageActionState GetActionState(IPackageVersion version, out string text, out string tooltip) { if (!IsVisible(version)) { text = string.Empty; tooltip = string.Empty; if (IsHiddenWhenInProgress(version) && IsInProgress(version)) return PackageActionState.InProgress; return PackageActionState.None; } var isInProgress = IsInProgress(version); text = GetText(version, isInProgress); if (isInProgress) { tooltip = GetTooltip(version, true); return PackageActionState.Visible | PackageActionState.DisabledForPackage | PackageActionState.InProgress; } var disableCondition = GetActiveDisableCondition(version); if (disableCondition != null) { tooltip = disableCondition.tooltip; return PackageActionState.Visible | PackageActionState.DisabledForPackage; } var temporaryDisableCondition = GetActiveTemporaryDisableCondition(); if (temporaryDisableCondition != null) { tooltip = temporaryDisableCondition.tooltip; return PackageActionState.Visible | PackageActionState.DisabledTemporarily; } tooltip = GetTooltip(version, false); return PackageActionState.Visible; } public void TriggerAction(IPackageVersion version) { if (TriggerActionImplementation(version)) onActionTriggered?.Invoke(); } // Returns true if the action is triggered, false otherwise. protected abstract bool TriggerActionImplementation(IPackageVersion version); public void TriggerAction(IList<IPackageVersion> versions) { if (TriggerActionImplementation(versions)) onActionTriggered?.Invoke(); } // By default buttons does not support bulk action protected virtual bool TriggerActionImplementation(IList<IPackageVersion> versions) => false; public abstract bool IsInProgress(IPackageVersion version); protected virtual bool IsHiddenWhenInProgress(IPackageVersion version) => false; public abstract bool IsVisible(IPackageVersion version); public abstract string GetTooltip(IPackageVersion version, bool isInProgress); public abstract string GetText(IPackageVersion version, bool isInProgress); public virtual string GetMultiSelectText(IPackageVersion version, bool isInProgress) => GetText(version, isInProgress); // Temporary disable conditions refer to conditions that are temporary and not related to the state of a package // For example, when the network is lost or when there are scripting compiling protected virtual IEnumerable<DisableCondition> GetAllTemporaryDisableConditions() => Enumerable.Empty<DisableCondition>(); public virtual DisableCondition GetActiveTemporaryDisableCondition() { return GetAllTemporaryDisableConditions().FirstOrDefault(condition => condition.active); } protected virtual IEnumerable<DisableCondition> GetAllDisableConditions(IPackageVersion version) => Enumerable.Empty<DisableCondition>(); public virtual DisableCondition GetActiveDisableCondition(IPackageVersion version) { return GetAllDisableConditions(version).FirstOrDefault(condition => condition.active); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/PackageAction.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/PackageAction.cs", "repo_id": "UnityCsReference", "token_count": 1363 }
406
// 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; namespace UnityEditor.PackageManager.UI.Internal { internal interface IPackageLinkFactory : IService { PackageLink CreateUpmDocumentationLink(IPackageVersion version); PackageLink CreateUpmChangelogLink(IPackageVersion version); PackageLink CreateVersionHistoryChangelogLink(IPackageVersion version); PackageLink CreateUpmLicenseLink(IPackageVersion version); PackageLink CreateUpmQuickStartLink(IPackageVersion version); PackageLink CreateProductLink(IPackageVersion version); PackageLink CreateAuthorLink(IPackageVersion version); PackageLink CreatePublisherSupportLink(IPackageVersion version); PackageLink CreatePublisherWebsiteLink(IPackageVersion version); PackageLink CreateUseCasesLink(IPackageVersion version); PackageLink CreateDashboardLink(IPackageVersion version); } internal class PackageLinkFactory : BaseService<IPackageLinkFactory>, IPackageLinkFactory { private readonly IUpmCache m_UpmCache; private readonly IAssetStoreCache m_AssetStoreCache; private readonly IApplicationProxy m_Application; private readonly IIOProxy m_IOProxy; public PackageLinkFactory(IUpmCache upmCache, IAssetStoreCache assetStoreCache, IApplicationProxy application, IIOProxy iOProxy) { m_UpmCache = RegisterDependency(upmCache); m_AssetStoreCache = RegisterDependency(assetStoreCache); m_Application = RegisterDependency(application); m_IOProxy = RegisterDependency(iOProxy); } private string GetDocumentationUrl(PackageInfo packageInfo, bool isUnityPackage) { if (packageInfo == null) return string.Empty; if (!string.IsNullOrEmpty(packageInfo.documentationUrl)) return packageInfo.documentationUrl; if (packageInfo.ExtractUrlFromDescription(m_Application.docsUrlWithShortUnityVersion, out var result)) return result; if (!isUnityPackage) return string.Empty; var shortVersionId = packageInfo.GetShortVersionId(); if (string.IsNullOrEmpty(shortVersionId)) return string.Empty; return $"https://docs.unity3d.com/Packages/{shortVersionId}/index.html"; } private string GetChangelogUrl(PackageInfo packageInfo, bool isUnityPackage) { if (packageInfo == null) return string.Empty; if (!string.IsNullOrEmpty(packageInfo.changelogUrl)) return packageInfo.changelogUrl; if (!isUnityPackage) return string.Empty; var shortVersionId = packageInfo.GetShortVersionId(); if (string.IsNullOrEmpty(shortVersionId)) return string.Empty; return $"https://docs.unity3d.com/Packages/{shortVersionId}/changelog/CHANGELOG.html"; } private string GetLicensesUrl(PackageInfo packageInfo, bool isUnityPackage) { if (packageInfo == null) return string.Empty; if (!string.IsNullOrEmpty(packageInfo.licensesUrl)) return packageInfo.licensesUrl; if (!isUnityPackage) return string.Empty; var shortVersionId = packageInfo.GetShortVersionId(); if (string.IsNullOrEmpty(shortVersionId)) return string.Empty; return $"https://docs.unity3d.com/Packages/{shortVersionId}/license/index.html"; } private string GetQuickStartUrl(PackageInfo packageInfo) { var upmReserved = m_UpmCache.ParseUpmReserved(packageInfo); return upmReserved?.GetString("quickstart") ?? string.Empty; } private string GetOfflineDocumentationPath(PackageInfo packageInfo) { if (!string.IsNullOrEmpty(packageInfo?.resolvedPath)) { try { var docsFolder = m_IOProxy.PathsCombine(packageInfo.resolvedPath, "Documentation~"); if (!m_IOProxy.DirectoryExists(docsFolder)) docsFolder = m_IOProxy.PathsCombine(packageInfo.resolvedPath, "Documentation"); if (!m_IOProxy.DirectoryExists(docsFolder)) { var readMeFile = m_IOProxy.PathsCombine(packageInfo.resolvedPath, "README.md"); return m_IOProxy.FileExists(readMeFile) ? readMeFile : string.Empty; } else { var mdFiles = m_IOProxy.DirectoryGetFiles(docsFolder, "*.md", System.IO.SearchOption.TopDirectoryOnly); var docsMd = mdFiles.FirstOrDefault(d => m_IOProxy.GetFileName(d).ToLower() == "index.md") ?? mdFiles.FirstOrDefault(d => m_IOProxy.GetFileName(d).ToLower() == "tableofcontents.md") ?? mdFiles.FirstOrDefault(); if (!string.IsNullOrEmpty(docsMd)) return docsMd; } } catch (System.IO.IOException) { } } return string.Empty; } private string GetOfflineChangelogPath(PackageInfo packageInfo) { if (!string.IsNullOrEmpty(packageInfo?.resolvedPath)) { try { var changelogFile = m_IOProxy.PathsCombine(packageInfo.resolvedPath, "CHANGELOG.md"); return m_IOProxy.FileExists(changelogFile) ? changelogFile : string.Empty; } catch (System.IO.IOException) { } } return string.Empty; } private string GetOfflineLicensesPath(PackageInfo packageInfo) { if (!string.IsNullOrEmpty(packageInfo?.resolvedPath)) { try { // Attempt preferred Markdown extension var markdownLicense = m_IOProxy.PathsCombine(packageInfo.resolvedPath, "LICENSE.md"); if (m_IOProxy.FileExists(markdownLicense)) { return markdownLicense; } // Follow up with GitHub preferred naming var githubLicense = m_IOProxy.PathsCombine(packageInfo.resolvedPath, "LICENSE"); if (m_IOProxy.FileExists(githubLicense)) { return githubLicense; } return string.Empty; } catch (System.IO.IOException) { } } return string.Empty; } public PackageLink CreateUpmDocumentationLink(IPackageVersion version) { var packageInfo = m_UpmCache.GetBestMatchPackageInfo(version.name, version.isInstalled, version.versionString); var isUnityPackage = version.HasTag(PackageTag.Unity); return new PackageUpmDocumentationLink(version) { url = GetDocumentationUrl(packageInfo, isUnityPackage), offlinePath = GetOfflineDocumentationPath(packageInfo), analyticsEventName = "viewDocs", displayName = L10n.Tr("Documentation") }; } public PackageLink CreateUpmChangelogLink(IPackageVersion version) { var packageInfo = m_UpmCache.GetBestMatchPackageInfo(version.name, version.isInstalled, version.versionString); var isUnityPackage = version.HasTag(PackageTag.Unity); return new PackageUpmChangelogLink(version) { url = GetChangelogUrl(packageInfo, isUnityPackage), offlinePath = GetOfflineChangelogPath(packageInfo), analyticsEventName = "viewChangelog", displayName = L10n.Tr("Changelog") }; } public PackageLink CreateVersionHistoryChangelogLink(IPackageVersion version) { var packageInfo = m_UpmCache.GetBestMatchPackageInfo(version.name, version.isInstalled, version.versionString); var isUnityPackage = version.HasTag(PackageTag.Unity); return new PackageUpmVersionHistoryChangelogLink(version) { url = GetChangelogUrl(packageInfo, isUnityPackage), offlinePath = GetOfflineChangelogPath(packageInfo), analyticsEventName = "viewChangelog", displayName = L10n.Tr("Changelog") }; } public PackageLink CreateUpmLicenseLink(IPackageVersion version) { var packageInfo = m_UpmCache.GetBestMatchPackageInfo(version.name, version.isInstalled, version.versionString); var isUnityPackage = version.HasTag(PackageTag.Unity); return new PackageUpmLicenseLink(version) { url = GetLicensesUrl(packageInfo, isUnityPackage), offlinePath = GetOfflineLicensesPath(packageInfo), analyticsEventName = "viewLicense", displayName = L10n.Tr("Licenses") }; } public PackageLink CreateUpmQuickStartLink(IPackageVersion version) { var packageInfo = version != null && version.HasTag(PackageTag.Feature) ? m_UpmCache.GetBestMatchPackageInfo(version.name, version.isInstalled, version.versionString) : null; return new PackageLink(version) { url = GetQuickStartUrl(packageInfo), offlinePath = string.Empty, analyticsEventName = "viewQuickstart", displayName = L10n.Tr("QuickStart") }; } public PackageLink CreateProductLink(IPackageVersion version) { var productInfo = m_AssetStoreCache.GetProductInfo(version.package.product?.id); return new PackageLink(version) { url = productInfo?.assetStoreProductUrl ?? string.Empty, offlinePath = string.Empty, analyticsEventName = "viewProductInAssetStore", displayName = L10n.Tr("View in Asset Store") }; } public PackageLink CreateAuthorLink(IPackageVersion version) { var productInfo = m_AssetStoreCache.GetProductInfo(version?.package.product?.id); return new PackageLink(version) { url = productInfo?.assetStorePublisherUrl ?? string.Empty, offlinePath = string.Empty, analyticsEventName = "viewAuthorLink", displayName = productInfo?.publisherName ?? string.Empty }; } public PackageLink CreatePublisherSupportLink(IPackageVersion version) { var productInfo = m_AssetStoreCache.GetProductInfo(version.package.product?.id); return new PackageLink(version) { url = productInfo?.publisherSupportUrl ?? string.Empty, offlinePath = string.Empty, analyticsEventName = "viewPublisherSupport", displayName = L10n.Tr("Publisher Support") }; } public PackageLink CreatePublisherWebsiteLink(IPackageVersion version) { var productInfo = m_AssetStoreCache.GetProductInfo(version.package.product?.id); return new PackageLink(version) { url = productInfo?.publisherWebsiteUrl ?? string.Empty, offlinePath = string.Empty, analyticsEventName = "viewPublisherWebsite", displayName = L10n.Tr("Publisher Website") }; } public PackageLink CreateUseCasesLink(IPackageVersion version) { return new PackageLink(version) { url = EditorGameServiceExtension.GetUseCasesUrl(version) ?? string.Empty, offlinePath = string.Empty, analyticsEventName = "viewUseCases", displayName = L10n.Tr("Use Cases") }; } public PackageLink CreateDashboardLink(IPackageVersion version) { return new PackageLink(version) { url = EditorGameServiceExtension.GetDashboardUrl(version) ?? string.Empty, offlinePath = string.Empty, analyticsEventName = "viewDashboard", displayName = L10n.Tr("Go to Dashboard") }; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageLink/PackageLinkFactory.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageLink/PackageLinkFactory.cs", "repo_id": "UnityCsReference", "token_count": 5993 }
407
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { internal interface IPageManager : IService { event Action<IPage> onActivePageChanged; event Action<IPage> onListRebuild; event Action<IPage, PageFilters> onFiltersChange; event Action<IPage, string> onTrimmedSearchTextChanged; event Action<PageSelectionChangeArgs> onSelectionChanged; event Action<VisualStateChangeArgs> onVisualStateChange; event Action<ListUpdateArgs> onListUpdate; event Action<IPage> onSupportedStatusFiltersChanged; IPage lastActivePage { get; } IPage activePage { get; set; } IEnumerable<IPage> orderedExtensionPages { get; } void AddExtensionPage(ExtensionPageArgs args); IPage GetPage(string pageId); IPage GetPage(RegistryInfo registryInfo); IPage FindPage(IPackage package, IPackageVersion version = null); IPage FindPage(IList<IPackageVersion> packageVersions); void OnWindowDestroy(); } [Serializable] internal class PageManager : BaseService<IPageManager>, IPageManager, ISerializationCallbackReceiver { public const string k_DefaultPageId = InProjectPage.k_Id; public event Action<IPage> onActivePageChanged = delegate {}; public event Action<IPage> onListRebuild = delegate {}; public event Action<IPage, PageFilters> onFiltersChange = delegate {}; public event Action<IPage, string> onTrimmedSearchTextChanged = delegate {}; public event Action<PageSelectionChangeArgs> onSelectionChanged = delegate {}; public event Action<VisualStateChangeArgs> onVisualStateChange = delegate {}; public event Action<ListUpdateArgs> onListUpdate = delegate {}; public event Action<IPage> onSupportedStatusFiltersChanged = delegate {}; private Dictionary<string, IPage> m_Pages = new(); [SerializeField] private string m_SerializedLastActivePageId; [SerializeField] private string m_SerializedActivePageId; public IPage lastActivePage { get; private set; } private IPage m_ActivePage; public IPage activePage { get { m_ActivePage ??= m_Pages.Values.FirstOrDefault(p => p.isActivePage); if (m_ActivePage != null) return m_ActivePage; m_ActivePage = GetPage(k_DefaultPageId); m_ActivePage.OnActivated(); return m_ActivePage; } set { lastActivePage = activePage; m_ActivePage = value; if (activePage == lastActivePage) return; activePage.OnActivated(); lastActivePage?.OnDeactivated(); onActivePageChanged?.Invoke(activePage); } } [NonSerialized] private List<ExtensionPageArgs> m_OrderedExtensionPageArgs = new(); public IEnumerable<IPage> orderedExtensionPages => m_OrderedExtensionPageArgs.Select(a => GetPage(a.id)); [SerializeReference] private IPage[] m_SerializedPages = Array.Empty<IPage>(); private readonly IUnityConnectProxy m_UnityConnect; private readonly IPackageDatabase m_PackageDatabase; private readonly IProjectSettingsProxy m_SettingsProxy; private readonly IUpmRegistryClient m_UpmRegistryClient; private readonly IPageFactory m_PageFactory; public PageManager(IUnityConnectProxy unityConnect, IPackageDatabase packageDatabase, IProjectSettingsProxy settingsProxy, IUpmRegistryClient upmRegistryClient, IPageFactory pageFactory) { m_UnityConnect = RegisterDependency(unityConnect); m_PackageDatabase = RegisterDependency(packageDatabase); m_SettingsProxy = RegisterDependency(settingsProxy); m_UpmRegistryClient = RegisterDependency(upmRegistryClient); m_PageFactory = RegisterDependency(pageFactory); } public void OnBeforeSerialize() { m_SerializedPages = m_Pages.Values.ToArray(); m_SerializedLastActivePageId = lastActivePage?.id ?? string.Empty; m_SerializedActivePageId = m_ActivePage?.id ?? string.Empty; } public void OnAfterDeserialize() { foreach (var page in m_SerializedPages) { m_Pages[page.id] = page; RegisterPageEvents(page); } lastActivePage = string.IsNullOrEmpty(m_SerializedLastActivePageId) ? null : GetPage(m_SerializedLastActivePageId); m_ActivePage = string.IsNullOrEmpty(m_SerializedActivePageId) ? null : GetPage(m_SerializedActivePageId); foreach (var page in m_Pages.Values) m_PageFactory.ResolveDependenciesForPage(page); } private IPage CreatePageFromId(string pageId) { var page = m_PageFactory.CreatePageFromId(pageId); return page != null ? OnNewPageCreated(page) : null; } private IPage OnNewPageCreated(IPage page) { page.OnEnable(); m_Pages[page.id] = page; RegisterPageEvents(page); return page; } private void RegisterPageEvents(IPage page) { page.onVisualStateChange += args => onVisualStateChange?.Invoke(args); page.onListUpdate += args => onListUpdate?.Invoke(args); page.onSelectionChanged += args => onSelectionChanged?.Invoke(args); page.onListRebuild += p => onListRebuild?.Invoke(p); page.onFiltersChange += filters => onFiltersChange?.Invoke(page, filters); page.onTrimmedSearchTextChanged += text => onTrimmedSearchTextChanged?.Invoke(page, text); page.onSupportedStatusFiltersChanged += p => onSupportedStatusFiltersChanged?.Invoke(p); } public void AddExtensionPage(ExtensionPageArgs args) { if (string.IsNullOrEmpty(args.name)) { Debug.LogWarning(L10n.Tr("An extension page needs to have a non-empty unique name.")); return; } if (m_OrderedExtensionPageArgs.Any(a => a.name == args.name)) { Debug.LogWarning(string.Format(L10n.Tr("An extension page with name {0} already exists. Please use a different name."), args.name)); return; } m_OrderedExtensionPageArgs.Add(args); m_OrderedExtensionPageArgs.Sort((x, y) => x.priority - y.priority); // Since the pages are serialized but m_OrderedExtensionPageArgs is not serialized, after domain reload // we will find an existing page even though we already checked for duplicates earlier. This is expected, // we will use as much of the existing page as we and update the fields that cannot be serialized (the functions) if (m_Pages.Get(ExtensionPage.GetIdFromName(args.name)) is ExtensionPage existingPage) existingPage.UpdateArgs(args); else OnNewPageCreated(m_PageFactory.CreateExtensionPage(args)); } public IPage GetPage(string pageId) { return !string.IsNullOrEmpty(pageId) && m_Pages.TryGetValue(pageId, out var page) ? page : CreatePageFromId(pageId); } public IPage GetPage(RegistryInfo registryInfo) { if (registryInfo == null) return null; var pageId = ScopedRegistryPage.GetIdFromRegistry(registryInfo); return m_Pages.TryGetValue(pageId, out var page) ? page : OnNewPageCreated(m_PageFactory.CreateScopedRegistryPage(registryInfo)); } private void OnPackagesChanged(PackagesChangeArgs args) { activePage.OnPackagesChanged(args); } private void OnRegistriesModified() { // Here we only want to remove outdated pages and update existing pages when needed // We will delay the creation of new pages to when the UI is displaying them to save some resources var scopedRegistries = m_SettingsProxy.scopedRegistries.ToDictionary(r => r.id, r => r); var scopedRegistryPages = m_Pages.Values.OfType<ScopedRegistryPage>().ToArray(); var pagesToRemove = new HashSet<string>(); foreach (var page in scopedRegistryPages) { if (scopedRegistries.TryGetValue(page.registry.id, out var registryInfo)) page.UpdateRegistry(registryInfo); else pagesToRemove.Add(page.id); } if (pagesToRemove.Contains(activePage.id)) activePage = GetPage(k_DefaultPageId); foreach (var pageId in pagesToRemove) m_Pages.Remove(pageId); if (scopedRegistries.Count > 0) return; GetPage(MyRegistriesPage.k_Id).ClearFilters(true); } private void OnUserLoginStateChange(bool userInfoReady, bool loggedIn) { GetPage(MyAssetsPage.k_Id).ClearFilters(true); } public IPage FindPage(IPackage package, IPackageVersion version = null) { return FindPage(new[] { version ?? package?.versions.primary }); } public IPage FindPage(IList<IPackageVersion> packageVersions) { if (packageVersions?.Any() != true || packageVersions.All(v => activePage.visualStates.Contains(v.package.uniqueId) || activePage.ShouldInclude(v.package))) return activePage; var pageIdsToCheck = new[] { BuiltInPage.k_Id, InProjectPage.k_Id, UnityRegistryPage.k_Id, MyAssetsPage.k_Id, MyRegistriesPage.k_Id}; foreach (var page in pageIdsToCheck.Select(GetPage).Where(p => !p.isActivePage)) if (packageVersions.All(v => page.ShouldInclude(v.package))) return page; if (!m_SettingsProxy.enablePreReleasePackages && packageVersions.Any(v => v.version?.Prerelease.StartsWith("pre.") == true)) Debug.Log(L10n.Tr("You must check \"Enable Pre-release Packages\" in Project Settings > Package Manager in order to see this package.")); return null; } [ExcludeFromCodeCoverage] public override void OnEnable() { foreach (var page in m_Pages.Values) page.OnEnable(); m_PackageDatabase.onPackagesChanged += OnPackagesChanged; m_UpmRegistryClient.onRegistriesModified += OnRegistriesModified; m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange; } [ExcludeFromCodeCoverage] public override void OnDisable() { foreach (var page in m_Pages.Values) page.OnDisable(); m_PackageDatabase.onPackagesChanged -= OnPackagesChanged; m_UpmRegistryClient.onRegistriesModified -= OnRegistriesModified; m_UnityConnect.onUserLoginStateChange -= OnUserLoginStateChange; } public void OnWindowDestroy() { // Since extension pages are added on Window creation time we need to clear them on Window destroy, so the next // time the Package Manager window is created (which would happen when it is closed and reopened), we will not // report a false alarm of page name duplication. m_OrderedExtensionPageArgs.Clear(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageManager.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageManager.cs", "repo_id": "UnityCsReference", "token_count": 5109 }
408
// 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.CodeAnalysis; using System.Linq; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class VisualStateList : ISerializationCallbackReceiver, IVisualStateList { [SerializeField] protected List<VisualState> m_OrderedVisualStates = new(); protected virtual IEnumerable<VisualState> orderedListBeforeGrouping => m_OrderedVisualStates; [SerializeField] private string[] m_OrderedGroups = Array.Empty<string>(); public virtual IList<string> orderedGroups => m_OrderedGroups; public virtual long countLoaded => m_OrderedVisualStates.Count; public virtual long countTotal => m_OrderedVisualStates.Count; // a reverse look up table such that we can find an visual state easily through package unique id protected Dictionary<string, int> m_UniqueIdToIndexLookup = new(); public VisualStateList() : this(Enumerable.Empty<string>()) {} public VisualStateList(IEnumerable<string> packageUniqueIds) { Rebuild(packageUniqueIds ?? Enumerable.Empty<string>()); } [ExcludeFromCodeCoverage] public void OnBeforeSerialize() { } [ExcludeFromCodeCoverage] public void OnAfterDeserialize() { SetupLookupTable(); } public void Rebuild(IEnumerable<string> packageUniqueIds) { Rebuild(packageUniqueIds.Select(id => Get(id) ?? new VisualState(id))); } public void Rebuild(IEnumerable<VisualState> orderedVisualStates, IEnumerable<string> orderedGroupNames = null) { m_OrderedVisualStates = orderedVisualStates.ToList(); m_OrderedGroups = orderedGroupNames?.ToArray() ?? Array.Empty<string>(); SetupLookupTable(); } public virtual VisualState Get(string packageUniqueId) { if (!string.IsNullOrEmpty(packageUniqueId) && m_UniqueIdToIndexLookup.TryGetValue(packageUniqueId, out var index)) return m_OrderedVisualStates[index]; return null; } public virtual bool Contains(string packageUniqueId) { return !string.IsNullOrEmpty(packageUniqueId) && m_UniqueIdToIndexLookup.ContainsKey(packageUniqueId); } protected void SetupLookupTable() { m_UniqueIdToIndexLookup.Clear(); for (var i = 0; i < m_OrderedVisualStates.Count; i++) m_UniqueIdToIndexLookup[m_OrderedVisualStates[i].packageUniqueId] = i; } public virtual IEnumerator<VisualState> GetEnumerator() { // The final ordering of the visual states is decided by the order of the group and the order of the items // We prioritize the order of the groups, i.e. items matching the first group name will always be enumerated first // The order of items within each group is kept untouched if (m_OrderedGroups.Length > 1) foreach (var groupName in m_OrderedGroups) foreach (var v in orderedListBeforeGrouping.Where(v => v.groupName == groupName)) yield return v; else foreach (var v in orderedListBeforeGrouping) yield return v; } [ExcludeFromCodeCoverage] IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/VisualStateList.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/VisualStateList.cs", "repo_id": "UnityCsReference", "token_count": 1529 }
409
// 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.Diagnostics.CodeAnalysis; using UnityEditor.Connect; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { internal interface IUnityConnectProxy : IService { event Action<bool, bool> onUserLoginStateChange; bool isUserInfoReady { get; } bool isUserLoggedIn { get; } string GetConfigurationURL(CloudConfigUrl config); void ShowLogin(); void OpenAuthorizedURLInWebBrowser(string url); } [Serializable] [ExcludeFromCodeCoverage] internal class UnityConnectProxy : BaseService<IUnityConnectProxy>, IUnityConnectProxy { [SerializeField] private bool m_IsUserInfoReady; [SerializeField] private bool m_HasAccessToken; [SerializeField] private string m_UserId = string.Empty; public event Action<bool, bool> onUserLoginStateChange = delegate {}; public bool isUserInfoReady => m_IsUserInfoReady; public bool isUserLoggedIn => m_IsUserInfoReady && m_HasAccessToken; public override void OnEnable() { m_IsUserInfoReady = UnityConnect.instance.isUserInfoReady; m_HasAccessToken = !string.IsNullOrEmpty(UnityConnect.instance.userInfo.accessToken); UnityConnect.instance.UserStateChanged += OnUserStateChanged; } public override void OnDisable() { UnityConnect.instance.UserStateChanged -= OnUserStateChanged; } public string GetConfigurationURL(CloudConfigUrl config) { return UnityConnect.instance.GetConfigurationURL(config); } public void ShowLogin() { UnityConnect.instance.ShowLogin(); } public void OpenAuthorizedURLInWebBrowser(string url) { UnityConnect.instance.OpenAuthorizedURLInWebBrowser(url); } private void OnUserStateChanged(UserInfo newInfo) { var prevIsUserInfoReady = isUserInfoReady; var prevIsUserLoggedIn = isUserLoggedIn; m_IsUserInfoReady = UnityConnect.instance.isUserInfoReady; m_HasAccessToken = !string.IsNullOrEmpty(UnityConnect.instance.userInfo.accessToken); if (isUserInfoReady != prevIsUserInfoReady || isUserLoggedIn != prevIsUserLoggedIn || newInfo.userId != m_UserId) onUserLoginStateChange?.Invoke(isUserInfoReady, isUserLoggedIn); m_UserId = newInfo.userId; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/UnityConnectProxy.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/UnityConnectProxy.cs", "repo_id": "UnityCsReference", "token_count": 1061 }
410
// 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.PackageManager.Requests; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { internal interface IUpmRegistryClient : IService { event Action<int> onRegistriesAdded; event Action onRegistriesModified; event Action<string, UIError> onRegistryOperationError; void AddRegistry(string name, string url, string[] scopes); void UpdateRegistry(string oldName, string newName, string url, string[] scopes); void RemoveRegistry(string name); void CheckRegistriesChanged(); } [Serializable] internal class UpmRegistryClient : BaseService<IUpmRegistryClient>, IUpmRegistryClient, ISerializationCallbackReceiver { public event Action<int> onRegistriesAdded = delegate {}; public event Action onRegistriesModified = delegate {}; public event Action<string, UIError> onRegistryOperationError = delegate {}; [SerializeField] private UpmGetRegistriesOperation m_GetRegistriesOperation; private UpmGetRegistriesOperation getRegistriesOperation => CreateOperation(ref m_GetRegistriesOperation); [SerializeField] private UpmAddRegistryOperation m_AddRegistryOperation; private UpmAddRegistryOperation addRegistryOperation => CreateOperation(ref m_AddRegistryOperation); [SerializeField] private UpmUpdateRegistryOperation m_UpdateRegistryOperation; private UpmUpdateRegistryOperation updateRegistryOperation => CreateOperation(ref m_UpdateRegistryOperation); [SerializeField] private UpmRemoveRegistryOperation m_RemoveRegistryOperation; private UpmRemoveRegistryOperation removeRegistryOperation => CreateOperation(ref m_RemoveRegistryOperation); private readonly IUpmCache m_UpmCache; private readonly IProjectSettingsProxy m_SettingsProxy; private readonly IClientProxy m_ClientProxy; private readonly IApplicationProxy m_ApplicationProxy; public UpmRegistryClient(IUpmCache upmCache, IProjectSettingsProxy settingsProxy, IClientProxy clientProxy, IApplicationProxy applicationProxy) { m_UpmCache = RegisterDependency(upmCache); m_SettingsProxy = RegisterDependency(settingsProxy); m_ClientProxy = RegisterDependency(clientProxy); m_ApplicationProxy = RegisterDependency(applicationProxy); } public void AddRegistry(string name, string url, string[] scopes) { addRegistryOperation.Add(name, url, scopes); addRegistryOperation.onProcessResult += OnProcessAddRegistryResult; addRegistryOperation.onOperationError += (op, error) => onRegistryOperationError?.Invoke(name, error); } private void OnProcessAddRegistryResult(AddScopedRegistryRequest request) { var result = request.Result; if (m_SettingsProxy.AddRegistry(result)) { m_SettingsProxy.Save(); onRegistriesModified?.Invoke(); m_ClientProxy.Resolve(); } } public void UpdateRegistry(string oldName, string newName, string url, string[] scopes) { updateRegistryOperation.Update(oldName, newName, url, scopes); updateRegistryOperation.onProcessResult += OnProcessUpdateRegistryResult; updateRegistryOperation.onOperationError += (op, error) => onRegistryOperationError?.Invoke(oldName, error); } private void OnProcessUpdateRegistryResult(UpdateScopedRegistryRequest request) { var result = request.Result; if (m_SettingsProxy.UpdateRegistry(updateRegistryOperation.registryName, result)) { m_SettingsProxy.Save(); onRegistriesModified?.Invoke(); m_ClientProxy.Resolve(); } } public void RemoveRegistry(string name) { if (string.IsNullOrEmpty(name)) return; var installedPackageInfoOnRegistry = m_UpmCache.installedPackageInfos.Where(p => p.registry?.name == name); if (installedPackageInfoOnRegistry.Any()) { Debug.LogError(string.Format(L10n.Tr("[Package Manager Window] There are packages installed from the registry {0}. Please remove the packages before removing the registry."), name)); return; } removeRegistryOperation.Remove(name); removeRegistryOperation.onProcessResult += OnProcessRemoveRegistryResult; removeRegistryOperation.onOperationError += (op, error) => onRegistryOperationError?.Invoke(name, error); } private void OnProcessRemoveRegistryResult(RemoveScopedRegistryRequest request) { if (m_SettingsProxy.RemoveRegistry(removeRegistryOperation.registryName)) { m_SettingsProxy.Save(); onRegistriesModified?.Invoke(); m_ClientProxy.Resolve(); } } public void CheckRegistriesChanged() { if (Unsupported.IsRegistryValidationDisabled) return; if (getRegistriesOperation.isInProgress) getRegistriesOperation.Cancel(); getRegistriesOperation.GetRegistries(); getRegistriesOperation.onProcessResult += OnProcessGetRegistriesResult; getRegistriesOperation.logErrorInConsole = true; } private void OnProcessGetRegistriesResult(GetRegistriesRequest request) { var registriesListResult = request.Result ?? new RegistryInfo[0]; var registriesCount = registriesListResult.Length; if (m_SettingsProxy.registries.Any() && m_SettingsProxy.registries.Count < registriesCount) onRegistriesAdded?.Invoke(registriesCount - m_SettingsProxy.registries.Count); if (!registriesListResult.SequenceEqual(m_SettingsProxy.registries, new RegistryInfoComparer())) { var name = registriesListResult.FirstOrDefault(r => !m_SettingsProxy.registries.Contains(r, new RegistryInfoComparer()))?.name; if (!string.IsNullOrEmpty(name)) m_SettingsProxy.SelectRegistry(name); m_SettingsProxy.SetRegistries(registriesListResult); m_SettingsProxy.Save(); onRegistriesModified?.Invoke(); } } private T CreateOperation<T>(ref T operation) where T : UpmBaseOperation, new() { if (operation != null) return operation; operation = new T(); operation.ResolveDependencies(m_ClientProxy, m_ApplicationProxy); return operation; } internal class RegistryInfoComparer : IEqualityComparer<RegistryInfo> { public bool Equals(RegistryInfo x, RegistryInfo y) { if (x == y) return true; if (x == null || y == null) return false; var equals = (x.id ?? string.Empty) == (y.id ?? string.Empty) && (x.name ?? string.Empty) == (y.name ?? string.Empty) && (x.url ?? string.Empty) == (y.url ?? string.Empty) && x.isDefault == y.isDefault; if (!equals) return false; var xScopes = x.scopes ?? new string[0]; var yScopes = y.scopes ?? new string[0]; return xScopes.Where(s => !string.IsNullOrEmpty(s)).SequenceEqual(yScopes.Where(s => !string.IsNullOrEmpty(s))); } public int GetHashCode(RegistryInfo obj) { var hashCode = (obj.id != null ? obj.id.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.name != null ? obj.name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.url != null ? obj.url.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (obj.scopes != null ? obj.scopes.GetHashCode() : 0); hashCode = (hashCode * 397) ^ obj.isDefault.GetHashCode(); return hashCode; } } public void OnBeforeSerialize() { } public void OnAfterDeserialize() { m_GetRegistriesOperation?.ResolveDependencies(m_ClientProxy, m_ApplicationProxy); m_AddRegistryOperation?.ResolveDependencies(m_ClientProxy, m_ApplicationProxy); m_UpdateRegistryOperation?.ResolveDependencies(m_ClientProxy, m_ApplicationProxy); m_RemoveRegistryOperation?.ResolveDependencies(m_ClientProxy, m_ApplicationProxy); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmRegistryClient.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmRegistryClient.cs", "repo_id": "UnityCsReference", "token_count": 3860 }
411
// 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.PackageManager.UI.Internal { internal class SelectableLabel : Label { [Serializable] internal new class UxmlSerializedData : Label.UxmlSerializedData { public override object CreateInstance() => new SelectableLabel(); } public SelectableLabel() { SetAsSelectableAndElided(); } public void SetAsSelectableAndElided() { selection.isSelectable = true; focusable = true; displayTooltipWhenElided = true; } public void SetValueWithoutNotify(string value) { text = value; } public bool multiline { get; set; } public string value { get => text; set => text = value; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/SelectableLabel.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/SelectableLabel.cs", "repo_id": "UnityCsReference", "token_count": 454 }
412
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class GenericInputDropdown : DropdownContent { public static readonly string k_DefaultSubmitButtonText = L10n.Tr("Submit"); private static readonly Vector2 k_DefaultWindowSize = new Vector2(320, 50); private Vector2 m_WindowSize; internal override Vector2 windowSize => m_WindowSize; public Action<string> submitClicked { get; set; } private TextFieldPlaceholder m_InputPlaceholder; private EditorWindow m_AnchorWindow; private IResourceLoader m_ResourceLoader; private void ResolveDependencies(IResourceLoader resourceLoader) { m_ResourceLoader = resourceLoader; } public GenericInputDropdown(IResourceLoader resourceLoader, EditorWindow anchorWindow, InputDropdownArgs args) { ResolveDependencies(resourceLoader); styleSheets.Add(m_ResourceLoader.inputDropdownStyleSheet); var root = m_ResourceLoader.GetTemplate("GenericInputDropdown.uxml"); Add(root); cache = new VisualElementCache(root); Init(anchorWindow, args); } internal override void OnDropdownShown() { inputTextField.Focus(); m_AnchorWindow?.rootVisualElement?.SetEnabled(false); } internal override void OnDropdownClosed() { m_InputPlaceholder.OnDisable(); inputTextField.UnregisterCallback<ChangeEvent<string>>(OnTextFieldChange); inputTextField.UnregisterCallback<KeyDownEvent>(OnKeyDownShortcut, TrickleDown.TrickleDown); submitButton.clickable.clicked -= SubmitClicked; if (m_AnchorWindow != null) { m_AnchorWindow.rootVisualElement.SetEnabled(true); m_AnchorWindow = null; } inputTextField.value = string.Empty; submitButton.text = string.Empty; submitClicked = null; } private void Init(EditorWindow anchorWindow, InputDropdownArgs args) { m_AnchorWindow = anchorWindow; m_WindowSize = args.windowSize ?? k_DefaultWindowSize; inputTextField.value = args.defaultValue ?? string.Empty; inputTextField.RegisterCallback<ChangeEvent<string>>(OnTextFieldChange); inputTextField.RegisterCallback<KeyDownEvent>(OnKeyDownShortcut, TrickleDown.TrickleDown); m_InputPlaceholder = new TextFieldPlaceholder(inputTextField); m_InputPlaceholder.text = args.placeholderText ?? string.Empty; mainTitle.text = args.title ?? string.Empty; UIUtils.SetElementDisplay(mainTitle, !string.IsNullOrEmpty(mainTitle.text)); var showIcon = false; if (!string.IsNullOrEmpty(args.iconUssClass)) { showIcon = true; icon.AddToClassList(args.iconUssClass); } else if (args.icon != null) { showIcon = true; icon.style.backgroundImage = new StyleBackground((Background)args.icon); } UIUtils.SetElementDisplay(icon, showIcon); submitButton.clickable.clicked += SubmitClicked; submitButton.SetEnabled(!string.IsNullOrWhiteSpace(inputTextField.value)); submitButton.text = !string.IsNullOrEmpty(args.submitButtonText) ? args.submitButtonText : k_DefaultSubmitButtonText; if (args.onInputSubmitted != null) submitClicked = args.onInputSubmitted; } internal void SubmitClicked() { var value = inputTextField.value.Trim(); if (string.IsNullOrEmpty(value)) return; submitClicked?.Invoke(value); Close(); } private void OnTextFieldChange(ChangeEvent<string> evt) { submitButton.SetEnabled(!string.IsNullOrWhiteSpace(inputTextField.value)); } private void OnKeyDownShortcut(KeyDownEvent evt) { switch (evt.keyCode) { case KeyCode.Escape: Close(); break; case KeyCode.Return: case KeyCode.KeypadEnter: SubmitClicked(); break; } } private VisualElementCache cache { get; set; } private VisualElement icon => cache.Get<VisualElement>("icon"); private Label mainTitle => cache.Get<Label>("mainTitle"); private TextField inputTextField => cache.Get<TextField>("inputTextField"); private Button submitButton => cache.Get<Button>("submitButton"); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/GenericInputDropdown.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/GenericInputDropdown.cs", "repo_id": "UnityCsReference", "token_count": 2195 }
413
// 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; namespace UnityEditor.PackageManager.UI.Internal { internal class RemoveFoldoutGroup : MultiSelectFoldoutGroup { public RemoveFoldoutGroup(IApplicationProxy applicationProxy, IPackageManagerPrefs packageManagerPrefs, IPackageDatabase packageDatabase, IPackageOperationDispatcher operationDispatcher, IPageManager pageManager) : base(new RemoveAction(operationDispatcher, applicationProxy, packageManagerPrefs, packageDatabase, pageManager)) { } public override void Refresh() { if (mainFoldout.versions.FirstOrDefault()?.HasTag(PackageTag.BuiltIn) == true) mainFoldout.headerTextTemplate = L10n.Tr("Disable {0}"); else mainFoldout.headerTextTemplate = L10n.Tr("Remove {0}"); if (inProgressFoldout.versions.FirstOrDefault()?.HasTag(PackageTag.BuiltIn) == true) inProgressFoldout.headerTextTemplate = L10n.Tr("Disabling {0}"); else inProgressFoldout.headerTextTemplate = L10n.Tr("Removing {0}"); base.Refresh(); } public override bool AddPackageVersion(IPackageVersion version) { return version.HasTag(PackageTag.UpmFormat) && base.AddPackageVersion(version); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/RemoveFoldoutGroup.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/RemoveFoldoutGroup.cs", "repo_id": "UnityCsReference", "token_count": 721 }
414
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageDetailsReleasesTab : PackageDetailsTabElement { public const string k_Id = "releases"; private readonly VisualElement m_ReleasesContainer; protected override bool requiresUserSignIn => true; public override bool IsValid(IPackageVersion version) { return version != null && version.package.product != null && !version.HasTag(PackageTag.UpmFormat); } public PackageDetailsReleasesTab(IUnityConnectProxy unityConnect) : base(unityConnect) { m_Id = k_Id; m_DisplayName = L10n.Tr("Releases"); m_ReleasesContainer = new VisualElement { name = "releasesContainer" }; m_ContentContainer.Add(m_ReleasesContainer); } protected override void RefreshContent(IPackageVersion version) { m_ReleasesContainer.Clear(); if (version is PlaceholderPackageVersion) return; if (version?.package.product?.firstPublishedDate != null) { var latest = version.package.versions.latest; m_ReleasesContainer.Add(new PackageReleaseDetailsItem(latest.versionString, latest.publishedDate, latest == version, latest.package.product.latestReleaseNotes)); if (latest != version) m_ReleasesContainer.Add(new PackageReleaseDetailsItem(version.versionString, version.publishedDate, true, version.localReleaseNotes)); m_ReleasesContainer.Add(new PackageReleaseDetailsItem(L10n.Tr("Original"), version.package.product.firstPublishedDate)); } } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsReleasesTab.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsReleasesTab.cs", "repo_id": "UnityCsReference", "token_count": 730 }
415
// 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.PackageManager.UI.Internal { internal class PackageLoadBar : VisualElement { internal const int k_FixedHeight = 30; [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new PackageLoadBar(); } public enum AssetsToLoad { Min = 25, Max = 50, All = -1 } private long m_Total; private long m_NumberOfPackagesShown; private static readonly string k_All = L10n.Tr("All"); private bool m_Enabled; private long m_LoadMore; private string m_LoadedText; private bool m_DoShowLoadMoreLabel; private bool m_LoadMoreInProgress; private bool m_LoadAllDiff; private IResourceLoader m_ResourceLoader; private IApplicationProxy m_Application; private IUnityConnectProxy m_UnityConnect; private IPageManager m_PageManager; private IProjectSettingsProxy m_SettingsProxy; private IPageRefreshHandler m_PageRefreshHandler; private void ResolveDependencies() { var container = ServicesContainer.instance; m_ResourceLoader = container.Resolve<IResourceLoader>(); m_Application = container.Resolve<IApplicationProxy>(); m_UnityConnect = container.Resolve<IUnityConnectProxy>(); m_PageManager = container.Resolve<IPageManager>(); m_SettingsProxy = container.Resolve<IProjectSettingsProxy>(); m_PageRefreshHandler = container.Resolve<IPageRefreshHandler>(); } public PackageLoadBar() { ResolveDependencies(); var root = m_ResourceLoader.GetTemplate("PackageLoadBar.uxml"); Add(root); cache = new VisualElementCache(root); var dropdownButton = new DropdownButton(); dropdownButton.name = "loadAssetsDropdown"; loadAssetsDropdownContainer.Add(dropdownButton); loadMoreLabel.OnLeftClick(LoadItemsClicked); } public void OnEnable() { m_Enabled = true; m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange; m_Application.onInternetReachabilityChange += OnInternetReachabilityChange; m_PageRefreshHandler.onRefreshOperationFinish += Refresh; Refresh(); } public void OnDisable() { m_Enabled = false; m_UnityConnect.onUserLoginStateChange -= OnUserLoginStateChange; m_Application.onInternetReachabilityChange -= OnInternetReachabilityChange; m_PageRefreshHandler.onRefreshOperationFinish -= Refresh; } public void UpdateMenu() { var menu = new DropdownMenu(); EditorApplication.delayCall -= UpdateMenu; if (m_Enabled && m_Total == 0) EditorApplication.delayCall += UpdateMenu; AddDropdownItems(menu); loadAssetsDropdown.menu = menu.MenuItems().Count > 0 ? menu : null; } public void AddDropdownItems(DropdownMenu menu) { m_LoadAllDiff = m_Total - m_NumberOfPackagesShown <= (int)AssetsToLoad.Min; var minDiff = m_LoadAllDiff; if (!minDiff) AddDropdownItem(menu, (int)AssetsToLoad.Min); m_LoadAllDiff = m_Total - m_NumberOfPackagesShown <= (int)AssetsToLoad.Max; var maxDiff = m_LoadAllDiff; if (!maxDiff) AddDropdownItem(menu, (int)AssetsToLoad.Max); var showDropDownArea = !minDiff || !maxDiff; if (showDropDownArea) AddDropdownItem(menu, (int)AssetsToLoad.All); } public void AddDropdownItem(DropdownMenu menu, int value) { var textValue = value == (int)AssetsToLoad.All ? k_All : value.ToString(); textValue = L10n.Tr(textValue); menu.AppendAction(textValue, a => { loadAssetsDropdown.text = textValue; m_SettingsProxy.loadAssets = value; m_SettingsProxy.Save(); UpdateLoadBarMessage(); LoadItemsClicked(); UpdateMenu(); PackageManagerWindowAnalytics.SendEvent($"load {value}"); }, a => m_SettingsProxy.loadAssets == value ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } private void OnUserLoginStateChange(bool userInfoReady, bool loggedIn) { UpdateLoadBarMessage(); } private void OnInternetReachabilityChange(bool value) { loadMoreLabel.SetEnabled(value && !m_LoadMoreInProgress); } public void UpdateVisibility(string pageId = null) { pageId = string.IsNullOrEmpty(pageId) ? m_PageManager.activePage.id : pageId; UIUtils.SetElementDisplay(this, pageId == MyAssetsPage.k_Id); Refresh(); } public void Refresh() { if (!UIUtils.IsElementVisible(this)) return; var visualStates = m_PageManager.activePage?.visualStates; Set(visualStates?.countTotal ?? 0, visualStates?.countLoaded?? 0); UpdateMenu(); OnInternetReachabilityChange(m_Application.isInternetReachable); } internal void Set(long total, long current) { Reset(); m_Total = total; m_NumberOfPackagesShown = current; loadMoreLabel.SetEnabled(true); m_LoadMoreInProgress = false; UpdateLoadBarMessage(); } internal void Reset() { m_DoShowLoadMoreLabel = true; } public void LoadItemsClicked() { loadMoreLabel.SetEnabled(false); m_LoadMoreInProgress = true; m_PageManager.activePage.LoadMore(m_LoadMore); UpdateMenu(); } private void UpdateLoadBarMessage() { if (!m_UnityConnect.isUserLoggedIn || m_Total == 0 || m_NumberOfPackagesShown == 0) { UIUtils.SetElementDisplay(loadBarContainer, false); return; } if (m_Total <= m_NumberOfPackagesShown) { m_DoShowLoadMoreLabel = false; m_LoadedText = m_Total == 1 ? L10n.Tr("One package shown") : string.Format(L10n.Tr("All {0} packages shown"), m_NumberOfPackagesShown); } else { var diff = m_Total - m_NumberOfPackagesShown; var max = m_SettingsProxy.loadAssets == (long)AssetsToLoad.All ? m_Total : m_SettingsProxy.loadAssets; if (diff >= max) { m_LoadAllDiff = false; m_LoadMore = max; } else { m_LoadAllDiff = true; m_LoadMore = diff; } m_LoadedText = string.Format(L10n.Tr("{0} of {1}"), m_NumberOfPackagesShown, m_Total); } SetLabels(); } private void SetLabels() { var loadAll = m_SettingsProxy.loadAssets == (int)AssetsToLoad.All ? true : false; loadAssetsDropdown.text = loadAll || m_LoadAllDiff ? k_All : m_LoadMore.ToString(); loadedLabel.text = m_LoadedText; UIUtils.SetElementDisplay(loadAssetsDropdown, m_DoShowLoadMoreLabel); UIUtils.SetElementDisplay(loadMoreLabel, m_DoShowLoadMoreLabel); UIUtils.SetElementDisplay(loadBarContainer, true); } private VisualElementCache cache { get; set; } private Label loadedLabel { get { return cache.Get<Label>("loadedLabel"); } } private Label loadMoreLabel { get { return cache.Get<Label>("loadMoreLabel"); } } private VisualElement loadBarContainer { get { return cache.Get<VisualElement>("loadBarContainer"); } } private VisualElement loadAssetsDropdownContainer { get { return cache.Get<VisualElement>("loadAssetsDropdownContainer"); } } private DropdownButton loadAssetsDropdown { get { return cache.Get<DropdownButton>("loadAssetsDropdown"); } } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageLoadBar.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageLoadBar.cs", "repo_id": "UnityCsReference", "token_count": 3983 }
416
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal abstract class PackageBaseTagLabel : Label { public new static readonly string ussClassName = "package-tag-label"; public PackageBaseTagLabel() { AddToClassList(ussClassName); } public abstract void Refresh(IPackageVersion version); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageTagLabel/PackageBaseTagLabel.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageTagLabel/PackageBaseTagLabel.cs", "repo_id": "UnityCsReference", "token_count": 192 }
417
// 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.UIElements; namespace UnityEditor.PackageManager.UI.Internal; internal class Sidebar : ScrollView { [Serializable] public new class UxmlSerializedData : ScrollView.UxmlSerializedData { public override object CreateInstance() => new Sidebar(); } private IUpmRegistryClient m_UpmRegistryClient; private IProjectSettingsProxy m_SettingsProxy; private IPageManager m_PageManager; private Dictionary<string, SidebarRow> m_ScopedRegistryRows = new(); private SidebarRow m_CurrentlySelectedRow; private void ResolveDependencies() { var container = ServicesContainer.instance; m_UpmRegistryClient = container.Resolve<IUpmRegistryClient>(); m_SettingsProxy = container.Resolve<IProjectSettingsProxy>(); m_PageManager = container.Resolve<IPageManager>(); } public Sidebar() { ResolveDependencies(); } public void OnEnable() { m_UpmRegistryClient.onRegistriesModified += UpdateScopedRegistryRelatedRows; m_PageManager.onActivePageChanged += OnActivePageChanged; } public void OnCreateGUI() { CreateRows(); OnActivePageChanged(m_PageManager.activePage); } public void OnDisable() { m_UpmRegistryClient.onRegistriesModified -= UpdateScopedRegistryRelatedRows; m_PageManager.onActivePageChanged -= OnActivePageChanged; } private void CreateRows() { CreateAndAddSeparator(); CreateAndAddSidebarRow(m_PageManager.GetPage(InProjectPage.k_Id)); CreateAndAddSidebarRow(m_PageManager.GetPage(InProjectUpdatesPage.k_Id), isIndented: true); CreateAndAddSeparator(); CreateAndAddSidebarRow(m_PageManager.GetPage(UnityRegistryPage.k_Id)); CreateAndAddSidebarRow(m_PageManager.GetPage(MyAssetsPage.k_Id)); CreateAndAddSidebarRow(m_PageManager.GetPage(BuiltInPage.k_Id)); CreateAndAddSeparator(); foreach (var page in m_PageManager.orderedExtensionPages) CreateAndAddSidebarRow(page); CreateAndAddSeparator(); CreateAndAddSidebarRow(m_PageManager.GetPage(MyRegistriesPage.k_Id)); UpdateScopedRegistryRelatedRows(); } private void CreateAndAddSidebarRow(IPage page, bool isScopedRegistryPage = false, bool isIndented = false) { var pageId = page.id; var sidebarRow = new SidebarRow(page.id, page.displayName, page.icon, isIndented); sidebarRow.OnLeftClick(() => OnRowClick(pageId)); if (isScopedRegistryPage) m_ScopedRegistryRows[page.id] = sidebarRow; Add(sidebarRow); } private void CreateAndAddSeparator() { Add(new VisualElement { classList = { "sidebarSeparator" } }); } private void OnRowClick(string pageId) { if (pageId == m_PageManager.activePage.id) return; m_PageManager.activePage = m_PageManager.GetPage(pageId); PackageManagerWindowAnalytics.SendEvent("changeFilter"); } private void OnActivePageChanged(IPage page) { m_CurrentlySelectedRow?.SetSelected(false); m_CurrentlySelectedRow = GetRow(page.id); m_CurrentlySelectedRow?.SetSelected(true); } private void UpdateScopedRegistryRelatedRows() { var scopedRegistryPages = m_SettingsProxy.scopedRegistries.Select(r => m_PageManager.GetPage(r)).ToArray(); // We remove the rows from the hierarchy so we can add it back later with the right order foreach (var row in m_ScopedRegistryRows.Values) Remove(row); var deletedOrHiddenPageIds = m_ScopedRegistryRows.Keys.ToHashSet(); foreach (var page in scopedRegistryPages) { if (m_ScopedRegistryRows.TryGetValue(page.id, out var row)) { deletedOrHiddenPageIds.Remove(page.id); Add(row); } else CreateAndAddSidebarRow(page, true, true); } foreach (var pageId in deletedOrHiddenPageIds) m_ScopedRegistryRows.Remove(pageId); var myRegistriesRowVisible = scopedRegistryPages.Any(); UIUtils.SetElementDisplay(GetRow(MyRegistriesPage.k_Id), myRegistriesRowVisible); if (!myRegistriesRowVisible) deletedOrHiddenPageIds.Add(MyRegistriesPage.k_Id); if (deletedOrHiddenPageIds.Contains(m_PageManager.activePage.id)) m_PageManager.activePage = m_PageManager.GetPage(PageManager.k_DefaultPageId); } public SidebarRow GetRow(string pageId) { return Children().OfType<SidebarRow>().FirstOrDefault(i => i.pageId == pageId); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/Sidebar/Sidebar.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Sidebar/Sidebar.cs", "repo_id": "UnityCsReference", "token_count": 1989 }
418
// 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 System.Runtime.InteropServices; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEngine { [NativeHeader("ParticleSystemScriptingClasses.h")] [NativeHeader("Modules/ParticleSystem/ParticleSystemRenderer.h")] [NativeHeader("Modules/ParticleSystem/ScriptBindings/ParticleSystemRendererScriptBindings.h")] [RequireComponent(typeof(Transform))] public sealed partial class ParticleSystemRenderer : Renderer { [NativeName("RenderAlignment")] extern public ParticleSystemRenderSpace alignment { get; set; } extern public ParticleSystemRenderMode renderMode { get; set; } extern public ParticleSystemMeshDistribution meshDistribution { get; set; } extern public ParticleSystemSortMode sortMode { get; set; } extern public float lengthScale { get; set; } extern public float velocityScale { get; set; } extern public float cameraVelocityScale { get; set; } extern public float normalDirection { get; set; } extern public float shadowBias { get; set; } extern public float sortingFudge { get; set; } extern public float minParticleSize { get; set; } extern public float maxParticleSize { get; set; } extern public Vector3 pivot { get; set; } extern public Vector3 flip { get; set; } extern public SpriteMaskInteraction maskInteraction { get; set; } extern public Material trailMaterial { get; set; } extern internal Material oldTrailMaterial { set; } extern public bool enableGPUInstancing { get; set; } extern public bool allowRoll { get; set; } extern public bool freeformStretching { get; set; } extern public bool rotateWithStretchDirection { get; set; } // Mesh used as particle instead of billboarded texture. extern public Mesh mesh { [FreeFunction(Name = "ParticleSystemRendererScriptBindings::GetMesh", HasExplicitThis = true)] get; [FreeFunction(Name = "ParticleSystemRendererScriptBindings::SetMesh", HasExplicitThis = true)] set; } [RequiredByNativeCode] // Added to any method to prevent stripping of the class [FreeFunction(Name = "ParticleSystemRendererScriptBindings::GetMeshes", HasExplicitThis = true)] extern public int GetMeshes([NotNull][Out] Mesh[] meshes); [FreeFunction(Name = "ParticleSystemRendererScriptBindings::SetMeshes", HasExplicitThis = true)] extern public void SetMeshes([NotNull] Mesh[] meshes, int size); public void SetMeshes(Mesh[] meshes) { SetMeshes(meshes, meshes.Length); } [FreeFunction(Name = "ParticleSystemRendererScriptBindings::GetMeshWeightings", HasExplicitThis = true)] extern public int GetMeshWeightings([NotNull][Out] float[] weightings); [FreeFunction(Name = "ParticleSystemRendererScriptBindings::SetMeshWeightings", HasExplicitThis = true)] extern public void SetMeshWeightings([NotNull] float[] weightings, int size); public void SetMeshWeightings(float[] weightings) { SetMeshWeightings(weightings, weightings.Length); } extern public int meshCount { get; } public void BakeMesh(Mesh mesh, ParticleSystemBakeMeshOptions options) { BakeMesh(mesh, Camera.main, options); } extern public void BakeMesh([NotNull] Mesh mesh, [NotNull] Camera camera, ParticleSystemBakeMeshOptions options); public void BakeTrailsMesh(Mesh mesh, ParticleSystemBakeMeshOptions options) { BakeTrailsMesh(mesh, Camera.main, options); } extern public void BakeTrailsMesh([NotNull] Mesh mesh, [NotNull] Camera camera, ParticleSystemBakeMeshOptions options); internal struct BakeTextureOutput { [NativeName("first")] internal Texture2D vertices; [NativeName("second")] internal Texture2D indices; } public int BakeTexture(ref Texture2D verticesTexture, ParticleSystemBakeTextureOptions options) { return BakeTexture(ref verticesTexture, Camera.main, options); } public int BakeTexture(ref Texture2D verticesTexture, Camera camera, ParticleSystemBakeTextureOptions options) { if (renderMode == ParticleSystemRenderMode.Mesh) throw new System.InvalidOperationException("Baking mesh particles to texture requires supplying an indices texture"); int indexCount; verticesTexture = BakeTextureNoIndicesInternal(verticesTexture, camera, options, out indexCount); return indexCount; } [FreeFunction(Name = "ParticleSystemRendererScriptBindings::BakeTextureNoIndices", HasExplicitThis = true)] extern private Texture2D BakeTextureNoIndicesInternal(Texture2D verticesTexture, [NotNull] Camera camera, ParticleSystemBakeTextureOptions options, out int indexCount); public int BakeTexture(ref Texture2D verticesTexture, ref Texture2D indicesTexture, ParticleSystemBakeTextureOptions options) { return BakeTexture(ref verticesTexture, ref indicesTexture, Camera.main, options); } public int BakeTexture(ref Texture2D verticesTexture, ref Texture2D indicesTexture, Camera camera, ParticleSystemBakeTextureOptions options) { int indexCount; var output = BakeTextureInternal(verticesTexture, indicesTexture, camera, options, out indexCount); verticesTexture = output.vertices; indicesTexture = output.indices; return indexCount; } [FreeFunction(Name = "ParticleSystemRendererScriptBindings::BakeTexture", HasExplicitThis = true)] extern private BakeTextureOutput BakeTextureInternal(Texture2D verticesTexture, Texture2D indicesTexture, [NotNull] Camera camera, ParticleSystemBakeTextureOptions options, out int indexCount); public int BakeTrailsTexture(ref Texture2D verticesTexture, ref Texture2D indicesTexture, ParticleSystemBakeTextureOptions options) { return BakeTrailsTexture(ref verticesTexture, ref indicesTexture, Camera.main, options); } public int BakeTrailsTexture(ref Texture2D verticesTexture, ref Texture2D indicesTexture, Camera camera, ParticleSystemBakeTextureOptions options) { int indexCount; var output = BakeTrailsTextureInternal(verticesTexture, indicesTexture, camera, options, out indexCount); verticesTexture = output.vertices; indicesTexture = output.indices; return indexCount; } [FreeFunction(Name = "ParticleSystemRendererScriptBindings::BakeTrailsTexture", HasExplicitThis = true)] extern private BakeTextureOutput BakeTrailsTextureInternal(Texture2D verticesTexture, Texture2D indicesTexture, [NotNull] Camera camera, ParticleSystemBakeTextureOptions options, out int indexCount); // Vertex streams extern public int activeVertexStreamsCount { get; } [FreeFunction(Name = "ParticleSystemRendererScriptBindings::SetActiveVertexStreams", HasExplicitThis = true)] extern public void SetActiveVertexStreams([NotNull] List<ParticleSystemVertexStream> streams); [FreeFunction(Name = "ParticleSystemRendererScriptBindings::GetActiveVertexStreams", HasExplicitThis = true)] extern public void GetActiveVertexStreams([NotNull] List<ParticleSystemVertexStream> streams); extern public int activeTrailVertexStreamsCount { get; } [FreeFunction(Name = "ParticleSystemRendererScriptBindings::SetActiveTrailVertexStreams", HasExplicitThis = true)] extern public void SetActiveTrailVertexStreams([NotNull] List<ParticleSystemVertexStream> streams); [FreeFunction(Name = "ParticleSystemRendererScriptBindings::GetActiveTrailVertexStreams", HasExplicitThis = true)] extern public void GetActiveTrailVertexStreams([NotNull] List<ParticleSystemVertexStream> streams); extern internal bool editorEnabled { get; set; } extern public bool supportsMeshInstancing { get; } extern internal void ConfigureTrailMaterialSlot(bool trailsEnabled); } }
UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystemRenderer.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystemRenderer.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2811 }
419
// 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 { class LightsModuleUI : ModuleUI { class Texts { public GUIContent ratio = EditorGUIUtility.TrTextContent("Ratio", "Amount of particles that have a light source attached to them."); public GUIContent randomDistribution = EditorGUIUtility.TrTextContent("Random Distribution", "Emit lights randomly, or at regular intervals."); public GUIContent light = EditorGUIUtility.TrTextContent("Light", "Light prefab to be used for spawning particle lights."); public GUIContent color = EditorGUIUtility.TrTextContent("Use Particle Color", "Check the option to multiply the particle color by the light color. Otherwise, only the color of the light is used."); public GUIContent range = EditorGUIUtility.TrTextContent("Size Affects Range", "Multiply the range of the light with the size of the particle."); public GUIContent intensity = EditorGUIUtility.TrTextContent("Alpha Affects Intensity", "Multiply the intensity of the light with the alpha of the particle."); public GUIContent rangeCurve = EditorGUIUtility.TrTextContent("Range Multiplier", "Apply a custom multiplier to the range of the lights. If you use a curve to set this value, the Particle System applies the curve over the lifetime of each particle."); public GUIContent intensityCurve = EditorGUIUtility.TrTextContent("Intensity Multiplier", "Apply a custom multiplier to the intensity of the lights. If you use a curve to set this value, the Particle System applies the curve over the lifetime of each particle."); public GUIContent maxLights = EditorGUIUtility.TrTextContent("Maximum Lights", "Limit the amount of lights the system can create. This module makes it very easy to create lots of lights, which can hurt performance."); } static Texts s_Texts; SerializedProperty m_Ratio; SerializedProperty m_RandomDistribution; SerializedProperty m_Light; SerializedProperty m_UseParticleColor; SerializedProperty m_SizeAffectsRange; SerializedProperty m_AlphaAffectsIntensity; SerializedMinMaxCurve m_Range; SerializedMinMaxCurve m_Intensity; SerializedProperty m_MaxLights; public LightsModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "LightsModule", displayName) { m_ToolTip = "Controls light sources attached to particles."; } protected override void Init() { // Already initialized? if (m_Ratio != null) return; if (s_Texts == null) s_Texts = new Texts(); m_Ratio = GetProperty("ratio"); m_RandomDistribution = GetProperty("randomDistribution"); m_Light = GetProperty("light"); m_UseParticleColor = GetProperty("color"); m_SizeAffectsRange = GetProperty("range"); m_AlphaAffectsIntensity = GetProperty("intensity"); m_MaxLights = GetProperty("maxLights"); m_Range = new SerializedMinMaxCurve(this, s_Texts.rangeCurve, "rangeCurve"); m_Intensity = new SerializedMinMaxCurve(this, s_Texts.intensityCurve, "intensityCurve"); } override public void OnInspectorGUI(InitialModuleUI initial) { GUIObject(s_Texts.light, m_Light); GUIFloat(s_Texts.ratio, m_Ratio); GUIToggle(s_Texts.randomDistribution, m_RandomDistribution); GUIToggle(s_Texts.color, m_UseParticleColor); GUIToggle(s_Texts.range, m_SizeAffectsRange); GUIToggle(s_Texts.intensity, m_AlphaAffectsIntensity); GUIMinMaxCurve(s_Texts.rangeCurve, m_Range); GUIMinMaxCurve(s_Texts.intensityCurve, m_Intensity); GUIInt(s_Texts.maxLights, m_MaxLights); if (m_Light.objectReferenceValue) { Light light = (Light)m_Light.objectReferenceValue; if (light.type != LightType.Point && light.type != LightType.Spot && light.type != LightType.Rectangle) { GUIContent warning = EditorGUIUtility.TrTextContent("Only point, spot, and rectangle area lights are supported on particles."); EditorGUILayout.HelpBox(warning.text, MessageType.Warning, true); } } } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/LightsModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/LightsModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 1825 }
420
// 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 { class ParticleSystemStyles { GUIStyle m_Label; GUIStyle m_LabelBold; GUIStyle m_EditableLabel; GUIStyle m_EditableLabelBold; GUIStyle m_ObjectField; GUIStyle m_ObjectFieldBold; GUIStyle m_NumberField; GUIStyle m_NumberFieldBold; GUIStyle m_ModuleHeaderStyle; GUIStyle m_ModuleHeaderStyleBold; GUIStyle m_PopupStyle; GUIStyle m_PopupStyleBold; GUIStyle m_EmitterHeaderStyle; GUIStyle m_EffectBgStyle; GUIStyle m_ModuleBgStyle; GUIStyle m_Plus; GUIStyle m_Minus; GUIStyle m_Checkmark; GUIStyle m_CheckmarkMixed; GUIStyle m_MinMaxCurveStateDropDown; GUIStyle m_Toggle; GUIStyle m_ToggleMixed; GUIStyle m_SelectionMarker; GUIStyle m_ToolbarButtonLeftAlignText; GUIStyle m_ModulePadding; GUIStyle m_CustomDataWindow; Texture2D m_WarningIcon; private static ParticleSystemStyles s_ParticleSystemStyles; public static ParticleSystemStyles Get() { if (s_ParticleSystemStyles == null) s_ParticleSystemStyles = new ParticleSystemStyles(); return s_ParticleSystemStyles; } public GUIStyle label { get { return EditorGUIUtility.GetBoldDefaultFont() ? m_LabelBold : m_Label; } } public GUIStyle editableLabel { get { return EditorGUIUtility.GetBoldDefaultFont() ? m_EditableLabelBold : m_EditableLabel; } } public GUIStyle objectField { get { return EditorGUIUtility.GetBoldDefaultFont() ? m_ObjectFieldBold : m_ObjectField; } } public GUIStyle numberField { get { return EditorGUIUtility.GetBoldDefaultFont() ? m_NumberFieldBold : m_NumberField; } } public GUIStyle moduleHeaderStyle { get { return EditorGUIUtility.GetBoldDefaultFont() ? m_ModuleHeaderStyleBold : m_ModuleHeaderStyle; } } public GUIStyle popup { get { return EditorGUIUtility.GetBoldDefaultFont() ? m_PopupStyleBold : m_PopupStyle; } } public GUIStyle emitterHeaderStyle { get { return m_EmitterHeaderStyle; } } public GUIStyle effectBgStyle { get { return m_EffectBgStyle; } } public GUIStyle moduleBgStyle { get { return m_ModuleBgStyle; } } public GUIStyle plus { get { return m_Plus; } } public GUIStyle minus { get { return m_Minus; } } public GUIStyle checkmark { get { return m_Checkmark; } } public GUIStyle checkmarkMixed { get { return m_CheckmarkMixed; } } public GUIStyle minMaxCurveStateDropDown { get { return m_MinMaxCurveStateDropDown; } } public GUIStyle toggle { get { return m_Toggle; } } public GUIStyle toggleMixed { get { return m_ToggleMixed; } } public GUIStyle selectionMarker { get { return m_SelectionMarker; } } public GUIStyle toolbarButtonLeftAlignText { get { return m_ToolbarButtonLeftAlignText; } } public GUIStyle modulePadding { get { return m_ModulePadding; } } public GUIStyle customDataWindow { get { return m_CustomDataWindow; } } public Texture2D warningIcon { get { return m_WarningIcon; } } ParticleSystemStyles() { InitStyle(out m_Label, out m_LabelBold, "ShurikenLabel"); InitStyle(out m_EditableLabel, out m_EditableLabelBold, "ShurikenEditableLabel"); InitStyle(out m_ObjectField, out m_ObjectFieldBold, "ShurikenObjectField"); InitStyle(out m_NumberField, out m_NumberFieldBold, "ShurikenValue"); InitStyle(out m_ModuleHeaderStyle, out m_ModuleHeaderStyleBold, "ShurikenModuleTitle"); InitStyle(out m_PopupStyle, out m_PopupStyleBold, "ShurikenPopUp"); InitStyle(out m_EmitterHeaderStyle, "ShurikenEmitterTitle"); InitStyle(out m_EmitterHeaderStyle, "ShurikenEmitterTitle"); InitStyle(out m_EffectBgStyle, "ShurikenEffectBg"); InitStyle(out m_ModuleBgStyle, "ShurikenModuleBg"); InitStyle(out m_Plus, "ShurikenPlus"); InitStyle(out m_Minus, "ShurikenMinus"); InitStyle(out m_Checkmark, "ShurikenCheckMark"); InitStyle(out m_CheckmarkMixed, "ShurikenCheckMarkMixed"); InitStyle(out m_MinMaxCurveStateDropDown, "ShurikenDropdown"); InitStyle(out m_Toggle, "ShurikenToggle"); InitStyle(out m_ToggleMixed, "ShurikenToggleMixed"); InitStyle(out m_SelectionMarker, "IN ThumbnailShadow"); InitStyle(out m_ToolbarButtonLeftAlignText, "ToolbarButton"); m_CustomDataWindow = new GUIStyle(GUI.skin.window); m_CustomDataWindow.font = EditorStyles.miniFont; // Todo: Fix in editor resources m_EmitterHeaderStyle.clipping = TextClipping.Clip; m_EmitterHeaderStyle.padding.right = 45; m_WarningIcon = EditorGUIUtility.LoadIcon("console.infoicon.sml"); // Don't change the original as it is used in areas other than particles. m_ToolbarButtonLeftAlignText = new GUIStyle(m_ToolbarButtonLeftAlignText); m_ToolbarButtonLeftAlignText.alignment = TextAnchor.MiddleLeft; m_ModulePadding = new GUIStyle(); m_ModulePadding.padding = new RectOffset(3, 3, 4, 2); } static void InitStyle(out GUIStyle normal, string name) { normal = FindStyle(name); } static void InitStyle(out GUIStyle normal, out GUIStyle bold, string name) { InitStyle(out normal, name); bold = new GUIStyle(normal); bold.font = EditorStyles.miniBoldFont; } static GUIStyle FindStyle(string styleName) { return styleName; } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemStyles.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemStyles.cs", "repo_id": "UnityCsReference", "token_count": 2611 }
421
// 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 System.Runtime.InteropServices; using UnityEngine.Internal; using System.Collections.Generic; namespace UnityEngine { public enum ArticulationJointType { FixedJoint = 0, PrismaticJoint = 1, RevoluteJoint = 2, SphericalJoint = 3 }; public enum ArticulationDofLock { LockedMotion = 0, LimitedMotion = 1, FreeMotion = 2 }; public enum ArticulationDriveType { Force = 0, Acceleration = 1, Target = 2, Velocity = 3, }; [NativeHeader("Modules/Physics/ArticulationBody.h")] [StructLayout(LayoutKind.Sequential)] public struct ArticulationDrive { public float lowerLimit; public float upperLimit; public float stiffness; public float damping; public float forceLimit; public float target; public float targetVelocity; public ArticulationDriveType driveType; } [NativeHeader("Modules/Physics/ArticulationBody.h")] [StructLayout(LayoutKind.Sequential)] public struct ArticulationReducedSpace { private unsafe fixed float x[3]; public unsafe float this[int i] { get { if (i < 0 || i >= dofCount) throw new IndexOutOfRangeException(); return x[i]; } set { if (i < 0 || i >= dofCount) throw new IndexOutOfRangeException(); x[i] = value; } } public unsafe ArticulationReducedSpace(float a) { x[0] = a; dofCount = 1; } public unsafe ArticulationReducedSpace(float a, float b) { x[0] = a; x[1] = b; dofCount = 2; } public unsafe ArticulationReducedSpace(float a, float b, float c) { x[0] = a; x[1] = b; x[2] = c; dofCount = 3; } public int dofCount; // currently, dofCoumt <= 3 } [NativeHeader("Modules/Physics/ArticulationBody.h")] public struct ArticulationJacobian { private int rowsCount; private int colsCount; private List<float> matrixData; public ArticulationJacobian(int rows, int cols) { rowsCount = rows; colsCount = cols; matrixData = new List<float>(rows * cols); for (int i = 0; i < rows * cols; i++) matrixData.Add(0.0f); } public float this[int row, int col] { get { if (row < 0 || row >= rowsCount) throw new IndexOutOfRangeException(); if (col < 0 || col >= colsCount) throw new IndexOutOfRangeException(); return matrixData[row * colsCount + col]; } set { if (row < 0 || row >= rowsCount) throw new IndexOutOfRangeException(); if (col < 0 || col >= colsCount) throw new IndexOutOfRangeException(); matrixData[row * colsCount + col] = value; } } public int rows { get { return rowsCount; } set { rowsCount = value; } } public int columns { get { return colsCount; } set { colsCount = value; } } public List<float> elements { get { return matrixData; } set { matrixData = value; } } } public enum ArticulationDriveAxis { X = 0, Y = 1, Z = 2 } [RequireComponent(typeof(Transform))] [NativeHeader("Modules/Physics/ArticulationBody.h")] [NativeClass("Physics::ArticulationBody")] public partial class ArticulationBody : Behaviour { extern public ArticulationJointType jointType { get; set; } extern public Vector3 anchorPosition { get; set; } extern public Vector3 parentAnchorPosition { get; set; } extern public Quaternion anchorRotation { get; set; } extern public Quaternion parentAnchorRotation { get; set; } extern public bool isRoot { get; } extern public bool matchAnchors { get; set; } extern public ArticulationDofLock linearLockX { get; set; } extern public ArticulationDofLock linearLockY { get; set; } extern public ArticulationDofLock linearLockZ { get; set; } extern public ArticulationDofLock swingYLock { get; set; } extern public ArticulationDofLock swingZLock { get; set; } extern public ArticulationDofLock twistLock { get; set; } extern public ArticulationDrive xDrive { get; set; } extern public ArticulationDrive yDrive { get; set; } extern public ArticulationDrive zDrive { get; set; } extern public bool immovable { get; set; } extern public bool useGravity { get; set; } extern public float linearDamping { get; set; } extern public float angularDamping { get; set; } extern public float jointFriction { get; set; } // Get/Set the Exclude Layers, extern public LayerMask excludeLayers { get; set; } // Get/Set the Include Layers, extern public LayerMask includeLayers { get; set; } extern public Vector3 GetAccumulatedForce([DefaultValue("Time.fixedDeltaTime")] float step); [ExcludeFromDocs] public Vector3 GetAccumulatedForce() { return GetAccumulatedForce(Time.fixedDeltaTime); } extern public Vector3 GetAccumulatedTorque([DefaultValue("Time.fixedDeltaTime")] float step); [ExcludeFromDocs] public Vector3 GetAccumulatedTorque() { return GetAccumulatedTorque(Time.fixedDeltaTime); } extern public void AddForce(Vector3 force, [DefaultValue("ForceMode.Force")] ForceMode mode); [ExcludeFromDocs] public void AddForce(Vector3 force) { AddForce(force, ForceMode.Force); } extern public void AddRelativeForce(Vector3 force, [DefaultValue("ForceMode.Force")] ForceMode mode); [ExcludeFromDocs] public void AddRelativeForce(Vector3 force) { AddRelativeForce(force, ForceMode.Force); } extern public void AddTorque(Vector3 torque, [DefaultValue("ForceMode.Force")] ForceMode mode); [ExcludeFromDocs] public void AddTorque(Vector3 torque) { AddTorque(torque, ForceMode.Force); } extern public void AddRelativeTorque(Vector3 torque, [DefaultValue("ForceMode.Force")] ForceMode mode); [ExcludeFromDocs] public void AddRelativeTorque(Vector3 torque) { AddRelativeTorque(torque, ForceMode.Force); } extern public void AddForceAtPosition(Vector3 force, Vector3 position, [DefaultValue("ForceMode.Force")] ForceMode mode); [ExcludeFromDocs] public void AddForceAtPosition(Vector3 force, Vector3 position) { AddForceAtPosition(force, position, ForceMode.Force); } extern public Vector3 linearVelocity { get; set; } extern public Vector3 angularVelocity { get; set; } extern public float mass { get; set; } extern public bool automaticCenterOfMass { get; set; } extern public Vector3 centerOfMass { get; set; } extern public Vector3 worldCenterOfMass { get; } extern public bool automaticInertiaTensor { get; set; } extern public Vector3 inertiaTensor { get; set; } extern internal Matrix4x4 worldInertiaTensorMatrix { get; } extern public Quaternion inertiaTensorRotation { get; set; } extern public void ResetCenterOfMass(); extern public void ResetInertiaTensor(); extern public void Sleep(); extern public bool IsSleeping(); extern public void WakeUp(); extern public float sleepThreshold { get; set; } extern public int solverIterations { get; set; } extern public int solverVelocityIterations { get; set; } extern public float maxAngularVelocity { get; set; } extern public float maxLinearVelocity { get; set; } extern public float maxJointVelocity { get; set; } extern public float maxDepenetrationVelocity { get; set; } extern public ArticulationReducedSpace jointPosition { get; set; } extern public ArticulationReducedSpace jointVelocity { get; set; } extern public ArticulationReducedSpace jointAcceleration { get; [Obsolete("Setting joint accelerations is not supported in forward kinematics. To have inverse dynamics take acceleration into account, use GetJointForcesForAcceleration instead", true)] set; } extern public ArticulationReducedSpace jointForce { get; set; } extern public ArticulationReducedSpace driveForce { get; } extern public int dofCount { get; } extern public int index { [NativeMethod("GetBodyIndex")] get; } extern public void TeleportRoot(Vector3 position, Quaternion rotation); extern public Vector3 GetClosestPoint(Vector3 point); extern public Vector3 GetRelativePointVelocity(Vector3 relativePoint); extern public Vector3 GetPointVelocity(Vector3 worldPoint); [NativeMethod("GetDenseJacobian")] extern private int GetDenseJacobian_Internal(ref ArticulationJacobian jacobian); public int GetDenseJacobian(ref ArticulationJacobian jacobian) { // Initialize matrixData if ArticulationJacobian struct was created with default constructor if(jacobian.elements == null) jacobian.elements = new List<float>(); return GetDenseJacobian_Internal(ref jacobian); } extern public int GetJointPositions(List<float> positions); extern public void SetJointPositions(List<float> positions); extern public int GetJointVelocities(List<float> velocities); extern public void SetJointVelocities(List<float> velocities); extern public int GetJointAccelerations(List<float> accelerations); extern public int GetJointForces(List<float> forces); extern public void SetJointForces(List<float> forces); extern public ArticulationReducedSpace GetJointForcesForAcceleration(ArticulationReducedSpace acceleration); extern public int GetDriveForces(List<float> forces); extern public int GetJointGravityForces(List<float> forces); extern public int GetJointCoriolisCentrifugalForces(List<float> forces); extern public int GetJointExternalForces(List<float> forces, float step); extern public int GetDriveTargets(List<float> targets); extern public void SetDriveTargets(List<float> targets); extern public int GetDriveTargetVelocities(List<float> targetVelocities); extern public void SetDriveTargetVelocities(List<float> targetVelocities); extern public int GetDofStartIndices(List<int> dofStartIndices); extern public void SetDriveTarget(ArticulationDriveAxis axis, float value); extern public void SetDriveTargetVelocity(ArticulationDriveAxis axis, float value); extern public void SetDriveLimits(ArticulationDriveAxis axis, float lower, float upper); extern public void SetDriveStiffness(ArticulationDriveAxis axis, float value); extern public void SetDriveDamping(ArticulationDriveAxis axis, float value); extern public void SetDriveForceLimit(ArticulationDriveAxis axis, float value); extern public CollisionDetectionMode collisionDetectionMode { get; set; } extern public void PublishTransform(); public void SnapAnchorToClosestContact() { if (!transform.parent) return; // GetComponentInParent returns enabled/disabled components, need to find enabled one. ArticulationBody parentBody = transform.parent.GetComponentInParent<ArticulationBody>(); while (parentBody && !parentBody.enabled) { parentBody = parentBody.transform.parent.GetComponentInParent<ArticulationBody>(); } if (!parentBody) return; Vector3 com = parentBody.worldCenterOfMass; Vector3 closestOnSurface = GetClosestPoint(com); anchorPosition = transform.InverseTransformPoint(closestOnSurface); anchorRotation = Quaternion.FromToRotation(Vector3.right, transform.InverseTransformDirection(com - closestOnSurface).normalized); } } }
UnityCsReference/Modules/Physics/ScriptBindings/Articulations.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/Articulations.bindings.cs", "repo_id": "UnityCsReference", "token_count": 5694 }
422
// 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; namespace UnityEngine { [Flags] public enum MeshColliderCookingOptions { None, [Obsolete("No longer used because the problem this was trying to solve is gone since Unity 2018.3", true)] InflateConvexMesh = 1 << 0, CookForFasterSimulation = 1 << 1, EnableMeshCleaning = 1 << 2, WeldColocatedVertices = 1 << 3, UseFastMidphase = 1 << 4 } [RequireComponent(typeof(Transform))] [NativeHeader("Modules/Physics/MeshCollider.h")] [NativeHeader("Runtime/Graphics/Mesh/Mesh.h")] public partial class MeshCollider : Collider { extern public Mesh sharedMesh { get; set; } extern public bool convex { get; set; } extern public MeshColliderCookingOptions cookingOptions { get; set; } } }
UnityCsReference/Modules/Physics/ScriptBindings/MeshCollider.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/MeshCollider.bindings.cs", "repo_id": "UnityCsReference", "token_count": 363 }
423
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Bindings; namespace UnityEngine { [RequireComponent(typeof(Transform))] [NativeHeader("Modules/Physics/SphereCollider.h")] public class SphereCollider : Collider { extern public Vector3 center { get; set; } extern public float radius { get; set; } } }
UnityCsReference/Modules/Physics/ScriptBindings/SphereCollider.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/SphereCollider.bindings.cs", "repo_id": "UnityCsReference", "token_count": 159 }
424
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Collections.Generic; using UnityEngine; using UnityEditorInternal; namespace UnityEditor { class EditableLineHandle2D { public enum LineIntersectionHighlight { // don't draw intersecting line segments with a red highlight None, // only draw the highlight when a new point is being inserted Inserting, // always draw the highlight on intersecting edges Always } const float k_LinePickDistance = 50f; const float k_PointPickDistance = 15f; const float k_ActiveLineSegmentWidth = 5f; static readonly int s_InsertPointHash = "s_InsertPointHash".GetHashCode(); static readonly int s_LineControlHash = "s_LineControlHash".GetHashCode(); static Vector3 s_InsertedPointPosition; static int s_InsertedIndex; const float k_DotHandleSize = .04f; const float k_ProximityDotHandleSize = .05f; static Vector3[] s_AAPolyLinePoints = new Vector3[2]; Vector3[] m_Points; bool m_Loop; int m_MinPointCount; LineIntersectionHighlight m_IntersectionHighlight; public Vector3[] points { get => m_Points; set => m_Points = value; } public EditableLineHandle2D(IList<Vector2> points, bool loop, int minPointCount, LineIntersectionHighlight intersectionHighlight = LineIntersectionHighlight.None) { int count = points.Count; m_Points = new Vector3[count]; for (int i = 0; i < count; i++) m_Points[i] = points[i]; m_Loop = loop; m_MinPointCount = minPointCount; m_IntersectionHighlight = intersectionHighlight; } public EditableLineHandle2D(IList<Vector3> points, bool loop, int minPointCount, LineIntersectionHighlight intersectionHighlight = LineIntersectionHighlight.None) { int count = points.Count; m_Points = new Vector3[count]; for (int i = 0; i < count; i++) m_Points[i] = points[i]; m_Loop = loop; m_MinPointCount = minPointCount; m_IntersectionHighlight = intersectionHighlight; } public void OnGUI(Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2) { Do(GUIUtility.GetControlID(s_LineControlHash, FocusType.Passive), ref m_Points, handleDir, slideDir1, slideDir2, k_DotHandleSize, Handles.DotHandleCap, EditorSnapSettings.move, false, m_IntersectionHighlight, m_Loop, m_MinPointCount); for (int i = 0, c = m_Points.Length; i < c; i++) { float guiSize = HandleUtility.GetHandleSize(m_Points[i]) * k_ProximityDotHandleSize; m_Points[i] = Handles.Slider2D(m_Points[i], Vector3.forward, Vector3.right, Vector3.up, guiSize, ProximityDotHandleCap, EditorSnapSettings.move); } HandleUtility.s_CustomPickDistance = HandleUtility.kPickDistance; } static void ProximityDotHandleCap( int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { // Draw the handle cap only if it is the hotcontrol or is the nearest control with no hotcontrol active. if (eventType == EventType.Repaint && !(GUIUtility.hotControl == controlID || HandleUtility.nearestControl == controlID && GUIUtility.hotControl == 0)) return; // This is effectively the "Handles.DotHandleCap(controlID, position, rotation, size, eventType);" call however // that is broken under larger scaling so use a simple distance to handle calculation here and simply draw the handle. if (eventType == EventType.Layout || eventType == EventType.MouseMove) { HandleUtility.s_CustomPickDistance = k_PointPickDistance; var distance = (Event.current.mousePosition - HandleUtility.WorldToGUIPoint(position)).magnitude; HandleUtility.AddControl(controlID, distance > k_PointPickDistance ? distance : 0f); } else if (eventType == EventType.Repaint) { // Only apply matrix to the position because DotCap is camera facing position = Handles.matrix.MultiplyPoint(position); var sideways = (Camera.current == null ? Vector3.right : Camera.current.transform.right) * size; var up = (Camera.current == null ? Vector3.up : Camera.current.transform.up) * size; // Draw the handle. var col = Handles.color * new Color(1, 1, 1, 0.99f); HandleUtility.ApplyWireMaterial(Handles.zTest); GL.Begin(GL.QUADS); GL.Color(col); GL.Vertex(position + sideways + up); GL.Vertex(position + sideways - up); GL.Vertex(position - sideways - up); GL.Vertex(position - sideways + up); GL.End(); } HandleUtility.s_CustomPickDistance = HandleUtility.kPickDistance; } static bool IsRemoveEvent(Event evt) { // this is matching existing 2d collider editor behaviour return GUIUtility.hotControl == 0 && (evt.command || evt.control); } public static void Do( ref Vector3[] line, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.CapFunction capFunction, LineIntersectionHighlight intersectionHighlight, bool loop, int minPointCount ) { int id = GUIUtility.GetControlID(s_InsertPointHash, FocusType.Passive); Do(id, ref line, handleDir, slideDir1, slideDir2, handleSize, capFunction, EditorSnapSettings.move, false, intersectionHighlight, loop, minPointCount); } public static void Do( int id, ref Vector3[] line, Vector3 handleDir, Vector3 slideDir1, Vector3 slideDir2, float handleSize, Handles.CapFunction capFunction, Vector2 snap, bool drawHelper, LineIntersectionHighlight intersectionHighlight, bool loop, int minPointCount ) { var evt = Event.current; var activeIndex = GUIUtility.hotControl == id ? s_InsertedIndex : -1; var evtType = evt.GetTypeForControl(id); int lineCount = line.Length; switch (evtType) { case EventType.Layout: case EventType.MouseMove: { HandleUtility.s_CustomPickDistance = k_LinePickDistance; if (line != null && line.Length > 1) HandleUtility.AddControl(id, HandleUtility.DistanceToPolyLine(line, loop, out _)); break; } case EventType.Repaint: { HandleUtility.DistanceToPolyLine(line, loop, out int hoveredEdgeIndex); var color = Handles.color; for (int n = 0, lineIterCount = loop ? line.Length : line.Length - 1; n < lineIterCount; n++) { int a = n, b = Wrap(n + 1, lineCount); // Inserting a point has special handling to draw the inserted lines thicker, and optionally // draw a red warning line if intersections are detected if (activeIndex > -1 && RangeContains(n, lineCount, activeIndex - 1, 2)) { Handles.color = intersectionHighlight != LineIntersectionHighlight.None && LineIntersectsPath(line, line[a], line[b], slideDir1, slideDir2, loop, a - 1, 3) ? Color.red : color; s_AAPolyLinePoints[0] = line[a]; s_AAPolyLinePoints[1] = line[b]; Handles.DrawAAPolyLine(k_ActiveLineSegmentWidth, s_AAPolyLinePoints); } else // Draw the hovered line segment with a thicker line. If this is a remove event, we also handle // drawing the next segment. if (GUIUtility.hotControl == 0 && HandleUtility.nearestControl == id && (a == hoveredEdgeIndex || (IsRemoveEvent(evt) && a == hoveredEdgeIndex + 1))) { Handles.color = intersectionHighlight == LineIntersectionHighlight.Always && LineIntersectsPath( line, line[a], line[b], slideDir1, slideDir2, loop, a - 1, 3) ? Color.red : color; // If we're in 'delete' mode, both the hovered edge and the following edge are highlighted // as removal candidates if (IsRemoveEvent(evt)) { Handles.color = Color.red; Handles.DrawAAPolyLine(k_ActiveLineSegmentWidth, line[hoveredEdgeIndex], line[Wrap(hoveredEdgeIndex + 1, lineCount)]); Handles.DrawAAPolyLine(k_ActiveLineSegmentWidth, line[Wrap(hoveredEdgeIndex + 1, lineCount)], line[loop ? Wrap(hoveredEdgeIndex + 2, lineCount) : Mathf.Clamp(hoveredEdgeIndex + 2, 0, lineCount - 1)]); } else { Handles.DrawAAPolyLine(k_ActiveLineSegmentWidth, line[a], line[b]); } } else { Handles.color = intersectionHighlight == LineIntersectionHighlight.Always && LineIntersectsPath( line, line[a], line[b], slideDir1, slideDir2, loop, a - 1, 3) ? Color.red : color; Handles.DrawLine(line[a], line[b]); } Handles.color = color; } // If this is the active hotcontrol, let Slider2D do the drawing if (GUIUtility.hotControl == id) goto default; // If no hotControl is active and we are the nearest control, show a preview of the insertion point if (GUIUtility.hotControl != 0 || HandleUtility.nearestControl != id || capFunction == null) break; var ls = Handles.matrix.MultiplyPoint3x4(line[Wrap(hoveredEdgeIndex, lineCount)]); var le = Handles.matrix.MultiplyPoint3x4(line[Wrap(hoveredEdgeIndex + 1, lineCount)]); var direction = le - ls; var constraint = Vector3.Normalize(direction); if (HandleUtility.CalcParamOnConstraint(Camera.current, evt.mousePosition, ls, constraint, out float param)) { var handlePosition = ls + constraint * Mathf.Clamp(param, 0f, direction.magnitude); var localSpace = Handles.inverseMatrix.MultiplyPoint3x4(handlePosition); capFunction(id, localSpace, Quaternion.identity, HandleUtility.GetHandleSize(localSpace) * handleSize, EventType.Repaint); } break; } case EventType.MouseDown: { if (HandleUtility.nearestControl == id && evt.button == 0 && GUIUtility.hotControl == 0 && !evt.alt) { HandleUtility.DistanceToPolyLine(line, loop, out int nearestEdgeIndex); int count = line.Length; if (IsRemoveEvent(evt)) { if (lineCount > minPointCount) { ArrayUtility.RemoveAt(ref line, (nearestEdgeIndex + 1) % count); } GUI.changed = true; evt.Use(); return; } var ls = Handles.matrix.MultiplyPoint3x4(line[nearestEdgeIndex]); var le = Handles.matrix.MultiplyPoint3x4(line[(nearestEdgeIndex + 1) % count]); activeIndex = nearestEdgeIndex; var direction = le - ls; var constraint = Vector3.Normalize(direction); if (!HandleUtility.CalcParamOnConstraint(Camera.current, evt.mousePosition, ls, constraint, out float param)) break; var handlePosition = ls + constraint * Mathf.Clamp(param, 0f, direction.magnitude); s_InsertedPointPosition = Handles.inverseMatrix.MultiplyPoint(handlePosition); if (activeIndex != -1) { s_InsertedIndex = (activeIndex + 1) % line.Length; ArrayUtility.Insert(ref line, s_InsertedIndex, s_InsertedPointPosition); GUI.changed = true; } goto default; } break; } case EventType.MouseUp: s_InsertedIndex = -1; goto default; default: { s_InsertedPointPosition = Slider2D.Do( id, s_InsertedPointPosition, Vector3.zero, handleDir, slideDir1, slideDir2, HandleUtility.GetHandleSize(s_InsertedPointPosition) * handleSize, capFunction, snap, drawHelper); if (GUIUtility.hotControl == id && s_InsertedIndex > -1) line[s_InsertedIndex] = s_InsertedPointPosition; break; } } } static int Wrap(int i, int c) { return ((i % c) + c) % c; } static bool RangeContains(int index, int count, int rangeStart, int rangeCount) { return (index >= rangeStart && index < rangeStart + rangeCount) || rangeStart + rangeCount >= count && index < Wrap(rangeStart + rangeCount, count); } internal static bool LineIntersectsPath(Vector3[] path, Vector3 lineA, Vector3 lineB, Vector3 slideDir1, Vector3 slideDir2, bool loop, int ignoreIndex, int ignoreCount) { Vector3 tan = slideDir1.normalized; Vector3 bitan = slideDir2.normalized; Vector2 a = Project(lineA, tan, bitan); Vector2 b = Project(lineB, tan, bitan); Vector2 prev = Project(path[0], tan, bitan); for (int i = 1, c = path.Length; i < (loop ? c + 1 : c); i++) { Vector2 next = Project(path[i % c], tan, bitan); int edge = (i % c) - 1; // ignore intersections between the source edge it's neighbours if (!RangeContains(edge, c, ignoreIndex, ignoreCount) && GetLineSegmentIntersect(a, b, prev, next)) return true; prev = next; } return false; } static Vector2 Project(Vector3 point, Vector3 tan, Vector3 bitan) { return new Vector2(Vector3.Dot(tan, point), Vector3.Dot(bitan, point)); } internal static bool GetLineSegmentIntersect(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3) { Vector2 s1, s2; s1.x = p1.x - p0.x; s1.y = p1.y - p0.y; s2.x = p3.x - p2.x; s2.y = p3.y - p2.y; float s, t; s = (-s1.y * (p0.x - p2.x) + s1.x * (p0.y - p2.y)) / (-s2.x * s1.y + s1.x * s2.y); t = (s2.x * (p0.y - p2.y) - s2.y * (p0.x - p2.x)) / (-s2.x * s1.y + s1.x * s2.y); return s > 0f && s < 1 && t > 0f && t < 1f; } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EditableLineHandle2D.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EditableLineHandle2D.cs", "repo_id": "UnityCsReference", "token_count": 9408 }
425
// 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 { [CustomEditor(typeof(Joint2D))] [CanEditMultipleObjects] internal class Joint2DEditor : Editor { SerializedProperty m_BreakAction; SerializedProperty m_BreakForce; SerializedProperty m_BreakTorque; public void OnEnable() { m_BreakAction = serializedObject.FindProperty("m_BreakAction"); m_BreakForce = serializedObject.FindProperty("m_BreakForce"); m_BreakTorque = serializedObject.FindProperty("m_BreakTorque"); } public override void OnInspectorGUI() { // Ensure that the connected body doesn't span physics scenes. if (targets.Length == 1) { var joint = target as Joint2D; if (joint.connectedBody != null && joint.gameObject.activeInHierarchy && joint.connectedBody.gameObject.activeInHierarchy && joint.gameObject.scene.GetPhysicsScene2D() != joint.connectedBody.gameObject.scene.GetPhysicsScene2D()) { EditorGUILayout.HelpBox("This joint will not function because it is connected to a Rigidbody2D in a different physics scene. This is not supported.", MessageType.Warning); } } base.OnInspectorGUI(); EditorGUILayout.PropertyField(m_BreakAction); EditorGUILayout.PropertyField(m_BreakForce); // Distance/Spring/Target joints produce no reaction torque so they're not supported. var targetType = target.GetType(); if (targetType != typeof(DistanceJoint2D) && targetType != typeof(TargetJoint2D) && targetType != typeof(SpringJoint2D)) EditorGUILayout.PropertyField(m_BreakTorque); serializedObject.ApplyModifiedProperties(); } public class Styles { public readonly GUIStyle anchor = "U2D.pivotDot"; public readonly GUIStyle anchorActive = "U2D.pivotDotActive"; public readonly GUIStyle connectedAnchor = "U2D.dragDot"; public readonly GUIStyle connectedAnchorActive = "U2D.dragDotActive"; } protected static Styles s_Styles; protected bool HandleAnchor(ref Vector3 position, bool isConnectedAnchor) { if (s_Styles == null) s_Styles = new Styles(); var drawCapFunction = isConnectedAnchor ? (Handles.CapFunction)ConnectedAnchorHandleCap : (Handles.CapFunction)AnchorHandleCap; int id = target.GetInstanceID() + (isConnectedAnchor ? 1 : 0); EditorGUI.BeginChangeCheck(); position = Handles.Slider2D(id, position, Vector3.back, Vector3.right, Vector3.up, 0, drawCapFunction, Vector2.zero); return EditorGUI.EndChangeCheck(); } public static void AnchorHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { if (controlID == GUIUtility.keyboardControl) HandleCap(controlID, position, s_Styles.anchorActive, eventType); else HandleCap(controlID, position, s_Styles.anchor, eventType); } public static void ConnectedAnchorHandleCap(int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType) { if (controlID == GUIUtility.keyboardControl) HandleCap(controlID, position, s_Styles.connectedAnchorActive, eventType); else HandleCap(controlID, position, s_Styles.connectedAnchor, eventType); } static void HandleCap(int controlID, Vector3 position, GUIStyle guiStyle, EventType eventType) { switch (eventType) { case EventType.Layout: case EventType.MouseMove: HandleUtility.AddControl(controlID, HandleUtility.DistanceToRectangleInternal(position, Quaternion.identity, Vector2.zero)); break; case EventType.Repaint: Handles.BeginGUI(); position = HandleUtility.WorldToGUIPoint(position); var w = guiStyle.fixedWidth; var h = guiStyle.fixedHeight; var r = new Rect(position.x - w / 2f, position.y - h / 2f, w, h); guiStyle.Draw(r, GUIContent.none, controlID); Handles.EndGUI(); break; } } public static void DrawAALine(Vector3 start, Vector3 end) { Handles.DrawAAPolyLine(new Vector3[] { start, end }); } public static void DrawDistanceGizmo(Vector3 anchor, Vector3 connectedAnchor, float distance) { Vector3 direction = (anchor - connectedAnchor).normalized; Vector3 endPosition = connectedAnchor + (direction * distance); Vector3 normal = Vector3.Cross(direction, Vector3.forward); normal *= HandleUtility.GetHandleSize(connectedAnchor) * 0.16f; Handles.color = Color.green; DrawAALine(anchor, endPosition); DrawAALine(connectedAnchor + normal, connectedAnchor - normal); DrawAALine(endPosition + normal, endPosition - normal); } static Matrix4x4 GetAnchorSpaceMatrix(Transform transform) { // Anchor space transformation matrix return Matrix4x4.TRS(transform.position, Quaternion.Euler(0, 0, transform.rotation.eulerAngles.z), transform.lossyScale); } protected static Vector3 TransformPoint(Transform transform, Vector3 position) { // Local to World return GetAnchorSpaceMatrix(transform).MultiplyPoint(position); } protected static Vector3 InverseTransformPoint(Transform transform, Vector3 position) { // World to Local return GetAnchorSpaceMatrix(transform).inverse.MultiplyPoint(position); } protected static Vector3 SnapToSprite(SpriteRenderer spriteRenderer, Vector3 position, float snapDistance) { if (spriteRenderer == null || spriteRenderer.sprite == null) return position; snapDistance = HandleUtility.GetHandleSize(position) * snapDistance; var x = spriteRenderer.sprite.bounds.size.x / 2; var y = spriteRenderer.sprite.bounds.size.y / 2; var anchors = new[] { new Vector2(-x, -y), new Vector2(0, -y), new Vector2(x, -y), new Vector2(-x, 0), new Vector2(0, 0), new Vector2(x, 0), new Vector2(-x, y), new Vector2(0, y), new Vector2(x, y)}; foreach (var anchor in anchors) { var worldAnchor = spriteRenderer.transform.TransformPoint(anchor); if (Vector2.Distance(position, worldAnchor) <= snapDistance) return worldAnchor; } return position; } protected static Vector3 SnapToPoint(Vector3 position, Vector3 snapPosition, float snapDistance) { snapDistance = HandleUtility.GetHandleSize(position) * snapDistance; return Vector3.Distance(position, snapPosition) <= snapDistance ? snapPosition : position; } protected static Vector2 RotateVector2(Vector2 direction, float angle) { var theta = Mathf.Deg2Rad * -angle; var cs = Mathf.Cos(theta); var sn = Mathf.Sin(theta); var px = direction.x * cs - direction.y * sn; var py = direction.x * sn + direction.y * cs; return new Vector2(px, py); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Joints/Joint2DEditor.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Joints/Joint2DEditor.cs", "repo_id": "UnityCsReference", "token_count": 3627 }
426
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEditor.EditorTools; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace UnityEditor { [EditorTool("Edit Box Collider", typeof(BoxCollider))] class BoxPrimitiveColliderTool : PrimitiveColliderTool<BoxCollider> { readonly BoxBoundsHandle m_BoundsHandle = new BoxBoundsHandle(); protected override PrimitiveBoundsHandle boundsHandle { get { return m_BoundsHandle; } } protected override void CopyColliderPropertiesToHandle(BoxCollider collider) { m_BoundsHandle.center = TransformColliderCenterToHandleSpace(collider.transform, collider.center); m_BoundsHandle.size = Vector3.Scale(collider.size, collider.transform.lossyScale); } protected override void CopyHandlePropertiesToCollider(BoxCollider collider) { collider.center = TransformHandleCenterToColliderSpace(collider.transform, m_BoundsHandle.center); Vector3 size = Vector3.Scale(m_BoundsHandle.size, InvertScaleVector(collider.transform.lossyScale)); size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z)); collider.size = size; } } [CustomEditor(typeof(BoxCollider))] [CanEditMultipleObjects] class BoxColliderEditor : Collider3DEditorBase { SerializedProperty m_Center; SerializedProperty m_Size; private static class Styles { public static readonly GUIContent sizeContent = EditorGUIUtility.TrTextContent("Size", "The size of the Collider in the X, Y, Z directions."); } public override void OnEnable() { base.OnEnable(); m_Center = serializedObject.FindProperty("m_Center"); m_Size = serializedObject.FindProperty("m_Size"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.EditorToolbarForTarget(EditorGUIUtility.TrTempContent("Edit Collider"), this); GUILayout.Space(5); EditorGUILayout.PropertyField(m_IsTrigger, BaseStyles.triggerContent); EditorGUILayout.PropertyField(m_ProvidesContacts, BaseStyles.providesContacts); EditorGUILayout.PropertyField(m_Material, BaseStyles.materialContent); EditorGUILayout.PropertyField(m_Center, BaseStyles.centerContent); EditorGUILayout.PropertyField(m_Size, Styles.sizeContent); ShowLayerOverridesProperties(); serializedObject.ApplyModifiedProperties(); } } }
UnityCsReference/Modules/PhysicsEditor/BoxColliderEditor.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/BoxColliderEditor.cs", "repo_id": "UnityCsReference", "token_count": 1077 }
427
// 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; using System; using System.Collections.Generic; using UnityEngine.Assertions; using UnityEditor.UIElements; using System.Runtime.CompilerServices; using IPhysicsProjectSettingsECSInspectorExtension = UnityEditorInternal.IPhysicsProjectSettingsECSInspectorExtension; [assembly: InternalsVisibleTo("Unity.Physics.Editor.ProjectSettingsBridge")] namespace UnityEditor { class PhysicsManagerInspector { public static IPhysicsProjectSettingsECSInspectorExtension EcsExtension = null; static class AssetPath { public const string dynamics = "ProjectSettings/DynamicsManager.asset"; public static readonly string dynamicsError = $"{nameof(PhysicsManagerInspector.CreatePhysicsSettingsItemProvider)} failed to load asset {dynamics} containing data for the PhysicsManager."; public const string tags = "ProjectSettings/TagManager.asset"; public static readonly string tagsError = $"{nameof(PhysicsManagerInspector.CreatePhysicsSettingsItemProvider)} failed to load asset {tags} containing data for the TagManager."; } static class StyleSheetPath { public const string projectSettingsSheet = "StyleSheets/ProjectSettings/ProjectSettingsCommon.uss"; public const string commonSheet = "StyleSheets/Extensions/base/common.uss"; public const string darkSheet = "StyleSheets/Extensions/base/dark.uss"; public const string lightSheet = "StyleSheets/Extensions/base/light.uss"; } static class UXMLPath { public const string projectSettingsMain = "Physics/UXML/ProjectSettings.uxml"; public const string projectSettingsSub = "Physics/UXML/ProjectSettingsSub.uxml"; public const string physicsLayerGrid = "Physics/UXML/PhysicsLayerGrid.uxml"; } const string k_layerMatrixFoldoutPref = "project-settings-collision-matrix-unfold"; const int k_MaxLayers = 32; static SerializedObject LoadGameManagerAssetAtPath(string path) { var found = AssetDatabase.LoadAllAssetsAtPath(path); if (found == null) return null; return new SerializedObject(found[0]); } //create the main page, shows warnings/info [SettingsProvider] static SettingsProvider CreatePhysicsSettingsItemProvider() { var provider = new SettingsProvider("Project/Physics", SettingsScope.Project) { label = "Physics", keywords = SettingsProvider.GetSearchKeywordsFromPath(AssetPath.dynamics), activateHandler = (searchContext, rootElement) => { var serializedObject = LoadGameManagerAssetAtPath(AssetPath.dynamics); if (serializedObject == null) { Debug.LogError(AssetPath.dynamicsError); return; } var mainUXML = EditorGUIUtility.Load(UXMLPath.projectSettingsMain) as VisualTreeAsset; mainUXML.CloneTree(rootElement); var content = rootElement.Q<ScrollView>(className: "project-settings-section-content"); content.styleSheets.Add(EditorGUIUtility.Load(StyleSheetPath.projectSettingsSheet) as StyleSheet); content.styleSheets.Add(EditorGUIUtility.Load(StyleSheetPath.commonSheet) as StyleSheet); content.styleSheets.Add(EditorGUIUtility.Load(EditorGUIUtility.isProSkin ? StyleSheetPath.darkSheet : StyleSheetPath.lightSheet) as StyleSheet); //direct memory access to the infos array, shouldn't be bound to any callback ReadOnlySpan<IntegrationInfo> infos = Physics.GetIntegrationInfos(); var classicEngineDropdown = rootElement.Q<DropdownField>(name: "classic-dropdown"); var classicEngineHelpboxWarning = rootElement.Q<HelpBox>(name: "classic-helpbox-warning"); classicEngineHelpboxWarning.text = "You've changed the active physics SDK integration. This requires a restart of the Editor for the change to take effect."; classicEngineHelpboxWarning.visible = false; int currentChoiceIndex = 0; uint currentId = Physics.GetCurrentIntegrationId(); for (int i = 0; i < infos.Length; ++i) { IntegrationInfo info = infos[i]; classicEngineDropdown.choices.Add(info.Name); if (currentId == info.Id) currentChoiceIndex = i; } classicEngineDropdown.value = classicEngineDropdown.choices[currentChoiceIndex]; if (!Unsupported.IsDeveloperMode() || Application.isPlaying) classicEngineDropdown.SetEnabled(false); else { classicEngineDropdown.RegisterValueChangedCallback((evt) => { if (evt.newValue == evt.previousValue) return; uint oldIntegrationId = Physics.GetCurrentIntegrationId(); uint newIntegrationId = 0; ReadOnlySpan<IntegrationInfo> integrationInfos = Physics.GetIntegrationInfos(); for (int i = 0; i < integrationInfos.Length; ++i) { IntegrationInfo info = integrationInfos[i]; if (info.Name == evt.newValue) { newIntegrationId = info.Id; } } var idProp = serializedObject.FindProperty("m_CurrentBackendId"); idProp.uintValue = newIntegrationId; //force apply the property here as we want to ensure that the change is done immediately serializedObject.ApplyModifiedProperties(); //enable warning box if we are swapping classicEngineHelpboxWarning.visible = newIntegrationId != Physics.GetCurrentIntegrationId(); }); } var ecsEngineDropdown = rootElement.Q<DropdownField>(name: "ecs-dropdown"); var ecsEngineHelpboxInfo = rootElement.Q<HelpBox>(name: "ecs-helpbox-info"); var ecsEngineHelpboxWarning = rootElement.Q<HelpBox>(name: "ecs-helpbox-warning"); if (EcsExtension != null) { EcsExtension.SetupMainPageItems(ecsEngineDropdown, ecsEngineHelpboxInfo, ecsEngineHelpboxWarning, serializedObject); } else { ecsEngineDropdown.choices.Add("None"); ecsEngineDropdown.value = ecsEngineDropdown.choices[0]; ecsEngineDropdown.visible = false; ecsEngineHelpboxInfo.visible = false; ecsEngineHelpboxWarning.visible = false; } //bind data object rootElement.Bind(serializedObject); } }; return provider; } struct LayerData { public int bit; public string name; } class ToggleData { public int gridX; public int gridY; public int layerBit0; public int layerBit1; public VisualElement sideLabels; public VisualElement topLabels; public VisualElement overlay; } class LayerGridData { public List<LayerData> layers; public SerializedObject physicsManager; public SerializedObject tagManager; } static void AddGridOverlayLines(VisualElement toggle) { var userData = toggle.userData as ToggleData; var horizontalLabel = userData.sideLabels[userData.gridX]; var verticalLabel = userData.topLabels[(userData.topLabels.childCount - 1) - userData.gridY]; //both side and top labels have the same number of active labels //but only top labels has the exact number of children as it is being generated. int totalLabelsPerside = userData.topLabels.childCount; //horizontal bar var horizontalBox = new Box(); horizontalBox.AddToClassList("project-settings___physics__highlight-box"); horizontalBox.style.height = horizontalLabel.resolvedStyle.height; horizontalBox.style.width = horizontalLabel.resolvedStyle.width + (totalLabelsPerside - userData.gridX) * (toggle.resolvedStyle.width + toggle.resolvedStyle.marginLeft + toggle.resolvedStyle.marginRight); //absolute pos calculate for horizontal bar horizontalBox.style.left = userData.sideLabels.resolvedStyle.width - horizontalLabel.resolvedStyle.width; horizontalBox.style.top = userData.topLabels.resolvedStyle.width + ((horizontalLabel.resolvedStyle.height) * userData.gridX) + horizontalLabel.resolvedStyle.paddingTop; //vertical bar var verticalBox = new Box(); verticalBox.AddToClassList("project-settings___physics__highlight-box"); verticalBox.style.width = verticalLabel.resolvedStyle.height; verticalBox.style.height = verticalLabel.resolvedStyle.width + horizontalLabel.resolvedStyle.paddingRight + (totalLabelsPerside - userData.gridY) * (toggle.resolvedStyle.height + toggle.resolvedStyle.marginTop + toggle.resolvedStyle.marginBottom); //absolute pos calculate for vertical bar verticalBox.style.left = userData.sideLabels.resolvedStyle.width + verticalLabel.resolvedStyle.height * userData.gridY; verticalBox.style.top = userData.topLabels.resolvedStyle.width - verticalLabel.resolvedStyle.width; userData.overlay.Add(horizontalBox); userData.overlay.Add(verticalBox); } static void ClearGridOverlayLines(VisualElement toggle) { var userData = toggle.userData as ToggleData; while (userData.overlay.childCount > 0) userData.overlay.RemoveAt(0); } static void SetupLayerCollisionMatrix(VisualElement layerGridContainer) { var topLeftSpacer = layerGridContainer.Q<VisualElement>(name: "top-left-spacer"); var topLabels = layerGridContainer.Q<VisualElement>(name: "top-labels"); var sideLabels = layerGridContainer.Q<VisualElement>(name: "side-labels"); var toggles = layerGridContainer.Q<VisualElement>(name: "toggles"); var overlay = layerGridContainer.Q<VisualElement>(name: "layer-grid-overlay"); Assert.AreEqual(k_MaxLayers, sideLabels.childCount); Assert.AreEqual(sideLabels.childCount, toggles.childCount); var data = layerGridContainer.userData as LayerGridData; data.layers.Clear(); data.layers.Capacity = k_MaxLayers; for (int i = 0; i < k_MaxLayers; i++) { var layerName = LayerMask.LayerToName(i); if (LayerMask.LayerToName(i) == string.Empty) continue; data.layers.Add(new LayerData() { bit = i, name = layerName }); } for (int i = 0; i < data.layers.Count; ++i) { var layer0 = data.layers[i]; var label = sideLabels[i] as Label; label.text = layer0.name; var tLabel = new Label(); tLabel.AddToClassList("project-settings___physics__toggle-col-label"); tLabel.text = layer0.name; topLabels.Add(tLabel); var line = toggles[i]; //generate visible toggles, for (int j = 0; j < data.layers.Count - i; ++j) { var toggle = line[j] as Toggle; toggle.AddToClassList("project-settings___physics__toggle"); var layer1 = data.layers[(data.layers.Count - 1) - j]; toggle.value = !Physics.GetIgnoreLayerCollision(layer0.bit, layer1.bit); toggle.userData = new ToggleData() { gridX = i, gridY = j, layerBit0 = layer0.bit, layerBit1 = layer1.bit, sideLabels = sideLabels, topLabels = topLabels, overlay = overlay }; toggle.RegisterValueChangedCallback((evt) => { if (evt.newValue == evt.previousValue) return; var userData = ((evt.target as VisualElement).userData as ToggleData); Physics.IgnoreLayerCollision(userData.layerBit0, userData.layerBit1, !evt.newValue); }); toggle.RegisterCallback((MouseEnterEvent evt) => { AddGridOverlayLines((evt.target as VisualElement)); }, TrickleDown.NoTrickleDown); toggle.RegisterCallback((MouseLeaveEvent evt) => { ClearGridOverlayLines((evt.target as VisualElement)); }, TrickleDown.NoTrickleDown); } //disable invisible toggles inside the active lines for (int j = data.layers.Count - i; j < line.childCount; ++j) { var toggle = line[j] as Toggle; toggle.style.display = DisplayStyle.None; } } //loop over the following labels + toggle lines and disable them for (int i = data.layers.Count; i < sideLabels.childCount; ++i) { sideLabels[i].style.display = DisplayStyle.None; toggles[i].style.display = DisplayStyle.None; } SerializedProperty layerCollisionMatrix = data.physicsManager.FindProperty("m_LayerCollisionMatrix"); toggles.TrackPropertyValue(layerCollisionMatrix); toggles.TrackPropertyValue(layerCollisionMatrix, (prop) => { for (int i = 0; i < k_MaxLayers; ++i) { var line = toggles[i]; if (line.style.display == DisplayStyle.None) continue; for (int j = 0; j < line.childCount; ++j) { var toggle = line[j] as Toggle; if (toggle.style.display == DisplayStyle.None) continue; var userData = toggle.userData as ToggleData; toggle.value = !Physics.GetIgnoreLayerCollision(userData.layerBit0, userData.layerBit1); } } }); var enableAll = layerGridContainer.Q<Button>("enable-all"); enableAll.clicked += () => { for (int i = 0; i < k_MaxLayers; ++i) { var line = toggles[i]; for (int j = i; j < k_MaxLayers; ++j) { Physics.IgnoreLayerCollision(i, j, false); if (line.style.display == DisplayStyle.None || j >= line.childCount) continue; var toggle = line[j] as Toggle; if (toggle.style.display == DisplayStyle.None) continue; toggle.SetValueWithoutNotify(true); } } }; var disableAll = layerGridContainer.Q<Button>("disable-all"); disableAll.clicked += () => { for (int i = 0; i < k_MaxLayers; ++i) { var line = toggles[i]; for (int j = i; j < k_MaxLayers; ++j) { Physics.IgnoreLayerCollision(i, j, true); if (line.style.display == DisplayStyle.None || j >= line.childCount) continue; var toggle = line[j] as Toggle; if (toggle.style.display == DisplayStyle.None) continue; toggle.SetValueWithoutNotify(false); } } }; layerGridContainer.RegisterCallbackOnce<GeometryChangedEvent>((evt) => { //resize elements so they properly align topLeftSpacer.style.width = sideLabels.resolvedStyle.width; topLeftSpacer.style.height = sideLabels.resolvedStyle.width; float longestLineWidth = 0.0f; for (int i = 0; i < toggles.childCount; ++i) { var lineWidth = toggles[i].resolvedStyle.width; if (longestLineWidth < lineWidth) longestLineWidth = lineWidth; } toggles.style.width = longestLineWidth; topLabels.style.width = sideLabels.resolvedStyle.width; topLabels.style.height = sideLabels.resolvedStyle.height; topLabels.style.left = sideLabels.resolvedStyle.width + longestLineWidth; }); } static void SetupSharedTab(VisualElement tab, SerializedObject serializedObject, SerializedObject tagManager) { tab.Add(new PropertyField(serializedObject.FindProperty("m_Gravity"))); bool fold = false; if (EditorPrefs.HasKey(k_layerMatrixFoldoutPref)) fold = EditorPrefs.GetBool(k_layerMatrixFoldoutPref); var layerGridContainer = new VisualElement(); var layerGridUXML = EditorGUIUtility.Load(UXMLPath.physicsLayerGrid) as VisualTreeAsset; layerGridUXML.CloneTree(layerGridContainer); layerGridContainer.userData = new LayerGridData() { layers = new List<LayerData>(), physicsManager = serializedObject, tagManager = tagManager }; SetupLayerCollisionMatrix(layerGridContainer); layerGridContainer.TrackPropertyValue(tagManager.FindProperty("layers"), (prop) => { //scrap the whole tree layerGridContainer.RemoveAt(0); layerGridUXML.CloneTree(layerGridContainer); SetupLayerCollisionMatrix(layerGridContainer); }); var foldOut = new Foldout() { text = "Layer Collision Matrix", value = true }; foldOut.RegisterValueChangedCallback((evt) => { EditorPrefs.SetBool(k_layerMatrixFoldoutPref, evt.newValue); }); //patch in the correct initial value now that we've computed the layout with the unfolded values //we do this step due to the deffered layout computation for the top labels of the collision layer matrix foldOut.RegisterCallbackOnce<GeometryChangedEvent>((evt) => { foldOut.SetValueWithoutNotify(fold); }); foldOut.Add(layerGridContainer); tab.Add(foldOut); } static void SetupClassicTab(VisualElement tab, SerializedObject serializedObject) { tab.Add(new PropertyField(serializedObject.FindProperty("m_DefaultMaterial"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_BounceThreshold"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_DefaultMaxDepenetrationVelocity"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_SleepThreshold"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_DefaultContactOffset"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_DefaultSolverIterations"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_DefaultSolverVelocityIterations"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_QueriesHitBackfaces"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_QueriesHitTriggers"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_EnableAdaptiveForce"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_SimulationMode"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_AutoSyncTransforms"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_ReuseCollisionCallbacks"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_InvokeCollisionCallbacks"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_ContactPairsMode"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_BroadphaseType"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_FrictionType"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_EnableEnhancedDeterminism"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_EnableUnifiedHeightmaps"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_ImprovedPatchFriction"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_SolverType"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_DefaultMaxAngularSpeed"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_ScratchBufferChunkCount"))); tab.Add(new PropertyField(serializedObject.FindProperty("m_FastMotionThreshold"))); } static void SetupClothTab(VisualElement tab, SerializedObject serializedObject) { tab.Add(new PropertyField(serializedObject.FindProperty("m_ClothGravity"), "Gravity Override")); var interCollisionToggle = new PropertyField(serializedObject.FindProperty("m_ClothInterCollisionSettingsToggle"), "Enable Inter-Collision"); var interCollisionDistance = new PropertyField(serializedObject.FindProperty("m_ClothInterCollisionDistance"), "Inter-Collision Distance"); var interCollisionStiffness = new PropertyField(serializedObject.FindProperty("m_ClothInterCollisionStiffness"), "Inter-Collision Stiffness"); interCollisionToggle.RegisterValueChangeCallback( (evt) => { bool res = evt.changedProperty.boolValue; interCollisionDistance.style.display = res ? DisplayStyle.Flex : DisplayStyle.None; interCollisionStiffness.style.display = res ? DisplayStyle.Flex : DisplayStyle.None; }); tab.Add(interCollisionToggle); tab.Add(interCollisionDistance); tab.Add(interCollisionStiffness); } static void SetupECSTab(TabView tabs, SerializedObject serializedObject) { if (EcsExtension == null) return; var tab = new Tab() { label = "ECS", name = "tab__ecs" }; var tabContent = new VisualElement() { name = "tab-content__ecs" }; tabContent.AddToClassList("project-settings__physics__tab-content"); try { EcsExtension.SetupSettingsTab(tab, serializedObject); tab.Add(tabContent); tabs.Add(tab); } catch (Exception ex) { //consume the exception without breaking the settings pane Debug.LogException(ex); } } [SettingsProvider] static SettingsProvider CreatePhysicsSettingsPageProvider() { var provider = new SettingsProvider("Project/Physics/Settings", SettingsScope.Project) { label = "Settings", keywords = SettingsProvider.GetSearchKeywordsFromPath(AssetPath.dynamics) }; provider.activateHandler = (searchContext, rootElement) => { var serializedObject = LoadGameManagerAssetAtPath(AssetPath.dynamics); if (serializedObject == null) { Debug.LogError(AssetPath.dynamicsError); return; } var serializedTagManager = LoadGameManagerAssetAtPath(AssetPath.tags); if (serializedObject == null) { Debug.LogError(AssetPath.tagsError); return; } var subUXML = EditorGUIUtility.Load(UXMLPath.projectSettingsSub) as VisualTreeAsset; subUXML.CloneTree(rootElement); var content = rootElement.Q<ScrollView>(className: "project-settings-section-content"); content.styleSheets.Add(EditorGUIUtility.Load(StyleSheetPath.projectSettingsSheet) as StyleSheet); content.styleSheets.Add(EditorGUIUtility.Load(StyleSheetPath.commonSheet) as StyleSheet); content.styleSheets.Add(EditorGUIUtility.Load(EditorGUIUtility.isProSkin ? StyleSheetPath.darkSheet : StyleSheetPath.lightSheet) as StyleSheet); SetupSharedTab(content.Q(name: "tab-content__shared"), serializedObject, serializedTagManager); SetupClassicTab(content.Q(name: "tab-content__classic"), serializedObject); SetupClothTab(content.Q(name: "tab-content__cloth"), serializedObject); SetupECSTab(content.Q<TabView>(name: "setting-tabs"), serializedObject); //bind data object rootElement.Bind(serializedObject); }; return provider; } } }
UnityCsReference/Modules/PhysicsEditor/PhysicsManagerInspector.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/PhysicsManagerInspector.cs", "repo_id": "UnityCsReference", "token_count": 12409 }
428
// 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 UnityEditorInternal; using UnityEngine; using UnityEngine.Bindings; namespace UnityEditor.Presets { [NativeType(Header = "Modules/PresetsEditor/Public/PresetManager.h")] internal class PresetManager : ProjectSettingsBase { internal extern void AddPresetType(PresetType presetType); } [NativeType(Header = "Modules/PresetsEditor/Public/PresetManager.h")] [StructLayout(LayoutKind.Sequential)] [Serializable] public struct DefaultPreset { [SerializeField] [Obsolete("Use the new getter/setter instead. (UnityUpgradable) -> filter")] public string m_Filter; [SerializeField] [Obsolete("Use the new getter/setter instead. (UnityUpgradable) -> preset")] public Preset m_Preset; [SerializeField] private bool m_Disabled; public string filter { #pragma warning disable 618 get { return m_Filter; } set { m_Filter = value; } #pragma warning restore 618 } public Preset preset { #pragma warning disable 618 get { return m_Preset; } set { m_Preset = value; } #pragma warning restore 618 } public bool enabled { get { return !m_Disabled; } set { m_Disabled = !value; } } public DefaultPreset(string filter, Preset preset) : this(filter, preset, true) {} public DefaultPreset(string filter, Preset preset, bool enabled) { #pragma warning disable 618 m_Filter = filter; m_Preset = preset; #pragma warning restore 618 m_Disabled = !enabled; } } }
UnityCsReference/Modules/PresetsEditor/Public/PresetManager.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/PresetsEditor/Public/PresetManager.bindings.cs", "repo_id": "UnityCsReference", "token_count": 791 }
429
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Analytics; namespace UnityEditor.Profiling { internal interface IAnalyticsService { AnalyticsResult SendAnalytic(IAnalytic analytic); } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Analytics/IAnalyticsService.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Analytics/IAnalyticsService.cs", "repo_id": "UnityCsReference", "token_count": 105 }
430
// 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 Unity.Profiling.Editor.UI { class TimeFormatterUtility { public static string FormatTimeNsToMs(UInt64 timeNs) { return string.Format($"{timeNs * 1.0e-6f:F3}ms"); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/Shared/TimeFormatterUtility.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/Shared/TimeFormatterUtility.cs", "repo_id": "UnityCsReference", "token_count": 161 }
431
// 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.Globalization; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEditor.Profiling; using UnityEngine; namespace UnityEditorInternal.Profiling { internal class ProfilerCallersAndCalleeData { public float totalSelectedPropertyTime { get; private set; } public CallsData callersData => m_CallersData; public CallsData calleesData => m_CalleesData; internal IProfilerSampleNameProvider profilerSampleNameProvider { get; set; } CallsData m_CallersData = new CallsData() {calls = new List<CallInformation>(), totalSelectedPropertyTime = 0 }; CallsData m_CalleesData = new CallsData() {calls = new List<CallInformation>(), totalSelectedPropertyTime = 0 }; Dictionary<int, CallInformation> m_Callers = new Dictionary<int, CallInformation>(); Dictionary<int, CallInformation> m_Callees = new Dictionary<int, CallInformation>(); List<int> m_ChildrenIds = new List<int>(256); Stack<int> m_Stack = new Stack<int>(); internal struct CallsData { public List<CallInformation> calls; public float totalSelectedPropertyTime; } internal class CallInformation { public int id; // FrameDataView item id public string name; public int callsCount; public int gcAllocBytes; public float totalCallTimeMs; public float totalSelfTimeMs; public float timePercent; // Cached value - calculated based on view type } internal void UpdateData(HierarchyFrameDataView frameDataView, int selectedMarkerId) { totalSelectedPropertyTime = 0; var topDownHierarchyData = frameDataView; var targetInvertedHierarchy = frameDataView; if (frameDataView.viewMode.HasFlag(HierarchyFrameDataView.ViewModes.InvertHierarchy)) { topDownHierarchyData = ProfilerDriver.GetHierarchyFrameDataView(frameDataView.frameIndex, frameDataView.threadIndex, frameDataView.viewMode ^ HierarchyFrameDataView.ViewModes.InvertHierarchy, HierarchyFrameDataView.columnDontSort, false); } m_Callers.Clear(); m_Callees.Clear(); m_ChildrenIds.Clear(); m_Stack.Clear(); m_Stack.Push(topDownHierarchyData.GetRootItemID()); while (m_Stack.Count > 0) { var current = m_Stack.Pop(); if (!topDownHierarchyData.HasItemChildren(current)) continue; var markerId = topDownHierarchyData.GetItemMarkerID(current); topDownHierarchyData.GetItemChildren(current, m_ChildrenIds); foreach (var childId in m_ChildrenIds) { var childMarkerId = topDownHierarchyData.GetItemMarkerID(childId); // Add markerId to callers (except root) if (childMarkerId == selectedMarkerId) { var totalSelfTime = topDownHierarchyData.GetItemColumnDataAsSingle(childId, HierarchyFrameDataView.columnTotalTime); totalSelectedPropertyTime += totalSelfTime; // Skip root sample if (current != 0) { // Add markerId to callers (except root) CallInformation callInfo; var totalTime = topDownHierarchyData.GetItemColumnDataAsSingle(current, HierarchyFrameDataView.columnTotalTime); // Display sample details in the scope of caller. var calls = (int)topDownHierarchyData.GetItemColumnDataAsSingle(childId, HierarchyFrameDataView.columnCalls); var gcAlloc = (int)topDownHierarchyData.GetItemColumnDataAsSingle(childId, HierarchyFrameDataView.columnGcMemory); if (!m_Callers.TryGetValue(markerId, out callInfo)) { m_Callers.Add(markerId, new CallInformation() { id = current, name = profilerSampleNameProvider.GetItemName(topDownHierarchyData, current), callsCount = calls, gcAllocBytes = gcAlloc, totalCallTimeMs = totalTime, totalSelfTimeMs = totalSelfTime }); } else { callInfo.callsCount += calls; // Ignore adding time and gc allocations for recursive like calls if (markerId != childMarkerId) { callInfo.gcAllocBytes += gcAlloc; callInfo.totalCallTimeMs += totalTime; callInfo.totalSelfTimeMs += totalSelfTime; } } } } if (markerId == selectedMarkerId) { // Add childMarkerId to callees CallInformation callInfo; var totalTime = topDownHierarchyData.GetItemColumnDataAsSingle(childId, HierarchyFrameDataView.columnTotalTime); var calls = (int)topDownHierarchyData.GetItemColumnDataAsSingle(childId, HierarchyFrameDataView.columnCalls); var gcAlloc = (int)topDownHierarchyData.GetItemColumnDataAsSingle(childId, HierarchyFrameDataView.columnGcMemory); if (!m_Callees.TryGetValue(childMarkerId, out callInfo)) { m_Callees.Add(childMarkerId, new CallInformation() { id = childId, name = profilerSampleNameProvider.GetItemName(topDownHierarchyData, childId), callsCount = calls, gcAllocBytes = gcAlloc, totalCallTimeMs = totalTime, totalSelfTimeMs = 0 }); } else { callInfo.callsCount += calls; // Ignore adding time and gc allocations for recursive like calls if (markerId != childMarkerId) { callInfo.gcAllocBytes += gcAlloc; callInfo.totalCallTimeMs += totalTime; } } } m_Stack.Push(childId); } } // Remap ids to the target inverted hierarchy if (!topDownHierarchyData.Equals(targetInvertedHierarchy)) { var invertedHierarchyChildren = new List<int>(); targetInvertedHierarchy.GetItemChildren(targetInvertedHierarchy.GetRootItemID(), invertedHierarchyChildren); var rawIndices = new List<int>(); MigrateItemIds(m_Callees, topDownHierarchyData, targetInvertedHierarchy, invertedHierarchyChildren, rawIndices); MigrateItemIds(m_Callers, topDownHierarchyData, targetInvertedHierarchy, invertedHierarchyChildren, rawIndices); topDownHierarchyData.Dispose(); } UpdateCallsData(ref m_CallersData, m_Callers, totalSelectedPropertyTime); UpdateCallsData(ref m_CalleesData, m_Callees, totalSelectedPropertyTime); } static void MigrateItemIds(Dictionary<int, CallInformation> calls, HierarchyFrameDataView topDownHierarchyData, HierarchyFrameDataView targetInvertedHierarchy, List<int> invertedHierarchyChildren, List<int> cachedRawIndices) { foreach (var c in calls) { var fromId = c.Value.id; topDownHierarchyData.GetItemRawFrameDataViewIndices(fromId, cachedRawIndices); var rawIndex = cachedRawIndices[0]; for (var i = 0; i < invertedHierarchyChildren.Count; ++i) { if (targetInvertedHierarchy.ItemContainsRawFrameDataViewIndex(invertedHierarchyChildren[i], rawIndex)) { c.Value.id = invertedHierarchyChildren[i]; break; } } } } private void UpdateCallsData(ref CallsData callsData, Dictionary<int, CallInformation> data, float totalSelectedPropertyTime) { callsData.calls.Clear(); callsData.calls.AddRange(data.Values); callsData.totalSelectedPropertyTime = totalSelectedPropertyTime; } } [Serializable] internal class ProfilerDetailedCallsView : ProfilerDetailedView { static class Content { public static readonly string totalSelectedPropertyTimeTooltip = L10n.Tr("Total time of all calls of the selected function in the frame."); } [NonSerialized] bool m_Initialized = false; internal IProfilerSampleNameProvider profilerSampleNameProvider => m_CPUOrGPUProfilerModule; [NonSerialized] GUIContent m_TotalSelectedPropertyTimeLabel; [SerializeField] SplitterState m_VertSplit; [SerializeField] CallsTreeViewController m_CalleesTreeView; [SerializeField] CallsTreeViewController m_CallersTreeView; public delegate void FrameItemCallback(int id); public event FrameItemCallback frameItemEvent; [NonSerialized] ProfilerCallersAndCalleeData callersAndCalleeData = null; class CallsTreeView : TreeView { public enum Type { Callers, Callees } public enum Column { Name, Calls, GcAlloc, TimeMs, TimePercent, Count } internal ProfilerCallersAndCalleeData.CallsData m_CallsData; Type m_Type; public event FrameItemCallback frameItemEvent; public CallsTreeView(Type type, TreeViewState treeViewState, MultiColumnHeader multicolumnHeader) : base(treeViewState, multicolumnHeader) { m_Type = type; showBorder = true; showAlternatingRowBackgrounds = true; multicolumnHeader.sortingChanged += OnSortingChanged; Reload(); } public void SetCallsData(ProfilerCallersAndCalleeData.CallsData callsData) { m_CallsData = callsData; // Cache Time % value if (m_CallsData.calls != null) { foreach (var callInfo in m_CallsData.calls) { callInfo.timePercent = m_Type == Type.Callees ? callInfo.totalCallTimeMs / m_CallsData.totalSelectedPropertyTime : callInfo.totalSelfTimeMs / callInfo.totalCallTimeMs; } } OnSortingChanged(multiColumnHeader); } protected override TreeViewItem BuildRoot() { var root = new TreeViewItem { id = 0, depth = -1 }; var allItems = new List<TreeViewItem>(); if (m_CallsData.calls != null && m_CallsData.calls.Count != 0) { allItems.Capacity = m_CallsData.calls.Count; for (var i = 0; i < m_CallsData.calls.Count; i++) allItems.Add(new TreeViewItem { id = i + 1, depth = 0, displayName = m_CallsData.calls[i].name }); } else { allItems.Add(new TreeViewItem { id = 1, depth = 0, displayName = kNoneText }); } SetupParentsAndChildrenFromDepths(root, allItems); return root; } protected override void RowGUI(RowGUIArgs args) { if (Event.current.rawType != EventType.Repaint) return; for (var i = 0; i < args.GetNumVisibleColumns(); ++i) { CellGUI(args.GetCellRect(i), args.item, (Column)args.GetColumn(i), ref args); } } void CellGUI(Rect cellRect, TreeViewItem item, Column column, ref RowGUIArgs args) { if (m_CallsData.calls.Count == 0) { base.RowGUI(args); return; } var callInfo = m_CallsData.calls[args.item.id - 1]; CenterRectUsingSingleLineHeight(ref cellRect); switch (column) { case Column.Name: { DefaultGUI.Label(cellRect, callInfo.name, args.selected, args.focused); } break; case Column.Calls: { var value = callInfo.callsCount.ToString(); DefaultGUI.Label(cellRect, value, args.selected, args.focused); } break; case Column.GcAlloc: { var value = callInfo.gcAllocBytes; DefaultGUI.Label(cellRect, value.ToString(), args.selected, args.focused); } break; case Column.TimeMs: { var value = callInfo.totalSelfTimeMs; DefaultGUI.Label(cellRect, value.ToString("f2", CultureInfo.InvariantCulture.NumberFormat), args.selected, args.focused); } break; case Column.TimePercent: { DefaultGUI.Label(cellRect, (callInfo.timePercent * 100f).ToString("f2", CultureInfo.InvariantCulture.NumberFormat), args.selected, args.focused); } break; } } void OnSortingChanged(MultiColumnHeader header) { if (header.sortedColumnIndex == -1) return; // No column to sort for (just use the order the data are in) if (m_CallsData.calls != null) { var orderMultiplier = header.IsSortedAscending(header.sortedColumnIndex) ? 1 : -1; Comparison<ProfilerCallersAndCalleeData.CallInformation> comparison; switch ((Column)header.sortedColumnIndex) { case Column.Name: comparison = (callInfo1, callInfo2) => callInfo1.name.CompareTo(callInfo2.name) * orderMultiplier; break; case Column.Calls: comparison = (callInfo1, callInfo2) => callInfo1.callsCount.CompareTo(callInfo2.callsCount) * orderMultiplier; break; case Column.GcAlloc: comparison = (callInfo1, callInfo2) => callInfo1.gcAllocBytes.CompareTo(callInfo2.gcAllocBytes) * orderMultiplier; break; case Column.TimeMs: comparison = (callInfo1, callInfo2) => callInfo1.totalCallTimeMs.CompareTo(callInfo2.totalCallTimeMs) * orderMultiplier; break; case Column.TimePercent: comparison = (callInfo1, callInfo2) => callInfo1.timePercent.CompareTo(callInfo2.timePercent) * orderMultiplier; break; case Column.Count: comparison = (callInfo1, callInfo2) => callInfo1.callsCount.CompareTo(callInfo2.callsCount) * orderMultiplier; break; default: return; } m_CallsData.calls.Sort(comparison); } Reload(); } protected override void DoubleClickedItem(int id) { if (m_CallsData.calls == null || m_CallsData.calls.Count == 0) return; if (frameItemEvent != null) frameItemEvent.Invoke(m_CallsData.calls[id - 1].id); } } [Serializable] class CallsTreeViewController { [NonSerialized] bool m_Initialized; [NonSerialized] CallsTreeView.Type m_Type; [SerializeField] TreeViewState m_ViewState; [SerializeField] MultiColumnHeaderState m_ViewHeaderState; CallsTreeView m_View; static class Styles { public static GUIContent callersLabel = EditorGUIUtility.TrTextContent("Called From", "Parents the selected function is called from\n\n(Press 'F' for frame selection)"); public static GUIContent calleesLabel = EditorGUIUtility.TrTextContent("Calls To", "Functions which are called from the selected function\n\n(Press 'F' for frame selection)"); public static GUIContent callsLabel = EditorGUIUtility.TrTextContent("Calls", "Total number of calls in a selected frame"); public static GUIContent gcAllocLabel = EditorGUIUtility.TrTextContent("GC Alloc"); public static GUIContent timeMsCallersLabel = EditorGUIUtility.TrTextContent("Time ms", "Total time the selected function spends within a parent"); public static GUIContent timeMsCalleesLabel = EditorGUIUtility.TrTextContent("Time ms", "Total time the child call spends within selected function"); public static GUIContent timePctCallersLabel = EditorGUIUtility.TrTextContent("Time %", "Shows how often the selected function was called from the parent call"); public static GUIContent timePctCalleesLabel = EditorGUIUtility.TrTextContent("Time %", "Shows how often child call was called from the selected function"); } public event FrameItemCallback frameItemEvent; readonly string k_PrefKeyPrefix; string multiColumnHeaderStatePrefKey => k_PrefKeyPrefix + "MultiColumnHeaderState"; public CallsTreeViewController(string prefKeyPrefix) { k_PrefKeyPrefix = prefKeyPrefix; } void InitIfNeeded() { if (m_Initialized) return; if (m_ViewState == null) m_ViewState = new TreeViewState(); var headerState = CreateDefaultMultiColumnHeaderState(); var multiColumnHeaderStateData = SessionState.GetString(multiColumnHeaderStatePrefKey, ""); if (!string.IsNullOrEmpty(multiColumnHeaderStateData)) { try { var restoredHeaderState = JsonUtility.FromJson<MultiColumnHeaderState>(multiColumnHeaderStateData); if (restoredHeaderState != null) m_ViewHeaderState = restoredHeaderState; } catch{} // Nevermind, we'll just fall back to the default } if (MultiColumnHeaderState.CanOverwriteSerializedFields(m_ViewHeaderState, headerState)) MultiColumnHeaderState.OverwriteSerializedFields(m_ViewHeaderState, headerState); var firstInit = m_ViewHeaderState == null; m_ViewHeaderState = headerState; var multiColumnHeader = new MultiColumnHeader(m_ViewHeaderState) { height = 25 }; if (firstInit) { multiColumnHeader.state.visibleColumns = new[] { (int)CallsTreeView.Column.Name, (int)CallsTreeView.Column.Calls, (int)CallsTreeView.Column.GcAlloc, (int)CallsTreeView.Column.TimeMs, (int)CallsTreeView.Column.TimePercent, }; multiColumnHeader.ResizeToFit(); } multiColumnHeader.visibleColumnsChanged += OnMultiColumnHeaderChanged; multiColumnHeader.sortingChanged += OnMultiColumnHeaderChanged; m_View = new CallsTreeView(m_Type, m_ViewState, multiColumnHeader); m_View.frameItemEvent += frameItemEvent; m_Initialized = true; } void OnMultiColumnHeaderChanged(MultiColumnHeader header) { SessionState.SetString(multiColumnHeaderStatePrefKey, JsonUtility.ToJson(header.state)); } MultiColumnHeaderState CreateDefaultMultiColumnHeaderState() { var columns = new[] { new MultiColumnHeaderState.Column { headerContent = (m_Type == CallsTreeView.Type.Callers ? Styles.callersLabel : Styles.calleesLabel), headerTextAlignment = TextAlignment.Left, sortedAscending = true, sortingArrowAlignment = TextAlignment.Right, width = 150, minWidth = 150, autoResize = true, allowToggleVisibility = false }, new MultiColumnHeaderState.Column { headerContent = Styles.callsLabel, headerTextAlignment = TextAlignment.Left, sortedAscending = false, sortingArrowAlignment = TextAlignment.Right, width = 60, minWidth = 60, autoResize = false, allowToggleVisibility = true }, new MultiColumnHeaderState.Column { headerContent = Styles.gcAllocLabel, headerTextAlignment = TextAlignment.Left, sortedAscending = false, sortingArrowAlignment = TextAlignment.Right, width = 60, minWidth = 60, autoResize = false, allowToggleVisibility = true }, new MultiColumnHeaderState.Column { headerContent = (m_Type == CallsTreeView.Type.Callers ? Styles.timeMsCallersLabel : Styles.timeMsCalleesLabel), headerTextAlignment = TextAlignment.Left, sortedAscending = false, sortingArrowAlignment = TextAlignment.Right, width = 60, minWidth = 60, autoResize = false, allowToggleVisibility = true }, new MultiColumnHeaderState.Column { headerContent = (m_Type == CallsTreeView.Type.Callers ? Styles.timePctCallersLabel : Styles.timePctCalleesLabel), headerTextAlignment = TextAlignment.Left, sortedAscending = false, sortingArrowAlignment = TextAlignment.Right, width = 60, minWidth = 60, autoResize = false, allowToggleVisibility = true }, }; var state = new MultiColumnHeaderState(columns) { sortedColumnIndex = (int)CallsTreeView.Column.TimeMs }; return state; } public void SetType(CallsTreeView.Type type) { m_Type = type; } public void SetCallsData(ProfilerCallersAndCalleeData.CallsData callsData) { InitIfNeeded(); m_View.SetCallsData(callsData); } public void OnGUI(Rect r) { InitIfNeeded(); m_View.OnGUI(r); } } readonly string k_PrefKeyPrefix; string callsTreePrefKeyPrefix => k_PrefKeyPrefix + "CallsTree."; string calleesTreePrefKey => k_PrefKeyPrefix + "CalleesTree."; string spillter0StatePrefKey => k_PrefKeyPrefix + "Splitter.Relative[0]"; string spillter1StatePrefKey => k_PrefKeyPrefix + "Splitter.Relative[1]"; string selectedIDpathprefKey => k_PrefKeyPrefix + "SelectedPath"; public ProfilerDetailedCallsView(string prefKeyPrefix) { k_PrefKeyPrefix = prefKeyPrefix; } void InitIfNeeded() { if (m_Initialized) return; if (m_VertSplit == null || !m_VertSplit.IsValid()) m_VertSplit = SplitterState.FromRelative(new[] { SessionState.GetFloat(spillter0StatePrefKey, 40f), SessionState.GetFloat(spillter1StatePrefKey, 60f) }, new[] { 50f, 50f }, null); if (m_FrameDataView != null && m_FrameDataView.valid && m_SelectedID >= 0) { var restoredPath = m_FrameDataView.GetItemPath(m_SelectedID); var storedPath = SessionState.GetString(selectedIDpathprefKey, string.Empty); if (restoredPath != storedPath) m_SelectedID = -1; } else { m_SelectedID = -1; } if (m_CalleesTreeView == null) m_CalleesTreeView = new CallsTreeViewController(callsTreePrefKeyPrefix); m_CalleesTreeView.SetType(CallsTreeView.Type.Callees); m_CalleesTreeView.frameItemEvent += frameItemEvent; if (m_CallersTreeView == null) m_CallersTreeView = new CallsTreeViewController(calleesTreePrefKey); m_CallersTreeView.SetType(CallsTreeView.Type.Callers); m_CallersTreeView.frameItemEvent += frameItemEvent; callersAndCalleeData = new ProfilerCallersAndCalleeData(); callersAndCalleeData.profilerSampleNameProvider = profilerSampleNameProvider; m_TotalSelectedPropertyTimeLabel = new GUIContent(); m_Initialized = true; } public void DoGUI(GUIStyle headerStyle, HierarchyFrameDataView frameDataView, IList<int> selection) { if (frameDataView == null || !frameDataView.valid || selection.Count == 0) { DrawEmptyPane(headerStyle); return; } var selectedId = selection[0]; InitIfNeeded(); UpdateIfNeeded(frameDataView, selectedId); GUILayout.Label(m_TotalSelectedPropertyTimeLabel, EditorStyles.label); SplitterGUILayout.BeginVerticalSplit(m_VertSplit, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true)); // Callees var rect = EditorGUILayout.BeginHorizontal(); m_CalleesTreeView.OnGUI(rect); EditorGUILayout.EndHorizontal(); // Callers rect = EditorGUILayout.BeginHorizontal(); m_CallersTreeView.OnGUI(rect); EditorGUILayout.EndHorizontal(); SplitterGUILayout.EndVerticalSplit(); } void UpdateIfNeeded(HierarchyFrameDataView frameDataView, int selectedId) { var needReload = m_SelectedID != selectedId || !Equals(m_FrameDataView, frameDataView); if (!needReload) return; m_FrameDataView = frameDataView; m_SelectedID = selectedId; callersAndCalleeData.UpdateData(m_FrameDataView, m_FrameDataView.GetItemMarkerID(m_SelectedID)); m_CallersTreeView.SetCallsData(callersAndCalleeData.callersData); m_CalleesTreeView.SetCallsData(callersAndCalleeData.calleesData); var sampleDetails = profilerSampleNameProvider.GetItemName(m_FrameDataView, selectedId) + UnityString.Format(" - Total time: {0:f2} ms", callersAndCalleeData.totalSelectedPropertyTime); m_TotalSelectedPropertyTimeLabel.text = sampleDetails; m_TotalSelectedPropertyTimeLabel.tooltip = string.Concat(sampleDetails, "\n\n", Content.totalSelectedPropertyTimeTooltip); } public void Clear() { m_SelectedID = -1; if (m_CallersTreeView != null) m_CallersTreeView.SetCallsData(new ProfilerCallersAndCalleeData.CallsData() { calls = null, totalSelectedPropertyTime = 0 }); if (m_CalleesTreeView != null) m_CalleesTreeView.SetCallsData(new ProfilerCallersAndCalleeData.CallsData() { calls = null, totalSelectedPropertyTime = 0 }); } override public void SaveViewSettings() { if (m_FrameDataView != null && m_FrameDataView.valid && m_SelectedID >= 0) { SessionState.SetString(selectedIDpathprefKey, m_FrameDataView.GetItemPath(m_SelectedID)); } if (m_VertSplit != null && m_VertSplit.relativeSizes != null && m_VertSplit.relativeSizes.Length >= 2) { SessionState.SetFloat(spillter0StatePrefKey, m_VertSplit.relativeSizes[0]); SessionState.GetFloat(spillter1StatePrefKey, m_VertSplit.relativeSizes[1]); } } public override void OnEnable(CPUOrGPUProfilerModule cpuOrGpuProfilerModule, ProfilerFrameDataHierarchyView profilerFrameDataHierarchyView) { base.OnEnable(cpuOrGpuProfilerModule, profilerFrameDataHierarchyView); } override public void OnDisable() { SaveViewSettings(); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerDetailedCallsView.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerDetailedCallsView.cs", "repo_id": "UnityCsReference", "token_count": 15944 }
432
// 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.Profiling; using Unity.Profiling.Editor; using Unity.Profiling.LowLevel; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEditor.Profiling; using UnityEditor.Profiling.Analytics; using UnityEditorInternal; using UnityEngine; namespace UnityEditor.Profiling { internal interface IProfilerFrameTimeViewSampleSelectionControllerInternal { int FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(int frameIndex, int threadIndex, string sampleName, out List<int> markerIdPath, string markerNamePath = null); int FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(int frameIndex, int threadIndex, ref string sampleName, ref List<int> markerIdPath, int sampleMarkerId); void SetSelectionWithoutIntegrityChecks(ProfilerTimeSampleSelection selectionToSet, List<int> markerIdPath); IProfilerWindowController profilerWindow { get; } int GetActiveVisibleFrameIndexOrLatestFrameForSettingTheSelection(); } public interface IProfilerFrameTimeViewSampleSelectionController { event Action<IProfilerFrameTimeViewSampleSelectionController, ProfilerTimeSampleSelection> selectionChanged; ProfilerTimeSampleSelection selection { get; } string sampleNameSearchFilter { get; set; } int focusedThreadIndex { get; set; } bool SetSelection(ProfilerTimeSampleSelection selection); void ClearSelection(); } } namespace UnityEditorInternal.Profiling { interface IProfilerSampleNameProvider { string GetItemName(HierarchyFrameDataView frameData, int itemId); string GetMarkerName(HierarchyFrameDataView frameData, int markerId); string GetItemName(RawFrameDataView frameData, int itemId); } [Serializable] // TODO: refactor: rename to CpuOrGpuProfilerModule // together with CpuProfilerModule and GpuProfilerModule // in a PR that doesn't affect performance so that the sample names can be fixed as well without loosing comparability in Performance tests. internal abstract class CPUOrGPUProfilerModule : ProfilerModuleBase, IProfilerSampleNameProvider, IProfilerFrameTimeViewSampleSelectionController, IProfilerFrameTimeViewSampleSelectionControllerInternal { [SerializeField] protected ProfilerViewType m_ViewType = ProfilerViewType.Timeline; // internal because it is used by performance tests [SerializeField] internal bool updateViewLive; [SerializeField] int m_CurrentFrameIndex = FrameDataView.invalidOrCurrentFrameIndex; protected int CurrentFrameIndex { get { return m_CurrentFrameIndex; } set { if (m_CurrentFrameIndex != value) { m_CurrentFrameIndex = value; FrameChanged(value); } } } IProfilerWindowController IProfilerFrameTimeViewSampleSelectionControllerInternal.profilerWindow => ProfilerWindow; protected CPUOrGPUProfilerModule() : base(ProfilerModuleChartType.StackedTimeArea) { // check that the selection is still valid and wasn't badly deserialized on Domain Reload if (selection != null && (selection.markerPathDepth <= 0 || selection.rawSampleIndices == null)) m_Selection = null; } internal override void LegacyModuleInitialize() { base.LegacyModuleInitialize(); k_HierarchyViewAnalyticsName = DisplayName + ".Hierarchy"; k_RawHierarchyViewAnalyticsName = DisplayName + ".RawHierarchy"; k_InvertedHierarchyViewAnalyticsName = DisplayName + ".InvertedHierarchy"; k_TimelineViewAnalyticsName = DisplayName + ".Timeline"; } protected bool fetchData { get { return !(ProfilerWindow == null || ProfilerWindow.ProfilerWindowOverheadIsAffectingProfilingRecordingData()) || updateViewLive; } } string k_HierarchyViewAnalyticsName { get; set; } string k_RawHierarchyViewAnalyticsName { get; set; } string k_InvertedHierarchyViewAnalyticsName { get; set; } string k_TimelineViewAnalyticsName { get; set; } protected const string k_MainThreadName = "Main Thread"; const string k_ViewTypeSettingsKey = "ViewType"; const string k_HierarchyViewSettingsKeyPrefix = "HierarchyView."; protected abstract string SettingsKeyPrefix { get; } string ViewTypeSettingsKey { get { return SettingsKeyPrefix + k_ViewTypeSettingsKey; } } string HierarchyViewSettingsKeyPrefix { get { return SettingsKeyPrefix + k_HierarchyViewSettingsKeyPrefix; } } string ProfilerViewFilteringOptionsKey => SettingsKeyPrefix + nameof(m_ProfilerViewFilteringOptions); protected abstract ProfilerViewType DefaultViewTypeSetting { get; } ProfilerTimeSampleSelection m_Selection; public ProfilerTimeSampleSelection selection { get { return m_Selection; } private set { if (selection != null) // revoke frameIndex guarantee on old selection before we loose control over it selection.frameIndexIsSafe = false; m_Selection = value; // as soon as any selection is made, the thread focus will now be driven by the selection m_HierarchyOverruledThreadFromSelection = false; // I'm not sure how this can happen, but it does. if (selectionChanged == null) selectionChanged = delegate {}; selectionChanged(this, value); } } public event Action<IProfilerFrameTimeViewSampleSelectionController, ProfilerTimeSampleSelection> selectionChanged = delegate {}; // anything that resets the selection, resets this override // this is here so that a user can purposefully change aways from a thread with a selection in it and go through other frames without being reset to the thread of the selection [SerializeField] bool m_HierarchyOverruledThreadFromSelection = false; // err on the side of caution, don't serialize this. // This bool is only used for a performance optimization and precise selection of one particular instance of a sample when switching views on the same frame. [NonSerialized] protected bool m_FrameIndexOfSelectionGuaranteedToBeValid = false; [Flags] public enum ProfilerViewFilteringOptions { None = 0, CollapseEditorBoundarySamples = 1 << 0, // Session based override, default to off ShowFullScriptingMethodNames = 1 << 1, ShowExecutionFlow = 1 << 2, } static readonly GUIContent[] k_ProfilerViewFilteringOptions = { EditorGUIUtility.TrTextContent("Collapse EditorOnly Samples", "Samples that are only created due to profiling the editor are collapsed by default, renamed to EditorOnly [<FunctionName>] and any GC Alloc incurred by them will not be accumulated."), EditorGUIUtility.TrTextContent("Show Full Scripting Method Names", "Display fully qualified method names including assembly name and namespace."), EditorGUIUtility.TrTextContent("Show Flow Events", "Visualize job scheduling and execution."), }; [SerializeField] int m_ProfilerViewFilteringOptions = (int)ProfilerViewFilteringOptions.CollapseEditorBoundarySamples; string m_SampleNameSearchFilter = null; public string sampleNameSearchFilter { get => m_SampleNameSearchFilter; set { m_SampleNameSearchFilter = value; if (m_FrameDataHierarchyView != null) m_FrameDataHierarchyView.treeView.searchString = value; } } public int focusedThreadIndex { // From a user's perspective: // When in Timeline view, with an active selection, the thread index in which the selection resides in. // Otherwise, whatever thread index (Raw) Hierarchy view is currently showing or will be showing when the view next changes to it. // // Actually, the shown thread in Hierarchy views is driven by the active selection, unless overruled by m_HierarchyOverruledThreadFromSelection // and will otherwise just be what ever the user chose via this API or the thread selection dropdown. // // The effect from a user's persepective is pretty much the same but m_FrameDataHierarchyView might not yet have been set to reflect this as it does so somewhat lazyily // Therefore this API does some checks to establish the effect before it will happen in a way that users shouldn't need to care about. get { // if (multiple threads or a thread group is focused / shown in Hierarchy) // return FrameDataView.invalidThreadIndex; var hierarchyThreadIndex = m_FrameDataHierarchyView != null ? m_FrameDataHierarchyView.threadIndex : FrameDataView.invalidThreadIndex; if (ViewType != ProfilerViewType.Timeline && m_HierarchyOverruledThreadFromSelection && hierarchyThreadIndex >= 0) return m_FrameDataHierarchyView.threadIndex; if (selection != null && ProfilerWindow.selectedFrameIndex >= 0) return selection.GetThreadIndex((int)ProfilerWindow.selectedFrameIndex); return hierarchyThreadIndex; } set { if (ProfilerWindow.selectedFrameIndex < 0) { throw new InvalidOperationException($"Can't set {nameof(focusedThreadIndex)} while it is not showing any frame data {nameof(FrameDataView)}."); } if (value < 0) throw new ArgumentOutOfRangeException("value", $"The thread index {value} can't be set because it is negative."); using (var iter = new ProfilerFrameDataIterator()) { var threadCount = iter.GetThreadCount((int)ProfilerWindow.selectedFrameIndex); if (value >= threadCount) throw new ArgumentOutOfRangeException("value", $"The chosen thread index {value} is out of range of valid thread indices in this frame. Frame index: {ProfilerWindow.selectedFrameIndex}, thread count: {threadCount}."); m_HierarchyOverruledThreadFromSelection = true; // Frame the thread. This is independent of the checks below, as it only relates to Timeline view. // For Timeline view it doesn't matter what the status on the Hierarchy view was: setting this value should trigger a one-off framing of the thread. FrameThread(value); // only reload frame data if the thread index to focus is different to the thread index of the currently shown frame data view. if (value != m_FrameDataHierarchyView.threadIndex) { using (var dataView = new RawFrameDataView((int)ProfilerWindow.selectedFrameIndex, value)) { var frameDataView = GetFrameDataView(dataView.threadGroupName, dataView.threadName, dataView.threadId); // once a valid thread has been chosen, based on the thread index, the thread index should no longer be used to determine which thread to focus on going forward // because the thread index is too unstable frame over frame. The thread group name and name, as well as the thread ID are way more reliable, and will be gotten from m_FrameDataHierarchyView. // if it isn't valid m_FocusedThreadIndex will stay at its set value until it resolves to a valid one druing an OnGUI phase. if (frameDataView == null || !frameDataView.valid) throw new InvalidOperationException($"The provided thread index does not belong to a valid {nameof(FrameDataView)}."); m_FrameDataHierarchyView.SetFrameDataView(frameDataView); } } } } } protected virtual void FrameThread(int threadIndex) { } [SerializeField] protected ProfilerFrameDataHierarchyView m_FrameDataHierarchyView; // Used by Tests/PerformanceTests/Profiler ProfilerWindowTests.CPUViewTests.SelectAndDisplayDetailsForAFrame_WithSearchFiltering to avoid brittle tests due to reflection internal ProfilerFrameDataHierarchyView FrameDataHierarchyView => m_FrameDataHierarchyView; internal ProfilerViewFilteringOptions ViewOptions => (ProfilerViewFilteringOptions)m_ProfilerViewFilteringOptions; // Used by Tests/PerformanceTests/Profiler ProfilerWindowTests.CPUViewTests internal virtual ProfilerViewType ViewType { get { return m_ViewType; } set { CPUOrGPUViewTypeChanged(value); } } internal override void OnEnable() { base.OnEnable(); if (m_FrameDataHierarchyView == null) m_FrameDataHierarchyView = new ProfilerFrameDataHierarchyView(HierarchyViewSettingsKeyPrefix); m_FrameDataHierarchyView.OnEnable(this, ProfilerWindow, false); // safety guarding against event registration leaks due to an imbalance of OnEnable/OnDisable Calls, by deregistering first m_FrameDataHierarchyView.viewTypeChanged -= CPUOrGPUViewTypeChanged; m_FrameDataHierarchyView.viewTypeChanged += CPUOrGPUViewTypeChanged; m_FrameDataHierarchyView.selectionChanged -= SetSelectionWithoutIntegrityChecksOnSelectionChangeInDetailedView; m_FrameDataHierarchyView.selectionChanged += SetSelectionWithoutIntegrityChecksOnSelectionChangeInDetailedView; m_FrameDataHierarchyView.userChangedThread -= ThreadSelectionInHierarchyViewChanged; m_FrameDataHierarchyView.userChangedThread += ThreadSelectionInHierarchyViewChanged; if (!string.IsNullOrEmpty(sampleNameSearchFilter)) m_FrameDataHierarchyView.treeView.searchString = sampleNameSearchFilter; m_FrameDataHierarchyView.searchChanged -= SearchFilterInHierarchyViewChanged; m_FrameDataHierarchyView.searchChanged += SearchFilterInHierarchyViewChanged; ProfilerDriver.profileLoaded -= ProfileLoaded; ProfilerDriver.profileLoaded += ProfileLoaded; ProfilerDriver.profileCleared -= ProfileCleared; ProfilerDriver.profileCleared += ProfileCleared; m_ViewType = (ProfilerViewType)EditorPrefs.GetInt(ViewTypeSettingsKey, (int)DefaultViewTypeSetting); m_ProfilerViewFilteringOptions = SessionState.GetInt(ProfilerViewFilteringOptionsKey, m_ProfilerViewFilteringOptions); } private protected override void OnSelected() { base.OnSelected(); TryRestoringSelection(); SendViewTypeAnalytics(m_ViewType); } internal override void SaveViewSettings() { base.SaveViewSettings(); EditorPrefs.SetInt(ViewTypeSettingsKey, (int)m_ViewType); SessionState.SetInt(ProfilerViewFilteringOptionsKey, m_ProfilerViewFilteringOptions); m_FrameDataHierarchyView?.SaveViewSettings(); } internal override void OnDisable() { SaveViewSettings(); base.OnDisable(); m_FrameDataHierarchyView?.OnDisable(); if (m_FrameDataHierarchyView != null) { m_FrameDataHierarchyView.viewTypeChanged -= CPUOrGPUViewTypeChanged; m_FrameDataHierarchyView.selectionChanged -= SetSelectionWithoutIntegrityChecksOnSelectionChangeInDetailedView; } ProfilerDriver.profileLoaded -= ProfileLoaded; ProfilerDriver.profileCleared -= ProfileCleared; Clear(); } public override void DrawToolbar(Rect position) { // Hierarchy view still needs to be broken apart into Toolbar and View. } public void DrawOptionsMenuPopup() { var position = GUILayoutUtility.GetRect(ProfilerWindow.Styles.optionsButtonContent, EditorStyles.toolbarButton); if (GUI.Button(position, ProfilerWindow.Styles.optionsButtonContent, EditorStyles.toolbarButton)) { var pm = new GenericMenu(); for (var i = 0; i < k_ProfilerViewFilteringOptions.Length; i++) { var option = (ProfilerViewFilteringOptions)(1 << i); if (ViewType == ProfilerViewType.Timeline && option == ProfilerViewFilteringOptions.CollapseEditorBoundarySamples) continue; if (option == ProfilerViewFilteringOptions.ShowExecutionFlow && ViewType != ProfilerViewType.Timeline) continue; pm.AddItem(k_ProfilerViewFilteringOptions[i], OptionEnabled(option), () => ToggleOption(option)); } pm.Popup(position, -1); } } bool OptionEnabled(ProfilerViewFilteringOptions option) { return (option & (ProfilerViewFilteringOptions)m_ProfilerViewFilteringOptions) != ProfilerViewFilteringOptions.None; } internal virtual void SetOption(ProfilerViewFilteringOptions option, bool on) { if (on) m_ProfilerViewFilteringOptions = (int)((ProfilerViewFilteringOptions)m_ProfilerViewFilteringOptions | option); else m_ProfilerViewFilteringOptions = (int)((ProfilerViewFilteringOptions)m_ProfilerViewFilteringOptions & ~option); SessionState.SetInt(ProfilerViewFilteringOptionsKey, m_ProfilerViewFilteringOptions); m_FrameDataHierarchyView.Clear(); } protected virtual void ToggleOption(ProfilerViewFilteringOptions option) { SetOption(option, !OptionEnabled(option)); } public override void DrawDetailsView(Rect position) { CurrentFrameIndex = (int)ProfilerWindow.selectedFrameIndex; m_FrameDataHierarchyView.DoGUI(fetchData ? GetFrameDataView() : null, fetchData, ref updateViewLive, m_ViewType); } HierarchyFrameDataView GetFrameDataView() { return GetFrameDataView(m_FrameDataHierarchyView.groupName, m_FrameDataHierarchyView.threadName, m_FrameDataHierarchyView.threadId); } HierarchyFrameDataView GetFrameDataView(string threadGroupName, string threadName, ulong threadId) { var viewMode = HierarchyFrameDataView.ViewModes.Default; if (m_ViewType == ProfilerViewType.Hierarchy) viewMode |= HierarchyFrameDataView.ViewModes.MergeSamplesWithTheSameName; if (m_ViewType == ProfilerViewType.InvertedHierarchy) viewMode |= HierarchyFrameDataView.ViewModes.InvertHierarchy; return ProfilerWindow.GetFrameDataView(threadGroupName, threadName, threadId, viewMode | GetFilteringMode(), m_FrameDataHierarchyView.sortedProfilerColumn, m_FrameDataHierarchyView.sortedProfilerColumnAscending); } HierarchyFrameDataView GetFrameDataView(int threadIndex) { var viewMode = HierarchyFrameDataView.ViewModes.Default; if (m_ViewType == ProfilerViewType.Hierarchy) viewMode |= HierarchyFrameDataView.ViewModes.MergeSamplesWithTheSameName; if (m_ViewType == ProfilerViewType.InvertedHierarchy) viewMode |= HierarchyFrameDataView.ViewModes.InvertHierarchy; return ProfilerWindow.GetFrameDataView(threadIndex, viewMode | GetFilteringMode(), m_FrameDataHierarchyView.sortedProfilerColumn, m_FrameDataHierarchyView.sortedProfilerColumnAscending); } protected virtual HierarchyFrameDataView.ViewModes GetFilteringMode() { return HierarchyFrameDataView.ViewModes.Default; } protected void CPUOrGPUViewTypeChanged(ProfilerViewType newViewType) { if (m_ViewType == newViewType) return; var previousViewType = m_ViewType; m_ViewType = newViewType; SendViewTypeAnalytics(m_ViewType); //Update the module chart when changing the view from/to the inverted hierarchy. if (newViewType == ProfilerViewType.InvertedHierarchy || previousViewType == ProfilerViewType.InvertedHierarchy) { Update(); } // reset the hierarchy overruling if the user leaves the Hierarchy space // otherwise, switching back and forth between hierarchy views and Timeline feels inconsistent once you overruled the thread selection // basically, the override is in effect as long as the user sees the thread selection drop down, once that's gone, so is the override. (out of sight, out of mind) if (newViewType == ProfilerViewType.Timeline) { m_HierarchyOverruledThreadFromSelection = false; } ApplySelection(true, true); } void ThreadSelectionInHierarchyViewChanged(string threadGroupName, string threadName, int threadIndex) { var frameDataView = (threadIndex != FrameDataView.invalidThreadIndex) ? GetFrameDataView(threadIndex) : GetFrameDataView(threadGroupName, threadName, FrameDataView.invalidThreadId); m_FrameDataHierarchyView.SetFrameDataView(frameDataView); if (frameDataView != null && frameDataView.valid) { // once a valid thread has been chosen, based on the thread index, the thread index should no longer be used to determine which thread to focus on going forward // because the thread index is too unstable frame over frame. The thread group name and name, as well as the thread ID are way more reliable, and will be gotten from m_FrameDataHierarchyView. // if it isn't valid m_FocusedThreadIndex will stay at its set value until it resolves to a valid one druing an OnGUI phase. m_HierarchyOverruledThreadFromSelection = true; return; } // fail save, we should actually never get here but even if, fail silently and gracefully. m_HierarchyOverruledThreadFromSelection = false; } void SearchFilterInHierarchyViewChanged(string sampleNameSearchFiler) { m_SampleNameSearchFilter = sampleNameSearchFiler; } void FrameChanged(int frameIndex) { if (selection != null) { ApplySelection(false, fetchData); } } void ProfileLoaded() { if (selection != null) selection.frameIndexIsSafe = false; Clear(); TryRestoringSelection(); } void ProfileCleared() { if (selection != null) selection.frameIndexIsSafe = false; Clear(); } internal static readonly ProfilerMarker setSelectionIntegrityCheckMarker = new ProfilerMarker($"{nameof(CPUOrGPUProfilerModule)}.{nameof(CPUOrGPUProfilerModule.SetSelection)} Integrity Check"); internal static readonly ProfilerMarker setSelectionApplyMarker = new ProfilerMarker($"{nameof(CPUOrGPUProfilerModule)}.{nameof(CPUOrGPUProfilerModule.SetSelection)} Apply Selection"); internal static int IntegrityCheckFrameAndThreadDataOfSelection(long frameIndex, string threadGroupName, string threadName, ref ulong threadId) { if (string.IsNullOrEmpty(threadName)) throw new ArgumentException($"{nameof(threadName)} can't be null or empty."); if (ProfilerDriver.firstFrameIndex == FrameDataView.invalidOrCurrentFrameIndex) throw new Exception("No frame data is loaded, so there's no data to select from."); if (frameIndex > ProfilerDriver.lastFrameIndex || frameIndex < ProfilerDriver.firstFrameIndex) throw new ArgumentOutOfRangeException(nameof(frameIndex)); var threadIndex = FrameDataView.invalidThreadIndex; using (var frameView = new ProfilerFrameDataIterator()) { var threadCount = frameView.GetThreadCount((int)frameIndex); if (threadGroupName == null) threadGroupName = string.Empty; // simplify null to empty threadIndex = ProfilerTimeSampleSelection.GetThreadIndex((int)frameIndex, threadGroupName, threadName, threadId); if (threadIndex < 0 || threadIndex >= threadCount) throw new ArgumentException($"A Thread named: \"{threadName}\" in group \"{threadGroupName}\" could not be found in frame {frameIndex}"); using (var frameData = ProfilerDriver.GetRawFrameDataView((int)frameIndex, threadIndex)) { if (threadId != FrameDataView.invalidThreadId && frameData.threadId != threadId) throw new ArgumentException($"A Thread named: \"{threadName}\" in group \"{threadGroupName}\" was found in frame {frameIndex}, but its thread id {frameData.threadId} did not match the provided {threadId}"); else threadId = frameData.threadId; } } return threadIndex; } public bool SetSelection(ProfilerTimeSampleSelection selection) { var markerIdPath = new List<int>(); using (setSelectionIntegrityCheckMarker.Auto()) { // this could've come from anywhere, check the inputs first if (selection == null) throw new ArgumentException($"{nameof(selection)} can't be invalid. To clear a selection, use {nameof(ClearSelection)} instead."); // Since SetSelection is going to validate the the frame index, it is fine to use the unsafeFrameIndex and set selection.frameIndexIsSafe once everything is checked var threadId = selection.threadId; var threadIndex = IntegrityCheckFrameAndThreadDataOfSelection(selection.frameIndex, selection.threadGroupName, selection.threadName, ref threadId); if (threadId != selection.threadId) throw new ArgumentException($"The {nameof(selection)}.{nameof(selection.threadId)} of {selection.threadId} does not match to a fitting thread in frame {selection.frameIndex}."); if (selection.rawSampleIndices != null && selection.rawSampleIndices.Count > 1) { // multiple rawSampleIndices are currently only allowed if they all correspond to one item in Hierarchy view using (var frameData = new HierarchyFrameDataView((int)selection.frameIndex, threadIndex, HierarchyFrameDataView.ViewModes.MergeSamplesWithTheSameName, m_FrameDataHierarchyView.sortedProfilerColumn, m_FrameDataHierarchyView.sortedProfilerColumnAscending)) { var itemId = m_FrameDataHierarchyView.treeView.GetItemIDFromRawFrameDataViewIndex(frameData, selection.rawSampleIndex, null); var rawIds = new List<int>(); frameData.GetItemRawFrameDataViewIndices(itemId, rawIds); for (int i = 1; i < selection.rawSampleIndices.Count; i++) { var found = false; for (int j = 0; j < rawIds.Count; j++) { if (selection.rawSampleIndices[i] < 0) { throw new ArgumentException($"The passed raw id {selection.rawSampleIndices[i]} is invalid."); } if (selection.rawSampleIndices[i] == rawIds[j]) { found = true; break; } } if (!found) { throw new ArgumentException($"The passed raw id {selection.rawSampleIndices[i]} does not belong to the same Hierarchy Item as {selection.rawSampleIndices[0]}"); } } } } using (var frameData = new RawFrameDataView((int)selection.frameIndex, threadIndex)) { var name = string.Empty; var foundSampleIndex = ProfilerTimelineGUI.GetItemMarkerIdPath(frameData, this, selection.rawSampleIndex, ref name, ref markerIdPath); if (foundSampleIndex != selection.rawSampleIndex) throw new ArgumentException($"Provided {nameof(selection.rawSampleIndex)}: {selection.rawSampleIndex} was not found."); // don't trust the name and marker id data, override with found data. // Reason: Marker Ids could change and the sample name could be altered by the sample name formatter (e.g. to be/not be the fully qualified method name) selection.GenerateMarkerNamePath(frameData, name, markerIdPath); } } using (setSelectionApplyMarker.Auto()) { // looks good, apply selection.frameIndexIsSafe = true; SetSelectionWithoutIntegrityChecks(selection, markerIdPath); ApplySelection(false, true); return true; } } public void ClearSelection() { SetSelectionWithoutIntegrityChecks(null, null); ApplySelection(false, false); } public ProfilerTimeSampleSelection GetSelection() { return selection; } // Used for testing internal virtual void GetSelectedSampleIdsForCurrentFrameAndView(ref List<int> ids) { ids.Clear(); if (selection != null) { ids.AddRange(m_FrameDataHierarchyView.treeView.GetSelection()); } } // Only call this for SetSelection code that runs before SetSelectionWithoutIntegrityChecks sets the active visible Frame index // We don't want to desync from ProfilerWindow.m_LastFrameFromTick unless we're about to set it to something else and forcing a repaint anyways. // Most OnGUI scope code in this class should be able to rely on CurrentFrameIndex instead. int IProfilerFrameTimeViewSampleSelectionControllerInternal.GetActiveVisibleFrameIndexOrLatestFrameForSettingTheSelection() => GetActiveVisibleFrameIndexOrLatestFrameForSettingTheSelection(); int GetActiveVisibleFrameIndexOrLatestFrameForSettingTheSelection() { if (ProfilerWindow == null) return FrameDataView.invalidOrCurrentFrameIndex; var currentFrame = (int)ProfilerWindow.selectedFrameIndex; return currentFrame == FrameDataView.invalidOrCurrentFrameIndex ? ProfilerDriver.lastFrameIndex : currentFrame; } protected void SetSelectionWithoutIntegrityChecksOnSelectionChangeInDetailedView(ProfilerTimeSampleSelection selection) { if (selection == null) { ClearSelection(); return; } // trust the internal views to provide a correct frame index selection.frameIndexIsSafe = true; SetSelectionWithoutIntegrityChecks(selection, null); } void IProfilerFrameTimeViewSampleSelectionControllerInternal.SetSelectionWithoutIntegrityChecks(ProfilerTimeSampleSelection selectionToSet, List<int> markerIdPath) { SetSelectionWithoutIntegrityChecks(selectionToSet, markerIdPath); ApplySelection(false, true); } protected void SetSelectionWithoutIntegrityChecks(ProfilerTimeSampleSelection selectionToSet, List<int> markerIdPath) { if (selectionToSet != null) { if (selectionToSet.safeFrameIndex != ProfilerWindow.selectedFrameIndex) ProfilerWindow.SetActiveVisibleFrameIndex(selectionToSet.safeFrameIndex != FrameDataView.invalidOrCurrentFrameIndex ? (int)selectionToSet.safeFrameIndex : ProfilerDriver.lastFrameIndex); if (string.IsNullOrEmpty(selectionToSet.legacyMarkerPath)) { var frameDataView = GetFrameDataView(selectionToSet.threadGroupName, selectionToSet.threadName, selectionToSet.threadId); if (frameDataView == null || !frameDataView.valid) return; selectionToSet.GenerateMarkerNamePath(frameDataView, markerIdPath); } selection = selectionToSet; SetSelectedPropertyPath(selectionToSet.legacyMarkerPath, selectionToSet.threadName); } else { selection = null; ClearSelectedPropertyPath(); } } protected virtual void SetSelectedPropertyPath(string path, string threadName) { // Only CPU view currently supports Chart filtering by property path } protected virtual void ClearSelectedPropertyPath() { // Only CPU view currently supports Chart filtering by property path } protected void TryRestoringSelection() { if (selection != null) { // check that the selection is still valid and wasn't badly deserialized on Domain Reload if (selection.markerPathDepth <= 0 || selection.rawSampleIndices == null) { m_Selection = null; return; } if (ProfilerDriver.firstFrameIndex >= 0 && ProfilerDriver.lastFrameIndex >= 0) { ApplySelection(true, true); } SetSelectedPropertyPath(selection.legacyMarkerPath, selection.threadName); } } protected static readonly ProfilerMarker k_ApplyValidSelectionMarker = new ProfilerMarker($"{nameof(CPUOrGPUProfilerModule)}.{nameof(ApplySelection)}"); protected static readonly ProfilerMarker k_ApplySelectionClearMarker = new ProfilerMarker($"{nameof(CPUOrGPUProfilerModule)}.{nameof(ApplySelection)} Clear"); protected virtual void ApplySelection(bool viewChanged, bool frameSelection) { if (ViewType == ProfilerViewType.RawHierarchy || ViewType == ProfilerViewType.Hierarchy || ViewType == ProfilerViewType.InvertedHierarchy) { if (selection != null) { using (k_ApplyValidSelectionMarker.Auto()) { var currentFrame = ProfilerWindow.selectedFrameIndex; if (selection.frameIndexIsSafe && selection.safeFrameIndex == currentFrame) { var treeViewID = ProfilerFrameDataHierarchyView.invalidTreeViewId; if (fetchData) { var frameDataView = m_HierarchyOverruledThreadFromSelection ? GetFrameDataView() : GetFrameDataView(selection.threadGroupName, selection.threadName, selection.threadId); // avoid Selection Migration happening twice during SetFrameDataView by clearing the old one out first m_FrameDataHierarchyView.ClearSelection(); m_FrameDataHierarchyView.SetFrameDataView(frameDataView); if (!frameDataView.valid) return; // GetItemIDFromRawFrameDataViewIndex is a bit expensive so only use that if showing the Raw view (where the raw id is relevant) // or when the cheaper option (setting selection via MarkerIdPath) isn't available if (ViewType == ProfilerViewType.RawHierarchy || (selection.markerPathDepth <= 0)) { treeViewID = m_FrameDataHierarchyView.treeView.GetItemIDFromRawFrameDataViewIndex(frameDataView, selection.rawSampleIndex, selection.markerIdPath); } } if (treeViewID == ProfilerFrameDataHierarchyView.invalidTreeViewId) { if (selection.markerPathDepth > 0) { m_FrameDataHierarchyView.SetSelection(selection, viewChanged || frameSelection); } } else { var ids = new List<int>() { treeViewID }; m_FrameDataHierarchyView.treeView.SetSelection(ids, TreeViewSelectionOptions.RevealAndFrame); } } else if (currentFrame >= 0 && selection.markerPathDepth > 0) { if (fetchData) { var frameDataView = m_HierarchyOverruledThreadFromSelection ? GetFrameDataView() : GetFrameDataView(selection.threadGroupName, selection.threadName, selection.threadId); if (!frameDataView.valid) return; // avoid Selection Migration happening twice during SetFrameDataView by clearing the old one out first m_FrameDataHierarchyView.ClearSelection(); m_FrameDataHierarchyView.SetFrameDataView(frameDataView); } m_FrameDataHierarchyView.SetSelection(selection, (viewChanged || frameSelection)); } // else: the selection was not in the shown frame AND there was no other frame to select it in or the Selection contains no marker path. // So either there is no data to apply the selection to, or the selection isn't one that can be applied to another frame because there is no path // either way, it is save to not Apply the selection. } } else { using (k_ApplySelectionClearMarker.Auto()) { m_FrameDataHierarchyView.ClearSelection(); } } } } protected int GetThreadIndexInCurrentFrameToApplySelectionFromAnotherFrame(ProfilerTimeSampleSelection selection) { var currentFrame = (int)ProfilerWindow.selectedFrameIndex; return selection.GetThreadIndex(currentFrame); } int IProfilerFrameTimeViewSampleSelectionControllerInternal.FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(int frameIndex, int threadIndex, string sampleName, out List<int> markerIdPath, string markerNamePath) => FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(frameIndex, threadIndex, sampleName, out markerIdPath, markerNamePath); protected virtual int FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(int frameIndex, int threadIndex, string sampleName, out List<int> markerIdPath, string markerNamePath = null) { if (ViewType == ProfilerViewType.RawHierarchy || ViewType == ProfilerViewType.Hierarchy || ViewType == ProfilerViewType.InvertedHierarchy) { markerIdPath = null; return FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(frameIndex, threadIndex, ref sampleName, ref markerIdPath, markerNamePath, FrameDataView.invalidMarkerId); } markerIdPath = new List<int>(); return RawFrameDataView.invalidSampleIndex; } int IProfilerFrameTimeViewSampleSelectionControllerInternal.FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(int frameIndex, int threadIndex, ref string sampleName, ref List<int> markerIdPath, int sampleMarkerId) => FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(frameIndex, threadIndex, ref sampleName, ref markerIdPath, sampleMarkerId); protected virtual int FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(int frameIndex, int threadIndex, ref string sampleName, ref List<int> markerIdPath, int sampleMarkerId) { if (ViewType == ProfilerViewType.RawHierarchy || ViewType == ProfilerViewType.Hierarchy || ViewType == ProfilerViewType.InvertedHierarchy) { Debug.Assert(sampleMarkerId != RawFrameDataView.invalidSampleIndex); return FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(frameIndex, threadIndex, ref sampleName, ref markerIdPath, null, sampleMarkerId); } return RawFrameDataView.invalidSampleIndex; } struct HierarchySampleIterationInfo { public int sampleId; public int sampleDepth; } int FindMarkerPathAndRawSampleIndexToFirstMatchingSampleInCurrentView(int frameIndex, int threadIndex, ref string sampleName, ref List<int> markerIdPath, string markerNamePath, int sampleMarkerId) { if (ViewType == ProfilerViewType.RawHierarchy || ViewType == ProfilerViewType.Hierarchy || ViewType == ProfilerViewType.InvertedHierarchy) { if (frameIndex < 0) // If the last frame was supposed to be looked at, and this happens during a SetSelection call, it should have been adjusted to a valid frame index there. // This method here should not cause the Profiler Window to toggle on the "Current Frame" toggle. throw new ArgumentOutOfRangeException("frameIndex", "frameIndex can't be below 0"); ProfilerWindow.SetActiveVisibleFrameIndex(frameIndex); var frameData = GetFrameDataView(threadIndex); var invertedHierarchy = frameData.viewMode.HasFlag(HierarchyFrameDataView.ViewModes.InvertHierarchy); var sampleIdPath = new List<int>(); var children = new List<int>(); frameData.GetItemChildren(frameData.GetRootItemID(), children); var yetToVisit = new Stack<HierarchySampleIterationInfo>(); var rawIds = new List<int>(); int foundSampleIndex = RawFrameDataView.invalidSampleIndex; if (sampleMarkerId == FrameDataView.invalidMarkerId) sampleMarkerId = frameData.GetMarkerId(sampleName); if (markerIdPath != null && markerIdPath.Count > 0) { if (invertedHierarchy) markerIdPath.Reverse(); int enclosingScopeId = FindNextMatchingSampleIdInScope(frameData, null, sampleIdPath, children, yetToVisit, false, markerIdPath[sampleIdPath.Count]); while (enclosingScopeId != RawFrameDataView.invalidSampleIndex && sampleIdPath.Count <= markerIdPath.Count) { if (sampleIdPath.Count == markerIdPath.Count) { // lets, for a moment, assume that the searched sample is the last one in the specified path var sampleId = enclosingScopeId; var expectedMarkerId = invertedHierarchy ? markerIdPath[0] : markerIdPath[sampleIdPath.Count - 1]; if ((sampleMarkerId != FrameDataView.invalidMarkerId && sampleMarkerId != expectedMarkerId) || (sampleName != null && frameData.GetMarkerName(expectedMarkerId) != sampleName)) { // the searched sample is NOT the same as the last one in the path, so search for it if (sampleMarkerId == FrameDataView.invalidMarkerId) sampleId = FindNextMatchingSampleIdInScope(frameData, sampleName, sampleIdPath, children, yetToVisit, true); else sampleId = FindNextMatchingSampleIdInScope(frameData, null, sampleIdPath, children, yetToVisit, true, sampleMarkerId); } if (sampleId != RawFrameDataView.invalidSampleIndex) { foundSampleIndex = sampleId; // add further marker Ids as needed for (int i = markerIdPath.Count; i < sampleIdPath.Count; i++) { markerIdPath.Add(frameData.GetItemMarkerID(sampleIdPath[i])); } break; } // searched sample wasn't found, continue search one scope higher than the full path while (sampleIdPath.Count >= markerIdPath.Count && sampleIdPath.Count > 0) { sampleIdPath.RemoveAt(sampleIdPath.Count - 1); } } enclosingScopeId = FindNextMatchingSampleIdInScope(frameData, null, sampleIdPath, children, yetToVisit, false, markerIdPath[sampleIdPath.Count]); } if (invertedHierarchy) { markerIdPath.Reverse(); if (sampleIdPath.Count > 0) foundSampleIndex = sampleIdPath[0]; sampleIdPath.Reverse(); } } else if (!string.IsNullOrEmpty(markerNamePath)) { var normalizedPath = new List<string>(markerNamePath.Split('/')); if (normalizedPath.Count > 0) { // FindNextMatchingSampleIdInScope works on the hierarchy data, but markerNamePath is top-down representation if (invertedHierarchy) normalizedPath.Reverse(); int enclosingScopeId = FindNextMatchingSampleIdInScope(frameData, normalizedPath[sampleIdPath.Count], sampleIdPath, children, yetToVisit, false); while (enclosingScopeId != RawFrameDataView.invalidSampleIndex && sampleIdPath.Count <= normalizedPath.Count) { if (sampleIdPath.Count == normalizedPath.Count) { // lets, for a moment, assume that the searched sample is the last one in the specified path var sampleId = enclosingScopeId; var expectedMarkerName = invertedHierarchy ? normalizedPath[0] : normalizedPath[sampleIdPath.Count - 1]; if (expectedMarkerName != sampleName) { // the searched sample is NOT the same as the last one in the path, so search for it sampleId = FindNextMatchingSampleIdInScope(frameData, sampleName, sampleIdPath, children, yetToVisit, true); } if (sampleId != RawFrameDataView.invalidSampleIndex) { foundSampleIndex = sampleId; break; } // searched sample wasn't found, continue search one scope higher than the full path while (sampleIdPath.Count >= normalizedPath.Count && sampleIdPath.Count > 0) { sampleIdPath.RemoveAt(sampleIdPath.Count - 1); } } enclosingScopeId = FindNextMatchingSampleIdInScope(frameData, normalizedPath[sampleIdPath.Count], sampleIdPath, children, yetToVisit, false); } if (invertedHierarchy) { if (sampleIdPath.Count > 0) foundSampleIndex = sampleIdPath[0]; sampleIdPath.Reverse(); } } } else { // Inverted hierarchy will have sampleName at the first level // foundSampleIndex is valid as any first sample with sampleName is acceptable if (sampleMarkerId == FrameDataView.invalidMarkerId) foundSampleIndex = FindNextMatchingSampleIdInScope(frameData, sampleName, sampleIdPath, children, yetToVisit, !invertedHierarchy); else foundSampleIndex = FindNextMatchingSampleIdInScope(frameData, null, sampleIdPath, children, yetToVisit, !invertedHierarchy, sampleMarkerId); // Populate sampleIdPath with the first path to the root sample. if (invertedHierarchy && foundSampleIndex != RawFrameDataView.invalidSampleIndex) { var sampleId = sampleIdPath[0]; while (frameData.HasItemChildren(sampleId)) { frameData.GetItemChildren(sampleId, children); sampleId = children[0]; sampleIdPath.Add(sampleId); } sampleIdPath.Reverse(); } } if (foundSampleIndex != RawFrameDataView.invalidSampleIndex) { if (string.IsNullOrEmpty(sampleName)) sampleName = GetItemName(frameData, foundSampleIndex); if (markerIdPath == null) markerIdPath = new List<int>(); if (markerIdPath.Count == 0) { ProfilerTimeSampleSelection.GetCleanMarkerIdsFromSampleIds(frameData, sampleIdPath, markerIdPath); } frameData.GetItemRawFrameDataViewIndices(foundSampleIndex, rawIds); Debug.Assert(rawIds.Count > 0, "Frame data is Invalid"); return rawIds[0]; } } markerIdPath = new List<int>(); return RawFrameDataView.invalidSampleIndex; } int FindNextMatchingSampleIdInScope(HierarchyFrameDataView frameData, string sampleName, List<int> sampleIdPath, List<int> children, Stack<HierarchySampleIterationInfo> yetToVisit, bool searchRecursively, int markerId = FrameDataView.invalidMarkerId) { if (markerId == FrameDataView.invalidMarkerId) markerId = frameData.GetMarkerId(sampleName); if (children.Count > 0) { for (int i = children.Count - 1; i >= 0; i--) { yetToVisit.Push(new HierarchySampleIterationInfo { sampleId = children[i], sampleDepth = sampleIdPath.Count }); } children.Clear(); } while (yetToVisit.Count > 0) { var sample = yetToVisit.Pop(); int higherlevelScopeSampleToReturnTo = RawFrameDataView.invalidSampleIndex; while (sample.sampleDepth < sampleIdPath.Count && sampleIdPath.Count > 0) { // if this sample came from a higher scope, step backwards on the path. higherlevelScopeSampleToReturnTo = sampleIdPath[sampleIdPath.Count - 1]; sampleIdPath.RemoveAt(sampleIdPath.Count - 1); } if (!searchRecursively && higherlevelScopeSampleToReturnTo >= 0) { // the sample scope to check against is no longer the one that was provided to this method, so bail out and get the right one yetToVisit.Push(sample); return higherlevelScopeSampleToReturnTo; } var isEditorOnlySample = (frameData.GetItemMarkerFlags(sample.sampleId) & MarkerFlags.AvailabilityEditor) != 0; bool found = (isEditorOnlySample && (sampleName != null && GetItemName(frameData, sample.sampleId).Contains(sampleName) || sampleName == null && GetItemName(frameData, sample.sampleId).Contains(frameData.GetMarkerName(markerId)))) || markerId == FrameDataView.invalidMarkerId && GetItemName(frameData, sample.sampleId) == sampleName || markerId == frameData.GetItemMarkerID(sample.sampleId); if (found || searchRecursively) { sampleIdPath.Add(sample.sampleId); frameData.GetItemChildren(sample.sampleId, children); for (int i = children.Count - 1; i >= 0; i--) { yetToVisit.Push(new HierarchySampleIterationInfo { sampleId = children[i], sampleDepth = sampleIdPath.Count }); } children.Clear(); if (found) return sample.sampleId; } } return RawFrameDataView.invalidSampleIndex; } internal override void Clear() { base.Clear(); m_CurrentFrameIndex = FrameDataView.invalidOrCurrentFrameIndex; m_FrameDataHierarchyView?.Clear(); m_FrameIndexOfSelectionGuaranteedToBeValid = false; } public void Repaint() { ProfilerWindow.Repaint(); } static readonly ProfilerMarker k_GetItemNameScriptingSimplificationMarker = new ProfilerMarker($"{nameof(CPUOrGPUProfilerModule)}.{nameof(GetItemName)} Scripting Name Simplification"); const int k_AnyFullManagedMarker = (int)(MarkerFlags.ScriptInvoke | MarkerFlags.ScriptDeepProfiler); public string GetItemName(HierarchyFrameDataView frameData, int itemId) { var name = frameData.GetItemName(itemId); if ((ViewOptions & ProfilerViewFilteringOptions.ShowFullScriptingMethodNames) != 0) return name; var flags = frameData.GetItemMarkerFlags(itemId); if (((int)flags & k_AnyFullManagedMarker) == 0) return name; var namespaceDelimiterIndex = name.IndexOf(':'); if (namespaceDelimiterIndex == -1) return name; // Marker added so we can attribute the GC Alloc and time spend for simplifying the name and have performance tests against this // TODO: Use MutableString for this once available. using (k_GetItemNameScriptingSimplificationMarker.Auto()) { ++namespaceDelimiterIndex; if (namespaceDelimiterIndex < name.Length && name[namespaceDelimiterIndex] == ':') return name.Substring(namespaceDelimiterIndex + 1); return name; } } public string GetMarkerName(HierarchyFrameDataView frameData, int markerId) { var name = frameData.GetMarkerName(markerId); if ((ViewOptions & ProfilerViewFilteringOptions.ShowFullScriptingMethodNames) != 0) return name; var namespaceDelimiterIndex = name.IndexOf(':'); if (namespaceDelimiterIndex == -1) return name; // Marker added so we can attribute the GC Alloc and time spend for simplifying the name and have performance tests against this // TODO: Use MutableString for this once available. using (k_GetItemNameScriptingSimplificationMarker.Auto()) { ++namespaceDelimiterIndex; if (namespaceDelimiterIndex < name.Length && name[namespaceDelimiterIndex] == ':') return name.Substring(namespaceDelimiterIndex + 1); return name; } } public string GetItemName(RawFrameDataView frameData, int itemId) { var name = frameData.GetSampleName(itemId); if ((ViewOptions & ProfilerViewFilteringOptions.ShowFullScriptingMethodNames) != 0) return name; var flags = frameData.GetSampleFlags(itemId); if (((int)flags & k_AnyFullManagedMarker) == 0) return name; var namespaceDelimiterIndex = name.IndexOf(':'); if (namespaceDelimiterIndex == -1) return name; // Marker added so we can attribute the GC Alloc and time spend for simplifying the name and have performance tests against this // TODO: Use MutableString for this once available. using (k_GetItemNameScriptingSimplificationMarker.Auto()) { ++namespaceDelimiterIndex; if (namespaceDelimiterIndex < name.Length && name[namespaceDelimiterIndex] == ':') return name.Substring(namespaceDelimiterIndex + 1); return name; } } void SendViewTypeAnalytics(ProfilerViewType viewtype) { string viewName = viewtype switch { ProfilerViewType.Hierarchy => k_HierarchyViewAnalyticsName, ProfilerViewType.Timeline => k_TimelineViewAnalyticsName, ProfilerViewType.RawHierarchy => k_RawHierarchyViewAnalyticsName, ProfilerViewType.InvertedHierarchy => k_InvertedHierarchyViewAnalyticsName, _ => throw new ArgumentOutOfRangeException(nameof(viewtype), viewtype, null) }; ProfilerWindowAnalytics.SwitchActiveView(viewName); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPUorGPUProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPUorGPUProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 26831 }
433
// 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 UnityEngine; using Unity.Profiling.Memory; using MemoryProfilerAPI = Unity.Profiling.Memory.MemoryProfiler; // The entire API in this file is deprecated and will likely be removed in 2023.x. // A new API for taking memory snapshots exists in Unity.Profiling.Memory.MemoryProfiler.TakeSnaphshot. // A new API for reading the snapshots will eventually be exposed through the Memory Profiler Package (com.unity.memoryprofiler). namespace UnityEditor.MemoryProfiler { // Not automatically Upgradeable as the new API won't fire an event but calls a callback instead. // Also that callback gets called with an "Experimental.PackedMemorySnapshot" object, // not the non-experimental one that MemorySnapshot.OnSnapshotReceived uses. [Obsolete("Use Unity.Profiling.Memory.MemoryProfiler instead")] public static class MemorySnapshot { // Not automatically Upgradeable as the new API won't fire an event but calls a callback instead. // Also that callback gets called with an "Experimental.PackedMemorySnapshot" object, // not the non-experimental one that MemorySnapshot.OnSnapshotReceived uses. [Obsolete("Use Unity.Profiling.Memory.MemoryProfiler.TakeSnapshot() instead")] public static event Action<PackedMemorySnapshot> OnSnapshotReceived; private static void SnapshotFinished(string path, bool result) { if (result) { Profiling.Memory.Experimental.PackedMemorySnapshot snapshot = Profiling.Memory.Experimental.PackedMemorySnapshot.Load(path); var oldSnapshot = new PackedMemorySnapshot(snapshot); snapshot.Dispose(); File.Delete(path); OnSnapshotReceived(oldSnapshot); } else { if (File.Exists(path)) File.Delete(path); OnSnapshotReceived(null); } } // Not automatically Upgradeable as the new API won't fire an event but calls a callback instead. // Also that callback gets called with an "Experimental.PackedMemorySnapshot" object, // not the non-experimental one that MemorySnapshot.OnSnapshotReceived uses. [Obsolete("Use Unity.Profiling.Memory.MemoryProfiler.TakeSnapshot() instead")] internal static string GetTemporarySnapshotPath() { string[] s = Application.dataPath.Split('/'); string projectName = s[s.Length - 2]; return Path.Combine(Application.temporaryCachePath, projectName + ".snap"); } // Not automatically Upgradeable as the new API won't fire an event but calls a callback instead. // Also that callback gets called with an "Experimental.PackedMemorySnapshot" object, // not the non-experimental one that MemorySnapshot.OnSnapshotReceived uses. [Obsolete("Use Unity.Profiling.Memory.MemoryProfiler.TakeSnapshot() instead")] public static void RequestNewSnapshot() { MemoryProfilerAPI.TakeSnapshot(GetTemporarySnapshotPath(), SnapshotFinished, CaptureFlags.NativeObjects | CaptureFlags.ManagedObjects); } } // Note: this snapshot is completely serializable by unity's serializer. // !!!!! NOTE: Keep in sync with Runtime\Profiler\MemorySnapshots.cpp [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public class PackedMemorySnapshot { internal const string ObsoleteMessage = "This API is outdated and will be removed. Please check out the Memory Profiler Package (https://docs.unity3d.com/Packages/com.unity.memoryprofiler@latest/)"; [SerializeField] internal PackedNativeType[] m_NativeTypes = null; [SerializeField] internal PackedNativeUnityEngineObject[] m_NativeObjects = null; [SerializeField] internal PackedGCHandle[] m_GCHandles = null; [SerializeField] internal Connection[] m_Connections = null; [SerializeField] internal MemorySection[] m_ManagedHeapSections = null; [SerializeField] internal MemorySection[] m_ManagedStacks = null; [SerializeField] internal TypeDescription[] m_TypeDescriptions = null; [SerializeField] internal VirtualMachineInformation m_VirtualMachineInformation = default(VirtualMachineInformation); public PackedMemorySnapshot(Profiling.Memory.Experimental.PackedMemorySnapshot snapshot) { int cacheCapacity = 128; string[] cacheString = new string[cacheCapacity]; string[] cacheString2 = new string[cacheCapacity]; int[] cacheInt = new int[cacheCapacity]; int[] cacheInt2 = new int[cacheCapacity]; int[] cacheInt3 = new int[cacheCapacity]; ulong[] cacheULong = new ulong[cacheCapacity]; ulong[] cacheULong2 = new ulong[cacheCapacity]; byte[][] cacheBytes = new byte[cacheCapacity][]; m_NativeTypes = new PackedNativeType[snapshot.nativeTypes.GetNumEntries()]; { for (int offset = 0; offset < m_NativeTypes.Length; offset += cacheCapacity) { uint size = (uint)Math.Min(m_NativeTypes.Length - offset, cacheCapacity); snapshot.nativeTypes.typeName.GetEntries((uint)offset, size, ref cacheString); snapshot.nativeTypes.nativeBaseTypeArrayIndex.GetEntries((uint)offset, size, ref cacheInt); for (uint i = 0; i < size; i++) { m_NativeTypes[offset + i] = new PackedNativeType(cacheString[i], cacheInt[i]); } } } m_NativeObjects = new PackedNativeUnityEngineObject[snapshot.nativeObjects.GetNumEntries()]; { UnityEditor.Profiling.Memory.Experimental.ObjectFlags[] cacheObjectFlags = new UnityEditor.Profiling.Memory.Experimental.ObjectFlags[cacheCapacity]; UnityEngine.HideFlags[] cacheHideFlags = new UnityEngine.HideFlags[cacheCapacity]; for (int offset = 0; offset < m_NativeObjects.Length; offset += cacheCapacity) { uint size = (uint)Math.Min(m_NativeObjects.Length - offset, cacheCapacity); snapshot.nativeObjects.objectName.GetEntries((uint)offset, size, ref cacheString); snapshot.nativeObjects.instanceId.GetEntries((uint)offset, size, ref cacheInt); snapshot.nativeObjects.size.GetEntries((uint)offset, size, ref cacheULong); snapshot.nativeObjects.nativeTypeArrayIndex.GetEntries((uint)offset, size, ref cacheInt2); snapshot.nativeObjects.hideFlags.GetEntries((uint)offset, size, ref cacheHideFlags); snapshot.nativeObjects.flags.GetEntries((uint)offset, size, ref cacheObjectFlags); snapshot.nativeObjects.nativeObjectAddress.GetEntries((uint)offset, size, ref cacheULong2); for (uint i = 0; i < size; i++) { m_NativeObjects[offset + i] = new PackedNativeUnityEngineObject( cacheString[i], cacheInt[i], (int)cacheULong[i], cacheInt2[i], cacheHideFlags[i], (PackedNativeUnityEngineObject.ObjectFlags)cacheObjectFlags[i], (long)cacheULong2[i]); } } } m_GCHandles = new PackedGCHandle[snapshot.gcHandles.GetNumEntries()]; { for (int offset = 0; offset < m_GCHandles.Length; offset += cacheCapacity) { uint size = (uint)Math.Min(m_GCHandles.Length - offset, cacheCapacity); snapshot.gcHandles.target.GetEntries((uint)offset, size, ref cacheULong); for (uint i = 0; i < size; i++) { m_GCHandles[offset + i] = new PackedGCHandle((UInt64)cacheULong[i]); } } } m_Connections = new Connection[snapshot.connections.GetNumEntries()]; { for (int offset = 0; offset < m_Connections.Length; offset += cacheCapacity) { uint size = (uint)Math.Min(m_Connections.Length - offset, cacheCapacity); snapshot.connections.from.GetEntries((uint)offset, (uint)size, ref cacheInt); snapshot.connections.to.GetEntries((uint)offset, (uint)size, ref cacheInt2); for (uint i = 0; i < size; i++) { m_Connections[offset + i] = new Connection(cacheInt[i], cacheInt2[i]); } } } m_ManagedHeapSections = new MemorySection[snapshot.managedHeapSections.GetNumEntries()]; { for (int offset = 0; offset < m_ManagedHeapSections.Length; offset += cacheCapacity) { uint size = (uint)Math.Min(m_ManagedHeapSections.Length - offset, cacheCapacity); snapshot.managedHeapSections.startAddress.GetEntries((uint)offset, (uint)size, ref cacheULong); snapshot.managedHeapSections.bytes.GetEntries((uint)offset, (uint)size, ref cacheBytes); for (uint i = 0; i < size; i++) { m_ManagedHeapSections[offset + i] = new MemorySection(cacheBytes[i], (UInt64)cacheULong[i]); } } } m_TypeDescriptions = new TypeDescription[snapshot.typeDescriptions.GetNumEntries()]; { UnityEditor.Profiling.Memory.Experimental.TypeFlags[] cacheFlags = new UnityEditor.Profiling.Memory.Experimental.TypeFlags[cacheCapacity]; int[][] cacheRange = new int[cacheCapacity][]; string[] cacheSmallString = new string[1]; int[] cacheSmallInt = new int[1]; int[] cacheSmallInt2 = new int[1]; bool[] cacheSmallBool = new bool[1]; for (int offset = 0; offset < m_TypeDescriptions.Length; offset += cacheCapacity) { uint size = (uint)Math.Min(m_TypeDescriptions.Length - offset, cacheCapacity); snapshot.typeDescriptions.typeDescriptionName.GetEntries((uint)offset, (uint)size, ref cacheString); snapshot.typeDescriptions.assembly.GetEntries((uint)offset, (uint)size, ref cacheString2); snapshot.typeDescriptions.fieldIndices.GetEntries((uint)offset, (uint)size, ref cacheRange); snapshot.typeDescriptions.staticFieldBytes.GetEntries((uint)offset, (uint)size, ref cacheBytes); snapshot.typeDescriptions.baseOrElementTypeIndex.GetEntries((uint)offset, (uint)size, ref cacheInt); snapshot.typeDescriptions.size.GetEntries((uint)offset, (uint)size, ref cacheInt2); snapshot.typeDescriptions.typeInfoAddress.GetEntries((uint)offset, (uint)size, ref cacheULong); snapshot.typeDescriptions.typeIndex.GetEntries((uint)offset, (uint)size, ref cacheInt3); snapshot.typeDescriptions.flags.GetEntries((uint)offset, (uint)size, ref cacheFlags); for (int i = 0; i < size; ++i) { FieldDescription[] fieldDescription = new FieldDescription[cacheRange[i].Length]; for (uint j = 0; j < cacheRange[i].Length; j++) { snapshot.fieldDescriptions.fieldDescriptionName.GetEntries((uint)cacheRange[i][j], 1, ref cacheSmallString); snapshot.fieldDescriptions.offset.GetEntries((uint)cacheRange[i][j], 1, ref cacheSmallInt); snapshot.fieldDescriptions.typeIndex.GetEntries((uint)cacheRange[i][j], 1, ref cacheSmallInt2); snapshot.fieldDescriptions.isStatic.GetEntries((uint)cacheRange[i][j], 1, ref cacheSmallBool); fieldDescription[j] = new FieldDescription(cacheSmallString[0], cacheSmallInt[0], cacheSmallInt2[0], cacheSmallBool[0]); } m_TypeDescriptions[offset + i] = new TypeDescription( cacheString[i], cacheString2[i], fieldDescription, cacheBytes[i], cacheInt[i], cacheInt2[i], (UInt64)cacheULong[i], cacheInt3[i], (TypeDescription.TypeFlags)cacheFlags[i]); } } } m_VirtualMachineInformation = new VirtualMachineInformation(snapshot.virtualMachineInformation); } public PackedNativeType[] nativeTypes { get { return m_NativeTypes; } } public PackedNativeUnityEngineObject[] nativeObjects { get { return m_NativeObjects; } } public PackedGCHandle[] gcHandles { get { return m_GCHandles; } } public Connection[] connections { get { return m_Connections; } } public MemorySection[] managedHeapSections { get { return m_ManagedHeapSections; } } public TypeDescription[] typeDescriptions { get { return m_TypeDescriptions; } } public VirtualMachineInformation virtualMachineInformation { get { return m_VirtualMachineInformation; } } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct PackedNativeType { [SerializeField] internal string m_Name; [SerializeField] internal int m_NativeBaseTypeArrayIndex; public PackedNativeType(string name, int nativeBaseTypeArrayIndex) { m_Name = name; m_NativeBaseTypeArrayIndex = nativeBaseTypeArrayIndex; } public string name { get { return m_Name; } } [Obsolete("PackedNativeType.baseClassId is obsolete. Use PackedNativeType.nativeBaseTypeArrayIndex instead (UnityUpgradable) -> nativeBaseTypeArrayIndex")] public int baseClassId { get { return m_NativeBaseTypeArrayIndex; } } public int nativeBaseTypeArrayIndex { get { return m_NativeBaseTypeArrayIndex; } } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct PackedNativeUnityEngineObject { [SerializeField] internal string m_Name; [SerializeField] internal int m_InstanceId; [SerializeField] internal int m_Size; [SerializeField] internal int m_NativeTypeArrayIndex; [SerializeField] internal UnityEngine.HideFlags m_HideFlags; [SerializeField] internal ObjectFlags m_Flags; [SerializeField] internal long m_NativeObjectAddress; public PackedNativeUnityEngineObject(string name, int instanceId, int size, int nativeTypeArrayIndex, UnityEngine.HideFlags hideFlags, ObjectFlags flags, long nativeObjectAddress) { m_Name = name; m_InstanceId = instanceId; m_Size = size; m_NativeTypeArrayIndex = nativeTypeArrayIndex; m_HideFlags = hideFlags; m_Flags = flags; m_NativeObjectAddress = nativeObjectAddress; } public bool isPersistent { get { return (m_Flags & ObjectFlags.IsPersistent) != 0; } } public bool isDontDestroyOnLoad { get { return (m_Flags & ObjectFlags.IsDontDestroyOnLoad) != 0; } } public bool isManager { get { return (m_Flags & ObjectFlags.IsManager) != 0; } } public string name { get { return m_Name; } } public int instanceId { get { return m_InstanceId; } } public int size { get { return m_Size; } } [Obsolete("PackedNativeUnityEngineObject.classId is obsolete. Use PackedNativeUnityEngineObject.nativeTypeArrayIndex instead (UnityUpgradable) -> nativeTypeArrayIndex")] public int classId { get { return m_NativeTypeArrayIndex; } } public int nativeTypeArrayIndex { get { return m_NativeTypeArrayIndex; } } public UnityEngine.HideFlags hideFlags { get { return m_HideFlags; } } public long nativeObjectAddress { get { return m_NativeObjectAddress; } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] public enum ObjectFlags { IsDontDestroyOnLoad = 0x1, IsPersistent = 0x2, IsManager = 0x4, } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct PackedGCHandle { [SerializeField] internal UInt64 m_Target; public PackedGCHandle(UInt64 target) { m_Target = target; } public UInt64 target { get { return m_Target; } } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct Connection { [SerializeField] private int m_From; [SerializeField] private int m_To; public Connection(int from, int to) { m_From = from; m_To = to; } public int from { get { return m_From; } set { m_From = value; } } public int to { get { return m_To; } set { m_To = value; } } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct MemorySection { [SerializeField] internal byte[] m_Bytes; [SerializeField] internal UInt64 m_StartAddress; public MemorySection(byte[] bytes, UInt64 startAddress) { m_Bytes = bytes; m_StartAddress = startAddress; } public byte[] bytes { get { return m_Bytes; } } public UInt64 startAddress { get { return m_StartAddress; } } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct TypeDescription { [SerializeField] internal string m_Name; [SerializeField] internal string m_Assembly; [SerializeField] internal FieldDescription[] m_Fields; [SerializeField] internal byte[] m_StaticFieldBytes; [SerializeField] internal int m_BaseOrElementTypeIndex; [SerializeField] internal int m_Size; [SerializeField] internal UInt64 m_TypeInfoAddress; [SerializeField] internal int m_TypeIndex; [SerializeField] internal TypeFlags m_Flags; public TypeDescription(string name, string assembly, FieldDescription[] fields, byte[] staticFieldBytes, int baseOrElementTypeIndes, int size, UInt64 typeInfoAddress, int typeIndex, TypeFlags flags) { m_Name = name; m_Assembly = assembly; m_Fields = fields; m_StaticFieldBytes = staticFieldBytes; m_BaseOrElementTypeIndex = baseOrElementTypeIndes; m_Size = size; m_TypeInfoAddress = typeInfoAddress; m_TypeIndex = typeIndex; m_Flags = flags; } public bool isValueType { get { return (m_Flags & TypeFlags.kValueType) != 0; } } public bool isArray { get { return (m_Flags & TypeFlags.kArray) != 0; } } public int arrayRank { get { return (int)(m_Flags & TypeFlags.kArrayRankMask) >> 16; } } public string name { get { return m_Name; } } public string assembly { get { return m_Assembly; } } public FieldDescription[] fields { get { return m_Fields; } } public byte[] staticFieldBytes { get { return m_StaticFieldBytes; } } public int baseOrElementTypeIndex { get { return m_BaseOrElementTypeIndex; } } public int size { get { return m_Size; } } public UInt64 typeInfoAddress { get { return m_TypeInfoAddress; } } public int typeIndex { get { return m_TypeIndex; } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] public enum TypeFlags { kNone = 0, kValueType = 1 << 0, kArray = 1 << 1, kArrayRankMask = unchecked((int)0xFFFF0000) } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct FieldDescription { [SerializeField] internal string m_Name; [SerializeField] internal int m_Offset; [SerializeField] internal int m_TypeIndex; [SerializeField] internal bool m_IsStatic; public FieldDescription(string name, int offset, int typeIndex, bool isStatic) { m_Name = name; m_Offset = offset; m_TypeIndex = typeIndex; m_IsStatic = isStatic; } public string name { get { return m_Name; } } public int offset { get { return m_Offset; } } public int typeIndex { get { return m_TypeIndex; } } public bool isStatic { get { return m_IsStatic; } } } [Obsolete(PackedMemorySnapshot.ObsoleteMessage)] [Serializable] public struct VirtualMachineInformation { [SerializeField] internal int m_PointerSize; [SerializeField] internal int m_ObjectHeaderSize; [SerializeField] internal int m_ArrayHeaderSize; [SerializeField] internal int m_ArrayBoundsOffsetInHeader; [SerializeField] internal int m_ArraySizeOffsetInHeader; [SerializeField] internal int m_AllocationGranularity; public int pointerSize { get { return m_PointerSize; } } public int objectHeaderSize { get { return m_ObjectHeaderSize; } } public int arrayHeaderSize { get { return m_ArrayHeaderSize; } } public int arrayBoundsOffsetInHeader { get { return m_ArrayBoundsOffsetInHeader; } } public int arraySizeOffsetInHeader { get { return m_ArraySizeOffsetInHeader; } } public int allocationGranularity { get { return m_AllocationGranularity; } } public int heapFormatVersion { get { return 0; } } internal VirtualMachineInformation(Profiling.Memory.Experimental.VirtualMachineInformation virtualMachineInformation) { m_PointerSize = virtualMachineInformation.pointerSize; m_ObjectHeaderSize = virtualMachineInformation.objectHeaderSize; m_ArrayHeaderSize = virtualMachineInformation.arrayHeaderSize; m_ArrayBoundsOffsetInHeader = virtualMachineInformation.arrayBoundsOffsetInHeader; m_ArraySizeOffsetInHeader = virtualMachineInformation.arraySizeOffsetInHeader; m_AllocationGranularity = virtualMachineInformation.allocationGranularity; } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemorySnapshot.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemorySnapshot.cs", "repo_id": "UnityCsReference", "token_count": 10201 }
434
// 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.Profiling.Editor; using UnityEditor; using UnityEngine.Profiling; namespace UnityEditorInternal.Profiling { [Serializable] [ProfilerModuleMetadata("UI Details", typeof(LocalizationResource), IconPath = "Profiler.UIDetails")] internal class UIDetailsProfilerModule : UIProfilerModule { const int k_DefaultOrderIndex = 11; const ProfilerModuleChartType k_ChartType = ProfilerModuleChartType.Line; public UIDetailsProfilerModule() : base(k_ChartType) {} internal override ProfilerArea area => ProfilerArea.UIDetails; public override bool usesCounters => false; private protected override int defaultOrderIndex => k_DefaultOrderIndex; private protected override string legacyPreferenceKey => "ProfilerChartUIDetails"; UISystemProfilerChart UISystemProfilerChart => m_Chart as UISystemProfilerChart; private protected override ProfilerChart InstantiateChart(float defaultChartScale, float chartMaximumScaleInterpolationValue) { // [Coverity Defect 53724] Intentionally not calling the base class here to instantiate a custom chart type. m_Chart = new UISystemProfilerChart(k_ChartType, defaultChartScale, chartMaximumScaleInterpolationValue, m_LegacyChartCounters.Count, DisplayName, DisplayName, IconPath); return m_Chart; } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/uGui/UIDetailsProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/uGui/UIDetailsProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 508 }
435
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Profiling; using Unity.Profiling.Editor; using Unity.Profiling.LowLevel; using UnityEditorInternal; using UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; namespace UnityEditor.Profiling { [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public struct ProfilerCategoryInfo { UInt16 m_Id; UnityEngine.Color32 m_Color; string m_Name; ProfilerCategoryFlags m_Flags; public UInt16 id { get => m_Id; } public UnityEngine.Color32 color { get => m_Color; } public string name { get => m_Name; } public ProfilerCategoryFlags flags { get => m_Flags; } }; [NativeHeader("Modules/ProfilerEditor/ProfilerHistory/FrameDataView.h")] [StructLayout(LayoutKind.Sequential)] public abstract class FrameDataView : IDisposable { protected IntPtr m_Ptr; public const int invalidMarkerId = -1; public const int invalidThreadIndex = -1; public const ulong invalidThreadId = 0; internal const int invalidOrCurrentFrameIndex = -1; ~FrameDataView() { DisposeInternal(); } public void Dispose() { DisposeInternal(); GC.SuppressFinalize(this); } // Protected implementation of Dispose pattern. void DisposeInternal() { if (m_Ptr != IntPtr.Zero) { Internal_Destroy(m_Ptr); m_Ptr = IntPtr.Zero; } } [ThreadSafe] static extern void Internal_Destroy(IntPtr ptr); public bool valid { get { return m_Ptr != IntPtr.Zero; } } public extern int frameIndex { [ThreadSafe] get; } public extern int threadIndex { [ThreadSafe] get; } public extern string threadGroupName { [ThreadSafe] get; } public extern string threadName { [ThreadSafe] get; } public extern ulong threadId { [ThreadSafe] get; } public extern double frameStartTimeMs { [ThreadSafe] get; } public extern ulong frameStartTimeNs { [ThreadSafe] get; } public extern float frameTimeMs { [ThreadSafe] get; } public extern ulong frameTimeNs { [ThreadSafe] get; } public extern float frameGpuTimeMs { [ThreadSafe] get; } public extern ulong frameGpuTimeNs { [ThreadSafe] get; } public extern float frameFps { [ThreadSafe] get; } public extern int sampleCount { [ThreadSafe] get; } public extern int maxDepth { [ThreadSafe] get; } // the current runtime (Editor or Player) session id. This is different from the internal extern uint runtimeSessionId { [ThreadSafe] get; } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public struct MarkerMetadataInfo { public ProfilerMarkerDataType type; public ProfilerMarkerDataUnit unit; public string name; }; [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public struct MarkerInfo { public int id; public ushort category; public MarkerFlags flags; public string name; public MarkerMetadataInfo[] metadataInfo; }; [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern ushort GetMarkerCategoryIndex(int markerId); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern MarkerFlags GetMarkerFlags(int markerId); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern string GetMarkerName(int markerId); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern MarkerMetadataInfo[] GetMarkerMetadataInfo(int markerId); [NativeMethod(IsThreadSafe = true)] public extern int GetMarkerId(string markerName); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern void GetMarkers(List<MarkerInfo> markerInfoList); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern ProfilerCategoryInfo GetCategoryInfo(UInt16 id); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public extern void GetAllCategories(List<ProfilerCategoryInfo> categoryInfoList); [NativeMethod(Name = "profiling::FrameDataView::GetBuiltinMarkerCategoryColor", IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] internal static extern UnityEngine.Color32 GetMarkerCategoryColor(ushort category); [StructLayout(LayoutKind.Sequential)] internal struct Data { public IntPtr ptr; public int size; } [ThreadSafe] extern AtomicSafetyHandle GetSafetyHandle(); public NativeArray<T> GetFrameMetaData<T>(Guid id, int tag) where T : struct { return GetFrameMetaData<T>(id, tag, 0); } public unsafe NativeArray<T> GetFrameMetaData<T>(Guid id, int tag, int index) where T : struct { var stride = UnsafeUtility.SizeOf<T>(); var data = GetFrameMetaData(id.ToByteArray(), tag, index); var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(data.ptr.ToPointer(), data.size / stride, Allocator.None); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, GetSafetyHandle()); return array; } public int GetFrameMetaDataCount(Guid id, int tag) { return GetFrameMetaDataCount(id.ToByteArray(), tag); } [ThreadSafe] extern Data GetFrameMetaData(byte[] statsId, int tag, int index); [ThreadSafe] extern int GetFrameMetaDataCount(byte[] statsId, int tag); public NativeArray<T> GetSessionMetaData<T>(Guid id, int tag) where T : struct { return GetSessionMetaData<T>(id, tag, 0); } public unsafe NativeArray<T> GetSessionMetaData<T>(Guid id, int tag, int index) where T : struct { var stride = UnsafeUtility.SizeOf<T>(); var data = GetSessionMetaData(id.ToByteArray(), tag, index); var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(data.ptr.ToPointer(), data.size / stride, Allocator.None); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, GetSafetyHandle()); return array; } public int GetSessionMetaDataCount(Guid id, int tag) { return GetSessionMetaDataCount(id.ToByteArray(), tag); } [ThreadSafe] extern Data GetSessionMetaData(byte[] statsId, int tag, int index); [ThreadSafe] extern int GetSessionMetaDataCount(byte[] statsId, int tag); internal T GetProfilingSessionMetaData<T>(ProfilingSessionMetaDataEntry entry) where T : unmanaged { using (var ret = GetSessionMetaData<T>(ProfilerDriver.profilerInternalSessionMetaDataGuid, (int)entry)) { Debug.Assert(ret.Length > 0, $"A ProfilingSessionMetaDataEntry {entry} of type {typeof(T)} does not exist for this session."); return ret[ret.Length-1]; } } internal string GetProfilingSessionMetaDataString(ProfilingSessionMetaDataEntry entry) { using (var ret = GetSessionMetaData<byte>(ProfilerDriver.profilerInternalSessionMetaDataGuid, (int)entry)) { Debug.Assert(ret.Length > 0, $"A ProfilingSessionMetaDataEntry {entry} of type string does not exist for this session."); unsafe { return System.Text.Encoding.UTF8.GetString((byte*)ret.GetUnsafePtr(), ret.Length); } } } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public struct MethodInfo { public string methodName; public string sourceFileName; public uint sourceFileLine; } public extern MethodInfo ResolveMethodInfo(ulong addr); [NativeMethod(IsThreadSafe = true)] public unsafe extern void* GetCounterValuePtr(int markerId); public unsafe bool HasCounterValue(int markerId) { return GetCounterValuePtr(markerId) != null; } [NativeMethod(IsThreadSafe = true)] public extern int GetCounterValueAsInt(int markerId); [NativeMethod(IsThreadSafe = true)] public extern long GetCounterValueAsLong(int markerId); [NativeMethod(IsThreadSafe = true)] public extern float GetCounterValueAsFloat(int markerId); [NativeMethod(IsThreadSafe = true)] public extern double GetCounterValueAsDouble(int markerId); [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public struct UnityObjectInfo { [NativeName("name")] readonly string m_Name; [NativeName("relatedGameObjectInstanceId")] readonly int m_RelatedGameObjectInstanceId; [NativeName("nativeTypeIndex")] readonly int m_NativeTypeIndex; [NativeName("rootId")] readonly ulong m_RootId; public string name => m_Name; public int nativeTypeIndex => m_NativeTypeIndex; public int relatedGameObjectInstanceId => m_RelatedGameObjectInstanceId; public ulong allocationRootId => m_RootId; } [NativeMethod(IsThreadSafe = true)] public extern bool GetUnityObjectInfo(int instanceId, out UnityObjectInfo info); [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public struct UnityObjectNativeTypeInfo { [NativeName("name")] readonly string m_Name; [NativeName("baseNativeTypeIndex")] readonly int m_BaseNativeTypeIndex; public string name => m_Name; public int baseNativeTypeIndex => m_BaseNativeTypeIndex; } [NativeMethod(IsThreadSafe = true)] public extern bool GetUnityObjectNativeTypeInfo(int nativeTypeIndex, out UnityObjectNativeTypeInfo info); [NativeMethod(IsThreadSafe = true)] public extern int GetUnityObjectNativeTypeInfoCount(); [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public struct GfxResourceInfo { [NativeName("rootId")] readonly ulong m_RootId; [NativeName("instanceId")] readonly int m_InstanceId; public ulong relatedAllocationRootId => m_RootId; public int relatedInstanceId => m_InstanceId; } [NativeMethod(IsThreadSafe = true)] public extern bool GetGfxResourceInfo(ulong gfxResourceId, out GfxResourceInfo info); internal static class BindingsMarshaller { public static IntPtr ConvertToNative(FrameDataView frameDataView) => frameDataView.m_Ptr; } } }
UnityCsReference/Modules/ProfilerEditor/Public/FrameDataView.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/Public/FrameDataView.bindings.cs", "repo_id": "UnityCsReference", "token_count": 5498 }
436
// 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 Unity.Properties { public static partial class PropertyContainer { internal class SetValueVisitor<TSrcValue> : PathVisitor { public static readonly UnityEngine.Pool.ObjectPool<SetValueVisitor<TSrcValue>> Pool = new UnityEngine.Pool.ObjectPool<SetValueVisitor<TSrcValue>>(() => new SetValueVisitor<TSrcValue>(), null, v => v.Reset()); public TSrcValue Value; public override void Reset() { base.Reset(); Value = default; } protected override void VisitPath<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value) { if (property.IsReadOnly) { ReturnCode = VisitReturnCode.AccessViolation; return; } if (TypeConversion.TryConvert(ref Value, out TValue v)) { property.SetValue(ref container, v); } else { ReturnCode = VisitReturnCode.InvalidCast; } } } /// <summary> /// Sets the value of a property by name to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="name">The name of the property to set.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TValue">The value type to set.</typeparam> /// <exception cref="ArgumentNullException">The specified container or path is null.</exception> /// <exception cref="InvalidContainerTypeException">The specified container type is not valid for visitation.</exception> /// <exception cref="MissingPropertyBagException">The specified container type has no property bag associated with it.</exception> /// <exception cref="InvalidCastException">The specified <typeparamref name="TValue"/> could not be assigned to the property.</exception> /// <exception cref="InvalidPathException">The specified <paramref name="name"/> was not found or could not be resolved.</exception> public static void SetValue<TContainer, TValue>(TContainer container, string name, TValue value) => SetValue(ref container, name, value); /// <summary> /// Sets the value of a property by name to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="name">The name of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <exception cref="ArgumentNullException">The specified container or path is null.</exception> /// <exception cref="InvalidContainerTypeException">The specified container type is not valid for visitation.</exception> /// <exception cref="MissingPropertyBagException">The specified container type has no property bag associated with it.</exception> /// <exception cref="InvalidCastException">The specified <typeparamref name="TValue"/> could not be assigned to the property.</exception> /// <exception cref="InvalidPathException">The specified <paramref name="name"/> was not found or could not be resolved.</exception> public static void SetValue<TContainer, TValue>(ref TContainer container, string name, TValue value) { var path = new PropertyPath(name); SetValue(ref container, path, value); } /// <summary> /// Sets the value of a property at the given path to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="path">The path of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <exception cref="ArgumentNullException">The specified container or path is null.</exception> /// <exception cref="InvalidContainerTypeException">The specified container type is not valid for visitation.</exception> /// <exception cref="MissingPropertyBagException">The specified container type has no property bag associated with it.</exception> /// <exception cref="InvalidCastException">The specified <typeparamref name="TValue"/> could not be assigned to the property.</exception> /// <exception cref="InvalidPathException">The specified <paramref name="path"/> was not found or could not be resolved.</exception> public static void SetValue<TContainer, TValue>(TContainer container, in PropertyPath path, TValue value) => SetValue(ref container, path, value); /// <summary> /// Sets the value of a property at the given path to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="path">The path of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <exception cref="ArgumentNullException">The specified container or path is null.</exception> /// <exception cref="InvalidContainerTypeException">The specified container type is not valid for visitation.</exception> /// <exception cref="MissingPropertyBagException">The specified container type has no property bag associated with it.</exception> /// <exception cref="InvalidCastException">The specified <typeparamref name="TValue"/> could not be assigned to the property.</exception> /// <exception cref="InvalidPathException">The specified <paramref name="path"/> was not found or could not be resolved.</exception> /// <exception cref="AccessViolationException">The specified <paramref name="path"/> is read-only.</exception> public static void SetValue<TContainer, TValue>(ref TContainer container, in PropertyPath path, TValue value) { if (path.Length == 0) throw new ArgumentNullException(nameof(path)); if (path.Length <= 0) throw new InvalidPathException("The specified PropertyPath is empty."); if (TrySetValue(ref container, path, value, out var returnCode)) return; switch (returnCode) { case VisitReturnCode.NullContainer: throw new ArgumentNullException(nameof(container)); case VisitReturnCode.InvalidContainerType: throw new InvalidContainerTypeException(container.GetType()); case VisitReturnCode.MissingPropertyBag: throw new MissingPropertyBagException(container.GetType()); case VisitReturnCode.InvalidCast: throw new InvalidCastException($"Failed to SetValue of Type=[{typeof(TValue).Name}] for property with path=[{path}]"); case VisitReturnCode.InvalidPath: throw new InvalidPathException($"Failed to SetValue for property with Path=[{path}]"); case VisitReturnCode.AccessViolation: throw new AccessViolationException($"Failed to SetValue for read-only property with Path=[{path}]"); default: throw new Exception($"Unexpected {nameof(VisitReturnCode)}=[{returnCode}]"); } } /// <summary> /// Tries to set the value of a property at the given path to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="name">The name of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <returns><see langword="true"/> if the value was set correctly; <see langword="false"/> otherwise.</returns> public static bool TrySetValue<TContainer, TValue>(TContainer container, string name, TValue value) => TrySetValue(ref container, name, value); /// <summary> /// Tries to set the value of a property at the given path to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="name">The name of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <returns><see langword="true"/> if the value was set correctly; <see langword="false"/> otherwise.</returns> public static bool TrySetValue<TContainer, TValue>(ref TContainer container, string name, TValue value) { var path = new PropertyPath(name); return TrySetValue(ref container, path, value); } /// <summary> /// Tries to set the value of a property at the given path to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="path">The path of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <returns><see langword="true"/> if the value was set correctly; <see langword="false"/> otherwise.</returns> public static bool TrySetValue<TContainer, TValue>(TContainer container, in PropertyPath path, TValue value) => TrySetValue(ref container, path, value); /// <summary> /// Tries to set the value of a property at the given path to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="path">The path of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <returns><see langword="true"/> if the value was set correctly; <see langword="false"/> otherwise.</returns> public static bool TrySetValue<TContainer, TValue>(ref TContainer container, in PropertyPath path, TValue value) => TrySetValue(ref container, path, value, out _); /// <summary> /// Tries to set the value of a property at the given path to the given value. /// </summary> /// <remarks> /// This method is NOT thread safe. /// </remarks> /// <param name="container">The container whose property will be set.</param> /// <param name="path">The path of the property to set.</param> /// <param name="value">The value to assign to the property.</param> /// <param name="returnCode">When this method returns, contains the return code.</param> /// <typeparam name="TContainer">The container type to set the value on.</typeparam> /// <typeparam name="TValue">The value type to set.</typeparam> /// <returns><see langword="true"/> if the value was set correctly; <see langword="false"/> otherwise.</returns> public static bool TrySetValue<TContainer, TValue>(ref TContainer container, in PropertyPath path, TValue value, out VisitReturnCode returnCode) { if (path.IsEmpty) { returnCode = VisitReturnCode.InvalidPath; return false; } var visitor = SetValueVisitor<TValue>.Pool.Get(); visitor.Path = path; visitor.Value = value; try { if (!TryAccept(visitor, ref container, out returnCode)) { return false; } returnCode = visitor.ReturnCode; } finally { SetValueVisitor<TValue>.Pool.Release(visitor); } return returnCode == VisitReturnCode.Ok; } } }
UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+SetValue.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+SetValue.cs", "repo_id": "UnityCsReference", "token_count": 5302 }
437
// 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 Unity.Properties { /// <summary> /// An <see cref="IPropertyBag{T}"/> implementation for a <see cref="HashSet{TElement}"/> type. /// </summary> /// <typeparam name="TElement">The element type.</typeparam> public class HashSetPropertyBag<TElement> : SetPropertyBagBase<HashSet<TElement>, TElement> { /// <inheritdoc/> protected override InstantiationKind InstantiationKind => InstantiationKind.PropertyBagOverride; /// <inheritdoc/> protected override HashSet<TElement> Instantiate() => new HashSet<TElement>(); } }
UnityCsReference/Modules/Properties/Runtime/PropertyBags/HashSetPropertyBag.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/HashSetPropertyBag.cs", "repo_id": "UnityCsReference", "token_count": 263 }
438
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace Unity.Properties { /// <summary> /// Implement this interface to intercept the visitation for a specific <see cref="TContainer"/> and <see cref="TValue"/> pair. /// </summary> /// <remarks> /// * <seealso cref="IVisitPropertyAdapter{TValue}"/> /// * <seealso cref="IVisitPropertyAdapter"/> /// </remarks> /// <typeparam name="TContainer">The container type being visited.</typeparam> /// <typeparam name="TValue">The value type being visited.</typeparam> public interface IVisitPropertyAdapter<TContainer, TValue> : IPropertyVisitorAdapter { /// <summary> /// Invoked when the visitor encounters specific a <see cref="TContainer"/> and <see cref="TValue"/> pair. /// </summary> /// <param name="context">The context being visited.</param> /// <param name="container">The container being visited.</param> /// <param name="value">The value being visited.</param> void Visit(in VisitContext<TContainer, TValue> context, ref TContainer container, ref TValue value); } /// <summary> /// Implement this interface to intercept the visitation for a specific <see cref="TValue"/> type. /// </summary> /// <remarks> /// <seealso cref="IVisitPropertyAdapter{TContainer,TValue}"/> /// <seealso cref="IVisitPropertyAdapter"/> /// </remarks> /// <typeparam name="TValue">The value type being visited.</typeparam> public interface IVisitPropertyAdapter<TValue> : IPropertyVisitorAdapter { /// <summary> /// Invoked when the visitor encounters specific <see cref="TValue"/> type with any container. /// </summary> /// <param name="context">The context being visited.</param> /// <param name="container">The container being visited.</param> /// <param name="value">The value being visited.</param> /// <typeparam name="TContainer">The container type being visited.</typeparam> void Visit<TContainer>(in VisitContext<TContainer, TValue> context, ref TContainer container, ref TValue value); } /// <summary> /// Implement this interface to handle visitation for all properties. /// </summary> /// <remarks> /// <seealso cref="IVisitPropertyAdapter{TContainer,TValue}"/> /// <seealso cref="IVisitPropertyAdapter{TValue}"/> /// </remarks> public interface IVisitPropertyAdapter : IPropertyVisitorAdapter { /// <summary> /// Invoked when the visitor encounters any property. /// </summary> /// <param name="context">The context being visited.</param> /// <param name="container">The container being visited.</param> /// <param name="value">The value being visited.</param> /// <typeparam name="TValue">The value type being visited.</typeparam> /// <typeparam name="TContainer">The container type being visited.</typeparam> void Visit<TContainer, TValue>(in VisitContext<TContainer, TValue> context, ref TContainer container, ref TValue value); } /// <summary> /// Implement this interface to intercept the visitation for a specific <see cref="TContainer"/> and <see cref="TValue"/> pair. /// </summary> /// <remarks> /// * <seealso cref="IVisitContravariantPropertyAdapter{TValue}"/> /// * <seealso cref="IVisitPropertyAdapter"/> /// </remarks> /// <typeparam name="TContainer">The container type being visited.</typeparam> /// <typeparam name="TValue">The value type being visited.</typeparam> public interface IVisitContravariantPropertyAdapter<TContainer, in TValue> : IPropertyVisitorAdapter { /// <summary> /// Invoked when the visitor encounters specific a <see cref="TContainer"/> and <see cref="TValue"/> pair. /// </summary> /// <param name="context">The context being visited.</param> /// <param name="container">The container being visited.</param> /// <param name="value">The value being visited.</param> void Visit(in VisitContext<TContainer> context, ref TContainer container, TValue value); } /// <summary> /// Implement this interface to intercept the visitation for a specific <see cref="TValue"/> type. /// </summary> /// <remarks> /// <seealso cref="IVisitContravariantPropertyAdapter{TContainer,TValue}"/> /// <seealso cref="IVisitPropertyAdapter"/> /// </remarks> /// <typeparam name="TValue">The value type being visited.</typeparam> public interface IVisitContravariantPropertyAdapter<in TValue> : IPropertyVisitorAdapter { /// <summary> /// Invoked when the visitor encounters specific <see cref="TValue"/> type with any container. /// </summary> /// <param name="context">The context being visited.</param> /// <param name="container">The container being visited.</param> /// <param name="value">The value being visited.</param> /// <typeparam name="TContainer">The container type being visited.</typeparam> void Visit<TContainer>(in VisitContext<TContainer> context, ref TContainer container, TValue value); } }
UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/Adapters/IVisitPropertyAdapter.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/Adapters/IVisitPropertyAdapter.cs", "repo_id": "UnityCsReference", "token_count": 1786 }
439
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License //#define QUICKSEARCH_DEBUG using System; using System.Collections.Generic; namespace UnityEditor.Search { /// <summary> /// Utility class to perform matching against query text using a fuzzy search algorithm. /// </summary> public static class FuzzySearch { struct ScoreIndx { public int i; public int score; public int prev_mi; } class FuzzyMatchData : IDisposable { public List<ScoreIndx>[] matches_indx; public bool[,] matchData; private FuzzyMatchData(int strN, int patternN) { matchData = new bool[strN, patternN]; matches_indx = new List<ScoreIndx>[patternN]; for (var k = 0; k < patternN; k++) { matches_indx[k] = new List<ScoreIndx>(8); } } public void Dispose() { } public static FuzzyMatchData Request(int strN, int patternN) { return new FuzzyMatchData(strN, patternN); } } internal struct ScopedProfiler : IDisposable { public ScopedProfiler(string name) { } public ScopedProfiler(string name, UnityEngine.Object targetObject) { } public void Dispose() { } } public static bool FuzzyMatch(string pattern, string origin, List<int> matches = null) { long score = 0; return FuzzyMatch(pattern, origin, ref score, matches); } /// <summary> /// Performs a fuzzy search on a string to see if it matches a pattern. /// </summary> /// <param name="pattern">Pattern that we try to match the source string</param> /// <param name="origin">String we are looking into for a match</param> /// <param name="outScore">Score of the match. A higher score means the pattern is a better match for the string.</param> /// <param name="matches">List of indices in the source string where a match was found.</param> /// <returns>Returns true if a match was found</returns> public static bool FuzzyMatch(string pattern, string origin, ref long outScore, List<int> matches = null) { int str_n; int pattern_n; int str_start; string str; using (new ScopedProfiler("[FM] Init")) { outScore = -100000; matches?.Clear(); if (string.IsNullOrEmpty(origin)) return false; if (string.IsNullOrEmpty(pattern)) return true; str = origin.ToLowerInvariant(); pattern = pattern.ToLowerInvariant(); pattern_n = pattern.Length; // find [str_start..str_end) that contains pattern's first and last letter str_start = 0; var str_end = str.Length - 1; var pattern_first_lower = pattern[0]; var pattern_end_lower = pattern[pattern.Length - 1]; for (; str_start < str.Length; ++str_start) if (pattern_first_lower == str[str_start]) break; for (; str_end >= 0; --str_end) if (pattern_end_lower == str[str_end]) break; ++str_end; str_n = str_end - str_start; // str subset is shorter than pattern if (str_n < pattern_n) return false; // do check that pattern is fully inside [str_start..str_end) var pattern_i = 0; var str_i = str_start; while (pattern_i < pattern_n && str_i < str_end) { if (pattern[pattern_i] == str[str_i]) ++pattern_i; ++str_i; } if (pattern_i < pattern_n) return false; } using (new ScopedProfiler("[FM] Body")) using (var d = FuzzyMatchData.Request(str_n, pattern_n)) { var str_n_minus_pattern_n_plus_1 = str_n - pattern_n + 1; var prev_min_i = 0; using (var _3 = new ScopedProfiler("[FM] Match loop")) for (var j = 0; j < pattern_n; ++j) { var min_i = str_n + 1; var first_match = true; for (int i = Math.Max(j, prev_min_i), end_i = str_n_minus_pattern_n_plus_1 + j; i < end_i; ++i) { // Skip existing <> tags if (str[i] == '<') { for (; i < end_i; ++i) { if (str[i] == '>') break; } } var si = i + str_start; var match = false; if (pattern[j] == str[si]) match = true; if (i >= d.matchData.GetLength(0) || j >= d.matchData.GetLength(1)) return false; d.matchData[i, j] = match; if (match) { if (first_match) { min_i = i; first_match = false; } d.matches_indx[j].Add(new ScoreIndx { i = i, score = 1, prev_mi = -1 }); } } if (first_match) return false; // no match for pattern[j] prev_min_i = min_i; } const int sequential_bonus = 75; // bonus for adjacent matches const int separator_bonus = 30; // bonus if match occurs after a separator const int camel_bonus = 30; // bonus if match is uppercase and prev is lower or symbol const int first_letter_bonus = 35; // bonus if the first letter is matched const int leading_letter_penalty = -5; // penalty applied for every letter in str before the first match const int max_leading_letter_penalty = -15; // maximum penalty for leading letters const int unmatched_letter_penalty = -1; // penalty for every letter that doesn't matter int unmatched = str_n - (matches?.Count ?? 0); // find best score using (new ScopedProfiler("[FM] Best score 0")) for (var mi = 0; mi < d.matches_indx[0].Count; ++mi) { var i = d.matches_indx[0][mi].i; var si = str_start + i; var s = 100 + unmatched_letter_penalty * unmatched; var penalty = leading_letter_penalty * si; if (penalty < max_leading_letter_penalty) penalty = max_leading_letter_penalty; s += penalty; if (si == 0) { s += first_letter_bonus; } else { var currOrigI = origin[si]; var prevOrigI = origin[si - 1]; if (char.IsUpper(currOrigI) && char.IsUpper(prevOrigI) == false) s += camel_bonus; else if (prevOrigI == '_' || prevOrigI == ' ') s += separator_bonus; } d.matches_indx[0][mi] = new ScoreIndx { i = i, score = s, prev_mi = -1 }; } using (new ScopedProfiler("[FM] Best score 1..pattern_n")) for (var j = 1; j < pattern_n; ++j) { for (var mi = 0; mi < d.matches_indx[j].Count; ++mi) { var match = d.matches_indx[j][mi]; var si = str_start + d.matches_indx[j][mi].i; var currOrigI = origin[si]; var prevOrigI = origin[si - 1]; if (char.IsUpper(currOrigI) && char.IsUpper(prevOrigI) == false) match.score += camel_bonus; else if (prevOrigI == '_' || prevOrigI == ' ') match.score += separator_bonus; // select from prev var best_pmi = 0; var best_score = -1; for (var pmi = 0; pmi < d.matches_indx[j - 1].Count; ++pmi) { var prev_i = d.matches_indx[j - 1][pmi].i; if (prev_i >= match.i) break; var pmi_score = d.matches_indx[j - 1][pmi].score; if (prev_i == match.i - 1) pmi_score += sequential_bonus; if (best_score < pmi_score) { best_score = pmi_score; best_pmi = pmi; } } match.score += best_score; match.prev_mi = best_pmi; d.matches_indx[j][mi] = match; } } var best_mi = 0; var max_j = pattern_n - 1; for (var mi = 1; mi < d.matches_indx[max_j].Count; ++mi) { if (d.matches_indx[max_j][best_mi].score < d.matches_indx[max_j][mi].score) best_mi = mi; } var bestScore = d.matches_indx[max_j][best_mi]; outScore = bestScore.score; if (matches != null) { using (new ScopedProfiler("[FM] Matches calc")) { matches.Capacity = pattern_n; matches.Add(bestScore.i + str_start); { var mi = bestScore.prev_mi; for (var j = pattern_n - 2; j >= 0; --j) { matches.Add(d.matches_indx[j][mi].i + str_start); mi = d.matches_indx[j][mi].prev_mi; } } matches.Reverse(); } } return true; } } } internal static class RichTextFormatter { static readonly char[] cache_result = new char[1024]; /// <summary> /// Color for matching text when using fuzzy search. /// </summary> public static string HighlightColorTag = EditorGUIUtility.isProSkin ? "<color=#FF6100>" : "<color=#EE4400>"; /// <summary> /// Color for special tags when using fuzzy search. /// </summary> public static string HighlightColorTagSpecial = EditorGUIUtility.isProSkin ? "<color=#FF6100>" : "<color=#BB1100>"; public static string FormatSuggestionTitle(string title, List<int> matches) { return FormatSuggestionTitle(title, matches, HighlightColorTag, HighlightColorTagSpecial); } public static string FormatSuggestionTitle(string title, List<int> matches, string selectedTextColorTag, string specialTextColorTag) { const string closingTag = "</color>"; int openCharCount = specialTextColorTag.Length; int closingCharCount = closingTag.Length; var N = title.Length + matches.Count * (closingCharCount + openCharCount); var MN = matches.Count; var result = cache_result; if (N > cache_result.Length) result = new char[N]; int t_i = 0; int t_j = 0; int t_k = 0; string tag = null; var needToClose = false; for (int guard = 0; guard < N; ++guard) { if (tag == null && needToClose == false && t_k < MN) // find tag for t_i { var indx = matches[t_k]; if (indx == t_i || indx == -t_i) { tag = (indx < 0) ? specialTextColorTag : selectedTextColorTag; ++t_k; } } if (tag != null) { result[guard] = tag[t_j++]; if (t_j >= tag.Length) { if (tag != closingTag) needToClose = true; tag = null; t_j = 0; } } else { result[guard] = title[Math.Min(t_i++, title.Length - 1)]; if (needToClose) { tag = closingTag; needToClose = false; } } } return new string(result, 0, N); } } }
UnityCsReference/Modules/QuickSearch/Editor/FuzzySearch.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/FuzzySearch.cs", "repo_id": "UnityCsReference", "token_count": 8698 }
440
// 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.Search { static class DefaultPropertyDatabaseSerializers { public static int fixedStringLengthByteSize => 1; [PropertyDatabaseSerializer(typeof(int))] internal static PropertyDatabaseRecordValue IntegerSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Integer, (int)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Integer)] internal static object IntegerDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value.int32_0; } [PropertyDatabaseSerializer(typeof(uint))] internal static PropertyDatabaseRecordValue UnsignedIntegerSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.UnsignedInteger, (uint)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.UnsignedInteger)] internal static object UnsignedIntegerDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value.uint32_0; } [PropertyDatabaseSerializer(typeof(byte))] internal static PropertyDatabaseRecordValue ByteSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Byte, (byte)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Byte)] internal static object ByteDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value[0]; } [PropertyDatabaseSerializer(typeof(short))] internal static PropertyDatabaseRecordValue ShortSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Short, (short)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Short)] internal static object ShortDeserializer(PropertyDatabaseDeserializationArgs args) { return (short)args.value.int32_0; } [PropertyDatabaseSerializer(typeof(ushort))] internal static PropertyDatabaseRecordValue UnsignedShortSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.UnsignedShort, (ushort)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.UnsignedShort)] internal static object UnsignedShortDeserializer(PropertyDatabaseDeserializationArgs args) { return (ushort)args.value.int32_0; } [PropertyDatabaseSerializer(typeof(long))] internal static PropertyDatabaseRecordValue LongSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Long, (long)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Long)] internal static object LongDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value.int64_0; } [PropertyDatabaseSerializer(typeof(ulong))] internal static PropertyDatabaseRecordValue UnsignedLongSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.UnsignedLong, (ulong)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.UnsignedLong)] internal static object UnsignedLongDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value.uint64_0; } [PropertyDatabaseSerializer(typeof(bool))] internal static PropertyDatabaseRecordValue BooleanSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Bool, (bool)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Bool)] internal static object BooleanDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value.boolean; } [PropertyDatabaseSerializer(typeof(double))] internal static PropertyDatabaseRecordValue DoubleSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Double, (double)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Double)] internal static object DoubleDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value.float64_0; } [PropertyDatabaseSerializer(typeof(float))] internal static PropertyDatabaseRecordValue FloatSerializer(PropertyDatabaseSerializationArgs args) { return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Float, (float)args.value); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Float)] internal static object FloatDeserializer(PropertyDatabaseDeserializationArgs args) { return args.value.float32_0; } [PropertyDatabaseSerializer(typeof(string))] internal static PropertyDatabaseRecordValue StringSerializer(PropertyDatabaseSerializationArgs args) { var stringValue = (string)args.value; var byteSize = PropertyStringTable.encoding.GetByteCount(stringValue); if (byteSize + fixedStringLengthByteSize <= PropertyDatabaseRecordValue.maxSize) { var bytes = new byte[byteSize + fixedStringLengthByteSize]; SetFixedStringLength(bytes, byteSize); PropertyStringTable.encoding.GetBytes(stringValue, 0, stringValue.Length, bytes, fixedStringLengthByteSize); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.FixedString, bytes); } var symbol = args.stringTableView.ToSymbol(stringValue); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.String, symbol); } [PropertyDatabaseDeserializer(PropertyDatabaseType.FixedString)] internal static object FixedStringDeserializer(PropertyDatabaseDeserializationArgs args) { var byteSize = GetFixedStringLength(args.value); var bytes = new byte[byteSize]; for (var i = 0; i < byteSize; ++i) { bytes[i] = args.value[i + fixedStringLengthByteSize]; } return PropertyStringTable.encoding.GetString(bytes); } [PropertyDatabaseDeserializer(PropertyDatabaseType.String)] internal static object StringDeserializer(PropertyDatabaseDeserializationArgs args) { var symbol = args.value.int32_0; return args.stringTableView.GetString(symbol); } [PropertyDatabaseSerializer(typeof(Vector4))] internal static PropertyDatabaseRecordValue Vector4Serializer(PropertyDatabaseSerializationArgs args) { var v = (Vector4)args.value; return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Vector4, v.x, v.y, v.z, v.w); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Vector4)] internal static object Vector4Deserializer(PropertyDatabaseDeserializationArgs args) { return new Vector4(args.value.float32_0, args.value.float32_1, args.value.float32_2, args.value.float32_3); } [PropertyDatabaseSerializer(typeof(GlobalObjectId))] internal static PropertyDatabaseRecordValue GlobalObjectIdSerializer(PropertyDatabaseSerializationArgs args) { var goid = (GlobalObjectId)args.value; var str = goid.ToString(); var symbol = args.stringTableView.ToSymbol(str); return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.GlobalObjectId, symbol); } [PropertyDatabaseDeserializer(PropertyDatabaseType.GlobalObjectId)] internal static object GlobalObjectIdDeserializer(PropertyDatabaseDeserializationArgs args) { var symbol = args.value.int32_0; var str = args.stringTableView.GetString(symbol); if (GlobalObjectId.TryParse(str, out var goid)) return goid; return null; } [PropertyDatabaseSerializer(typeof(Color))] internal static PropertyDatabaseRecordValue ColorSerializer(PropertyDatabaseSerializationArgs args) { var color = (Color)args.value; return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Color, color.r, color.g, color.b, color.a); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Color)] internal static object ColorDeserializer(PropertyDatabaseDeserializationArgs args) { return new Color(args.value.float32_0, args.value.float32_1, args.value.float32_2, args.value.float32_3); } [PropertyDatabaseSerializer(typeof(Color32))] internal static PropertyDatabaseRecordValue Color32Serializer(PropertyDatabaseSerializationArgs args) { var color = (Color32)args.value; return new PropertyDatabaseRecordValue((byte)PropertyDatabaseType.Color32, color.r, color.g, color.b, color.a); } [PropertyDatabaseDeserializer(PropertyDatabaseType.Color32)] internal static object Color32Deserializer(PropertyDatabaseDeserializationArgs args) { return new Color32(args.value[0], args.value[1], args.value[2], args.value[3]); } static void SetFixedStringLength(byte[] bytes, int byteSize) { bytes[0] = (byte)byteSize; } static byte GetFixedStringLength(PropertyDatabaseRecordValue value) { return value[0]; } } }
UnityCsReference/Modules/QuickSearch/Editor/PropertyDatabase/DefaultPropertyDatabaseSerializers.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/PropertyDatabase/DefaultPropertyDatabaseSerializers.cs", "repo_id": "UnityCsReference", "token_count": 3857 }
441
// 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 UnityEditor.Profiling; using UnityEngine; using System.Text.RegularExpressions; using System.Linq; namespace UnityEditor.Search.Providers { class PerformanceProvider : BasePerformanceProvider<string> { internal const string providerId = "performance"; static readonly UnitTypeHandle k_SecondUnitTypeHandle = UnitType.GetHandle("s"); [SearchItemProvider] public static SearchProvider CreateProvider() { var p = new PerformanceProvider(providerId, "Performance Trackers"); p.Initialize(); p.filterId = "perf:"; return p; } protected PerformanceProvider(string id, string displayName) : base(id, displayName) { AddUnitType("s", k_SecondUnitTypeHandle, UnitPowerType.One, UnitPowerType.Milli, UnitPowerType.Micro, UnitPowerType.Nano); } protected override IEnumerable<SearchAction> GetActions() { return base.GetActions().Append(new SearchAction("log", "Callstack", item => EditorPerformanceTracker.GetCallstack(item.id, cs => CaptureCallstack(item, cs)))); } protected override void ResetItems(SearchItem[] items) { foreach (var item in items) EditorPerformanceTracker.Reset(item.id); } [SearchSelector(sampleCountSelector, provider: providerId, cacheable = false)] static object SelectCount(SearchSelectorArgs args) => TrackerToValueWithUnit(EditorPerformanceTracker.GetSampleCount(args.current.id)); [SearchSelector(samplePeakSelector, provider: providerId, cacheable = false)] static object SelectPeak(SearchSelectorArgs args) => TrackerToValueWithUnit(EditorPerformanceTracker.GetPeakTime(args.current.id)); [SearchSelector(sampleAvgSelector, provider: providerId, cacheable = false)] static object SelectAvg(SearchSelectorArgs args) => TrackerToValueWithUnit(EditorPerformanceTracker.GetAverageTime(args.current.id)); [SearchSelector(sampleTotalSelector, provider: providerId, cacheable = false)] static object SelectTotal(SearchSelectorArgs args) => TrackerToValueWithUnit(EditorPerformanceTracker.GetTotalTime(args.current.id)); static void CaptureCallstack(in SearchItem item, string callstack) { Debug.Log(callstack); item.data = callstack; } protected override string FetchDescription(SearchItem item, SearchContext context) { var fullDescription = item.options.HasAny(SearchItemOptions.FullDescription); var description = GetTrackerDescription(item.id, fullDescription ? '\n' : ' '); if (fullDescription && item.data != null) return $"{description}\n\n{FormatCallstackForConsole((string)item.data)}"; if (item.options.HasAny(SearchItemOptions.Compacted)) return $"<b>{item.id}</b> {description}"; return description; } protected override string FormatColumnValue(SearchColumnEventArgs args) { if (args.value == null) return string.Empty; if (args.value is string valueStr) return valueStr; var valueWithUnit = (ValueWithUnit)args.value; if (args.column.selector == sampleCountSelector) return valueWithUnit.value.ToString("F0"); return GetTimeLabel(valueWithUnit.value, GetDefaultPerformanceLimit(args.column.selector)); } static string FormatCallstackForConsole(string callstack) { return Regex.Replace(callstack, "\\[(\\S+?):(\\d+)\\]", "[<a href=\"$1\" line=\"$2\">$1:$2</a>]"); } string GetTrackerDescription(string trackerName, char splitter) { var sampleCount = EditorPerformanceTracker.GetSampleCount(trackerName); var peakTime = EditorPerformanceTracker.GetPeakTime(trackerName); var avgTime = EditorPerformanceTracker.GetAverageTime(trackerName); var totalTime = EditorPerformanceTracker.GetTotalTime(trackerName); return $"Sample Count: <b>{sampleCount}</b>{splitter}" + $"Peak: {GetTimeLabel(peakTime, GetDefaultPerformanceLimit(samplePeakSelector))}{splitter}" + $"Avg: {GetTimeLabel(avgTime, GetDefaultPerformanceLimit(sampleAvgSelector))}{splitter}" + $"Total: {GetTimeLabel(totalTime, GetDefaultPerformanceLimit(sampleTotalSelector))}"; } protected override IEnumerable<string> YieldPerformanceDataWords(string trackerName) { yield return trackerName; } protected override ValueWithUnit GetPerformanceAverageValue(string trackerName) => TrackerToValueWithUnit(EditorPerformanceTracker.GetAverageTime(trackerName)); protected override ValueWithUnit GetPerformanceTotalValue(string trackerName) => TrackerToValueWithUnit(EditorPerformanceTracker.GetTotalTime(trackerName)); protected override ValueWithUnit GetPerformancePeakValue(string trackerName) => TrackerToValueWithUnit(EditorPerformanceTracker.GetPeakTime(trackerName)); protected override ValueWithUnit GetPerformanceSampleCountValue(string trackerName) => TrackerToValueWithUnit(EditorPerformanceTracker.GetSampleCount(trackerName)); static ValueWithUnit TrackerToValueWithUnit(double value) { return new ValueWithUnit(value, k_SecondUnitTypeHandle, UnitPowerType.One); } static ValueWithUnit TrackerToValueWithUnit(int value) { return new ValueWithUnit(value, k_UnitlessTypeHandle, UnitPowerType.One); } protected override IEnumerable<SearchItem> FetchItem(SearchContext context, SearchProvider provider) { var query = m_QueryEngine.ParseQuery(context.searchQuery); if (!query.valid) yield break; var trackers = EditorPerformanceTracker.GetAvailableTrackers(); foreach (var trackerName in query.Apply(trackers)) yield return CreateItem(context, provider, trackerName); } static SearchItem CreateItem(in SearchContext context, in SearchProvider provider, in string trackerName) { var item = provider.CreateItem(context, trackerName, trackerName, null, null, null); item.options = SearchItemOptions.AlwaysRefresh; return item; } } }
UnityCsReference/Modules/QuickSearch/Editor/Providers/PerformanceProvider.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/PerformanceProvider.cs", "repo_id": "UnityCsReference", "token_count": 2485 }
442
// 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.Search { interface IBlockSource { string name { get; } string editorTitle { get; } SearchContext context { get; } bool formatNames { get; } void Apply(in SearchProposition searchProposition); IEnumerable<SearchProposition> FetchPropositions(); void CloseEditor(); } interface IBlockEditor { EditorWindow window { get; } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/IBlockEditor.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/IBlockEditor.cs", "repo_id": "UnityCsReference", "token_count": 229 }
443
// 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; namespace UnityEditor.Search { /// <summary> /// Interface for query handlers. /// </summary> /// <typeparam name="TData">The filtered data type.</typeparam> /// <typeparam name="TPayload">The payload type.</typeparam> public interface IQueryHandler<TData, in TPayload> where TPayload : class { /// <summary> /// Implement this function to evaluate the query on a payload. /// </summary> /// <param name="payload">The input data of the query.</param> /// <returns>An enumerable of type TData.</returns> IEnumerable<TData> Eval(TPayload payload); /// <summary> /// Implement this function to evaluate the query on a single element. /// </summary> /// <param name="element">A single object to be tested.</param> /// <returns>True if the object passes the query, false otherwise.</returns> bool Eval(TData element); } /// <summary> /// Interface for query handler factories. /// </summary> /// <typeparam name="TData">The filtered data type.</typeparam> /// <typeparam name="TQueryHandler">The query handler type.</typeparam> /// <typeparam name="TPayload">The payload type.</typeparam> public interface IQueryHandlerFactory<TData, out TQueryHandler, TPayload> where TQueryHandler : IQueryHandler<TData, TPayload> where TPayload : class { /// <summary> /// Implement this function to create a new query handler for a specific query graph. /// </summary> /// <param name="graph">A graph representing a query.</param> /// <param name="errors">A collection of errors. Use this to report errors when needed.</param> /// <returns>An object of type TQueryHandler.</returns> TQueryHandler Create(QueryGraph graph, ICollection<QueryError> errors); } /// <summary> /// A Query defines an operation that can be used to filter a data set. /// </summary> /// <typeparam name="TData">The filtered data type.</typeparam> /// <typeparam name="TPayload">The payload type.</typeparam> public class ParsedQuery<TData, TPayload> where TPayload : class { /// <summary> /// The text that generated this query. /// </summary> public string text { get; } /// <summary> Indicates if the query is valid or not. </summary> public bool valid => errors.Count == 0 && evaluationGraph != null; /// <summary> List of QueryErrors. </summary> public ICollection<QueryError> errors { get; } /// <summary> /// List of tokens found in the query. /// </summary> public ICollection<string> tokens { get; } internal ICollection<QueryToggle> toggles { get; } internal IQueryHandler<TData, TPayload> graphHandler { get; set; } public QueryGraph evaluationGraph { get; } public QueryGraph queryGraph { get; } internal ParsedQuery(string text, QueryGraph evaluationGraph, QueryGraph queryGraph, ICollection<QueryError> errors, ICollection<string> tokens, ICollection<QueryToggle> toggles) { this.text = text; this.evaluationGraph = evaluationGraph; this.queryGraph = queryGraph; this.errors = errors; this.tokens = tokens; this.toggles = toggles; } internal ParsedQuery(string text, QueryGraph evaluationGraph, QueryGraph queryGraph, ICollection<QueryError> errors, ICollection<string> tokens, ICollection<QueryToggle> toggles, IQueryHandler<TData, TPayload> graphHandler) : this(text, evaluationGraph, queryGraph, errors, tokens, toggles) { if (valid) { this.graphHandler = graphHandler; } } /// <summary> /// Apply the filtering on a payload. /// </summary> /// <param name="payload">The data to filter</param> /// <returns>A filtered IEnumerable.</returns> public virtual IEnumerable<TData> Apply(TPayload payload = null) { if (!valid) return null; return graphHandler.Eval(payload); } /// <summary> /// Optimize the query by optimizing the underlying filtering graph. /// </summary> /// <param name="propagateNotToLeaves">Propagate "Not" operations to leaves, so only leaves can have "Not" operations as parents.</param> /// <param name="swapNotToRightHandSide">Swaps "Not" operations to the right hand side of combining operations (i.e. "And", "Or"). Useful if a "Not" operation is slow.</param> public void Optimize(bool propagateNotToLeaves, bool swapNotToRightHandSide) { evaluationGraph?.Optimize(propagateNotToLeaves, swapNotToRightHandSide); } /// <summary> /// Optimize the query by optimizing the underlying filtering graph. /// </summary> /// <param name="options">Optimization options.</param> public void Optimize(QueryGraphOptimizationOptions options) { evaluationGraph?.Optimize(options); } /// <summary> /// Get the query node located at the specified position in the query. /// </summary> /// <param name="position">The position of the query node in the text.</param> /// <returns>An IQueryNode.</returns> public IQueryNode GetNodeAtPosition(int position) { // Allow position at Length, to support cursor at end of word. if (position < 0 || position > text.Length) throw new ArgumentOutOfRangeException(nameof(position)); if (queryGraph == null || queryGraph.empty) return null; return GetNodeAtPosition(queryGraph.root, position); } internal bool HasToggle(string toggle) { return HasToggle(toggle, StringComparison.Ordinal); } internal bool HasToggle(string toggle, StringComparison stringComparison) { return toggles.Any(s => s.value.Equals(toggle, stringComparison)); } static IQueryNode GetNodeAtPosition(IQueryNode root, int position) { if (root.type == QueryNodeType.Where || root.type == QueryNodeType.Group) return GetNodeAtPosition(root.children[0], position); if (!string.IsNullOrEmpty(root.token.text) && position >= root.token.position && position <= root.token.position + root.token.length) return root; if (root.leaf || root.children == null) return null; if (root.children.Count == 1) return GetNodeAtPosition(root.children[0], position); // We have no more than two children return GetNodeAtPosition(position < root.token.position ? root.children[0] : root.children[1], position); } } /// <summary> /// A Query defines an operation that can be used to filter a data set. /// </summary> /// <typeparam name="T">The filtered data type.</typeparam> public class ParsedQuery<T> : ParsedQuery<T, IEnumerable<T>> { /// <summary> /// Boolean indicating if the original payload should be return when the query is empty. /// If set to false, an empty array is returned instead. /// </summary> public bool returnPayloadIfEmpty { get; set; } = true; internal ParsedQuery(string text, QueryGraph evaluationGraph, QueryGraph queryGraph, ICollection<QueryError> errors, ICollection<string> tokens, ICollection<QueryToggle> toggles, IQueryHandler<T, IEnumerable<T>> graphHandler) : base(text, evaluationGraph, queryGraph, errors, tokens, toggles, graphHandler) {} /// <summary> /// Apply the filtering on an IEnumerable data set. /// </summary> /// <param name="data">The data to filter</param> /// <returns>A filtered IEnumerable.</returns> public override IEnumerable<T> Apply(IEnumerable<T> data) { return Apply(data, returnPayloadIfEmpty); } internal IEnumerable<T> Apply(IEnumerable<T> data, bool returnInputIfEmpty) { if (!valid) return new T[] {}; if (evaluationGraph.empty) { return returnInputIfEmpty ? data : new T[] {}; } return graphHandler.Eval(data); } /// <summary> /// Test the query on a single object. Returns true if the test passes. /// </summary> /// <param name="element">A single object to be tested.</param> /// <returns>True if the object passes the query, false otherwise.</returns> public bool Test(T element) { if (!valid) return false; if (evaluationGraph.empty) { return returnPayloadIfEmpty; } return graphHandler.Eval(element); } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/ParsedQuery.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/ParsedQuery.cs", "repo_id": "UnityCsReference", "token_count": 3667 }
444
// 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.Linq; using System.Reflection; using UnityEngine.Assertions; namespace UnityEditor.Search { class WhereEnumerable<T> : IQueryEnumerable<T> { IEnumerable<T> m_Payload; public Func<T, bool> predicate { get; } public bool fastYielding { get; } public WhereEnumerable(Func<T, bool> predicate, bool fastYielding) { this.predicate = predicate; this.fastYielding = fastYielding; } public void SetPayload(IEnumerable<T> payload) { m_Payload = payload; } public IEnumerator<T> GetEnumerator() { if (fastYielding) return FastYieldingEnumerator(); return m_Payload.Where(e => e != null && predicate(e)).GetEnumerator(); } public IEnumerator<T> FastYieldingEnumerator() { foreach (var element in m_Payload) { if (element == null) yield return default; if (predicate(element)) yield return element; else yield return default; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [EnumerableCreator(QueryNodeType.Where)] class WhereEnumerableFactory : IQueryEnumerableFactory { public IQueryEnumerable<T> Create<T>(IQueryNode root, QueryEngine<T> engine, ICollection<QueryError> errors, bool fastYielding) { if (root.leaf || root.children == null || root.children.Count != 1) { errors.Add(new QueryError(root.token.position, root.token.length, "Where node must have a child.")); return null; } var predicateGraphRoot = root.children[0]; var predicate = BuildFunctionFromNode(predicateGraphRoot, engine, errors, fastYielding); var whereEnumerable = new WhereEnumerable<T>(predicate, fastYielding); return whereEnumerable; } private Func<T, bool> BuildFunctionFromNode<T>(IQueryNode node, QueryEngine<T> engine, ICollection<QueryError> errors, bool fastYielding) { Func<T, bool> noOp = o => false; if (node == null) return noOp; switch (node.type) { case QueryNodeType.And: { Assert.IsFalse(node.leaf, "And node cannot be leaf."); var leftFunc = BuildFunctionFromNode(node.children[0], engine, errors, fastYielding); var rightFunc = BuildFunctionFromNode(node.children[1], engine, errors, fastYielding); return o => leftFunc(o) && rightFunc(o); } case QueryNodeType.Or: { Assert.IsFalse(node.leaf, "Or node cannot be leaf."); var leftFunc = BuildFunctionFromNode(node.children[0], engine, errors, fastYielding); var rightFunc = BuildFunctionFromNode(node.children[1], engine, errors, fastYielding); return o => leftFunc(o) || rightFunc(o); } case QueryNodeType.Not: { Assert.IsFalse(node.leaf, "Not node cannot be leaf."); var childFunc = BuildFunctionFromNode(node.children[0], engine, errors, fastYielding); return o => !childFunc(o); } case QueryNodeType.Filter: { var filterNode = node as FilterNode; if (filterNode == null) return noOp; var filterOperation = GenerateFilterOperation(filterNode, engine, errors); if (filterOperation == null) return noOp; return o => filterOperation.Match(o); } case QueryNodeType.Search: { if (engine.searchDataCallback == null) return o => false; var searchNode = node as SearchNode; Assert.IsNotNull(searchNode); Func<string, bool> matchWordFunc; var stringComparison = engine.globalStringComparison; if (engine.searchDataOverridesStringComparison) stringComparison = engine.searchDataStringComparison; if (engine.searchWordMatcher != null) matchWordFunc = s => engine.searchWordMatcher(searchNode.searchValue, searchNode.exact, stringComparison, s); else { if (searchNode.exact) matchWordFunc = s => s != null && s.Equals(searchNode.searchValue, stringComparison); else matchWordFunc = s => s != null && s.IndexOf(searchNode.searchValue, stringComparison) >= 0; } return o => engine.searchDataCallback(o).Any(data => matchWordFunc(data)); } case QueryNodeType.FilterIn: { var filterNode = node as InFilterNode; if (filterNode == null) return noOp; var filterOperation = GenerateFilterOperation(filterNode, engine, errors); if (filterOperation == null) return noOp; var inFilterFunction = GenerateInFilterFunction(filterNode, filterOperation, engine, errors, fastYielding); return inFilterFunction; } } return noOp; } private static BaseFilterOperation<T> GenerateFilterOperation<T>(FilterNode node, QueryEngine<T> engine, ICollection<QueryError> errors) { var operatorIndex = node.token.position + node.filter.token.Length + (node.paramValueStringView.IsNullOrEmpty() ? 0 : node.paramValueStringView.length); var filterValueIndex = operatorIndex + node.op.token.Length; Type filterValueType; IParseResult parseResult = null; if (QueryEngineUtils.IsNestedQueryToken(node.filterValueStringView)) { if (node.filter?.nestedQueryHandlerTransformer == null) { errors.Add(new QueryError(filterValueIndex, node.filterValueStringView.length, $"No nested query handler transformer set on filter \"{node.filter.token}\".")); return null; } filterValueType = node.filter.nestedQueryHandlerTransformer.rightHandSideType; } else { parseResult = engine.ParseFilterValue(node.filterValue, node.filter, in node.op, out filterValueType); if (!parseResult.success) { errors.Add(new QueryError(filterValueIndex, node.filterValueStringView.length, $"The value \"{node.filterValue}\" could not be converted to any of the supported handler types.")); return null; } } IFilterOperationGenerator generator = engine.GetGeneratorForType(filterValueType); if (generator == null) { errors.Add(new QueryError(filterValueIndex, node.filterValueStringView.length, $"Unknown type \"{filterValueType}\". Did you set an operator handler for this type?")); return null; } var generatorData = new FilterOperationGeneratorData { filterName = node.filterId, filterValue = node.filterValueStringView, filterValueParseResult = parseResult, globalStringComparison = engine.globalStringComparison, op = node.op, paramValue = node.paramValueStringView, generator = generator }; var operation = node.filter.GenerateOperation(generatorData, operatorIndex, errors); return operation as BaseFilterOperation<T>; } private Func<T, bool> GenerateInFilterFunction<T>(InFilterNode node, BaseFilterOperation<T> filterOperation, QueryEngine<T> engine, ICollection<QueryError> errors, bool fastYielding) { if (node.leaf || node.children == null || node.children.Count == 0) { errors.Add(new QueryError(node.token.position, node.token.length, "InFilter node cannot be a leaf.")); return null; } var nestedQueryType = GetNestedQueryType(node); if (nestedQueryType == null) { errors.Add(new QueryError(node.token.position, node.token.length, "Could not deduce nested query type. Did you forget to set the nested query handler?")); return null; } var transformType = node.filter.nestedQueryHandlerTransformer.rightHandSideType; var inFilterFunc = typeof(WhereEnumerableFactory) .GetMethod("GenerateInFilterFunctionWithTypes", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance) ?.MakeGenericMethod(typeof(T), nestedQueryType, transformType) ?.Invoke(this, new object[] { node, filterOperation, engine, errors, fastYielding }) as Func<T, bool>; if (inFilterFunc == null) { errors.Add(new QueryError(node.token.position, node.token.length, "Could not create filter function with nested query.")); return null; } return inFilterFunc; } private Func<T, bool> GenerateInFilterFunctionWithTypes<T, TNested, TTransform>(InFilterNode node, BaseFilterOperation<T> filterOperation, QueryEngine<T> engine, ICollection<QueryError> errors, bool fastYielding) { var nestedQueryEnumerable = EnumerableCreator.Create<TNested>(node.children[0], null, errors, fastYielding); if (nestedQueryEnumerable == null) return null; var nestedQueryTransformer = node.filter.nestedQueryHandlerTransformer as NestedQueryHandlerTransformer<TNested, TTransform>; if (nestedQueryTransformer == null) return null; var transformerFunction = nestedQueryTransformer.handler; var dynamicFilterOperation = filterOperation as IDynamicFilterOperation<TTransform>; if (dynamicFilterOperation == null) return null; return o => { foreach (var item in nestedQueryEnumerable) { var transformedValue = transformerFunction(item); dynamicFilterOperation.SetFilterValue(transformedValue); if (filterOperation.Match(o)) return true; } return false; }; } private static Type GetNestedQueryType(IQueryNode node) { if (node.type == QueryNodeType.NestedQuery) { var nn = node as NestedQueryNode; return nn?.nestedQueryHandler.enumerableType; } if (node.leaf || node.children == null) return null; foreach (var child in node.children) { var type = GetNestedQueryType(child); if (type != null) return type; } return null; } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/WhereEnumerable.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/WhereEnumerable.cs", "repo_id": "UnityCsReference", "token_count": 5740 }
445
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using System.Collections.Generic; using System.ComponentModel; namespace UnityEditor.Search { static partial class Evaluators { static int s_NextGroupId = 0; [Description("Group search result by a specified @selector"), Category("Set Manipulation")] [SearchExpressionEvaluator(SearchExpressionEvaluationHints.ExpandSupported, SearchExpressionType.Iterable, SearchExpressionType.Selector | SearchExpressionType.Optional)] public static IEnumerable<SearchItem> GroupBy(SearchExpressionContext c) { string selector = null; if (c.args.Length > 1) selector = c.args[1].innerText.ToString(); var outputValueFieldName = System.Guid.NewGuid().ToString("N"); var dataSet = SelectorManager.SelectValues(c.search, c.args[0].Execute(c), selector, outputValueFieldName); foreach (var _group in dataSet.GroupBy(item => item.GetValue(outputValueFieldName))) { var group = _group; var groupId = group.Key?.ToString() ?? $"group{++s_NextGroupId}"; if (c.HasFlag(SearchExpressionExecutionFlags.Expand)) { var evaluator = new SearchExpressionEvaluator(groupId, _ => group, SearchExpressionEvaluationHints.Default); var genExpr = new SearchExpression(SearchExpressionType.Group, groupId.GetStringView(), groupId.GetStringView(), (group.Key?.ToString() ?? groupId).GetStringView(), evaluator); yield return SearchExpression.CreateSearchExpressionItem(genExpr); } else { SearchProvider groupProvider = null; foreach (var item in group) { if (groupProvider == null) groupProvider = SearchUtils.CreateGroupProvider(item.provider, groupId, s_NextGroupId); item.provider = groupProvider; yield return item; } } } } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/GroupByEvaluator.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/GroupByEvaluator.cs", "repo_id": "UnityCsReference", "token_count": 1082 }
446