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 UnityEngine.Bindings;
using MinMaxCurve = UnityEngine.ParticleSystem.MinMaxCurve;
using MinMaxCurveBlittable = UnityEngine.ParticleSystem.MinMaxCurveBlittable;
namespace UnityEngine
{
[NativeHeader("ParticleSystemScriptingClasses.h")]
[NativeHeader("Modules/ParticleSystem/ParticleSystem.h")]
[NativeHeader("Modules/ParticleSystem/ParticleSystemForceField.h")]
[NativeHeader("Modules/ParticleSystem/ParticleSystemForceFieldManager.h")]
[NativeHeader("Modules/ParticleSystem/ScriptBindings/ParticleSystemScriptBindings.h")]
[RequireComponent(typeof(Transform))]
public partial class ParticleSystemForceField : Behaviour
{
[NativeName("ForceShape")]
extern public ParticleSystemForceFieldShape shape { get; set; }
extern public float startRange { get; set; }
extern public float endRange { get; set; }
extern public float length { get; set; }
extern public float gravityFocus { get; set; }
extern public Vector2 rotationRandomness { get; set; }
extern public bool multiplyDragByParticleSize { get; set; }
extern public bool multiplyDragByParticleVelocity { get; set; }
extern public Texture3D vectorField { get; set; }
public MinMaxCurve directionX { get => directionXBlittable; set => directionXBlittable = value; }
[NativeName("DirectionX")] private extern MinMaxCurveBlittable directionXBlittable { get; set; }
public MinMaxCurve directionY { get => directionYBlittable; set => directionYBlittable = value; }
[NativeName("DirectionY")] private extern MinMaxCurveBlittable directionYBlittable { get; set; }
public MinMaxCurve directionZ { get => directionZBlittable; set => directionZBlittable = value; }
[NativeName("DirectionZ")] private extern MinMaxCurveBlittable directionZBlittable { get; set; }
public MinMaxCurve gravity { get => gravityBlittable; set => gravityBlittable = value; }
[NativeName("Gravity")] private extern MinMaxCurveBlittable gravityBlittable { get; set; }
public MinMaxCurve rotationSpeed { get => rotationSpeedBlittable; set => rotationSpeedBlittable = value; }
[NativeName("RotationSpeed")] private extern MinMaxCurveBlittable rotationSpeedBlittable { get; set; }
public MinMaxCurve rotationAttraction { get => rotationAttractionBlittable; set => rotationAttractionBlittable = value; }
[NativeName("RotationAttraction")] private extern MinMaxCurveBlittable rotationAttractionBlittable { get; set; }
public MinMaxCurve drag { get => dragBlittable; set => dragBlittable = value; }
[NativeName("Drag")] private extern MinMaxCurveBlittable dragBlittable { get; set; }
public MinMaxCurve vectorFieldSpeed { get => vectorFieldSpeedBlittable; set => vectorFieldSpeedBlittable = value; }
[NativeName("VectorFieldSpeed")] private extern MinMaxCurveBlittable vectorFieldSpeedBlittable { get; set; }
public MinMaxCurve vectorFieldAttraction { get => vectorFieldAttractionBlittable; set => vectorFieldAttractionBlittable = value; }
[NativeName("VectorFieldAttraction")] private extern MinMaxCurveBlittable vectorFieldAttractionBlittable { get; set; }
[StaticAccessor("GetParticleSystemForceFieldManager()", StaticAccessorType.Dot)]
[NativeMethod("GetForceFields")]
extern public static ParticleSystemForceField[] FindAll();
}
}
| UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystemForceField.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystemForceField.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1211
} | 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;
using System.Linq;
namespace UnityEditor
{
internal class InitialModuleUI : ModuleUI
{
public SerializedProperty m_LengthInSec;
public SerializedProperty m_Looping;
public SerializedProperty m_Prewarm;
public SerializedMinMaxCurve m_StartDelay;
public SerializedProperty m_PlayOnAwake;
public SerializedProperty m_SimulationSpace;
public SerializedProperty m_CustomSimulationSpace;
public SerializedProperty m_SimulationSpeed;
public SerializedProperty m_UseUnscaledTime;
public SerializedProperty m_ScalingMode;
public SerializedMinMaxCurve m_LifeTime;
public SerializedMinMaxCurve m_Speed;
public SerializedMinMaxGradient m_Color;
public SerializedProperty m_Size3D;
public SerializedMinMaxCurve m_SizeX;
public SerializedMinMaxCurve m_SizeY;
public SerializedMinMaxCurve m_SizeZ;
public SerializedProperty m_Rotation3D;
public SerializedMinMaxCurve m_RotationX;
public SerializedMinMaxCurve m_RotationY;
public SerializedMinMaxCurve m_RotationZ;
public SerializedProperty m_RandomizeRotationDirection;
public SerializedProperty m_GravitySource;
public SerializedMinMaxCurve m_GravityModifier;
public SerializedProperty m_EmitterVelocity;
public SerializedProperty m_EmitterVelocityMode;
public SerializedProperty m_MaxNumParticles;
public SerializedProperty m_AutoRandomSeed;
public SerializedProperty m_RandomSeed;
public SerializedProperty m_StopAction;
public SerializedProperty m_CullingMode;
public SerializedProperty m_RingBufferMode;
public SerializedProperty m_RingBufferLoopRange;
class Texts
{
public GUIContent duration = EditorGUIUtility.TrTextContent("Duration", "The length of time the Particle System is emitting particles. If the system is looping, this indicates the length of one cycle.");
public GUIContent looping = EditorGUIUtility.TrTextContent("Looping", "If true, the emission cycle will repeat after the duration.");
public GUIContent prewarm = EditorGUIUtility.TrTextContent("Prewarm", "When played, a prewarmed system will be in a state as if it had emitted one loop cycle. Can only be used if the system is looping.");
public GUIContent startDelay = EditorGUIUtility.TrTextContent("Start Delay", "Delay in seconds that this Particle System will wait before emitting particles. Cannot be used together with a prewarmed looping system.");
public GUIContent maxParticles = EditorGUIUtility.TrTextContent("Max Particles", "The number of particles in the system will be limited by this number. Emission will be temporarily halted if this is reached.");
public GUIContent lifetime = EditorGUIUtility.TrTextContent("Start Lifetime", "Start lifetime in seconds, particle will die when its lifetime reaches 0.");
public GUIContent speed = EditorGUIUtility.TrTextContent("Start Speed", "The start speed of particles, applied in the starting direction.");
public GUIContent color = EditorGUIUtility.TrTextContent("Start Color", "The start color of particles.");
public GUIContent size3D = EditorGUIUtility.TrTextContent("3D Start Size", "If enabled, you can control the size separately for each axis.");
public GUIContent size = EditorGUIUtility.TrTextContent("Start Size", "The start size of particles.");
public GUIContent rotation3D = EditorGUIUtility.TrTextContent("3D Start Rotation", "If enabled, you can control the rotation separately for each axis.");
public GUIContent rotation = EditorGUIUtility.TrTextContent("Start Rotation", "The start rotation of particles in degrees.");
public GUIContent randomizeRotationDirection = EditorGUIUtility.TrTextContent("Flip Rotation", "Cause some particles to spin in the opposite direction. (Set between 0 and 1, where a higher value causes more to flip)");
public GUIContent autoplay = EditorGUIUtility.TrTextContent("Play On Awake*", "If enabled, the system will start playing automatically. Note that this setting is shared between all Particle Systems in the current particle effect.");
public GUIContent gravitySource = EditorGUIUtility.TrTextContent("Gravity Source", "Use 2D or 3D physics gravity");
public GUIContent gravity = EditorGUIUtility.TrTextContent("Gravity Modifier", "Scales the gravity defined in Physics Manager");
public GUIContent scalingMode = EditorGUIUtility.TrTextContent("Scaling Mode", "Use the combined scale from our entire hierarchy, just this local particle node, or only apply scale to the shape module.");
public GUIContent simulationSpace = EditorGUIUtility.TrTextContent("Simulation Space", "Makes particle positions simulate in world, local or custom space. In local space they stay relative to their own Transform, and in custom space they are relative to the custom Transform.");
public GUIContent customSimulationSpace = EditorGUIUtility.TrTextContent("Custom Simulation Space", "Makes particle positions simulate relative to a custom Transform component.");
public GUIContent simulationSpeed = EditorGUIUtility.TrTextContent("Simulation Speed", "Scale the playback speed of the Particle System.");
public GUIContent deltaTime = EditorGUIUtility.TrTextContent("Delta Time", "Use either the Delta Time or the Unscaled Delta Time. Useful for playing effects whilst paused.");
public GUIContent autoRandomSeed = EditorGUIUtility.TrTextContent("Auto Random Seed", "Simulate differently each time the effect is played.");
public GUIContent randomSeed = EditorGUIUtility.TrTextContent("Random Seed", "Randomize the look of the Particle System. Using the same seed will make the Particle System play identically each time. After changing this value, restart the Particle System to see the changes, or check the Resimulate box.");
public GUIContent emitterVelocity = EditorGUIUtility.TrTextContent("Custom Velocity", "An extra velocity value added to emitted particles when the Emitter Velocity Mode is Custom.");
public GUIContent emitterVelocityMode = EditorGUIUtility.TrTextContent("Emitter Velocity Mode", "How to determine the extra velocity imparted to particles by the Particle System. Use the Transform option to add the velocity calculated from the system's Transform. Use Rigidbody to add the velocity of the system's Rigidbody. Use Custom to add the velocity specified in the Custom Velocity property.");
public GUIContent stopAction = EditorGUIUtility.TrTextContent("Stop Action", "When the Particle System is stopped and all particles have died, should the GameObject automatically disable/destroy itself?");
public GUIContent cullingMode = EditorGUIUtility.TrTextContent("Culling Mode", "Choose whether to continue simulating the Particle System when offscreen. Catch-up mode pauses offscreen simulations but performs a large simulation step when they become visible, giving the appearance that they were never paused. Automatic uses Pause mode for looping systems, and AlwaysSimulate if not looping.");
public GUIContent ringBufferMode = EditorGUIUtility.TrTextContent("Ring Buffer Mode", "Rather than dying when their lifetime has elapsed, particles will remain alive until the Max Particles buffer is full, at which point new particles will replace the oldest.");
public GUIContent ringBufferLoopRange = EditorGUIUtility.TrTextContent("Loop Range", "Particle lifetimes may loop between a fade-in and fade-out time, in order to use curves for the entire time they are alive. Values are in the 0-1 range.");
public GUIContent prewarmingSubEmitterWarning = EditorGUIUtility.TrTextContent("Pre-warming a sub-emitter is not necessary and wastes resources. You only need to pre-warm the root Particle System component.");
public GUIContent x = EditorGUIUtility.TextContent("X");
public GUIContent y = EditorGUIUtility.TextContent("Y");
public GUIContent z = EditorGUIUtility.TextContent("Z");
public GUIContent[] simulationSpaces = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Local"),
EditorGUIUtility.TrTextContent("World"),
EditorGUIUtility.TrTextContent("Custom")
};
public GUIContent[] scalingModes = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Hierarchy"),
EditorGUIUtility.TrTextContent("Local"),
EditorGUIUtility.TrTextContent("Shape")
};
public GUIContent[] stopActions = new GUIContent[]
{
EditorGUIUtility.TrTextContent("None"),
EditorGUIUtility.TrTextContent("Disable"),
EditorGUIUtility.TrTextContent("Destroy"),
EditorGUIUtility.TrTextContent("Callback")
};
public GUIContent[] cullingModes = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Automatic"),
EditorGUIUtility.TrTextContent("Pause and Catch-up"),
EditorGUIUtility.TrTextContent("Pause"),
EditorGUIUtility.TrTextContent("Always Simulate")
};
public GUIContent[] ringBufferModes = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Disabled"),
EditorGUIUtility.TrTextContent("Pause Until Replaced"),
EditorGUIUtility.TrTextContent("Loop Until Replaced")
};
public GUIContent[] emitterVelocityModes = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Transform"),
EditorGUIUtility.TrTextContent("Rigidbody"),
EditorGUIUtility.TrTextContent("Custom")
};
public GUIContent[] gravitySources = new GUIContent[]
{
EditorGUIUtility.TrTextContent("3D Physics"),
EditorGUIUtility.TrTextContent("2D Physics")
};
}
private static Texts s_Texts;
public InitialModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName)
: base(owner, o, "InitialModule", displayName, VisibilityState.VisibleAndFoldedOut)
{
Init(); // Should always be initialized since it is used by other modules (see ShapeModule)
}
public override bool DrawHeader(Rect rect, GUIContent label)
{
// When displaying prefab overrides, the whole UI is disabled, but we still need to be able to expand the modules to see the settings - this doesn't modify the asset
bool wasEnabled = GUI.enabled;
GUI.enabled = true;
var toggleState = GUI.Toggle(rect, foldout, label, ParticleSystemStyles.Get().emitterHeaderStyle);
GUI.enabled = wasEnabled;
return toggleState;
}
public override float GetXAxisScalar()
{
return m_ParticleSystemUI.GetEmitterDuration();
}
protected override void Init()
{
// Already initialized?
if (m_LengthInSec != null)
return;
if (s_Texts == null)
s_Texts = new Texts();
// general emitter state
m_LengthInSec = GetProperty0("lengthInSec");
m_Looping = GetProperty0("looping");
m_Prewarm = GetProperty0("prewarm");
m_StartDelay = new SerializedMinMaxCurve(this, s_Texts.startDelay, "startDelay", false, true);
m_StartDelay.m_AllowCurves = false;
m_PlayOnAwake = GetProperty0("playOnAwake");
m_SimulationSpace = GetProperty0("moveWithTransform");
m_CustomSimulationSpace = GetProperty0("moveWithCustomTransform");
m_SimulationSpeed = GetProperty0("simulationSpeed");
m_UseUnscaledTime = GetProperty0("useUnscaledTime");
m_ScalingMode = GetProperty0("scalingMode");
m_EmitterVelocityMode = GetProperty0("emitterVelocityMode");
m_AutoRandomSeed = GetProperty0("autoRandomSeed");
m_RandomSeed = GetProperty0("randomSeed");
m_StopAction = GetProperty0("stopAction");
m_CullingMode = GetProperty0("cullingMode");
m_RingBufferMode = GetProperty0("ringBufferMode");
m_RingBufferLoopRange = GetProperty0("ringBufferLoopRange");
// module properties
m_EmitterVelocity = GetProperty("customEmitterVelocity");
m_LifeTime = new SerializedMinMaxCurve(this, s_Texts.lifetime, "startLifetime");
m_Speed = new SerializedMinMaxCurve(this, s_Texts.speed, "startSpeed", kUseSignedRange);
m_Color = new SerializedMinMaxGradient(this, "startColor");
m_Color.m_AllowRandomColor = true;
m_Size3D = GetProperty("size3D");
m_SizeX = new SerializedMinMaxCurve(this, s_Texts.x, "startSize");
m_SizeY = new SerializedMinMaxCurve(this, s_Texts.y, "startSizeY", false, false, m_Size3D.boolValue);
m_SizeZ = new SerializedMinMaxCurve(this, s_Texts.z, "startSizeZ", false, false, m_Size3D.boolValue);
m_Rotation3D = GetProperty("rotation3D");
m_RotationX = new SerializedMinMaxCurve(this, s_Texts.x, "startRotationX", kUseSignedRange, false, m_Rotation3D.boolValue);
m_RotationY = new SerializedMinMaxCurve(this, s_Texts.y, "startRotationY", kUseSignedRange, false, m_Rotation3D.boolValue);
m_RotationZ = new SerializedMinMaxCurve(this, s_Texts.z, "startRotation", kUseSignedRange);
m_RotationX.m_RemapValue = Mathf.Rad2Deg;
m_RotationY.m_RemapValue = Mathf.Rad2Deg;
m_RotationZ.m_RemapValue = Mathf.Rad2Deg;
m_RotationX.m_DefaultCurveScalar = Mathf.PI;
m_RotationY.m_DefaultCurveScalar = Mathf.PI;
m_RotationZ.m_DefaultCurveScalar = Mathf.PI;
m_RandomizeRotationDirection = GetProperty("randomizeRotationDirection");
m_GravitySource = GetProperty("gravitySource");
m_GravityModifier = new SerializedMinMaxCurve(this, s_Texts.gravity, "gravityModifier", kUseSignedRange);
m_MaxNumParticles = GetProperty("maxNumParticles");
}
override public void OnInspectorGUI(InitialModuleUI initial)
{
GUIFloat(s_Texts.duration, m_LengthInSec);
EditorGUI.BeginChangeCheck();
bool looping = GUIToggle(s_Texts.looping, m_Looping);
if (EditorGUI.EndChangeCheck() && looping)
{
foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems)
{
if (ps.time >= ps.main.duration)
ps.time = 0.0f;
}
}
bool allLooping = !m_Looping.hasMultipleDifferentValues && m_Looping.boolValue;
using (new EditorGUI.DisabledScope(!allLooping))
{
GUIToggle(s_Texts.prewarm, m_Prewarm);
}
if (m_ParticleSystemUI.m_ParticleEffectUI.m_SubEmitterSelected)
{
bool anyPrewarmed = m_Prewarm.hasMultipleDifferentValues || m_Prewarm.boolValue;
if (anyPrewarmed)
EditorGUILayout.HelpBox(s_Texts.prewarmingSubEmitterWarning.text, MessageType.Warning, true);
}
using (new EditorGUI.DisabledScope(m_Prewarm.boolValue && m_Looping.boolValue))
{
GUIMinMaxCurve(s_Texts.startDelay, m_StartDelay);
}
GUIMinMaxCurve(s_Texts.lifetime, m_LifeTime);
GUIMinMaxCurve(s_Texts.speed, m_Speed);
// Size
EditorGUI.BeginChangeCheck();
bool size3D = GUIToggle(s_Texts.size3D, m_Size3D);
if (EditorGUI.EndChangeCheck())
{
// Remove old curves from curve editor
if (!size3D)
{
m_SizeY.RemoveCurveFromEditor();
m_SizeZ.RemoveCurveFromEditor();
}
}
// Keep states in sync
if (!m_SizeX.stateHasMultipleDifferentValues)
{
m_SizeZ.SetMinMaxState(m_SizeX.state, size3D);
m_SizeY.SetMinMaxState(m_SizeX.state, size3D);
}
if (size3D)
{
m_SizeX.m_DisplayName = s_Texts.x;
GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_SizeX, s_Texts.y, m_SizeY, s_Texts.z, m_SizeZ, null);
}
else
{
m_SizeX.m_DisplayName = s_Texts.size;
GUIMinMaxCurve(s_Texts.size, m_SizeX);
}
// Rotation
EditorGUI.BeginChangeCheck();
bool rotation3D = GUIToggle(s_Texts.rotation3D, m_Rotation3D);
if (EditorGUI.EndChangeCheck())
{
// Remove old curves from curve editor
if (!rotation3D)
{
m_RotationX.RemoveCurveFromEditor();
m_RotationY.RemoveCurveFromEditor();
}
}
// Keep states in sync
if (!m_RotationZ.stateHasMultipleDifferentValues)
{
m_RotationX.SetMinMaxState(m_RotationZ.state, rotation3D);
m_RotationY.SetMinMaxState(m_RotationZ.state, rotation3D);
}
if (rotation3D)
{
m_RotationZ.m_DisplayName = s_Texts.z;
GUITripleMinMaxCurve(GUIContent.none, s_Texts.x, m_RotationX, s_Texts.y, m_RotationY, s_Texts.z, m_RotationZ, null);
}
else
{
m_RotationZ.m_DisplayName = s_Texts.rotation;
GUIMinMaxCurve(s_Texts.rotation, m_RotationZ);
}
GUIFloat(s_Texts.randomizeRotationDirection, m_RandomizeRotationDirection);
GUIMinMaxGradient(s_Texts.color, m_Color, false);
GUIPopup(s_Texts.gravitySource, m_GravitySource, s_Texts.gravitySources);
GUIMinMaxCurve(s_Texts.gravity, m_GravityModifier);
int space = GUIPopup(s_Texts.simulationSpace, m_SimulationSpace, s_Texts.simulationSpaces);
if (space == 2 && m_CustomSimulationSpace != null)
GUIObject(s_Texts.customSimulationSpace, m_CustomSimulationSpace);
GUIFloat(s_Texts.simulationSpeed, m_SimulationSpeed);
GUIBoolAsPopup(s_Texts.deltaTime, m_UseUnscaledTime, new string[] { "Scaled", "Unscaled" });
GUIPopup(s_Texts.scalingMode, m_ScalingMode, s_Texts.scalingModes);
EditorGUI.BeginChangeCheck();
bool newPlayOnAwake = GUIToggle(s_Texts.autoplay, m_PlayOnAwake);
if (EditorGUI.EndChangeCheck())
{
m_ParticleSystemUI.m_ParticleEffectUI.PlayOnAwakeChanged(newPlayOnAwake);
}
GUIPopup(s_Texts.emitterVelocityMode, m_EmitterVelocityMode, s_Texts.emitterVelocityModes);
if (!m_EmitterVelocityMode.hasMultipleDifferentValues && m_EmitterVelocityMode.intValue == (int)ParticleSystemEmitterVelocityMode.Custom)
{
GUIVector3Field(s_Texts.emitterVelocity, m_EmitterVelocity);
}
GUIInt(s_Texts.maxParticles, m_MaxNumParticles);
bool autoRandomSeed = GUIToggle(s_Texts.autoRandomSeed, m_AutoRandomSeed);
if (!autoRandomSeed)
{
bool isInspectorView = m_ParticleSystemUI.m_ParticleEffectUI.m_Owner is ParticleSystemInspector;
if (isInspectorView)
{
GUILayout.BeginHorizontal();
GUIInt(s_Texts.randomSeed, m_RandomSeed);
if (!m_ParticleSystemUI.multiEdit && GUILayout.Button("Reseed", EditorStyles.miniButton, GUILayout.Width(60)))
m_RandomSeed.intValue = (int)m_ParticleSystemUI.m_ParticleSystems[0].GenerateRandomSeed();
GUILayout.EndHorizontal();
}
else
{
GUIInt(s_Texts.randomSeed, m_RandomSeed);
if (!m_ParticleSystemUI.multiEdit && GUILayout.Button("Reseed", EditorStyles.miniButton))
m_RandomSeed.intValue = (int)m_ParticleSystemUI.m_ParticleSystems[0].GenerateRandomSeed();
}
}
GUIPopup(s_Texts.stopAction, m_StopAction, s_Texts.stopActions);
GUIPopup(s_Texts.cullingMode, m_CullingMode, s_Texts.cullingModes);
ParticleSystemRingBufferMode ringBufferMode = (ParticleSystemRingBufferMode)GUIPopup(s_Texts.ringBufferMode, m_RingBufferMode, s_Texts.ringBufferModes);
if (!m_RingBufferMode.hasMultipleDifferentValues && ringBufferMode == ParticleSystemRingBufferMode.LoopUntilReplaced)
{
EditorGUI.indentLevel++;
GUIMinMaxRange(s_Texts.ringBufferLoopRange, m_RingBufferLoopRange);
EditorGUI.indentLevel--;
}
}
override public void UpdateCullingSupportedString(ref string text)
{
foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems)
{
if (ps.main.simulationSpace != ParticleSystemSimulationSpace.Local)
{
text += "\nLocal space simulation is not being used.";
break;
}
}
foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems)
{
if (ps.main.gravityModifier.mode != ParticleSystemCurveMode.Constant)
{
text += "\nGravity modifier is not constant.";
break;
}
}
foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems)
{
if (ps.main.stopAction != ParticleSystemStopAction.None)
{
text += "\nStop Action is being used.";
break;
}
}
}
}
} // namespace UnityEditor
| UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/InitialModuleUI.cs/0 | {
"file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/InitialModuleUI.cs",
"repo_id": "UnityCsReference",
"token_count": 9755
} | 415 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEditorInternal;
using UnityEngine.U2D;
using UnityEditor.U2D;
namespace UnityEditor
{
class UVModuleUI : ModuleUI
{
SerializedProperty m_Mode;
SerializedProperty m_TimeMode;
SerializedProperty m_FPS;
SerializedMinMaxCurve m_FrameOverTime;
SerializedMinMaxCurve m_StartFrame;
SerializedProperty m_SpeedRange;
SerializedProperty m_TilesX;
SerializedProperty m_TilesY;
SerializedProperty m_AnimationType;
SerializedProperty m_RowMode;
SerializedProperty m_RowIndex;
SerializedProperty m_Sprites;
SerializedProperty m_Cycles;
SerializedProperty m_UVChannelMask;
class Texts
{
public GUIContent mode = EditorGUIUtility.TrTextContent("Mode", "Animation frames can either be specified on a regular grid texture, or as a list of Sprites.");
public GUIContent timeMode = EditorGUIUtility.TrTextContent("Time Mode", "Play frames either based on the lifetime of the particle, the speed of the particle, or at a constant FPS, regardless of particle lifetime.");
public GUIContent fps = EditorGUIUtility.TrTextContent("FPS", "Specify the Frames Per Second of the animation.");
public GUIContent frameOverTime = EditorGUIUtility.TrTextContent("Frame over Time", "Controls the uv animation frame of each particle over its lifetime. On the horizontal axis you will find the lifetime. On the vertical axis you will find the sheet index.");
public GUIContent startFrame = EditorGUIUtility.TrTextContent("Start Frame", "Phase the animation, so it starts on a frame other than 0.");
public GUIContent speedRange = EditorGUIUtility.TrTextContent("Speed Range", "Remaps speed in the defined range to a 0-1 value through the animation.");
public GUIContent tiles = EditorGUIUtility.TrTextContent("Tiles", "Defines the tiling of the texture.");
public GUIContent tilesX = EditorGUIUtility.TextContent("X");
public GUIContent tilesY = EditorGUIUtility.TextContent("Y");
public GUIContent animation = EditorGUIUtility.TrTextContent("Animation", "Specifies the animation type: Whole Sheet or Single Row. Whole Sheet will animate over the whole texture sheet from left to right, top to bottom. Single Row will animate a single row in the sheet from left to right.");
public GUIContent rowMode = EditorGUIUtility.TrTextContent("Row Mode", "Determine how the row is selected for each particle.");
public GUIContent row = EditorGUIUtility.TrTextContent("Row", "The row in the sheet which will be played.");
public GUIContent sprites = EditorGUIUtility.TrTextContent("Sprites", "The list of Sprites to be played.");
public GUIContent frame = EditorGUIUtility.TrTextContent("Frame", "The frame in the sheet which will be used.");
public GUIContent cycles = EditorGUIUtility.TrTextContent("Cycles", "Specifies how many times the animation will loop during the lifetime of the particle.");
public GUIContent uvChannelMask = EditorGUIUtility.TrTextContent("Affected UV Channels", "Specifies which UV channels will be animated.");
public GUIContent[] modes = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Grid"),
EditorGUIUtility.TrTextContent("Sprites")
};
public GUIContent[] timeModes = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Lifetime"),
EditorGUIUtility.TrTextContent("Speed"),
EditorGUIUtility.TrTextContent("FPS")
};
public GUIContent[] types = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Whole Sheet"),
EditorGUIUtility.TrTextContent("Single Row")
};
public GUIContent[] rowModes = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Custom"),
EditorGUIUtility.TrTextContent("Random"),
EditorGUIUtility.TrTextContent("Mesh Index")
};
}
private static Texts s_Texts;
public UVModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName)
: base(owner, o, "UVModule", displayName)
{
m_ToolTip = "Particle UV animation. This allows you to specify a texture sheet (a texture with multiple tiles/sub frames) and animate or randomize over it per particle.";
}
protected override void Init()
{
// Already initialized?
if (m_TilesX != null)
return;
if (s_Texts == null)
s_Texts = new Texts();
m_Mode = GetProperty("mode");
m_TimeMode = GetProperty("timeMode");
m_FPS = GetProperty("fps");
m_FrameOverTime = new SerializedMinMaxCurve(this, s_Texts.frameOverTime, "frameOverTime");
m_StartFrame = new SerializedMinMaxCurve(this, s_Texts.startFrame, "startFrame");
m_StartFrame.m_AllowCurves = false;
m_SpeedRange = GetProperty("speedRange");
m_TilesX = GetProperty("tilesX");
m_TilesY = GetProperty("tilesY");
m_AnimationType = GetProperty("animationType");
m_RowMode = GetProperty("rowMode");
m_RowIndex = GetProperty("rowIndex");
m_Sprites = GetProperty("sprites");
m_Cycles = GetProperty("cycles");
m_UVChannelMask = GetProperty("uvChannelMask");
}
override public void OnInspectorGUI(InitialModuleUI initial)
{
int mode = GUIPopup(s_Texts.mode, m_Mode, s_Texts.modes);
if (!m_Mode.hasMultipleDifferentValues)
{
if (mode == (int)ParticleSystemAnimationMode.Grid)
{
GUIIntDraggableX2(s_Texts.tiles, s_Texts.tilesX, m_TilesX, s_Texts.tilesY, m_TilesY);
int type = GUIPopup(s_Texts.animation, m_AnimationType, s_Texts.types);
if (type == (int)ParticleSystemAnimationType.SingleRow)
{
GUIPopup(s_Texts.rowMode, m_RowMode, s_Texts.rowModes);
if (!m_RowMode.hasMultipleDifferentValues && m_RowMode.intValue == (int)ParticleSystemAnimationRowMode.Custom)
GUIInt(s_Texts.row, m_RowIndex);
m_FrameOverTime.m_RemapValue = (float)(m_TilesX.intValue);
m_StartFrame.m_RemapValue = (float)(m_TilesX.intValue);
}
else
{
m_FrameOverTime.m_RemapValue = (float)(m_TilesX.intValue * m_TilesY.intValue);
m_StartFrame.m_RemapValue = (float)(m_TilesX.intValue * m_TilesY.intValue);
}
}
else
{
DoListOfSpritesGUI();
ValidateSpriteList();
m_FrameOverTime.m_RemapValue = (float)(m_Sprites.arraySize);
m_StartFrame.m_RemapValue = (float)(m_Sprites.arraySize);
}
}
ParticleSystemAnimationTimeMode timeMode = (ParticleSystemAnimationTimeMode)GUIPopup(s_Texts.timeMode, m_TimeMode, s_Texts.timeModes);
if (!m_TimeMode.hasMultipleDifferentValues)
{
if (timeMode == ParticleSystemAnimationTimeMode.FPS)
{
GUIFloat(s_Texts.fps, m_FPS);
foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems)
{
if (ps.main.startLifetimeMultiplier == Mathf.Infinity)
{
EditorGUILayout.HelpBox("FPS mode does not work when using infinite particle lifetimes.", MessageType.Error, true);
break;
}
}
}
else if (timeMode == ParticleSystemAnimationTimeMode.Speed)
{
GUIMinMaxRange(s_Texts.speedRange, m_SpeedRange);
}
else
{
GUIMinMaxCurve(s_Texts.frameOverTime, m_FrameOverTime);
}
}
GUIMinMaxCurve(s_Texts.startFrame, m_StartFrame);
if (!m_TimeMode.hasMultipleDifferentValues && timeMode != ParticleSystemAnimationTimeMode.FPS)
GUIFloat(s_Texts.cycles, m_Cycles);
GUIEnumMaskUVChannelFlags(s_Texts.uvChannelMask, m_UVChannelMask);
}
private void DoListOfSpritesGUI()
{
if (m_Sprites.hasMultipleDifferentValues)
{
EditorGUILayout.HelpBox("Sprite editing is only available when all selected Particle Systems contain the same number of Sprites.", MessageType.Info, true);
return;
}
// Support multi edit of large arrays (case 1222515)
if (serializedObject.isEditingMultipleObjects && serializedObject.maxArraySizeForMultiEditing < m_Sprites.minArraySize)
{
// Increase maxArraySizeForMultiEditing so that arraySize and GetArrayElementAtIndex will work
serializedObject.maxArraySizeForMultiEditing = m_Sprites.minArraySize;
}
for (int i = 0; i < m_Sprites.arraySize; i++)
{
GUILayout.BeginHorizontal();
SerializedProperty spriteData = m_Sprites.GetArrayElementAtIndex(i);
SerializedProperty sprite = spriteData.FindPropertyRelative("sprite");
GUIObject(new GUIContent(" "), sprite, typeof(Sprite));
// add plus button to first element
if (i == 0)
{
if (GUILayout.Button(s_AddItem, "OL Plus", GUILayout.Width(16)))
{
m_Sprites.InsertArrayElementAtIndex(m_Sprites.arraySize);
SerializedProperty newSpriteData = m_Sprites.GetArrayElementAtIndex(m_Sprites.arraySize - 1);
SerializedProperty newSprite = newSpriteData.FindPropertyRelative("sprite");
newSprite.objectReferenceValue = null;
}
}
// add minus button to all other elements
else
{
if (GUILayout.Button(s_RemoveItem, "OL Minus", GUILayout.Width(16)))
m_Sprites.DeleteArrayElementAtIndex(i);
}
GUILayout.EndHorizontal();
}
}
// Ensure sprite mesh is a rect (we don't support non-rectangular sprites)
internal static bool ValidateSpriteUVs(Vector2[] uvs)
{
if (uvs.Length != 4)
return false;
Vector2Int secondUnique = new Vector2Int(-1, -1);
for (int j = 1; j < uvs.Length; j++)
{
for (int k = 0; k < 2; k++)
{
if (!Mathf.Approximately(uvs[j][k], uvs[0][k]))
{
if (secondUnique[k] == -1)
secondUnique[k] = j;
else if (!Mathf.Approximately(uvs[j][k], uvs[secondUnique[k]][k]))
return false;
}
}
}
return true;
}
private void ValidateSpriteList()
{
if (m_Sprites.hasMultipleDifferentValues)
return;
if (m_Sprites.arraySize <= 1)
return;
Texture texture = null;
for (int i = 0; i < m_Sprites.arraySize; i++)
{
SerializedProperty spriteData = m_Sprites.GetArrayElementAtIndex(i);
SerializedProperty prop = spriteData.FindPropertyRelative("sprite");
Sprite sprite = prop.objectReferenceValue as Sprite;
if (sprite != null)
{
// Find the sprite atlas asset for this texture, if it has one
var spriteAtlas = SpriteEditorExtension.GetActiveAtlas(sprite);
if (spriteAtlas != null)
{
if (spriteAtlas.GetPackingSettings().enableTightPacking)
{
EditorGUILayout.HelpBox("Tightly packed Sprite Atlases are not supported.", MessageType.Error, true);
break;
}
}
// Ensure sprite mesh is a rect (we don't support non-rectangular sprites)
bool uvsOk = ValidateSpriteUVs(sprite.uv);
if (!uvsOk)
{
EditorGUILayout.HelpBox("Sprites must use rectangles. Change the Atlas Mesh Type to Full Rect instead of Tight, if applicable.", MessageType.Error, true);
break;
}
if (texture == null)
{
texture = sprite.GetTextureForPlayMode();
}
else if (texture != sprite.GetTextureForPlayMode())
{
if (EditorSettings.spritePackerMode == SpritePackerMode.Disabled)
EditorGUILayout.HelpBox("To use multiple sprites, enable the Sprite Packer Mode in the Editor Project Settings, and create a Texture Atlas.", MessageType.Error, true);
else if (EditorSettings.spritePackerMode == SpritePackerMode.SpriteAtlasV2 || EditorSettings.spritePackerMode == SpritePackerMode.AlwaysOnAtlas || EditorSettings.spritePackerMode == SpritePackerMode.BuildTimeOnlyAtlas)
EditorGUILayout.HelpBox("All Sprites must share the same Texture Atlas. Also check that all your sprites fit onto 1 texture of the Sprite Atlas.", MessageType.Error, true);
else
EditorGUILayout.HelpBox("All Sprites must share the same texture. Either pack all Sprites into one Texture by setting the Packing Tag, or use a Multiple Mode Sprite.", MessageType.Error, true);
break;
}
else if (sprite.border != Vector4.zero)
{
EditorGUILayout.HelpBox("Sprite borders are not supported. They will be ignored.", MessageType.Warning, true);
break;
}
}
}
}
}
} // namespace UnityEditor
| UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/UVModuleUI.cs/0 | {
"file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/UVModuleUI.cs",
"repo_id": "UnityCsReference",
"token_count": 7237
} | 416 |
// 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.ComponentModel;
namespace UnityEngine
{
// The [[ConfigurableJoint]] attempts to attain position / velocity targets based on this flag
[Flags]
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("JointDriveMode is no longer supported")]
public enum JointDriveMode
{
[Obsolete("JointDriveMode.None is no longer supported")]
// Don't apply any forces to reach the target
None = 0,
[Obsolete("JointDriveMode.Position is no longer supported")]
// Try to reach the specified target position
Position = 1,
[Obsolete("JointDriveMode.Velocity is no longer supported")]
// Try to reach the specified target velocity
Velocity = 2,
[Obsolete("JointDriveMode.PositionAndvelocity is no longer supported")]
// Try to reach the specified target position and velocity
PositionAndVelocity = 3
}
public partial struct JointDrive
{
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("JointDriveMode is obsolete")]
public JointDriveMode mode { get { return JointDriveMode.None; } set { } }
}
}
| UnityCsReference/Modules/Physics/Managed/JointConstraints.deprecated.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics/Managed/JointConstraints.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 458
} | 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 UnityEngine.Bindings;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace UnityEngine.LowLevelPhysics
{
[StructLayout(LayoutKind.Sequential)]
public struct ImmediateTransform
{
private Quaternion m_Rotation;
private Vector3 m_Position;
public Quaternion Rotation { get { return m_Rotation; } set { m_Rotation = value; } }
public Vector3 Position { get { return m_Position; } set { m_Position = value; } }
}
[StructLayout(LayoutKind.Sequential)]
public struct ImmediateContact
{
private Vector3 m_Normal;
private float m_Separation;
private Vector3 m_Point;
private float m_MaxImpulse;
private Vector3 m_TargetVel;
private float m_StaticFriction;
private byte m_MaterialFlags;
private byte m_Pad;
private ushort m_InternalUse;
private uint m_InternalFaceIndex1;
private float m_DynamicFriction;
private float m_Restitution;
public Vector3 Normal { get { return m_Normal; } set { m_Normal = value; } }
public float Separation { get { return m_Separation; } set { m_Separation = value; } }
public Vector3 Point { get { return m_Point; } set { m_Point = value; } }
}
[NativeHeader("Modules/Physics/ImmediatePhysics.h")]
public static class ImmediatePhysics
{
[FreeFunction("Physics::Immediate::GenerateContacts", isThreadSafe: true)]
private static unsafe extern int GenerateContacts_Native(void* geom1, void* geom2, void* xform1, void* xform2, int numPairs, void* contacts, int contactArrayLength, void* sizes, int sizesArrayLength, float contactDistance);
public unsafe static int GenerateContacts(NativeArray<GeometryHolder>.ReadOnly geom1, NativeArray<GeometryHolder>.ReadOnly geom2,
NativeArray<ImmediateTransform>.ReadOnly xform1, NativeArray<ImmediateTransform>.ReadOnly xform2, int pairCount,
NativeArray<ImmediateContact> outContacts, NativeArray<int> outContactCounts, float contactDistance = 0.01f)
{
if (geom1.Length < pairCount ||
geom2.Length < pairCount ||
xform1.Length < pairCount ||
xform2.Length < pairCount)
throw new ArgumentException("Provided geometry or transform arrays are not large enough to fit the count of pairs.");
if (pairCount > outContactCounts.Length)
throw new ArgumentException("The output contact counts array is not big enough. The size of the array needs to match or exceed the amount of pairs.");
if (contactDistance <= 0)
throw new ArgumentException("Contact distance must be positive and not equal to zero.");
return GenerateContacts_Native(
geom1.GetUnsafeReadOnlyPtr(),
geom2.GetUnsafeReadOnlyPtr(),
xform1.GetUnsafeReadOnlyPtr(),
xform2.GetUnsafeReadOnlyPtr(),
pairCount,
outContacts.GetUnsafePtr(),
outContacts.Length,
outContactCounts.GetUnsafePtr(),
outContactCounts.Length,
contactDistance);
}
}
}
| UnityCsReference/Modules/Physics/ScriptBindings/ImmediatePhysics.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics/ScriptBindings/ImmediatePhysics.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1361
} | 418 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Bindings;
using UnityEngine.Internal;
namespace UnityEngine
{
public enum RigidbodyConstraints
{
None = 0,
FreezePositionX = 1 << 1,
FreezePositionY = 1 << 2,
FreezePositionZ = 1 << 3,
FreezeRotationX = 1 << 4,
FreezeRotationY = 1 << 5,
FreezeRotationZ = 1 << 6,
FreezePosition = FreezePositionX | FreezePositionY | FreezePositionZ,
FreezeRotation = FreezeRotationX | FreezeRotationY | FreezeRotationZ,
FreezeAll = FreezePosition | FreezeRotation
}
public enum RigidbodyInterpolation
{
None = 0,
Interpolate = 1,
Extrapolate = 2
}
[RequireComponent(typeof(Transform))]
[NativeHeader("Modules/Physics/Rigidbody.h")]
public partial class Rigidbody : Component
{
extern public Vector3 linearVelocity { get; set; }
extern public Vector3 angularVelocity { get; set; }
extern public float linearDamping { get; set; }
extern public float angularDamping { get; set; }
extern public float mass { get; set; }
extern public void SetDensity(float density);
extern public bool useGravity { get; set; }
extern public float maxDepenetrationVelocity { get; set; }
extern public bool isKinematic { get; set; }
public bool freezeRotation
{
get => constraints.HasFlag(RigidbodyConstraints.FreezeRotation);
set
{
if (value)
constraints |= RigidbodyConstraints.FreezeRotation;
else
constraints &= RigidbodyConstraints.FreezePosition;
}
}
extern public RigidbodyConstraints constraints { get; set; }
extern public CollisionDetectionMode collisionDetectionMode { 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 Quaternion inertiaTensorRotation { get; set; }
extern public Vector3 inertiaTensor { get; set; }
extern internal Matrix4x4 worldInertiaTensorMatrix { get; }
extern public bool detectCollisions { get; set; }
extern public Vector3 position { get; set; }
extern public Quaternion rotation { get; set; }
extern public RigidbodyInterpolation interpolation { get; set; }
extern public int solverIterations { get; set; }
extern public float sleepThreshold { get; set; }
extern public float maxAngularVelocity { get; set; }
extern public float maxLinearVelocity { get; set; }
extern public void MovePosition(Vector3 position);
extern public void MoveRotation(Quaternion rot);
extern public void Move(Vector3 position, Quaternion rotation);
extern public void Sleep();
extern public bool IsSleeping();
extern public void WakeUp();
extern public void ResetCenterOfMass();
extern public void ResetInertiaTensor();
extern public Vector3 GetRelativePointVelocity(Vector3 relativePoint);
extern public Vector3 GetPointVelocity(Vector3 worldPoint);
extern public int solverVelocityIterations { get; set; }
extern public void PublishTransform();
extern public LayerMask excludeLayers { get; set; }
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);
}
public void AddForce(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) { AddForce(new Vector3(x, y, z), mode); }
[ExcludeFromDocs]
public void AddForce(float x, float y, float z)
{
AddForce(new Vector3(x, y, z), ForceMode.Force);
}
extern public void AddRelativeForce(Vector3 force, [DefaultValue("ForceMode.Force")] ForceMode mode);
[ExcludeFromDocs]
public void AddRelativeForce(Vector3 force)
{
AddRelativeForce(force, ForceMode.Force);
}
public void AddRelativeForce(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) { AddRelativeForce(new Vector3(x, y, z), mode); }
[ExcludeFromDocs]
public void AddRelativeForce(float x, float y, float z)
{
AddRelativeForce(new Vector3(x, y, z), ForceMode.Force);
}
extern public void AddTorque(Vector3 torque, [DefaultValue("ForceMode.Force")] ForceMode mode);
[ExcludeFromDocs]
public void AddTorque(Vector3 torque)
{
AddTorque(torque, ForceMode.Force);
}
public void AddTorque(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) { AddTorque(new Vector3(x, y, z), mode); }
[ExcludeFromDocs]
public void AddTorque(float x, float y, float z)
{
AddTorque(new Vector3(x, y, z), ForceMode.Force);
}
extern public void AddRelativeTorque(Vector3 torque, [DefaultValue("ForceMode.Force")] ForceMode mode);
[ExcludeFromDocs]
public void AddRelativeTorque(Vector3 torque)
{
AddRelativeTorque(torque, ForceMode.Force);
}
public void AddRelativeTorque(float x, float y, float z, [DefaultValue("ForceMode.Force")] ForceMode mode) { AddRelativeTorque(new Vector3(x, y, z), mode); }
[ExcludeFromDocs]
public void AddRelativeTorque(float x, float y, float z)
{
AddRelativeTorque(x, y, z, 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 void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, [DefaultValue("0.0f")] float upwardsModifier, [DefaultValue("ForceMode.Force)")] ForceMode mode);
[ExcludeFromDocs]
public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius, float upwardsModifier)
{
AddExplosionForce(explosionForce, explosionPosition, explosionRadius, upwardsModifier, ForceMode.Force);
}
[ExcludeFromDocs]
public void AddExplosionForce(float explosionForce, Vector3 explosionPosition, float explosionRadius)
{
AddExplosionForce(explosionForce, explosionPosition, explosionRadius, 0.0f, ForceMode.Force);
}
[NativeName("ClosestPointOnBounds")]
extern private void Internal_ClosestPointOnBounds(Vector3 point, ref Vector3 outPos, ref float distance);
public Vector3 ClosestPointOnBounds(Vector3 position)
{
float dist = 0f;
Vector3 outpos = Vector3.zero;
Internal_ClosestPointOnBounds(position, ref outpos, ref dist);
return outpos;
}
extern private RaycastHit SweepTest(Vector3 direction, float maxDistance, QueryTriggerInteraction queryTriggerInteraction, ref bool hasHit);
public bool SweepTest(Vector3 direction, out RaycastHit hitInfo, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction)
{
float dirLength = direction.magnitude;
if (dirLength > float.Epsilon)
{
Vector3 normalizedDirection = direction / dirLength;
bool hasHit = false;
hitInfo = SweepTest(normalizedDirection, maxDistance, queryTriggerInteraction, ref hasHit);
return hasHit;
}
else
{
hitInfo = new RaycastHit();
return false;
}
}
[ExcludeFromDocs]
public bool SweepTest(Vector3 direction, out RaycastHit hitInfo, float maxDistance)
{
return SweepTest(direction, out hitInfo, maxDistance, QueryTriggerInteraction.UseGlobal);
}
[ExcludeFromDocs]
public bool SweepTest(Vector3 direction, out RaycastHit hitInfo)
{
return SweepTest(direction, out hitInfo, Mathf.Infinity, QueryTriggerInteraction.UseGlobal);
}
[NativeName("SweepTestAll")]
extern private RaycastHit[] Internal_SweepTestAll(Vector3 direction, float maxDistance, QueryTriggerInteraction queryTriggerInteraction);
public RaycastHit[] SweepTestAll(Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction)
{
float dirLength = direction.magnitude;
if (dirLength > float.Epsilon)
{
Vector3 normalizedDirection = direction / dirLength;
return Internal_SweepTestAll(normalizedDirection, maxDistance, queryTriggerInteraction);
}
else
{
return new RaycastHit[0];
}
}
[ExcludeFromDocs]
public RaycastHit[] SweepTestAll(Vector3 direction, float maxDistance)
{
return SweepTestAll(direction, maxDistance, QueryTriggerInteraction.UseGlobal);
}
[ExcludeFromDocs]
public RaycastHit[] SweepTestAll(Vector3 direction)
{
return SweepTestAll(direction, Mathf.Infinity, QueryTriggerInteraction.UseGlobal);
}
}
}
| UnityCsReference/Modules/Physics/ScriptBindings/Rigidbody.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics/ScriptBindings/Rigidbody.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 4327
} | 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;
using UnityEditor.AnimatedValues;
namespace UnityEditor
{
[CustomEditor(typeof(EdgeCollider2D))]
[CanEditMultipleObjects]
class EdgeCollider2DEditor : Collider2DEditorBase
{
SerializedProperty m_EdgeRadius;
SerializedProperty m_Points;
SerializedProperty m_UseAdjacentStartPoint;
SerializedProperty m_UseAdjacentEndPoint;
SerializedProperty m_AdjacentStartPoint;
SerializedProperty m_AdjacentEndPoint;
AnimBool m_ShowAdjacentStartPoint;
AnimBool m_ShowAdjacentEndPoint;
public override void OnEnable()
{
base.OnEnable();
m_EdgeRadius = serializedObject.FindProperty("m_EdgeRadius");
m_Points = serializedObject.FindProperty("m_Points");
m_Points.isExpanded = false;
m_UseAdjacentStartPoint = serializedObject.FindProperty("m_UseAdjacentStartPoint");
m_UseAdjacentEndPoint = serializedObject.FindProperty("m_UseAdjacentEndPoint");
m_AdjacentStartPoint = serializedObject.FindProperty("m_AdjacentStartPoint");
m_AdjacentEndPoint = serializedObject.FindProperty("m_AdjacentEndPoint");
m_ShowAdjacentStartPoint = new AnimBool(m_UseAdjacentStartPoint.boolValue);
m_ShowAdjacentStartPoint.valueChanged.AddListener(Repaint);
m_ShowAdjacentEndPoint = new AnimBool(m_UseAdjacentEndPoint.boolValue);
m_ShowAdjacentEndPoint.valueChanged.AddListener(Repaint);
}
public override void OnInspectorGUI()
{
BeginEditColliderInspector();
GUILayout.Space(5);
base.OnInspectorGUI();
EditorGUILayout.PropertyField(m_EdgeRadius);
if (targets.Length == 1)
{
EditorGUI.BeginDisabledGroup(editingCollider);
EditorGUILayout.PropertyField(m_Points, true);
EditorGUI.EndDisabledGroup();
}
// Adjacent start point.
m_ShowAdjacentStartPoint.target = m_UseAdjacentStartPoint.boolValue;
EditorGUILayout.PropertyField(m_UseAdjacentStartPoint);
if (EditorGUILayout.BeginFadeGroup(m_ShowAdjacentStartPoint.faded))
{
EditorGUILayout.PropertyField(m_AdjacentStartPoint);
}
EditorGUILayout.EndFadeGroup();
// Adjacent end point.
m_ShowAdjacentEndPoint.target = m_UseAdjacentEndPoint.boolValue;
EditorGUILayout.PropertyField(m_UseAdjacentEndPoint);
if (EditorGUILayout.BeginFadeGroup(m_ShowAdjacentEndPoint.faded))
{
EditorGUILayout.PropertyField(m_AdjacentEndPoint);
}
EditorGUILayout.EndFadeGroup();
FinalizeInspectorGUI();
}
}
}
| UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EdgeCollider2DEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/EdgeCollider2DEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 1366
} | 420 |
// 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 UnityEngine;
namespace UnityEditor
{
[CustomEditor(typeof(HingeJoint2D))]
[CanEditMultipleObjects]
internal class HingeJoint2DEditor : AnchoredJoint2DEditor
{
private JointAngularLimitHandle2D m_AngularLimitHandle = new JointAngularLimitHandle2D();
public override void OnInspectorGUI()
{
serializedObject.Update();
using (new EditorGUI.DisabledScope(!targets.Any(x => (x as HingeJoint2D).gameObject.activeInHierarchy)))
{
EditorGUILayout.EditorToolbarForTarget(EditorGUIUtility.TrTempContent("Edit Angular Limits"), this);
GUILayout.Space(5);
}
base.OnInspectorGUI();
}
}
}
| UnityCsReference/Modules/Physics2DEditor/Managed/Joints/HingeJoint2DEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Joints/HingeJoint2DEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 379
} | 421 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.IMGUI.Controls;
using UnityEditor.EditorTools;
using UnityEngine;
namespace UnityEditor
{
[EditorTool("Articulation Body Joint Limit Tool", typeof(ArticulationBody))]
class ArticulationBodyJointLimitsTool : EditorTool
{
private const float k_CapScale = 0.12f;
private const float k_DashSize = 1f;
private const float k_DashAlpha = 0.8f;
private const float k_PointerThickness = 1.3f;
private JointAngularLimitHandle m_AngularLimitHandle = new JointAngularLimitHandle();
protected static class Styles
{
public static readonly GUIContent toolbarIcon = new GUIContent(
EditorGUIUtility.IconContent("JointAngularLimits").image,
L10n.Tr("Edit the joint angular limits of this Articulation Body"));
}
public override GUIContent toolbarIcon => Styles.toolbarIcon;
public Handles.CapFunction prismaticHandleDrawFunction { get; set; }
private void OnEnable()
{
prismaticHandleDrawFunction = PrismaticHandleDrawFunction;
}
public override void OnToolGUI(EditorWindow window)
{
foreach (var obj in targets)
{
ArticulationBody body = obj as ArticulationBody;
if (body == null)
continue;
EditorGUI.BeginChangeCheck();
DisplayJointLimits(body);
if (EditorGUI.EndChangeCheck())
{
body.WakeUp();
}
}
}
private void DisplayJointLimits(ArticulationBody body)
{
ArticulationBody parentBody = ArticulationBodyEditorCommon.FindEnabledParentArticulationBody(body);
// Consider that the anchors are only actually matched when in play mode.
// So, if it's not play mode, we need to do that manually for the gizmos to be placed correctly.
Vector3 anchorPosition;
Quaternion anchorRotation;
if (body.matchAnchors & !EditorApplication.isPlaying)
{
anchorPosition = body.transform.TransformPoint(body.anchorPosition);
anchorRotation = body.transform.rotation * body.anchorRotation;
}
else
{
anchorPosition = parentBody.transform.TransformPoint(body.parentAnchorPosition);
anchorRotation = parentBody.transform.rotation * body.parentAnchorRotation;
}
Matrix4x4 parentAnchorSpace = Matrix4x4.TRS(anchorPosition, anchorRotation, Vector3.one);
// Show locked gizmo when root body or Fixed joint body
if (body.isRoot || body.jointType == ArticulationJointType.FixedJoint)
{
m_AngularLimitHandle.xMotion = (ConfigurableJointMotion)ArticulationDofLock.LockedMotion;
m_AngularLimitHandle.yMotion = (ConfigurableJointMotion)ArticulationDofLock.LockedMotion;
m_AngularLimitHandle.zMotion = (ConfigurableJointMotion)ArticulationDofLock.LockedMotion;
ShowSphericalLimits(m_AngularLimitHandle, body, parentAnchorSpace);
return;
}
if (body.jointType == ArticulationJointType.PrismaticJoint)
{
ShowPrismaticLimits(body, parentAnchorSpace, anchorPosition, anchorRotation);
return;
}
if (body.jointType == ArticulationJointType.RevoluteJoint)
{
// For the purposes of drawing Revolute limits, treat Z and Y motion as locked
m_AngularLimitHandle.xMotion = (ConfigurableJointMotion)body.twistLock;
m_AngularLimitHandle.yMotion = (ConfigurableJointMotion)ArticulationDofLock.LockedMotion;
m_AngularLimitHandle.zMotion = (ConfigurableJointMotion)ArticulationDofLock.LockedMotion;
ShowRevoluteLimits(m_AngularLimitHandle, body, parentAnchorSpace);
return;
}
if (body.jointType == ArticulationJointType.SphericalJoint)
{
m_AngularLimitHandle.xMotion = (ConfigurableJointMotion)body.twistLock;
m_AngularLimitHandle.yMotion = (ConfigurableJointMotion)body.swingYLock;
m_AngularLimitHandle.zMotion = (ConfigurableJointMotion)body.swingZLock;
ShowSphericalLimits(m_AngularLimitHandle, body, parentAnchorSpace);
}
}
private void ShowPrismaticLimits(ArticulationBody body, Matrix4x4 parentAnchorSpace, Vector3 anchorPosition, Quaternion anchorRotation)
{
Vector3 primaryAxis = Vector3.zero;
// compute the primary axis of the prismatic
ArticulationDrive drive = body.xDrive;
if (body.linearLockX != ArticulationDofLock.LockedMotion)
{
primaryAxis = Vector3.right;
drive = body.xDrive;
}
else if (body.linearLockY != ArticulationDofLock.LockedMotion)
{
primaryAxis = Vector3.up;
drive = body.yDrive;
}
else if (body.linearLockZ != ArticulationDofLock.LockedMotion)
{
primaryAxis = Vector3.forward;
drive = body.zDrive;
}
DisplayPrismaticJointPointer(parentAnchorSpace, body.jointPosition[0], primaryAxis);
if (body.linearLockX == ArticulationDofLock.FreeMotion || body.linearLockY == ArticulationDofLock.FreeMotion || body.linearLockZ == ArticulationDofLock.FreeMotion)
{
DrawFreePrismatic(body, primaryAxis, anchorPosition, anchorRotation);
return;
}
DrawLimitedPrismatic(body, primaryAxis, drive, parentAnchorSpace);
}
private void DrawFreePrismatic(ArticulationBody body, Vector3 primaryAxis, Vector3 anchorPosition, Quaternion anchorRotation)
{
Vector3 lp, up;
float paddingAmount = 15;
Handles.color = new Color(1f, 1f, 1f, k_DashAlpha);
Vector3 primaryAxisRotated = anchorRotation * primaryAxis;
Vector3 padding = primaryAxisRotated * paddingAmount;
// If not in play mode and match anchors is off, use the anchor position
if (!body.matchAnchors & !EditorApplication.isPlaying)
{
lp = anchorPosition - padding;
up = anchorPosition + padding;
}
// If in play mode or match anchors is on, calculate the correct position
else
{
Vector3 bodyPosOnPrimaryAxis = Vector3.Project(body.transform.position - anchorPosition, primaryAxisRotated);
lp = anchorPosition + bodyPosOnPrimaryAxis - padding;
up = anchorPosition + bodyPosOnPrimaryAxis + padding;
}
Handles.DrawDottedLine(lp, up, k_DashSize);
}
private void DrawLimitedPrismatic(ArticulationBody body, Vector3 primaryAxis, ArticulationDrive drive, Matrix4x4 parentAnchorSpace)
{
using (new Handles.DrawingScope(parentAnchorSpace))
{
Vector3 lowerPoint = primaryAxis * drive.lowerLimit;
Vector3 upperPoint = primaryAxis * drive.upperLimit;
Handles.DrawDottedLine(lowerPoint, upperPoint, k_DashSize);
int idLower = GUIUtility.GetControlID(Handles.s_SliderHash, FocusType.Passive);
int idUpper = GUIUtility.GetControlID(Handles.s_SliderHash, FocusType.Passive);
EditorGUI.BeginChangeCheck();
{
Handles.color = Handles.xAxisColor;
lowerPoint = Handles.Slider(idLower, lowerPoint, primaryAxis, k_CapScale, prismaticHandleDrawFunction, 0);
Handles.color = Handles.yAxisColor;
upperPoint = Handles.Slider(idUpper, upperPoint, primaryAxis, k_CapScale, prismaticHandleDrawFunction, 0);
}
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changing Articulation body parent anchor prismatic limits");
float newLowerLimit = drive.lowerLimit;
float newUpperLimit = drive.upperLimit;
// Disallow moving Lower limit past Upper limit and vice versa, based on which handle is being held down
if (GUIUtility.hotControl == idLower)
{
float directionLower = Mathf.Sign(lowerPoint.x + lowerPoint.y + lowerPoint.z);
newLowerLimit = lowerPoint.magnitude * directionLower;
if (newLowerLimit > drive.upperLimit) newLowerLimit = drive.upperLimit;
}
else if (GUIUtility.hotControl == idUpper)
{
float directionUpper = Mathf.Sign(upperPoint.x + upperPoint.y + upperPoint.z);
newUpperLimit = upperPoint.magnitude * directionUpper;
if (newUpperLimit < drive.lowerLimit) newUpperLimit = drive.lowerLimit;
}
ArticulationDrive tempDrive = SetDriveLimits(drive, newLowerLimit, newUpperLimit);
if (body.linearLockX == ArticulationDofLock.LimitedMotion)
{
body.xDrive = tempDrive;
}
else if (body.linearLockY == ArticulationDofLock.LimitedMotion)
{
body.yDrive = tempDrive;
}
else if (body.linearLockZ == ArticulationDofLock.LimitedMotion)
{
body.zDrive = tempDrive;
}
}
}
}
void DisplayPrismaticJointPointer(Matrix4x4 parentAnchorSpace, float jointPosition, Vector3 primaryAxis)
{
if (!Application.isPlaying)
return;
using (new Handles.DrawingScope(Color.white, parentAnchorSpace))
{
Vector3 discPosition = primaryAxis.normalized * jointPosition;
Handles.DrawSolidDisc(discPosition, primaryAxis, HandleUtility.GetHandleSize(discPosition) * 0.04f);
}
}
ArticulationDrive SetDriveLimits(ArticulationDrive drive, float lowerLimit, float upperLimit)
{
var tempDrive = drive;
tempDrive.lowerLimit = lowerLimit;
tempDrive.upperLimit = upperLimit;
return tempDrive;
}
public void PrismaticHandleDrawFunction(
int controlID, Vector3 position, Quaternion rotation, float size, EventType eventType
)
{
Handles.CylinderHandleCap(controlID, position, rotation, size * HandleUtility.GetHandleSize(position), eventType);
}
private void ShowRevoluteLimits(JointAngularLimitHandle handle, ArticulationBody body, Matrix4x4 parentAnchorSpace)
{
using (new Handles.DrawingScope(parentAnchorSpace))
{
handle.xMin = body.xDrive.lowerLimit;
handle.xMax = body.xDrive.upperLimit;
DisplayAngularJointPointer(parentAnchorSpace, body, handle, k_PointerThickness);
EditorGUI.BeginChangeCheck();
handle.radius = HandleUtility.GetHandleSize(Vector3.zero);
handle.DrawHandle(true);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changing Articulation body parent anchor rotation limits");
body.xDrive = SetDriveLimits(body.xDrive, handle.xMin, handle.xMax);
}
}
}
private void ShowSphericalLimits(JointAngularLimitHandle handle, ArticulationBody body, Matrix4x4 parentAnchorSpace)
{
using (new Handles.DrawingScope(parentAnchorSpace))
{
handle.xMin = body.xDrive.lowerLimit;
handle.xMax = body.xDrive.upperLimit;
handle.yMin = body.yDrive.lowerLimit;
handle.yMax = body.yDrive.upperLimit;
handle.zMin = body.zDrive.lowerLimit;
handle.zMax = body.zDrive.upperLimit;
DisplayAngularJointPointer(parentAnchorSpace, body, handle, k_PointerThickness);
EditorGUI.BeginChangeCheck();
handle.radius = HandleUtility.GetHandleSize(Vector3.zero);
handle.DrawHandle(true);
if (EditorGUI.EndChangeCheck())
{
Undo.RecordObject(target, "Changing Articulation body parent anchor rotation limits");
body.xDrive = SetDriveLimits(body.xDrive, handle.xMin, handle.xMax);
body.yDrive = SetDriveLimits(body.yDrive, handle.yMin, handle.yMax);
body.zDrive = SetDriveLimits(body.zDrive, handle.zMin, handle.zMax);
}
}
}
private void DisplayAngularJointPointer(Matrix4x4 parentAnchorSpace, ArticulationBody body, JointAngularLimitHandle handle, float pointerThickness)
{
if (body.isRoot || !Application.isPlaying)
return;
// Since ArticulationBody.jointPosition can return either 1, 2 or 3 available values
// and depending on configuration jointPosition[0] could be any of the enabled drives
// Though we are sure that they will always be in order X -> Y -> Z if they are enabled.
int nbEnabledDrives = 0;
float pointerLength = handle.radius;
ArticulationReducedSpace jointPosition = body.jointPosition;
Matrix4x4 twistAxisRotation = Matrix4x4.identity;
if (body.twistLock != ArticulationDofLock.LockedMotion)
{
// In the case of Limited Twist Axis, the whole gizmo will be rotated based on its upper and lower limits
// Because of that we need to make sure the pointer line also stays within the same plane on Y and Z axes
if (body.twistLock == ArticulationDofLock.LimitedMotion)
twistAxisRotation = Matrix4x4.Rotate(Quaternion.AngleAxis((body.xDrive.upperLimit + body.xDrive.lowerLimit) / 2, Vector3.left));
// Rotate the end point so that it matches the X axis on the gizmo
Quaternion axisRotationX = Quaternion.Euler(new Vector3(0, 0, 180));
var endPoint = GetPointOnAngularJointAxis(jointPosition[nbEnabledDrives], pointerLength, axisRotationX);
DrawJointPointerLine(parentAnchorSpace, endPoint, handle.xHandleColor, pointerThickness, Vector3.right);
nbEnabledDrives++;
}
if (body.swingYLock != ArticulationDofLock.LockedMotion)
{
// Rotate the end point so that it matches the Y axis on the gizmo
Quaternion axisRotationY = Quaternion.Euler(new Vector3(0, 0, -90));
var endPoint = GetPointOnAngularJointAxis(jointPosition[nbEnabledDrives], pointerLength, axisRotationY);
DrawJointPointerLine(parentAnchorSpace * twistAxisRotation, endPoint, handle.yHandleColor, pointerThickness, Vector3.up);
nbEnabledDrives++;
}
if (body.swingZLock != ArticulationDofLock.LockedMotion)
{
// Rotate the end point so that it matches the Z axis on the gizmo
Quaternion axisRotationZ = Quaternion.Euler(new Vector3(-90, 90, 0));
var endPoint = GetPointOnAngularJointAxis(jointPosition[nbEnabledDrives], pointerLength, axisRotationZ);
DrawJointPointerLine(parentAnchorSpace * twistAxisRotation, endPoint, handle.zHandleColor, pointerThickness, Vector3.forward);
}
}
private Vector3 GetPointOnAngularJointAxis(float jointPosition, float length, Quaternion axis)
{
return axis * (length * new Vector3(0, Mathf.Sin(jointPosition), Mathf.Cos(jointPosition)));
}
private void DrawJointPointerLine(Matrix4x4 parentAnchorSpace, Vector3 endPoint, Color color, float thickness, Vector3 discAxis, int dashCount = 4)
{
using (new Handles.DrawingScope(color, parentAnchorSpace))
{
// Implement a manual dashed line with thickness, since
// Handles.DrawDottedLine does not have an option for that
float screenSpaceMult = HandleUtility.GetHandleSize(Vector3.zero);
float dashLength = endPoint.magnitude / dashCount;
Vector3 endPointNormalized = endPoint.normalized;
Vector3 dirMultiplier = endPointNormalized * dashLength;
for (int i = 0; i < dashCount; i++)
{
Handles.DrawLine(dirMultiplier * i, dirMultiplier * (i + 1) - endPointNormalized * 0.05f * screenSpaceMult, thickness);
}
Handles.DrawSolidDisc(endPoint, discAxis, screenSpaceMult * 0.04f);
}
}
}
}
| UnityCsReference/Modules/PhysicsEditor/ArticulationBodyJointLimitTool.cs/0 | {
"file_path": "UnityCsReference/Modules/PhysicsEditor/ArticulationBodyJointLimitTool.cs",
"repo_id": "UnityCsReference",
"token_count": 8105
} | 422 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
public partial class PhysicsDebugWindow : EditorWindow
{
private void DrawInternalTab()
{
GUILayout.BeginHorizontal();
if (GUILayout.Button(Style.connectSDKVisualDebugger))
Physics.ConnectPhysicsSDKVisualDebugger();
if(GUILayout.Button(Style.disconnectSDKVisualDebugger))
Physics.DisconnectPhysicsSDKVisualDebugger();
GUILayout.EndHorizontal();
}
}
}
| UnityCsReference/Modules/PhysicsEditor/PhysicsDebugWindowInternal.cs/0 | {
"file_path": "UnityCsReference/Modules/PhysicsEditor/PhysicsDebugWindowInternal.cs",
"repo_id": "UnityCsReference",
"token_count": 273
} | 423 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor.Presets
{
class PresetManagerPostProcessor : AssetPostprocessor
{
public override int GetPostprocessOrder()
{
return -1000;
}
public void OnPreprocessAsset()
{
if (assetImporter != null && assetImporter.importSettingsMissing)
{
foreach (var preset in Preset.GetDefaultPresetsForObject(assetImporter))
{
preset.ApplyTo(assetImporter);
}
}
}
}
}
| UnityCsReference/Modules/PresetsEditor/PresetManagerPostProcessor.cs/0 | {
"file_path": "UnityCsReference/Modules/PresetsEditor/PresetManagerPostProcessor.cs",
"repo_id": "UnityCsReference",
"token_count": 321
} | 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;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using UnityEditorInternal;
using UnityEditor.Profiling;
using UnityEngine;
using UnityEditor.MPE;
namespace UnityEditor
{
static class ProfilerRoleProvider
{
const string k_RoleName = "profiler";
static int OOPProcessId
{
get => SessionState.GetInt(nameof(OOPProcessId), -1);
set => SessionState.SetInt(nameof(OOPProcessId), value);
}
internal enum EventType
{
UmpProfilerOpenPlayerConnection, // Profiler > Editor: Sent when the profiler OOP is ready and wants the master editor process to enable its profile and player connection
UmpProfilerRecordingStateChanged, // Profiler > Editor: Sent from the profiler OOP to have the master editor synchronize recording state changes in OOPP.
UmpProfilerDeepProfileChanged, // Profiler > Editor: Sent from the profiler OOP to have the master synchronize deep profile state and reload scripts.
UmpProfilerMemRecordModeChanged, // Profiler > Editor: Sent from the profiler OOP to have the master synchronize memory record mode.
UmpProfilerCurrentFrameChanged, // Profiler > Editor: The OOPP notifies the master editor that the user has selected a specific frame in the profiler chart.
UmpProfilerRecordToggle, // Editor > Profiler: The master editor requests the OOPP to start or end recording (i.e. used with F9)
UmpProfilerAboutToQuit, // Editor > Profiler: The master editor notifies the OOPP that he needs to quit/exit.
UmpProfilerExit, // Editor > Profiler: Request the OOPP to exit (used when the main editor is about to quit)
UmpProfilerEnteredPlayMode, // Editor > Profiler: Notification about entering Play Mode (used for ClearOnPlay functionality)
UmpProfilerPing, // Used for regression testing.
UmpProfilerRequestRecordState, // Used for regression testing.
UmpProfilerFocus // Used to focus the OOPP when a user tries to open a second instance
}
[Serializable]
struct PlayerConnectionInfo
{
public bool recording;
public bool profileEditor;
}
// Represents the Profiler Out-Of-Process is launched by the MainEditorProcess and connects to its EventServer at startup.
static class ProfilerProcess
{
static bool s_ProfilerDriverSetup = false;
static ProfilerWindow s_OOPProfilerWindow;
static string userPrefProfilerLayoutPath = Path.Combine(WindowLayout.layoutsDefaultModePreferencesPath, "Profiler.dwlt");
static string systemProfilerLayoutPath = Path.Combine(EditorApplication.applicationContentsPath, "Resources/Layouts/Profiler.dwlt");
[UsedImplicitly, RoleProvider(k_RoleName, ProcessEvent.Create)]
static void InitializeProfilerProcess()
{
if (!File.Exists(userPrefProfilerLayoutPath) ||
File.GetLastWriteTime(systemProfilerLayoutPath) > File.GetLastWriteTime(userPrefProfilerLayoutPath))
{
var parentDir = Path.GetDirectoryName(userPrefProfilerLayoutPath);
if (parentDir != null && !System.IO.Directory.Exists(parentDir))
System.IO.Directory.CreateDirectory(parentDir);
File.Copy(systemProfilerLayoutPath, userPrefProfilerLayoutPath, true);
}
WindowLayout.TryLoadWindowLayout(userPrefProfilerLayoutPath, false);
SessionState.SetBool("OOPP.Initialized", true);
EditorApplication.CallDelayed(InitializeProfilerProcessDomain);
Console.WriteLine("[UMPE] Initialize Profiler Out of Process");
}
[UsedImplicitly, RoleProvider(k_RoleName, ProcessEvent.AfterDomainReload)]
static void InitializeProfilerProcessDomain()
{
Console.WriteLine("[UMPE] Initialize Profiler Secondary Process Domain Triggered");
if (!SessionState.GetBool("OOPP.Initialized", false))
return;
s_OOPProfilerWindow = EditorWindow.GetWindow<ProfilerWindow>();
SetupProfilerWindow(s_OOPProfilerWindow);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerRecordToggle), HandleToggleRecording);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerRequestRecordState), HandleRequestRecordState);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerPing), HandlePingEvent);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerExit), HandleExitEvent);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerFocus), HandleFocus);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerEnteredPlayMode), HandleEnteredPlayMode);
EditorApplication.CallDelayed(SetupProfilerDriver);
EditorApplication.updateMainWindowTitle -= SetProfilerWindowTitle;
EditorApplication.updateMainWindowTitle += SetProfilerWindowTitle;
EditorApplication.quitting -= SaveWindowLayout;
EditorApplication.quitting += SaveWindowLayout;
Console.WriteLine("[UMPE] Initialize Profiler Secondary Process Domain Completed");
}
static void SaveWindowLayout()
{
WindowLayout.SaveWindowLayout(userPrefProfilerLayoutPath);
}
static void SetupProfilerWindow(ProfilerWindow profilerWindow)
{
profilerWindow.currentFrameChanged -= OnProfilerCurrentFrameChanged;
profilerWindow.recordingStateChanged -= OnProfilerWindowRecordingStateChanged;
profilerWindow.deepProfileChanged -= OnProfilerWindowDeepProfileChanged;
profilerWindow.memoryRecordingModeChanged -= OnProfilerWindowMemoryRecordModeChanged;
profilerWindow.currentFrameChanged += OnProfilerCurrentFrameChanged;
profilerWindow.recordingStateChanged += OnProfilerWindowRecordingStateChanged;
profilerWindow.deepProfileChanged += OnProfilerWindowDeepProfileChanged;
profilerWindow.memoryRecordingModeChanged += OnProfilerWindowMemoryRecordModeChanged;
}
static void SetupProfilerDriver()
{
if (s_ProfilerDriverSetup)
return;
ProfilerDriver.profileEditor = ProfilerUserSettings.defaultTargetMode == ProfilerEditorTargetMode.Editmode;
var playerConnectionInfo = new PlayerConnectionInfo
{
recording = ProfilerDriver.enabled,
profileEditor = ProfilerDriver.profileEditor
};
EventService.Request(nameof(EventType.UmpProfilerOpenPlayerConnection), HandlePlayerConnectionOpened, playerConnectionInfo, 5000L);
s_ProfilerDriverSetup = true;
}
static void SetupProfiledConnection(int connId)
{
if (ProfilerDriver.GetAvailableProfilers().Any(id => id == connId))
{
ProfilerDriver.SetRemoteEditorConnection(connId);
Menu.SetChecked("Edit/Record", s_OOPProfilerWindow.IsSetToRecord());
Menu.SetChecked("Edit/Deep Profiling", ProfilerDriver.deepProfiling);
EditorApplication.UpdateMainWindowTitle();
InternalEditorUtility.RepaintAllViews();
}
else
EditorApplication.CallDelayed(() => SetupProfiledConnection(connId), 0.250d);
}
static void HandlePlayerConnectionOpened(Exception err, object[] args)
{
if (err != null)
throw err;
var connectionId = Convert.ToInt32(args[0]);
SetupProfiledConnection(connectionId);
}
static object HandleToggleRecording(string eventType, object[] args)
{
s_OOPProfilerWindow.Focus();
s_OOPProfilerWindow.SetRecordingEnabled(!ProfilerDriver.enabled);
InternalEditorUtility.RepaintAllViews();
return s_OOPProfilerWindow.IsSetToRecord();
}
static void SetProfilerWindowTitle(ApplicationTitleDescriptor desc)
{
if (s_OOPProfilerWindow == null)
return;
if (s_OOPProfilerWindow.IsRecording())
{
var playStateHint = !ProfilerDriver.profileEditor ? "PLAY" : "EDIT";
desc.title = $"Profiler [RECORDING {playStateHint}] - {desc.projectName} - {desc.unityVersion}";
}
else
desc.title = $"Profiler - {desc.projectName} - {desc.unityVersion}";
}
static void OnProfilerWindowRecordingStateChanged(bool recording)
{
EventService.Emit(nameof(EventType.UmpProfilerRecordingStateChanged), new object[] { recording, ProfilerDriver.profileEditor });
EditorApplication.CallDelayed(EditorApplication.UpdateMainWindowTitle);
}
static void OnProfilerWindowDeepProfileChanged(bool deepProfiling)
{
EventService.Request(nameof(EventType.UmpProfilerDeepProfileChanged), (err, results) =>
{
if (err != null)
throw err;
var applied = Convert.ToBoolean(results[0]);
if (!applied)
ProfilerDriver.deepProfiling = !deepProfiling;
Menu.SetChecked("Edit/Deep Profiling", ProfilerDriver.deepProfiling);
}, deepProfiling);
}
static void OnProfilerWindowMemoryRecordModeChanged(ProfilerMemoryRecordMode memRecordMode)
{
EventService.Emit(nameof(EventType.UmpProfilerMemRecordModeChanged), (int)memRecordMode);
}
static void OnProfilerCurrentFrameChanged(int frame, bool paused)
{
if (frame == -1)
return;
EventService.Emit(nameof(EventType.UmpProfilerCurrentFrameChanged), new object[] { frame, paused });
}
// Only used by tests
static object HandlePingEvent(string type, object[] args)
{
return s_OOPProfilerWindow ? "Pong" : "";
}
static object HandleExitEvent(string type, object[] args)
{
EditorApplication.CallDelayed(() => EditorApplication.Exit(Convert.ToInt32(args[0])));
return null;
}
static object HandleRequestRecordState(string type, object[] args)
{
return ProfilerDriver.enabled;
}
static void HandleFocus(string type, object[] args)
{
EditorWindow.FocusWindowIfItsOpen(typeof(ProfilerWindow));
}
static void HandleEnteredPlayMode(string arg1, object[] arg2)
{
s_OOPProfilerWindow.ClearFramesOnPlayOrPlayerConnectionChange();
}
[UsedImplicitly, CommandHandler("Profiler/OpenProfileData", CommandHint.Menu)]
static void OnLoadProfileDataFileCommand(CommandExecuteContext ctx)
{
s_OOPProfilerWindow.LoadProfilingData(false);
}
[UsedImplicitly, CommandHandler("Profiler/SaveProfileData", CommandHint.Menu)]
static void OnSaveProfileDataFileCommand(CommandExecuteContext ctx)
{
s_OOPProfilerWindow.SaveProfilingData();
}
[UsedImplicitly, CommandHandler("Profiler/Record", CommandHint.Menu)]
static void OnRecordCommand(CommandExecuteContext ctx)
{
s_OOPProfilerWindow.SetRecordingEnabled(!s_OOPProfilerWindow.IsSetToRecord());
Menu.SetChecked("Edit/Record", s_OOPProfilerWindow.IsSetToRecord());
}
[UsedImplicitly, CommandHandler("Profiler/EnableDeepProfiling", CommandHint.Menu)]
static void OnEnableDeepProfilingCommand(CommandExecuteContext ctx)
{
OnProfilerWindowDeepProfileChanged(ProfilerDriver.deepProfiling);
}
}
// Represents the code running in the main (master) editor process.
static class MainEditorProcess
{
[UsedImplicitly, RoleProvider(ProcessLevel.Main, ProcessEvent.AfterDomainReload)]
static void InitializeProfilerMasterProcess()
{
EditorApplication.playModeStateChanged += (PlayModeStateChange state) =>
{
if (state != PlayModeStateChange.EnteredPlayMode || !EventService.isConnected)
return;
EventService.Emit(nameof(EventType.UmpProfilerEnteredPlayMode));
EventService.Tick(); // We really need the message to be sent now.
};
EditorApplication.quitting += () =>
{
if (!EventService.isConnected)
return;
EventService.Emit(nameof(EventType.UmpProfilerExit), 0);
EventService.Tick(); // We really need the message to be sent now.
};
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerAboutToQuit), OnProfilerExited);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerOpenPlayerConnection), OnOpenPlayerConnectionRequested);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerCurrentFrameChanged), OnProfilerCurrentFrameChanged);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerRecordingStateChanged), OnProfilerRecordingStateChanged);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerDeepProfileChanged), OnProfilerDeepProfileChanged);
EventService.RegisterEventHandler(nameof(EventType.UmpProfilerMemRecordModeChanged), OnProfilerMemoryRecordModeChanged);
}
[UsedImplicitly, CommandHandler("ProfilerRecordToggle", CommandHint.Shortcut)]
static void RecordToggle(CommandExecuteContext context)
{
if (ProcessService.level == ProcessLevel.Main &&
ProcessService.IsChannelServiceStarted() &&
ProcessService.GetProcessState(OOPProcessId) == ProcessState.Running &&
EventService.isConnected)
{
EventService.Request(nameof(EventType.UmpProfilerRecordToggle), (err, args) =>
{
bool recording = false;
if (err == null)
{
// Recording was toggled by profiler OOP
recording = (bool)args[0];
ProfilerDriver.enabled = recording;
}
else
{
if (!EditorWindow.HasOpenInstances<ProfilerWindow>())
return;
// Toggle profiling in-process
recording = !ProfilerDriver.enabled;
ProfilerDriver.profileEditor = !EditorApplication.isPlaying;
var profilerWindow = EditorWindow.GetWindow<ProfilerWindow>();
if (profilerWindow)
profilerWindow.SetRecordingEnabled(recording);
else
ProfilerDriver.enabled = recording;
}
if (recording)
Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Recording has started...");
else
Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, "Recording has ended.");
}, 250);
context.result = true;
}
else
{
context.result = false;
}
}
static object OnProfilerCurrentFrameChanged(string eventType, object[] args)
{
var paused = Convert.ToBoolean(args[1]);
if (paused)
EditorApplication.isPaused = true;
return EditorApplication.isPaused;
}
static object OnProfilerRecordingStateChanged(string eventType, object[] args)
{
// Sync some profiler state on the profiled master editor connection.
ProfilerDriver.profileEditor = Convert.ToBoolean(args[1]);
ProfilerDriver.enabled = Convert.ToBoolean(args[0]);
return null;
}
static object OnProfilerDeepProfileChanged(string eventType, object[] args)
{
var deep = Convert.ToBoolean(args[0]);
var doApply = ProfilerWindow.SetEditorDeepProfiling(deep);
return doApply;
}
static object OnProfilerMemoryRecordModeChanged(string eventType, object[] args)
{
ProfilerDriver.memoryRecordMode = (ProfilerMemoryRecordMode)Convert.ToInt32(args[0]);
return null;
}
static object OnProfilerExited(string eventType, object[] args)
{
ProcessService.DisableProfileConnection();
return null;
}
static object OnOpenPlayerConnectionRequested(string eventType, object[] args)
{
var info = (PlayerConnectionInfo)args[0];
var connectionId = ProcessService.EnableProfileConnection(Application.dataPath);
ProfilerDriver.enabled = info.recording;
ProfilerDriver.profileEditor = info.profileEditor;
return connectionId;
}
}
internal static bool IsRunning()
{
if (OOPProcessId == -1)
return false;
return ProcessService.GetProcessState(OOPProcessId) == ProcessState.Running;
}
internal static int LaunchProfilerProcess()
{
if (IsRunning())
{
Debug.LogWarning("Profiler (Standalone Process) already launched. Focusing window.");
EventService.Emit(nameof(EventType.UmpProfilerFocus), null);
return OOPProcessId;
}
const string umpCap = "ump-cap";
const string umpWindowTitleSwitch = "ump-window-title";
OOPProcessId = ProcessService.Launch(k_RoleName,
umpWindowTitleSwitch, "Profiler",
umpCap, "disable-extra-resources",
umpCap, "menu_bar",
"editor-mode", k_RoleName,
"disableManagedDebugger", "true");
return OOPProcessId;
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerOutOfProcess/ProfilerRoleProvider.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerOutOfProcess/ProfilerRoleProvider.cs",
"repo_id": "UnityCsReference",
"token_count": 9087
} | 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;
namespace Unity.Profiling.Editor.UI
{
class BottlenecksDetailsViewModel
{
public const int k_DescriptionLinkId_CpuTimeline = 1;
public const int k_DescriptionLinkId_ProfileAnalyzer = 2;
public const int k_DescriptionLinkId_FrameDebugger = 3;
public const int k_DescriptionLinkId_GpuProfilerDocumentation = 4;
public BottlenecksDetailsViewModel(
UInt64 cpuDurationNs,
UInt64 gpuDurationNs,
UInt64 targetFrameDurationNs,
string localizedBottleneckDescription)
{
CpuDurationNs = cpuDurationNs;
GpuDurationNs = gpuDurationNs;
TargetFrameDurationNs = targetFrameDurationNs;
LocalizedBottleneckDescription = localizedBottleneckDescription;
}
public UInt64 CpuDurationNs { get; }
public UInt64 GpuDurationNs { get; }
public UInt64 TargetFrameDurationNs { get; }
public string LocalizedBottleneckDescription { get; }
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/Data/BottlenecksDetailsViewModel.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/Data/BottlenecksDetailsViewModel.cs",
"repo_id": "UnityCsReference",
"token_count": 462
} | 426 |
// 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 Unity.Profiling.Editor;
namespace UnityEditor.Profiling
{
[System.Serializable]
struct ProfilerCounterData
{
public string m_Category;
public string m_Name;
public static ProfilerCounterData FromProfilerCounterDescriptor(in ProfilerCounterDescriptor counter)
{
return new ProfilerCounterData()
{
m_Name = counter.Name,
m_Category = counter.CategoryName,
};
}
public ProfilerCounterDescriptor ToProfilerCounterDescriptor()
{
return new ProfilerCounterDescriptor(m_Name, m_Category);
}
}
static class ProfilerCounterDataUtility
{
public static ProfilerCounterDescriptor[] ConvertFromLegacyCounterDatas(List<ProfilerCounterData> legacyCounters)
{
if (legacyCounters == null)
return new ProfilerCounterDescriptor[0];
var counters = new List<ProfilerCounterDescriptor>(legacyCounters.Count);
foreach (var legacyCounter in legacyCounters)
{
var counter = legacyCounter.ToProfilerCounterDescriptor();
counters.Add(counter);
}
return counters.ToArray();
}
public static List<ProfilerCounterData> ConvertToLegacyCounterDatas(ProfilerCounterDescriptor[] counters)
{
if (counters == null)
return new List<ProfilerCounterData>();
var legacyCounters = new List<ProfilerCounterData>(counters.Length);
foreach (var counter in counters)
{
var legacyCounter = ProfilerCounterData.FromProfilerCounterDescriptor(counter);
legacyCounters.Add(legacyCounter);
}
return legacyCounters;
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerCounterData.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerCounterData.cs",
"repo_id": "UnityCsReference",
"token_count": 872
} | 427 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditorInternal.Profiling
{
internal class ProfilerFrameTimingUtility
{
/// <summary>
/// Calculates the time offset, in milliseconds, between the two specified frames.
/// </summary>
/// <param name="fromFrameIndex"></param>
/// <param name="toFrameIndex"></param>
/// <returns>The time offset in milliseconds.</returns>
public static float TimeOffsetBetweenFrames(int fromFrameIndex, int toFrameIndex)
{
if (fromFrameIndex == toFrameIndex)
{
return 0f;
}
var timeOffset = 0f;
if (toFrameIndex > fromFrameIndex)
{
timeOffset = TimeOffsetForLaterFrame(fromFrameIndex, toFrameIndex);
}
else
{
timeOffset = TimeOffsetForEarlierFrame(fromFrameIndex, toFrameIndex);
}
return timeOffset;
}
private static float TimeOffsetForEarlierFrame(int fromFrameIndex, int toFrameIndex)
{
var timeOffset = 0f;
var frame = ProfilerDriver.GetPreviousFrameIndex(fromFrameIndex);
while ((frame >= toFrameIndex) && (frame != -1))
{
using (var frameData = ProfilerDriver.GetRawFrameDataView(frame, 0))
{
timeOffset -= frameData.frameTimeMs;
frame = ProfilerDriver.GetPreviousFrameIndex(frame);
}
}
return timeOffset;
}
private static float TimeOffsetForLaterFrame(int fromFrameIndex, int toFrameIndex)
{
var timeOffset = 0f;
var frame = fromFrameIndex;
while ((frame < toFrameIndex) && (frame != -1))
{
using (var frameData = ProfilerDriver.GetRawFrameDataView(frame, 0))
{
timeOffset += frameData.frameTimeMs;
frame = ProfilerDriver.GetNextFrameIndex(frame);
}
}
return timeOffset;
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPU/ProfilerFrameTimingUtility.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPU/ProfilerFrameTimingUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 1068
} | 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.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor
{
internal class MemoryElementDataManager
{
private static int SortByMemoryClassName(ObjectInfo x, ObjectInfo y)
{
return y.className.CompareTo(x.className);
}
private static int SortByMemorySize(MemoryElement x, MemoryElement y)
{
return y.totalMemory.CompareTo(x.totalMemory);
}
enum ObjectTypeFilter { Scene, Asset, BuiltinResource, DontSave, Other }
static ObjectTypeFilter GetObjectTypeFilter(ObjectInfo info)
{
var reason = (MemoryInfoGCReason)info.reason;
switch (reason)
{
case MemoryInfoGCReason.AssetReferenced:
case MemoryInfoGCReason.AssetReferencedByNativeCodeOnly:
case MemoryInfoGCReason.AssetMarkedDirtyInEditor:
return ObjectTypeFilter.Asset;
case MemoryInfoGCReason.BuiltinResource:
return ObjectTypeFilter.BuiltinResource;
case MemoryInfoGCReason.MarkedDontSave:
return ObjectTypeFilter.DontSave;
case MemoryInfoGCReason.NotApplicable:
return ObjectTypeFilter.Other;
default:
return ObjectTypeFilter.Scene;
}
}
static bool HasValidNames(List<MemoryElement> memory)
{
for (int i = 0; i < memory.Count; i++)
{
if (!string.IsNullOrEmpty(memory[i].name))
return true;
}
return false;
}
static List<MemoryElement> GenerateObjectTypeGroups(ObjectInfo[] memory, ObjectTypeFilter filter)
{
var objectGroups = new List<MemoryElement>();
// Generate groups
MemoryElement group = null;
foreach (ObjectInfo t in memory)
{
if (GetObjectTypeFilter(t) != filter)
continue;
if (group == null || t.className != group.name)
{
group = new MemoryElement(t.className);
objectGroups.Add(group);
//group.name = t.className;
//group.color = GetColorFromClassName(t.className);
}
group.AddChild(new MemoryElement(t, true));
}
objectGroups.Sort(SortByMemorySize);
// Sort by memory
foreach (MemoryElement typeGroup in objectGroups)
{
typeGroup.children.Sort(SortByMemorySize);
if (filter == ObjectTypeFilter.Other && !HasValidNames(typeGroup.children))
typeGroup.children.Clear();
}
return objectGroups;
}
static public MemoryElement GetTreeRoot(ObjectMemoryInfo[] memoryObjectList, int[] referencesIndices)
{
// run through all objects and do conversion from references to referenced_by
ObjectInfo[] allObjectInfo = new ObjectInfo[memoryObjectList.Length];
for (int i = 0; i < memoryObjectList.Length; i++)
{
ObjectInfo info = new ObjectInfo();
info.instanceId = memoryObjectList[i].instanceId;
info.memorySize = memoryObjectList[i].memorySize;
info.reason = memoryObjectList[i].reason;
info.name = memoryObjectList[i].name;
info.className = memoryObjectList[i].className;
allObjectInfo[i] = info;
}
int offset = 0;
for (int i = 0; i < memoryObjectList.Length; i++)
{
for (int j = 0; j < memoryObjectList[i].count; j++)
{
int referencedObjectIndex = referencesIndices[j + offset];
if (allObjectInfo[referencedObjectIndex].referencedBy == null)
allObjectInfo[referencedObjectIndex].referencedBy = new List<ObjectInfo>();
allObjectInfo[referencedObjectIndex].referencedBy.Add(allObjectInfo[i]);
}
offset += memoryObjectList[i].count;
}
MemoryElement root = new MemoryElement();
System.Array.Sort(allObjectInfo, SortByMemoryClassName);
root.AddChild(new MemoryElement("Scene Memory", GenerateObjectTypeGroups(allObjectInfo, ObjectTypeFilter.Scene)));
root.AddChild(new MemoryElement("Assets", GenerateObjectTypeGroups(allObjectInfo, ObjectTypeFilter.Asset)));
root.AddChild(new MemoryElement("Builtin Resources", GenerateObjectTypeGroups(allObjectInfo, ObjectTypeFilter.BuiltinResource)));
root.AddChild(new MemoryElement("Not Saved", GenerateObjectTypeGroups(allObjectInfo, ObjectTypeFilter.DontSave)));
root.AddChild(new MemoryElement("Other", GenerateObjectTypeGroups(allObjectInfo, ObjectTypeFilter.Other)));
root.children.Sort(SortByMemorySize);
return root;
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryElementDataManager.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryElementDataManager.cs",
"repo_id": "UnityCsReference",
"token_count": 2471
} | 429 |
// 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 UnityEngine;
using UnityEditor.Profiling;
using UnityEditor;
using UnityEngine.Profiling;
namespace UnityEditorInternal.Profiling
{
[Serializable]
[ProfilerModuleMetadata("Virtual Texturing", typeof(LocalizationResource), IconPath = "Profiler.VirtualTexturing")]
internal class VirtualTexturingProfilerModule : ProfilerModuleBase
{
[SerializeReference]
VirtualTexturingProfilerView m_VTProfilerView;
const int k_DefaultOrderIndex = 13;
static readonly string k_VTCountersCategoryName = ProfilerCategory.VirtualTexturing.Name;
static readonly string[] k_VirtualTexturingCounterNames =
{
"Required Tiles",
"Max Cache Mip Bias",
"Max Cache Demand",
"Missing Streaming Tiles",
"Missing Disk Data"
};
internal override ProfilerArea area => ProfilerArea.VirtualTexturing;
private protected override int defaultOrderIndex => k_DefaultOrderIndex;
internal override void OnEnable()
{
base.OnEnable();
if (m_VTProfilerView == null)
{
m_VTProfilerView = new VirtualTexturingProfilerView();
}
}
public override void DrawToolbar(Rect position)
{
}
public override void DrawDetailsView(Rect position)
{
m_VTProfilerView?.DrawUIPane(ProfilerWindow);
}
protected override List<ProfilerCounterData> CollectDefaultChartCounters()
{
var chartCounters = new List<ProfilerCounterData>(k_VirtualTexturingCounterNames.Length);
foreach (var counterName in k_VirtualTexturingCounterNames)
{
chartCounters.Add(new ProfilerCounterData()
{
m_Name = counterName,
m_Category = k_VTCountersCategoryName,
});
}
return chartCounters;
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/VirtualTexturing/VirtualTexturingProfilerModule.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/VirtualTexturing/VirtualTexturingProfilerModule.cs",
"repo_id": "UnityCsReference",
"token_count": 935
} | 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;
using System.Collections.Generic;
using UnityEngine.UIElements;
namespace Unity.Profiling.Editor.UI
{
// Base view controller class. A view controller is responsible for managing a single, logical unit of UI, known as a 'view'. View controllers may embed the views of other view controllers to form a modular hierarchy.
abstract class ViewController : IDisposable
{
// The view owned by this view controller.
VisualElement m_View;
// The view controller's child view controllers.
readonly List<ViewController> m_Children = new();
// The view controller's view. If the view does not exist when this method is called, it will be created.
public VisualElement View
{
get
{
if (m_View == null)
{
m_View = LoadView();
if (m_View == null)
throw new InvalidOperationException($"View controller did not create a view. Ensure your view controller's LoadView method returns a non-null VisualElement.");
ViewLoaded();
}
return m_View;
}
}
// Has the view controller's view been loaded?
public bool IsViewLoaded => m_View != null;
// Has this view controller been disposed?
public bool IsDisposed { get; private set; }
// Dispose this view controller. This calls Dispose on all children before removing its view from the view hierarchy.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// LoadView is called the first time the view controller's view is requested for display. Override this method to create the view controller's view.
protected abstract VisualElement LoadView();
// ViewLoaded is called immediately after the view controller's view has been created. Override this method to perform one-time view setup.
protected virtual void ViewLoaded() { }
// Dispose is called when the view controller is being disposed from memory. Override this method to perform one-time view clean-up. You must call the base class implementation after yours, as is standard in the C# Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (IsDisposed)
return;
if (disposing)
{
foreach (var child in m_Children)
child.Dispose();
m_View?.RemoveFromHierarchy();
m_View = null;
}
IsDisposed = true;
}
// Add viewController as a child of this view controller.
protected void AddChild(ViewController viewController)
{
m_Children.Add(viewController);
}
// Remove viewController from the children of this view controller.
protected void RemoveChild(ViewController viewController)
{
m_Children.Remove(viewController);
}
}
}
| UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ViewControllerSystem/ViewController.cs/0 | {
"file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ViewControllerSystem/ViewController.cs",
"repo_id": "UnityCsReference",
"token_count": 1264
} | 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;
namespace Unity.Properties
{
public static partial class PropertyContainer
{
class GetValueVisitor<TSrcValue> : PathVisitor
{
public static readonly UnityEngine.Pool.ObjectPool<GetValueVisitor<TSrcValue>> Pool = new UnityEngine.Pool.ObjectPool<GetValueVisitor<TSrcValue>>(() => new GetValueVisitor<TSrcValue>(), null, v => v.Reset());
public TSrcValue Value;
public override void Reset()
{
base.Reset();
Value = default;
ReadonlyVisit = true;
}
protected override void VisitPath<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
{
if (!TypeConversion.TryConvert(ref value, out Value))
{
ReturnCode = VisitReturnCode.InvalidCast;
}
}
}
/// <summary>
/// Gets the value of a property by name.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="name">The name of the property to get.</param>
/// <typeparam name="TValue">The value type.</typeparam>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <returns>The value for the specified name.</returns>
/// <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 TValue GetValue<TContainer, TValue>(TContainer container, string name)
=> GetValue<TContainer, TValue>(ref container, name);
/// <summary>
/// Gets the value of a property by name.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="name">The name of the property to get.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <returns>The value for the specified name.</returns>
/// <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 TValue GetValue<TContainer, TValue>(ref TContainer container, string name)
{
var path = new PropertyPath(name);
return GetValue<TContainer, TValue>(ref container, path);
}
/// <summary>
/// Gets the value of a property by path.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="path">The path of the property to get.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <returns>The value at the specified path.</returns>
/// <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 TValue GetValue<TContainer, TValue>(TContainer container, in PropertyPath path)
=> GetValue<TContainer, TValue>(ref container, path);
/// <summary>
/// Gets the value of a property by path.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="path">The path of the property to get.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <returns>The value at the specified path.</returns>
/// <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 TValue GetValue<TContainer, TValue>(ref TContainer container, in PropertyPath path)
{
if (path.IsEmpty)
throw new InvalidPathException("The specified PropertyPath is empty.");
if (TryGetValue(ref container, path, out TValue value, out var returnCode))
return value;
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 GetValue of Type=[{typeof(TValue).Name}] for property with path=[{path}]");
case VisitReturnCode.InvalidPath:
throw new InvalidPathException($"Failed to GetValue for property with Path=[{path}]");
default:
throw new Exception($"Unexpected {nameof(VisitReturnCode)}=[{returnCode}]");
}
}
/// <summary>
/// Gets the value of a property by name.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="name">The name of the property to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified name, if the property is found. otherwise the default value for the <typeparamref name="TValue"/>.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <returns><see langword="true"/> if the value exists for the specified name; otherwise, <see langword="false"/>.</returns>
public static bool TryGetValue<TContainer, TValue>(TContainer container, string name, out TValue value)
=> TryGetValue(ref container, name, out value);
/// <summary>
/// Gets the value of a property by name.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="name">The name of the property to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified name, if the property is found. otherwise the default value for the <typeparamref name="TValue"/>.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <returns><see langword="true"/> if the value exists for the specified name; otherwise, <see langword="false"/>.</returns>
public static bool TryGetValue<TContainer, TValue>(ref TContainer container, string name, out TValue value)
{
var path = new PropertyPath(name);
return TryGetValue(ref container, path, out value, out _);
}
/// <summary>
/// Gets the value of a property by path.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="path">The path of the property to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified path, if the property is found. otherwise the default value for the <typeparamref name="TValue"/>.</param>
/// <returns>The property value of the given container.</returns>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type to set.</typeparam>
/// <returns><see langword="true"/> if the value exists at the specified path; otherwise, <see langword="false"/>.</returns>
public static bool TryGetValue<TContainer, TValue>(TContainer container, in PropertyPath path, out TValue value)
=> TryGetValue(ref container, path, out value, out _);
/// <summary>
/// Gets the value of a property by path.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="path">The path of the property to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified path, if the property is found. otherwise the default value for the <typeparamref name="TValue"/>.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <returns><see langword="true"/> if the value exists at the specified path; otherwise, <see langword="false"/>.</returns>
public static bool TryGetValue<TContainer, TValue>(ref TContainer container, in PropertyPath path, out TValue value)
=> TryGetValue(ref container, path, out value, out _);
/// <summary>
/// Gets the value of a property by path.
/// </summary>
/// <param name="container">The container whose property value will be returned.</param>
/// <param name="path">The path of the property to get.</param>
/// <param name="value">When this method returns, contains the value associated with the specified path, if the property is found. otherwise the default value for the <typeparamref name="TValue"/>.</param>
/// <param name="returnCode">When this method returns, contains the return code.</param>
/// <typeparam name="TContainer">The container type.</typeparam>
/// <typeparam name="TValue">The value type.</typeparam>
/// <returns><see langword="true"/> if the value exists at the specified path; otherwise, <see langword="false"/>.</returns>
public static bool TryGetValue<TContainer, TValue>(ref TContainer container, in PropertyPath path, out TValue value, out VisitReturnCode returnCode)
{
if (path.IsEmpty)
{
returnCode = VisitReturnCode.InvalidPath;
value = default;
return false;
}
var visitor = GetValueVisitor<TValue>.Pool.Get();
visitor.Path = path;
visitor.ReadonlyVisit = true;
try
{
if (!TryAccept(visitor, ref container, out returnCode))
{
value = default;
return false;
}
value = visitor.Value;
returnCode = visitor.ReturnCode;
}
finally
{
GetValueVisitor<TValue>.Pool.Release(visitor);
}
return returnCode == VisitReturnCode.Ok;
}
}
}
| UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+GetValue.cs/0 | {
"file_path": "UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+GetValue.cs",
"repo_id": "UnityCsReference",
"token_count": 4729
} | 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;
namespace Unity.Properties
{
/// <summary>
/// Base class for implementing a static property bag for a specified container type. This is an abstract class.
/// </summary>
/// <remarks>
/// A <see cref="ContainerPropertyBag{TContainer}"/> is used to describe and traverse the properties for a specified <typeparamref name="TContainer"/> type.
///
/// In order for properties to operate on a type, a <see cref="ContainerPropertyBag{TContainer}"/> must exist and be pre-registered for that type.
///
/// _NOTE_ In editor use cases property bags can be generated dynamically through reflection. (see Unity.Properties.Reflection)
/// </remarks>
/// <typeparam name="TContainer">The container type.</typeparam>
public abstract class ContainerPropertyBag<TContainer> : PropertyBag<TContainer>, INamedProperties<TContainer>
{
static ContainerPropertyBag()
{
if (!TypeTraits.IsContainer(typeof(TContainer)))
{
throw new InvalidOperationException($"Failed to create a property bag for Type=[{typeof(TContainer)}]. The type is not a valid container type.");
}
}
readonly List<IProperty<TContainer>> m_PropertiesList = new List<IProperty<TContainer>>();
readonly Dictionary<string, IProperty<TContainer>> m_PropertiesHash = new Dictionary<string, IProperty<TContainer>>();
/// <summary>
/// Adds a <see cref="Property{TContainer,TValue}"/> to the property bag.
/// </summary>
/// <param name="property">The <see cref="Property{TContainer,TValue}"/> to add.</param>
/// <typeparam name="TValue">The value type for the given property.</typeparam>
protected void AddProperty<TValue>(Property<TContainer, TValue> property)
{
m_PropertiesList.Add(property);
m_PropertiesHash.Add(property.Name, property);
}
/// <inheritdoc/>
public override PropertyCollection<TContainer> GetProperties()
=> new PropertyCollection<TContainer>(m_PropertiesList);
/// <inheritdoc/>
public override PropertyCollection<TContainer> GetProperties(ref TContainer container)
=> new PropertyCollection<TContainer>(m_PropertiesList);
/// <summary>
/// Gets the property associated with the specified name.
/// </summary>
/// <param name="container">The container hosting the data.</param>
/// <param name="name">The name of the property to get.</param>
/// <param name="property">When this method returns, contains the property associated with the specified name, if the name is found; otherwise, null.</param>
/// <returns><see langword="true"/> if the <see cref="INamedProperties{TContainer}"/> contains a property with the specified name; otherwise, <see langword="false"/>.</returns>
public bool TryGetProperty(ref TContainer container, string name, out IProperty<TContainer> property)
=> m_PropertiesHash.TryGetValue(name, out property);
}
}
| UnityCsReference/Modules/Properties/Runtime/PropertyBags/ContainerPropertyBag.cs/0 | {
"file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/ContainerPropertyBag.cs",
"repo_id": "UnityCsReference",
"token_count": 1109
} | 433 |
// 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 filter visitation for a specific <see cref="TContainer"/> and <see cref="TValue"/> pair.
/// </summary>
/// <typeparam name="TContainer">The container type being visited.</typeparam>
/// <typeparam name="TValue">The value type being visited.</typeparam>
public interface IExcludePropertyAdapter<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>
/// <returns><see langword="true"/> if visitation should be skipped, <see langword="false"/> otherwise.</returns>
bool IsExcluded(in ExcludeContext<TContainer, TValue> context, ref TContainer container, ref TValue value);
}
/// <summary>
/// Implement this interface to filter visitation for a specific <see cref="TValue"/> type.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
public interface IExcludePropertyAdapter<TValue> : IPropertyVisitorAdapter
{
/// <summary>
/// Invoked when the visitor encounters specific a <see cref="TValue"/>.
/// </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>
/// <returns><see langword="true"/> if visitation should be skipped, <see langword="false"/> otherwise.</returns>
bool IsExcluded<TContainer>(in ExcludeContext<TContainer, TValue> context, ref TContainer container, ref TValue value);
}
/// <summary>
/// Implement this interface to filter visitation.
/// </summary>
public interface IExcludePropertyAdapter : 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="TContainer">The container type being visited.</typeparam>
/// <typeparam name="TValue">The value type being visited.</typeparam>
/// <returns><see langword="true"/> if visitation should be skipped, <see langword="false"/> otherwise.</returns>
bool IsExcluded<TContainer, TValue>(in ExcludeContext<TContainer, TValue> context, ref TContainer container, ref TValue value);
}
/// <summary>
/// Implement this interface to filter visitation for a specific <see cref="TContainer"/> and <see cref="TValue"/> pair.
/// </summary>
/// <typeparam name="TContainer">The container type being visited.</typeparam>
/// <typeparam name="TValue">The value type being visited.</typeparam>
public interface IExcludeContravariantPropertyAdapter<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>
/// <returns><see langword="true"/> if visitation should be skipped, <see langword="false"/> otherwise.</returns>
bool IsExcluded(in ExcludeContext<TContainer> context, ref TContainer container, TValue value);
}
/// <summary>
/// Implement this interface to filter visitation for a specific <see cref="TValue"/> type.
/// </summary>
/// <typeparam name="TValue">The value type.</typeparam>
public interface IExcludeContravariantPropertyAdapter<in TValue> : 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="TContainer">The container type being visited.</typeparam>
/// <returns><see langword="true"/> if visitation should be skipped, <see langword="false"/> otherwise.</returns>
bool IsExcluded<TContainer>(in ExcludeContext<TContainer> context, ref TContainer container, TValue value);
}
}
| UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/Adapters/IExcludePropertyAdapter.cs/0 | {
"file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyVisitors/Adapters/IExcludePropertyAdapter.cs",
"repo_id": "UnityCsReference",
"token_count": 1639
} | 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.Collections;
using System.Collections.Generic;
namespace UnityEditor.Search
{
class SearchResultCollection : ICollection<SearchResult>
{
private readonly HashSet<SearchResult> m_Set;
public int Count => m_Set.Count;
public bool IsReadOnly => false;
public SearchResultCollection()
{
m_Set = new HashSet<SearchResult>();
}
public SearchResultCollection(IEnumerable<SearchResult> inset)
{
m_Set = new HashSet<SearchResult>(inset);
}
public void Add(SearchResult item)
{
m_Set.Add(item);
}
public void Clear()
{
m_Set.Clear();
}
public bool Contains(SearchResult item)
{
return m_Set.Contains(item);
}
public bool TryGetValue(ref SearchResult item)
{
return true;
}
public void CopyTo(SearchResult[] array, int arrayIndex)
{
m_Set.CopyTo(array, arrayIndex);
}
public bool Remove(SearchResult item)
{
return m_Set.Remove(item);
}
public IEnumerator<SearchResult> GetEnumerator()
{
return m_Set.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return m_Set.GetEnumerator();
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchResultCollection.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchResultCollection.cs",
"repo_id": "UnityCsReference",
"token_count": 727
} | 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.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
namespace UnityEditor.Search.Providers
{
enum MissingReferenceFilter
{
Script,
Asset,
Prefab,
Any
}
class ObjectQueryEngine : ObjectQueryEngine<UnityEngine.Object>
{
}
class ObjectQueryEngine<T> where T : UnityEngine.Object
{
protected readonly List<T> m_Objects;
protected readonly Dictionary<int, GOD> m_GODS = new Dictionary<int, GOD>();
protected static readonly QueryValidationOptions k_QueryEngineOptions = new QueryValidationOptions { validateFilters = true, skipNestedQueries = true };
protected readonly QueryEngine<T> m_QueryEngine = new QueryEngine<T>(k_QueryEngineOptions);
protected HashSet<SearchProposition> m_TypePropositions;
[ThreadStatic] protected bool m_DoFuzzyMatch;
[ThreadStatic] List<int> m_FuzzyMatches = new List<int>();
public QueryEngine<T> engine => m_QueryEngine;
public bool reportError;
private static readonly char[] s_EntrySeparators = { '/', ' ', '_', '-', '.' };
private static readonly SearchProposition[] s_FixedPropositions = new SearchProposition[]
{
new SearchProposition(label: "id:", null, "Search object by ID"),
new SearchProposition(label: "path:", null, "Search object by transform path"),
new SearchProposition(label: "tag:", null, "Search object with tag"),
new SearchProposition(label: "layer:", "layer>0", "Search object by layer (number)"),
new SearchProposition(label: "size:", null, "Search object by volume size"),
new SearchProposition(label: "components:", "components>=2", "Search object with more than # components"),
new SearchProposition(label: "is:", null, "Search object by state"),
new SearchProposition(label: "is:child", null, "Search object with a parent"),
new SearchProposition(label: "is:leaf", null, "Search object without children"),
new SearchProposition(label: "is:root", null, "Search root objects"),
new SearchProposition(label: "is:visible", null, "Search view visible objects"),
new SearchProposition(label: "is:hidden", null, "Search hierarchically hidden objects"),
new SearchProposition(label: "is:static", null, "Search static objects"),
new SearchProposition(label: "is:prefab", null, "Search prefab objects"),
new SearchProposition(label: "prefab:root", null, "Search prefab roots"),
new SearchProposition(label: "prefab:top", null, "Search top-level prefab root instances"),
new SearchProposition(label: "prefab:instance", null, "Search objects that are part of a prefab instance"),
new SearchProposition(label: "prefab:nonasset", null, "Search prefab objects that are not part of an asset"),
new SearchProposition(label: "prefab:asset", null, "Search prefab objects that are part of an asset"),
new SearchProposition(label: "prefab:model", null, "Search prefab objects that are part of a model"),
new SearchProposition(label: "prefab:regular", null, "Search regular prefab objects"),
new SearchProposition(label: "prefab:variant", null, "Search variant prefab objects"),
new SearchProposition(label: "prefab:modified", null, "Search modified prefab assets"),
new SearchProposition(label: "prefab:altered", null, "Search modified prefab instances"),
new SearchProposition(label: "t:", null, "Search object by type", priority: -1),
new SearchProposition(label: "ref:", null, "Search object references"),
};
protected class GOD
{
public string id;
public string path;
public string tag;
public string[] types;
public string[] words;
public HashSet<int> refs;
public string[] attrs;
public int? layer;
public float size = float.MaxValue;
public bool? isChild;
public bool? isLeaf;
public bool missingScript;
public bool missingPrefab;
public bool missingAssetReference;
}
public bool InvalidateObject(int instanceId)
{
return m_GODS.Remove(instanceId);
}
public bool InvalidateObjectAndRefs(int instanceId)
{
// Invalidate all refs because depending on the topology changed it becomes costly and
// difficult to compute what needs to be updated. Example of Topology changed:
// - Reparent NodeA: invalidate every node referencing nodeA
// - Reparent NodeA which is the parent of a whole hierarchy: invalidate every node referencing nodeA AND any of
// the moved children since their TransformPath has changed as well
// TODO: Should we store scene dependency as GlobalObjectId in the query instead of path?
foreach (var god in m_GODS.Values)
{
god.refs = null;
}
return m_GODS.Remove(instanceId);
}
public ObjectQueryEngine()
: this(new T[0])
{
}
public ObjectQueryEngine(IEnumerable<T> objects)
{
m_Objects = objects.ToList();
m_QueryEngine.AddFilter<int>("id", GetId);
m_QueryEngine.AddFilter("path", GetPath);
m_QueryEngine.AddFilter<string>("is", OnIsFilter, new[] {":"});
m_QueryEngine.AddFilter<MissingReferenceFilter>("missing", OnMissing, new[] { ":" });
m_QueryEngine.AddFilter<string>("t", OnTypeFilter, new[] {"=", ":"});
m_QueryEngine.SetFilter<string>("ref", GetReferences, new[] {"=", ":"}).AddTypeParser(s =>
{
if (!s.StartsWith("GlobalObjectId", StringComparison.Ordinal) || !GlobalObjectId.TryParse(s, out var gid))
return ParseResult<string>.none;
if (gid.targetPrefabId == 0 && gid.identifierType != 2 && gid.identifierType != 4)
return new ParseResult<string>(true, AssetDatabase.GUIDToAssetPath(gid.assetGUID));
return new ParseResult<string>(true, GlobalObjectId.GlobalObjectIdentifierToInstanceIDSlow(gid).ToString());
});
SearchValue.SetupEngine(m_QueryEngine);
m_QueryEngine.AddOperatorHandler("=", (int? ev, int fv) => ev.HasValue && ev == fv);
m_QueryEngine.AddOperatorHandler("!=", (int? ev, int fv) => ev.HasValue && ev != fv);
m_QueryEngine.AddOperatorHandler("<=", (int? ev, int fv) => ev.HasValue && ev <= fv);
m_QueryEngine.AddOperatorHandler("<", (int? ev, int fv) => ev.HasValue && ev < fv);
m_QueryEngine.AddOperatorHandler(">=", (int? ev, int fv) => ev.HasValue && ev >= fv);
m_QueryEngine.AddOperatorHandler(">", (int? ev, int fv) => ev.HasValue && ev > fv);
m_QueryEngine.AddOperatorHandler("=", (float? ev, float fv) => ev.HasValue && ev == fv);
m_QueryEngine.AddOperatorHandler("!=", (float? ev, float fv) => ev.HasValue && ev != fv);
m_QueryEngine.AddOperatorHandler("<=", (float? ev, float fv) => ev.HasValue && ev <= fv);
m_QueryEngine.AddOperatorHandler("<", (float? ev, float fv) => ev.HasValue && ev < fv);
m_QueryEngine.AddOperatorHandler(">=", (float? ev, float fv) => ev.HasValue && ev >= fv);
m_QueryEngine.AddOperatorHandler(">", (float? ev, float fv) => ev.HasValue && ev > fv);
m_QueryEngine.SetSearchWordMatcher(OnSearchData);
m_QueryEngine.SetSearchDataCallback(OnSearchData, s => s.ToLowerInvariant(), StringComparison.Ordinal);
reportError = true;
}
public virtual void SetupQueryEnginePropositions()
{}
public virtual IEnumerable<SearchProposition> FindPropositions(SearchContext context, SearchPropositionOptions options)
{
if (options.StartsWith("t"))
return FetchTypePropositions(options.HasAny(SearchPropositionFlags.FilterOnly) ? null : "t:");
return s_FixedPropositions;
}
private HashSet<Type> FetchPropositionTypes()
{
var types = new HashSet<Type>();
foreach (var o in m_Objects)
{
if (!o)
continue;
types.Add(o.GetType());
if (o is GameObject go)
types.UnionWith(go.GetComponents<Component>().Where(c => c).Select(c => c.GetType()));
}
return types;
}
private IEnumerable<SearchProposition> FetchTypePropositions(string prefixFilterId = "t:")
{
if (m_TypePropositions == null && m_Objects != null)
{
var types = FetchPropositionTypes();
m_TypePropositions = new HashSet<SearchProposition>(types.Select(t => CreateTypeProposition(t, prefixFilterId)));
}
return m_TypePropositions ?? Enumerable.Empty<SearchProposition>();
}
static SearchProposition CreateTypeProposition(in Type t, string prefixFilterId)
{
var typeName = t.Name;
var label = typeName;
if (prefixFilterId != null)
label = prefixFilterId + label;
return new SearchProposition(label: label, null, $"Search {typeName} components", icon: Utils.FindTextureForType(t));
}
#region search_query_error_example
public IEnumerable<T> Search(SearchContext context, SearchProvider provider, IEnumerable<T> subset = null)
{
var query = m_QueryEngine.ParseQuery(context.searchQuery, true);
if (!query.valid)
{
if (reportError)
context.AddSearchQueryErrors(query.errors.Select(e => new SearchQueryError(e, context, provider)));
return Enumerable.Empty<T>();
}
m_DoFuzzyMatch = query.HasToggle("fuzzy");
IEnumerable<T> gameObjects = subset ?? m_Objects;
return query.Apply(gameObjects, false);
}
#endregion
public virtual bool GetId(T obj, QueryFilterOperator op, int instanceId)
{
return instanceId == obj.GetInstanceID();
}
protected virtual string GetPath(T obj)
{
var god = GetGOD(obj);
if (god.path == null)
god.path = AssetDatabase.GetAssetPath(obj);
return god.path;
}
protected GOD GetGOD(UnityEngine.Object obj)
{
var instanceId = obj.GetInstanceID();
if (!m_GODS.TryGetValue(instanceId, out var god))
{
god = new GOD();
m_GODS[instanceId] = god;
}
return god;
}
protected bool OnMissing(T obj, QueryFilterOperator op, MissingReferenceFilter value)
{
var god = GetGOD(obj);
if (god.refs == null)
{
BuildReferences(ref god, obj);
}
switch(value)
{
case MissingReferenceFilter.Any:
return god.missingAssetReference || god.missingScript || god.missingPrefab;
case MissingReferenceFilter.Script:
return god.missingScript;
case MissingReferenceFilter.Asset:
return god.missingAssetReference;
case MissingReferenceFilter.Prefab:
return god.missingPrefab;
default:
return false;
}
}
protected virtual bool OnIsFilter(T obj, QueryFilterOperator op, string value)
{
if (string.Equals(value, "object", StringComparison.Ordinal))
return true;
return false;
}
protected SearchValue FindPropertyValue(UnityEngine.Object obj, string propertyName)
{
var property = PropertySelectors.FindProperty(obj, propertyName, out var so);
if (property == null)
return SearchValue.invalid;
var v = SearchValue.ConvertPropertyValue(property);
so?.Dispose();
return v;
}
protected string ToReplacementValue(SerializedProperty sp, string replacement)
{
switch (sp.propertyType)
{
case SerializedPropertyType.Integer: return replacement + ">0";
case SerializedPropertyType.Boolean: return replacement + "=true";
case SerializedPropertyType.Float: return replacement + ">=0.0";
case SerializedPropertyType.String: return replacement + ":\"\"";
case SerializedPropertyType.Enum: return replacement + ":";
case SerializedPropertyType.ObjectReference: return replacement + ":";
case SerializedPropertyType.Color: return replacement + "=#FFFFBB";
case SerializedPropertyType.Bounds:
case SerializedPropertyType.BoundsInt:
case SerializedPropertyType.Rect:
return replacement + ">0";
case SerializedPropertyType.Generic:
case SerializedPropertyType.LayerMask:
case SerializedPropertyType.Vector2:
case SerializedPropertyType.Vector3:
case SerializedPropertyType.Vector4:
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.Character:
case SerializedPropertyType.AnimationCurve:
case SerializedPropertyType.Gradient:
case SerializedPropertyType.Quaternion:
case SerializedPropertyType.ExposedReference:
case SerializedPropertyType.FixedBufferSize:
case SerializedPropertyType.Vector2Int:
case SerializedPropertyType.Vector3Int:
case SerializedPropertyType.RectInt:
case SerializedPropertyType.ManagedReference:
default:
break;
}
return null;
}
bool OnTypeFilter(T obj, QueryFilterOperator op, string value)
{
if (!obj)
return false;
var god = GetGOD(obj);
if (god.types == null)
{
var types = new HashSet<string>(new[] { obj.GetType().Name.ToLowerInvariant() });
if (obj is GameObject go)
{
if (PrefabUtility.IsAnyPrefabInstanceRoot(go))
types.Add("prefab");
var gocs = go.GetComponents<Component>();
for (int componentIndex = 0; componentIndex < gocs.Length; ++componentIndex)
{
var c = gocs[componentIndex];
if (!c || (c.hideFlags & HideFlags.HideInInspector) == HideFlags.HideInInspector)
continue;
var componentType = c.GetType();
var shortName = componentType.Name;
types.Add(shortName.ToLowerInvariant());
if (componentType.FullName != shortName)
types.Add(componentType.FullName.ToLowerInvariant());
}
}
god.types = types.ToArray();
}
return CompareWords(op, value.ToLowerInvariant(), god.types);
}
private void BuildReferences(ref GOD god, T obj)
{
var refs = new HashSet<int>();
BuildReferences(obj, ref god, refs);
if (obj is GameObject go)
{
// Index any prefab reference
if (PrefabUtility.IsAnyPrefabInstanceRoot(go))
AddReference(go, PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(go), refs);
if (PrefabUtility.IsPrefabAssetMissing(go))
{
god.missingPrefab = true;
}
var gocs = go.GetComponents<Component>();
for (int componentIndex = 1; componentIndex < gocs.Length; ++componentIndex)
{
var c = gocs[componentIndex];
if (c == null || !c)
{
god.missingScript = true;
continue;
}
if ((c.hideFlags & HideFlags.HideInInspector) == HideFlags.HideInInspector)
continue;
BuildReferences(c, ref god, refs);
}
}
refs.Remove(obj.GetHashCode());
god.refs = refs;
}
private void BuildReferences(UnityEngine.Object obj, ref GOD god, ICollection<int> refs)
{
if (!obj)
return;
try
{
using (var so = new SerializedObject(obj))
{
var p = so.GetIterator();
var next = p.NextVisible(true);
while (next)
{
AddPropertyReferences(obj, p, ref god, refs);
// NOTE: Property iteration on managedReference does not handle cycle (ObjectReference does). Do not dig in managedReference for now.
next = p.NextVisible(p.propertyType != SerializedPropertyType.ManagedReference && p.hasVisibleChildren);
}
}
}
catch
{
// Do not add any references if an exception occurs because of user code.
}
}
private void AddPropertyReferences(UnityEngine.Object obj, SerializedProperty p, ref GOD god, ICollection<int> refs)
{
if (p.propertyType != SerializedPropertyType.ObjectReference)
return;
if (p.objectReferenceValue == null)
{
god.missingAssetReference = god.missingAssetReference || p.objectReferenceInstanceIDValue != 0;
return;
}
var refValue = AssetDatabase.GetAssetPath(p.objectReferenceValue);
if (string.IsNullOrEmpty(refValue) && p.objectReferenceValue is GameObject go)
refValue = SearchUtils.GetTransformPath(go.transform);
if (!string.IsNullOrEmpty(refValue))
AddReference(p.objectReferenceValue, refValue, refs);
refs.Add(p.objectReferenceValue.GetInstanceID());
if (p.objectReferenceValue is Component c)
{
refs.Add(c.gameObject.GetInstanceID());
var compRefValue = SearchUtils.GetTransformPath(c.gameObject.transform);
AddReference(c.gameObject, compRefValue, refs);
}
// Add custom object cases
if (p.objectReferenceValue is Material material && material.shader)
{
AddReference(material.shader, material.shader.name, refs);
}
}
private bool AddReference(UnityEngine.Object refObj, string refValue, ICollection<int> refs)
{
if (string.IsNullOrEmpty(refValue))
return false;
refValue = refValue.ToLowerInvariant();
if (refValue[0] == '/')
{
refs.Add(refValue.Substring(1).GetHashCode());
}
refs.Add(refValue.GetHashCode());
var refType = refObj?.GetType().Name;
if (refType != null)
refs.Add(refType.ToLowerInvariant().GetHashCode());
return true;
}
private bool GetReferences(T obj, QueryFilterOperator op, string value)
{
var god = GetGOD(obj);
if (god.refs == null)
{
BuildReferences(ref god, obj);
}
if (god.refs.Count == 0)
return false;
// Account for legacy ref:<InstanceID>: query that can be emitted by the various Find Reference in Scene menu items.
var potentialId = value;
if (value.EndsWith(":"))
{
potentialId = value.TrimEnd(':');
}
if (Utils.TryParse(potentialId, out int instanceId))
return god.refs.Contains(instanceId);
return god.refs.Contains(value.ToLowerInvariant().GetHashCode());
}
protected bool CompareWords(in QueryFilterOperator op, string value, in IEnumerable<string> words, StringComparison stringComparison = StringComparison.Ordinal)
{
if (op.type == FilterOperatorType.Equal)
return words.Any(t => t.Equals(value, stringComparison));
return words.Any(t => t.IndexOf(value, stringComparison) != -1);
}
IEnumerable<string> OnSearchData(T go)
{
var god = GetGOD(go);
if (god.words == null)
{
god.words = SplitName(go.name, s_EntrySeparators)
.Select(w => w.ToLowerInvariant())
.Where(w => w.Length > 1)
.ToArray();
}
return god.words;
}
bool OnSearchData(string term, bool exactMatch, StringComparison sc, string word)
{
if (!exactMatch && m_DoFuzzyMatch)
{
m_FuzzyMatches.Clear();
return FuzzySearch.FuzzyMatch(term, word, m_FuzzyMatches);
}
if (exactMatch)
return string.Equals(term, word, sc);
return word.IndexOf(term, sc) != -1;
}
private static IEnumerable<string> SplitName(string entry, char[] entrySeparators)
{
yield return entry;
var cleanName = CleanName(entry);
var nameTokens = cleanName.Split(entrySeparators);
var scc = nameTokens.SelectMany(s => SearchUtils.SplitCamelCase(s)).Where(s => s.Length > 0);
var fcc = scc.Aggregate("", (current, s) => current + s[0]);
yield return fcc;
}
private static string CleanName(string s)
{
return s.Replace("(", "").Replace(")", "");
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/Providers/ObjectQueryEngine.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/ObjectQueryEngine.cs",
"repo_id": "UnityCsReference",
"token_count": 10676
} | 436 |
// 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.Search
{
class QueryTextFieldBlock : QueryBlock
{
private ISearchField m_SearchField;
internal override bool wantsEvents => true;
internal new static readonly string ussClassName = "search-query-textfield-block";
public QueryTextFieldBlock(IQuerySource source, ISearchField searchField)
: base(source)
{
hideMenu = true;
value = string.Empty;
m_SearchField = searchField;
}
public override string ToString() => value;
internal override IBlockEditor OpenEditor(in Rect rect) => null;
internal ISearchField GetSearchField()
{
return m_SearchField;
}
internal override void CreateBlockElement(VisualElement container)
{
var textElement = m_SearchField.GetTextElement();
if (textElement == null)
return;
// Calling RegisterCallback for the same callback on the same phase has no effect,
// so no need to unregister if already registered.
textElement.RegisterCallback<PointerDownEvent>(OnPointerDownEvent);
container.AddToClassList(ussClassName);
container.Add(textElement);
}
void OnPointerDownEvent(PointerDownEvent evt)
{
source.BlockActivated(this);
}
internal override Color GetBackgroundColor()
{
return Color.clear;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryTextFieldBlock.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryTextFieldBlock.cs",
"repo_id": "UnityCsReference",
"token_count": 693
} | 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;
using System.Collections.Generic;
namespace UnityEditor.Search
{
class NestedQueryEnumerable<T> : IQueryEnumerable<T>
{
IEnumerable<T> m_NestedQueryEnumerable;
public bool fastYielding { get; }
public NestedQueryEnumerable(IEnumerable<T> nestedQueryEnumerable, bool fastYielding)
{
m_NestedQueryEnumerable = nestedQueryEnumerable;
this.fastYielding = fastYielding;
}
public void SetPayload(IEnumerable<T> payload)
{}
public IEnumerator<T> GetEnumerator()
{
return m_NestedQueryEnumerable.GetEnumerator();
}
public IEnumerator<T> FastYieldingEnumerator()
{
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
[EnumerableCreator(QueryNodeType.NestedQuery)]
class NestedQueryEnumerableFactory : IQueryEnumerableFactory
{
public IQueryEnumerable<T> Create<T>(IQueryNode root, QueryEngine<T> engine, ICollection<QueryError> errors, bool fastYielding)
{
var nestedQueryNode = root as NestedQueryNode;
var nestedQueryHandler = nestedQueryNode?.nestedQueryHandler as NestedQueryHandler<T>;
if (nestedQueryHandler == null)
{
errors.Add(new QueryError(root.token.position, root.token.length, "There is no handler set for nested queries."));
return null;
}
var nestedEnumerable = nestedQueryHandler.handler(nestedQueryNode.identifier, nestedQueryNode.associatedFilter);
if (nestedEnumerable == null)
{
errors.Add(new QueryError(root.token.position, root.token.length, "Could not create enumerable from nested query handler."));
}
return new NestedQueryEnumerable<T>(nestedEnumerable, fastYielding);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/NestedQueryEnumerable.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/NestedQueryEnumerable.cs",
"repo_id": "UnityCsReference",
"token_count": 895
} | 438 |
// 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;
using System.Text.RegularExpressions;
namespace UnityEditor.Search
{
enum ParseState
{
Matched,
NoMatch,
ParseError
}
static class QueryRegexValues
{
// To match a regex at a specific index, use \\G and Match(input, startIndex)
public const string k_BaseWordPattern = "[\\w.\\[\\]]+";
public const string k_FilterOperatorsInnerPattern = "[^\\w\\s-{}()\"\\[\\].,/|\\`]+";
// This is a balanced group for {} with an optional aggregator name
public const string k_NestedFilterPattern = "(?<agg>[a-zA-Z0-9]*?)(?<nested>\\{(?>(?<c>\\{)|[^{}]+|(?<-c>\\}))*(?(c)(?!))\\})";
public static readonly string k_FilterOperatorsPattern = $"(?<op>{k_FilterOperatorsInnerPattern})";
public static readonly string k_PartialFilterOperatorsPattern = $"(?<op>{k_FilterOperatorsInnerPattern})?";
public static readonly string k_FilterNamePattern = $"\\G(?<name>{k_BaseWordPattern})";
// To begin matching a partial filter, the name of the filter must be followed by either "(" or an operator
public static readonly string k_PartialFilterNamePattern = $"\\G(?<name>{k_BaseWordPattern})(?=\\(|(?:{k_FilterOperatorsInnerPattern}))";
public const string k_FilterFunctionPattern = "(?<f1>\\([^\\(\\)]+\\))?";
// This matches either a parenthesis opened with no space like "(asd", a close parenthesis with no space like "(asd)", or a close parenthesis with spaces like "( asd )"
public const string k_PartialFilterFunctionPattern = "(?<f1>\\((?!\\S*(?:\\s+\\S*)+\\))[^\\(\\)\\s]*\\)?)?(?<f2>(?(f1)|\\([^\\(\\)]*\\)))?";
public static readonly string k_FilterValuePattern = $"(?<value>{k_NestedFilterPattern}|[^\\s{{}}]+)";
public static readonly string k_PartialFilterValuePattern = $"(?<value>(?(op)({k_NestedFilterPattern}|[^\\s{{}}]+)))?";
public static readonly Regex k_BaseFilterNameRegex = new Regex(k_BaseWordPattern, RegexOptions.Compiled);
public static readonly Regex k_WordRx = new Regex("\\G!?\\S+", RegexOptions.Compiled);
public static readonly Regex k_NestedQueryRx = new Regex($"\\G{k_NestedFilterPattern}", RegexOptions.Compiled);
}
[Flags]
enum QueryTextDelimiterEscapeOptions
{
EscapeNone = 0,
EscapeOpening = 1,
EscapeClosing = 1 << 1,
EscapeAll = EscapeOpening | EscapeClosing
}
static class QueryTextDelimiterEscapeOptionsExtensions
{
public static bool HasAny(this QueryTextDelimiterEscapeOptions flags, QueryTextDelimiterEscapeOptions f) => (flags & f) != 0;
public static bool HasAll(this QueryTextDelimiterEscapeOptions flags, QueryTextDelimiterEscapeOptions all) => (flags & all) == all;
}
readonly struct QueryTextDelimiter : IEquatable<QueryTextDelimiter>
{
internal const string k_QueryHandlerDataKey = "delimiterHashCode";
internal const string k_WordBoundaryPattern = "(?=\\s|$)";
public readonly string openingToken;
public readonly string closingToken;
public readonly QueryTextDelimiterEscapeOptions escapeOptions;
public bool valid => !string.IsNullOrEmpty(openingToken) && !string.IsNullOrEmpty(closingToken);
public readonly string escapedOpeningToken;
public readonly string escapedClosingToken;
public static QueryTextDelimiter invalid = new QueryTextDelimiter(null, null, QueryTextDelimiterEscapeOptions.EscapeNone);
public QueryTextDelimiter(string openingToken, string closingToken)
: this(openingToken, closingToken, QueryTextDelimiterEscapeOptions.EscapeAll)
{}
public QueryTextDelimiter(string openingToken)
: this(openingToken, k_WordBoundaryPattern, QueryTextDelimiterEscapeOptions.EscapeOpening)
{}
public QueryTextDelimiter(string openingToken, string closingToken, QueryTextDelimiterEscapeOptions escapeOptions)
{
this.escapeOptions = escapeOptions;
this.openingToken = openingToken;
this.closingToken = closingToken;
escapedOpeningToken = EscapeToken(openingToken, QueryTextDelimiterEscapeOptions.EscapeOpening, escapeOptions);
escapedClosingToken = EscapeToken(closingToken, QueryTextDelimiterEscapeOptions.EscapeClosing, escapeOptions);
}
public bool Equals(QueryTextDelimiter other)
{
return openingToken == other.openingToken && closingToken == other.closingToken;
}
public override int GetHashCode()
{
return openingToken.GetHashCode() ^ closingToken.GetHashCode();
}
public override string ToString()
{
return $"({openingToken}, {closingToken})";
}
static string EscapeToken(string token, QueryTextDelimiterEscapeOptions requiredEscapeOptions, QueryTextDelimiterEscapeOptions currentEscapeOptions)
{
if (currentEscapeOptions.HasAll(requiredEscapeOptions))
return Regex.Escape(token);
return token;
}
}
abstract class QueryTokenizer<TUserData>
{
const string k_QuoteHandlerKey = "quoteHandler";
const string k_CommentHandlerKey = "commentHandler";
const string k_ToggleHandlerKey = "toggleHandler";
protected enum TokenHandlerPriority
{
Empty = 0,
Group = 100,
Combining = 200,
Nested = 300,
FilterWithQuotes = 350,
Filter = 400,
Toggle = 500,
Comment = 600,
Phrase = 650,
Word = 700
}
Regex m_FilterRx = new Regex(QueryRegexValues.k_FilterNamePattern +
QueryRegexValues.k_FilterFunctionPattern +
QueryRegexValues.k_FilterOperatorsPattern +
QueryRegexValues.k_FilterValuePattern, RegexOptions.Compiled);
static readonly List<string> k_CombiningToken = new List<string>
{
"and",
"or",
"not",
"-"
};
protected delegate int TokenMatcher(string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched);
protected delegate bool TokenConsumer(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected struct QueryTokenHandler
{
public TokenMatcher matcher;
public TokenConsumer consumer;
public int priority;
public int id;
public Dictionary<string, object> userData;
public QueryTokenHandler(TokenMatcher matcher, TokenConsumer consumer, int id, int priority)
{
this.matcher = matcher;
this.consumer = consumer;
this.priority = priority;
this.id = id;
userData = new Dictionary<string, object>();
}
public QueryTokenHandler(TokenMatcher matcher, TokenConsumer consumer, TokenHandlerPriority priority)
: this(matcher, consumer, 0, (int)priority)
{}
public QueryTokenHandler(TokenMatcher matcher, TokenConsumer consumer, int priority)
: this(matcher, consumer, 0, priority)
{}
public QueryTokenHandler(TokenMatcher matcher, TokenConsumer consumer, int id, TokenHandlerPriority priority)
: this(matcher, consumer, id, (int)priority)
{}
public QueryTokenHandler(int id, int priority)
: this(null, null, id, priority)
{}
public void AddOrUpdateUserData(string key, object value)
{
userData[key] = value;
}
}
protected List<QueryTokenHandler> m_TokenConsumers;
protected List<QueryTextDelimiter> m_QuoteDelimiters;
protected List<QueryTextDelimiter> m_CommentDelimiters;
protected List<QueryTextDelimiter> m_ToggleDelimiters;
protected QueryTokenizer()
{
m_TokenConsumers = new List<QueryTokenHandler>
{
new QueryTokenHandler(MatchEmpty, ConsumeEmpty, TokenHandlerPriority.Empty),
new QueryTokenHandler(MatchGroup, ConsumeGroup, TokenHandlerPriority.Group),
new QueryTokenHandler(MatchCombiningToken, ConsumeCombiningToken, TokenHandlerPriority.Combining),
new QueryTokenHandler(MatchNestedQuery, ConsumeNestedQuery, TokenHandlerPriority.Nested),
new QueryTokenHandler(MatchFilter, ConsumeFilter, TokenHandlerPriority.Filter),
new QueryTokenHandler(MatchWord, ConsumeWord, TokenHandlerPriority.Word)
};
m_QuoteDelimiters = new List<QueryTextDelimiter>
{
new QueryTextDelimiter("\"", "\"")
};
m_CommentDelimiters = new List<QueryTextDelimiter>();
m_ToggleDelimiters = new List<QueryTextDelimiter>
{
new QueryTextDelimiter("+")
};
AddCustomPhraseTokenHandler(0, (int)TokenHandlerPriority.Phrase, BuildPhraseRegex(m_QuoteDelimiters[0]), m_QuoteDelimiters[0], false);
AddCustomFilterWithQuotesTokenHandler(0, (int)TokenHandlerPriority.FilterWithQuotes, m_QuoteDelimiters[0], null, false);
AddCustomToggleTokenHandler(0, (int)TokenHandlerPriority.Toggle, BuildTextBlockRegex(m_ToggleDelimiters[0]), m_ToggleDelimiters[0], false);
m_TokenConsumers.Sort(QueryTokenHandlerComparer);
}
public virtual void AddQuoteDelimiter(in QueryTextDelimiter textDelimiter)
{
AddQuoteDelimiter(in textDelimiter, null);
}
public virtual void AddQuoteDelimiter(in QueryTextDelimiter textDelimiter, IEnumerable<string> operators, bool sort = true)
{
AddTextBlockDelimiter(in textDelimiter, m_QuoteDelimiters, delimiter =>
{
// We need a new visitor for Phrases and Filters
AddCustomPhraseTokenHandler(0, (int)TokenHandlerPriority.Phrase, BuildPhraseRegex(in delimiter), in delimiter, false);
AddCustomFilterWithQuotesTokenHandler(0, (int)TokenHandlerPriority.FilterWithQuotes, in delimiter, operators, false);
}, sort);
}
public virtual void RemoveQuoteDelimiter(in QueryTextDelimiter textDelimiter, bool sort = true)
{
RemoveTextBlockDelimiter(in textDelimiter, m_QuoteDelimiters, k_QuoteHandlerKey, sort);
}
public virtual void AddCommentDelimiter(in QueryTextDelimiter textDelimiter, bool sort = true)
{
AddTextBlockDelimiter(in textDelimiter, m_CommentDelimiters, delimiter =>
{
AddCustomCommentTokenHandler(0, (int)TokenHandlerPriority.Comment, BuildTextBlockRegex(in delimiter), in delimiter, false);
}, sort);
}
public virtual void RemoveCommentDelimiter(in QueryTextDelimiter textDelimiter, bool sort = true)
{
RemoveTextBlockDelimiter(in textDelimiter, m_CommentDelimiters, k_CommentHandlerKey, sort);
}
public virtual void AddToggleDelimiter(in QueryTextDelimiter textDelimiter, bool sort = true)
{
AddTextBlockDelimiter(in textDelimiter, m_ToggleDelimiters, delimiter =>
{
AddCustomToggleTokenHandler(0, (int)TokenHandlerPriority.Toggle, BuildTextBlockRegex(in delimiter), in delimiter, false);
}, sort);
}
public virtual void RemoveToggleDelimiter(in QueryTextDelimiter textDelimiter, bool sort = true)
{
RemoveTextBlockDelimiter(in textDelimiter, m_ToggleDelimiters, k_ToggleHandlerKey, sort);
}
void AddTextBlockDelimiter(in QueryTextDelimiter textDelimiter, IList<QueryTextDelimiter> currentDelimiters, Action<QueryTextDelimiter> addDelimiterTokenHandlers, bool sort = true)
{
if (TextBlockDelimiterExist(in textDelimiter, currentDelimiters))
return;
addDelimiterTokenHandlers?.Invoke(textDelimiter);
currentDelimiters.Add(textDelimiter);
if (sort)
SortQueryTokenHandlers();
}
void RemoveTextBlockDelimiter(in QueryTextDelimiter textDelimiter, IEnumerable<QueryTextDelimiter> currentDelimiters, string typeKey, bool sort = true)
{
if (!TextBlockDelimiterExist(in textDelimiter, currentDelimiters))
return;
var hashCode = textDelimiter.GetHashCode();
RemoveQueryTokenHandlers(handler =>
{
if (!handler.userData.ContainsKey(typeKey) || !handler.userData.TryGetValue(QueryTextDelimiter.k_QueryHandlerDataKey, out var data))
return false;
return (int)data == hashCode;
});
if (sort)
SortQueryTokenHandlers();
}
protected void AddCustomPhraseTokenHandler(int handlerId, int priority, Regex matchRx, in QueryTextDelimiter textDelimiter, bool sort = true)
{
var queryTokenHandler = new QueryTokenHandler(handlerId, priority)
{
matcher = (string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched) => MatchText(matchRx, text, startIndex, endIndex, errors, out sv, out match, out matched),
consumer = ConsumeWord
};
AddCustomQuoteTokenHandler(queryTokenHandler, in textDelimiter, sort);
}
protected void AddCustomCommentTokenHandler(int handlerId, int priority, Regex matchRx, in QueryTextDelimiter textDelimiter, bool sort = true)
{
var queryTokenHandler = new QueryTokenHandler(handlerId, priority)
{
matcher = (string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched) => MatchText(matchRx, text, startIndex, endIndex, errors, out sv, out match, out matched),
consumer = ConsumeComment
};
ConfigureCommentTokenHandler(queryTokenHandler, in textDelimiter);
AddQueryTokenHandler(queryTokenHandler, sort);
}
protected void AddCustomToggleTokenHandler(int handlerId, int priority, Regex matchRx, in QueryTextDelimiter textDelimiter, bool sort = true)
{
var queryTokenHandler = new QueryTokenHandler(handlerId, priority)
{
matcher = (string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched) => MatchText(matchRx, text, startIndex, endIndex, errors, out sv, out match, out matched),
consumer = ConsumeToggle
};
ConfigureToggleTokenHandler(queryTokenHandler, in textDelimiter);
AddQueryTokenHandler(queryTokenHandler, sort);
}
protected void AddCustomFilterWithQuotesTokenHandler(int handlerId, int priority, in QueryTextDelimiter textDelimiter, IEnumerable<string> operators, bool sort = true)
{
var customFilterRegex = BuildFilterRegex(QueryRegexValues.k_FilterNamePattern, BuildFilterValuePatternFromQuoteDelimiter(in textDelimiter), operators);
var queryTokenHandler = new QueryTokenHandler(handlerId, priority)
{
matcher = (string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched) => MatchFilter(customFilterRegex, text, startIndex, endIndex, errors, out sv, out match, out matched),
consumer = ConsumeFilter
};
AddCustomQuoteTokenHandler(queryTokenHandler, in textDelimiter, sort);
}
protected void AddCustomQuoteTokenHandler(QueryTokenHandler handler, in QueryTextDelimiter textDelimiter, bool sort)
{
ConfigureQuoteTokenHandler(handler, in textDelimiter);
AddQueryTokenHandler(handler, sort);
}
protected void ConfigureQuoteTokenHandler(QueryTokenHandler handler, in QueryTextDelimiter textDelimiter)
{
ConfigureTextBlockTokenHandler(handler, in textDelimiter, k_QuoteHandlerKey);
}
protected void ConfigureCommentTokenHandler(QueryTokenHandler handler, in QueryTextDelimiter textDelimiter)
{
ConfigureTextBlockTokenHandler(handler, in textDelimiter, k_CommentHandlerKey);
}
protected void ConfigureToggleTokenHandler(QueryTokenHandler handler, in QueryTextDelimiter textDelimiter)
{
ConfigureTextBlockTokenHandler(handler, in textDelimiter, k_ToggleHandlerKey);
}
protected void ConfigureTextBlockTokenHandler(QueryTokenHandler handler, in QueryTextDelimiter textDelimiter, string typeKey)
{
handler.AddOrUpdateUserData(QueryTextDelimiter.k_QueryHandlerDataKey, textDelimiter.GetHashCode());
handler.AddOrUpdateUserData(typeKey, true);
}
public bool QuoteDelimiterExist(in QueryTextDelimiter textDelimiter)
{
return TextBlockDelimiterExist(in textDelimiter, m_QuoteDelimiters);
}
public bool CommentDelimiterExist(in QueryTextDelimiter textDelimiter)
{
return TextBlockDelimiterExist(in textDelimiter, m_CommentDelimiters);
}
public bool ToggleDelimiterExist(in QueryTextDelimiter textDelimiter)
{
return TextBlockDelimiterExist(in textDelimiter, m_ToggleDelimiters);
}
public bool TextBlockDelimiterExist(in QueryTextDelimiter textDelimiter, IEnumerable<QueryTextDelimiter> currentDelimiters)
{
foreach (var delimiterTokens in currentDelimiters)
{
if (delimiterTokens.Equals(textDelimiter))
return true;
}
return false;
}
public bool IsPhraseToken(string token)
{
if (token.Length < 2)
return false;
var startIndex = token[0] == '!' ? 1 : 0;
var sv = token.GetStringView(startIndex);
return m_QuoteDelimiters.Any(tokens => sv.StartsWith(tokens.openingToken) && sv.EndsWith(tokens.closingToken));
}
public StringView RemoveQuotes(in StringView token)
{
if (token.length < 2)
return token;
foreach (var quoteDelimiter in m_QuoteDelimiters)
{
if (token.length < (quoteDelimiter.openingToken.Length + quoteDelimiter.closingToken.Length))
continue;
if (token.StartsWith(quoteDelimiter.openingToken) && token.EndsWith(quoteDelimiter.closingToken))
{
return token.Substring(quoteDelimiter.openingToken.Length, token.length - quoteDelimiter.openingToken.Length - quoteDelimiter.closingToken.Length);
}
}
return token;
}
protected void AddQueryTokenHandler(QueryTokenHandler handler, bool sort = true)
{
m_TokenConsumers.Add(handler);
if (sort)
SortQueryTokenHandlers();
}
protected void RemoveQueryTokenHandlers(int id)
{
RemoveQueryTokenHandlers(handler => handler.id == id);
}
protected void RemoveQueryTokenHandlers(Func<QueryTokenHandler, bool> predicate)
{
m_TokenConsumers.RemoveAll(handler => predicate(handler));
}
protected void SortQueryTokenHandlers()
{
m_TokenConsumers.Sort(QueryTokenHandlerComparer);
}
static int QueryTokenHandlerComparer(QueryTokenHandler x, QueryTokenHandler y)
{
return x.priority.CompareTo(y.priority);
}
public void RebuildAllBasicFilterRegex(IEnumerable<string> operators, bool sort = true)
{
// Rebuild default filter regex
BuildFilterRegex(operators);
// Rebuild all token handlers for filters with quotes
RemoveQueryTokenHandlers(handler => handler.priority == (int)TokenHandlerPriority.FilterWithQuotes);
foreach (var quoteDelimiter in m_QuoteDelimiters)
{
AddCustomFilterWithQuotesTokenHandler(0, (int)TokenHandlerPriority.FilterWithQuotes, in quoteDelimiter, operators, false);
}
if (sort)
SortQueryTokenHandlers();
}
public void BuildFilterRegex(IEnumerable<string> operators)
{
m_FilterRx = BuildFilterRegex(QueryRegexValues.k_FilterNamePattern, QueryRegexValues.k_FilterValuePattern, operators);
}
public static Regex BuildFilterRegex(string filterNamePattern, IEnumerable<string> operators)
{
return BuildFilterRegex(filterNamePattern, QueryRegexValues.k_FilterValuePattern, operators);
}
public static Regex BuildFilterRegex(string filterNamePattern, string filterValuePattern, IEnumerable<string> operators)
{
var filterOperatorsPattern = BuildOperatorsPattern(operators);
return new Regex(filterNamePattern + QueryRegexValues.k_FilterFunctionPattern + filterOperatorsPattern + filterValuePattern, RegexOptions.Compiled);
}
public static Regex BuildBooleanFilterRegex(string filterNamePattern)
{
return new Regex(filterNamePattern + QueryRegexValues.k_FilterFunctionPattern, RegexOptions.Compiled);
}
public static Regex BuildPartialFilterRegex(string filterNamePattern, IEnumerable<string> operators)
{
return BuildPartialFilterRegex(filterNamePattern, QueryRegexValues.k_PartialFilterValuePattern, operators);
}
public static Regex BuildPartialFilterRegex(string filterNamePattern, string filterValuePattern, IEnumerable<string> operators)
{
var partialOperatorsPattern = BuildOperatorsPattern(operators) + "?";
return new Regex(filterNamePattern + QueryRegexValues.k_PartialFilterFunctionPattern + partialOperatorsPattern + filterValuePattern);
}
public static string BuildFilterNamePatternFromToken(string token)
{
token = Regex.Escape(token);
return BuildBasicFilterNamePattern(token);
}
static string BuildBasicFilterNamePattern(string token)
{
return $"\\G(?<name>{token})";
}
public static string BuildFilterNamePatternFromToken(Regex token)
{
var tokenString = token.ToString().GetStringView();
if (tokenString.StartsWith("\\G"))
tokenString = tokenString.Substring(2, tokenString.length - 2);
var capturedGroup = GetCapturedGroup(tokenString);
if (!capturedGroup.valid || capturedGroup.length <= 2)
return BuildBasicFilterNamePattern(tokenString.ToString());
var capturePattern = GetCapturePattern(capturedGroup);
var sb = new StringBuilder(tokenString.length);
if (!tokenString.StartsWith("\\G"))
sb.Append("\\G");
for (var i = 0; i < capturedGroup.startIndex; ++i)
sb.Append(tokenString[i]);
sb.Append($"(?<name>{capturePattern})");
for (var i = capturedGroup.endIndex; i < tokenString.length; ++i)
sb.Append(tokenString[i]);
return sb.ToString();
}
static StringView GetCapturedGroup(StringView tokenString)
{
var startIndex = -1;
var nestedLevel = 0;
for (var i = 0; i < tokenString.length; ++i)
{
if (IsEscaped(tokenString, i))
continue;
// We can only get capture group that we can name or are already named.
if (startIndex == -1 && IsValidCaptureOpener(tokenString, i))
{
startIndex = i;
}
if (startIndex != -1 && tokenString[i] == '(')
nestedLevel++;
if (startIndex != -1 && IsValidCaptureCloser(tokenString, i))
{
--nestedLevel;
if (nestedLevel == 0)
{
var endIndex = i + 1;
return tokenString.Substring(startIndex, endIndex - startIndex);
}
}
}
return StringView.nil;
}
static StringView GetCapturePattern(StringView captureGroup)
{
// We suppose the captureGroup was validated with IsValidCaptureOpener and IsValidCaptureClose
if (!captureGroup.valid)
return StringView.nil;
if (!captureGroup.StartsWith('(') || !captureGroup.EndsWith(')'))
return StringView.nil;
if (captureGroup.length == 2)
return StringView.empty;
if (captureGroup[1] != '?')
return captureGroup.Substring(1, captureGroup.length - 2);
for (var i = 2; i < captureGroup.length - 1; ++i)
{
// End of the capture name
if (captureGroup[i] == '>')
return captureGroup.Substring(i + 1, captureGroup.length - i - 2);
}
return StringView.nil;
}
static bool IsEscaped(StringView tokenString, int index)
{
if (index < 1 || index >= tokenString.length)
return false;
if (tokenString[index - 1] == '\\')
return true;
return false;
}
static bool IsValidCaptureOpener(StringView tokenString, int index)
{
if (index < 0 || index >= tokenString.length)
return false;
if (tokenString[index] != '(')
return false;
if (IsEscaped(tokenString, index))
return false;
if (index < tokenString.length - 1 && tokenString[index + 1] != '?')
return true;
index = index + 2;
if (index >= tokenString.length)
return false;
if (tokenString[index] != '<')
return false;
++index;
if (index >= tokenString.length)
return false;
if (tokenString[index] == '=' || tokenString[index] == '!')
return false;
for (; index < tokenString.length; ++index)
{
if (tokenString[index] == '-')
return false;
if (tokenString[index] == '>')
return true;
}
return false;
}
static bool IsValidCaptureCloser(StringView tokenString, int index)
{
if (index < 0 || index >= tokenString.length)
return false;
if (tokenString[index] != ')')
return false;
if (IsEscaped(tokenString, index))
return false;
return true;
}
public static string BuildPartialFilterNamePatternFromToken(string token, IEnumerable<string> operators)
{
var filterNamePattern = BuildFilterNamePatternFromToken(token);
var innerOperatorsPattern = BuildInnerOperatorsPattern(operators);
return $"{filterNamePattern}(?=\\(|(?:{innerOperatorsPattern}))";
}
public static string BuildPartialFilterNamePatternFromToken(Regex token, IEnumerable<string> operators)
{
var filterNamePattern = BuildFilterNamePatternFromToken(token);
var innerOperatorsPattern = BuildInnerOperatorsPattern(operators);
return $"{filterNamePattern}(?=\\(|(?:{innerOperatorsPattern}))";
}
public static Regex BuildPhraseRegex(in QueryTextDelimiter textDelimiter)
{
return new Regex(BuildTextBlockRegexPattern(in textDelimiter, "\\G!?", string.Empty));
}
public static Regex BuildTextBlockRegex(in QueryTextDelimiter textDelimiter)
{
return new Regex(BuildTextBlockRegexPattern(in textDelimiter, "\\G", string.Empty));
}
public static string BuildFilterValuePatternFromQuoteDelimiter(in QueryTextDelimiter textDelimiter)
{
return BuildTextBlockRegexPattern(in textDelimiter, "(?<value>", ")");
}
public static string BuildPartialFilterValuePatternFromQuoteDelimiter(in QueryTextDelimiter textDelimiter)
{
return BuildTextBlockRegexPattern(in textDelimiter, "(?<value>(?(op)(", ")))?");
}
static string BuildTextBlockRegexPattern(in QueryTextDelimiter textDelimiter, string prefix, string suffix)
{
return $"{prefix}{textDelimiter.escapedOpeningToken}(?<inner>.*?){textDelimiter.escapedClosingToken}{suffix}";
}
public static string BuildOperatorsPattern(IEnumerable<string> operators)
{
var innerOperatorsPattern = BuildInnerOperatorsPattern(operators);
return $"(?<op>{innerOperatorsPattern})";
}
public static string BuildInnerOperatorsPattern(IEnumerable<string> operators)
{
if (operators == null)
return QueryRegexValues.k_FilterOperatorsInnerPattern;
var sortedOperators = operators.Select(Regex.Escape).ToList();
sortedOperators.Sort((s, s1) => s1.Length.CompareTo(s.Length));
return $"{string.Join("|", sortedOperators)}";
}
public ParseState Parse(string text, int startIndex, int endIndex, ICollection<QueryError> errors, TUserData userData)
{
var index = startIndex;
while (index < endIndex)
{
var matched = false;
foreach (var t in m_TokenConsumers)
{
var matchLength = t.matcher(text, index, endIndex, errors, out var sv, out var match, out var consumerMatched);
if (!consumerMatched)
continue;
var consumed = t.consumer(text, index, index + matchLength, in sv, match, errors, userData);
if (!consumed)
{
return ParseState.ParseError;
}
index += matchLength;
matched = true;
break;
}
if (!matched)
{
errors.Add(new QueryError { index = index, reason = $"Error parsing string. No token could be deduced at {index}" });
return ParseState.NoMatch;
}
}
return ParseState.Matched;
}
static int MatchEmpty(string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
var currentIndex = startIndex;
var lengthMatched = 0;
matched = false;
while (currentIndex < endIndex && QueryEngineUtils.IsWhiteSpaceChar(text[currentIndex]))
{
++currentIndex;
++lengthMatched;
matched = true;
}
sv = text.GetStringView(startIndex, startIndex + lengthMatched);
match = null;
return lengthMatched;
}
static int MatchCombiningToken(string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
match = null;
sv = text.GetWordView(startIndex);
var totalUsableLength = endIndex - startIndex;
foreach (var combiningToken in k_CombiningToken)
{
var tokenLength = combiningToken.Length;
if (tokenLength > totalUsableLength)
continue;
if (sv.Equals(combiningToken, StringComparison.OrdinalIgnoreCase))
{
matched = true;
return sv.length;
}
}
matched = false;
return -1;
}
int MatchFilter(string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
return MatchFilter(m_FilterRx, text, startIndex, endIndex, errors, out sv, out match, out matched);
}
protected static int MatchFilter(Regex filterRx, string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
sv = text.GetStringView();
match = filterRx.Match(text, startIndex, endIndex - startIndex);
if (!match.Success)
{
matched = false;
return -1;
}
matched = true;
return match.Length;
}
static int MatchWord(string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
return MatchText(QueryRegexValues.k_WordRx, text, startIndex, endIndex, errors, out sv, out match, out matched);
}
static int MatchText(Regex textRegex, string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
sv = text.GetStringView();
match = textRegex.Match(text, startIndex, endIndex - startIndex);
if (!match.Success)
{
matched = false;
return -1;
}
matched = true;
return match.Length;
}
static int MatchGroup(string text, int groupStartIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
sv = text.GetStringView();
match = null;
if (groupStartIndex >= text.Length || text[groupStartIndex] != '(')
{
matched = false;
return -1;
}
matched = true;
if (groupStartIndex < 0 || groupStartIndex >= text.Length)
{
errors.Add(new QueryError { index = 0, reason = $"A group should have been found but index was {groupStartIndex}" });
return -1;
}
var parenthesisCounter = 1;
var groupEndIndex = groupStartIndex + 1;
for (; groupEndIndex < text.Length && parenthesisCounter > 0; ++groupEndIndex)
{
if (text[groupEndIndex] == '(')
++parenthesisCounter;
else if (text[groupEndIndex] == ')')
--parenthesisCounter;
}
// Because of the final ++groupEndIndex, decrement the index
--groupEndIndex;
var charConsumed = groupEndIndex - groupStartIndex + 1;
if (parenthesisCounter != 0)
{
errors.Add(new QueryError { index = groupStartIndex, length = 1, reason = $"Unbalanced parentheses" });
return -1;
}
sv = text.GetStringView(groupStartIndex, groupStartIndex + charConsumed);
var innerSv = text.GetStringView(groupStartIndex + 1, groupStartIndex + charConsumed - 1);
if (innerSv.IsNullOrWhiteSpace())
{
errors.Add(new QueryError { index = groupStartIndex, length = charConsumed, reason = $"Empty group" });
return -1;
}
return charConsumed;
}
static int MatchNestedQuery(string text, int startIndex, int endIndex, ICollection<QueryError> errors, out StringView sv, out Match match, out bool matched)
{
sv = text.GetStringView();
match = QueryRegexValues.k_NestedQueryRx.Match(text, startIndex, endIndex - startIndex);
if (!match.Success)
{
matched = false;
return -1;
}
matched = true;
return match.Length;
}
protected abstract bool ConsumeEmpty(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected abstract bool ConsumeCombiningToken(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected abstract bool ConsumeFilter(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected abstract bool ConsumeWord(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected abstract bool ConsumeComment(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected abstract bool ConsumeToggle(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected abstract bool ConsumeGroup(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
protected abstract bool ConsumeNestedQuery(string text, int startIndex, int endIndex, in StringView sv, Match match, ICollection<QueryError> errors, TUserData userData);
}
}
| UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryTokenizer.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryTokenizer.cs",
"repo_id": "UnityCsReference",
"token_count": 16563
} | 439 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using UnityEditor.Utils;
using UnityEngine;
namespace UnityEditor.Search
{
static partial class Evaluators
{
static string GetSelectedPath()
{
string currentSelectedPath = string.Empty;
if (ProjectBrowser.s_LastInteractedProjectBrowser)
{
if (ProjectBrowser.s_LastInteractedProjectBrowser.IsTwoColumns())
currentSelectedPath = ProjectBrowser.s_LastInteractedProjectBrowser.GetActiveFolderPath() ?? string.Empty;
else
{
currentSelectedPath = ProjectBrowser.GetSelectedPath() ?? string.Empty;
var isFile = File.Exists(currentSelectedPath);
var isDirectory = Directory.Exists(currentSelectedPath);
if (!isDirectory && !isFile)
currentSelectedPath = string.Empty;
else if (isFile)
{
currentSelectedPath = Path.GetDirectoryName(currentSelectedPath) ?? string.Empty;
}
}
}
return currentSelectedPath;
}
[Description("Returns the currently selected folder."), Category("Env")]
[SearchExpressionEvaluator]
public static IEnumerable<SearchItem> CurrentFolder(SearchExpressionContext c)
{
var currentSelectedPath = GetSelectedPath();
if (!string.IsNullOrEmpty(currentSelectedPath))
currentSelectedPath = currentSelectedPath.ConvertSeparatorsToUnity();
yield return SearchExpression.CreateItem(currentSelectedPath, c.ResolveAlias("CurrentFolder"));
}
[Description("Returns the currently selected folder name"), Category("Env")]
[SearchExpressionEvaluator]
public static IEnumerable<SearchItem> CurrentFolderName(SearchExpressionContext c)
{
var currentSelectedPath = GetSelectedPath();
if (!string.IsNullOrEmpty(currentSelectedPath))
{
currentSelectedPath = Path.GetFileName(currentSelectedPath);
}
yield return SearchExpression.CreateItem(currentSelectedPath, c.ResolveAlias("CurrentFolderName"));
}
[Description("Returns the name of the current project."), Category("Env")]
[SearchExpressionEvaluator]
public static IEnumerable<SearchItem> ProjectName(SearchExpressionContext c)
{
var desc = TaskEvaluatorManager.EvaluateMainThread(() => EditorApplication.GetDefaultProjectName());
yield return SearchExpression.CreateItem(desc ?? string.Empty, c.ResolveAlias("ProjectName"));
}
[Description("Returns the name of the currently opened scene."), Category("Env")]
[SearchExpressionEvaluator]
public static IEnumerable<SearchItem> SceneName(SearchExpressionContext c)
{
var desc = TaskEvaluatorManager.EvaluateMainThread(() => EditorApplication.GetApplicationTitleDescriptor());
yield return SearchExpression.CreateItem(desc.activeSceneName ?? string.Empty, c.ResolveAlias("SceneName"));
}
readonly struct SelectionResult
{
public readonly int instanceId;
public readonly string assetPath;
public SelectionResult(int instanceId, string assetPath)
{
this.instanceId = instanceId;
this.assetPath = assetPath;
}
}
[Description("Returns the current selection."), Category("Env")]
[SearchExpressionEvaluator]
public static IEnumerable<SearchItem> Selection(SearchExpressionContext c)
{
var selection = TaskEvaluatorManager.EvaluateMainThread(() =>
{
var instanceIds = UnityEditor.Selection.instanceIDs;
return instanceIds.Select(id =>
{
string assetPath = AssetDatabase.GetAssetPath(id);
return new SelectionResult(id, assetPath);
}).ToList();
});
foreach (var selectionResult in selection)
{
if (string.IsNullOrEmpty(selectionResult.assetPath))
yield return SearchExpression.CreateItem(selectionResult.instanceId, c.ResolveAlias("Selection"));
else
yield return SearchExpression.CreateItem(selectionResult.assetPath, c.ResolveAlias("Selection"));
}
}
[Description("Returns the path to the game data folder."), Category("Env")]
[SearchExpressionEvaluator]
public static IEnumerable<SearchItem> DataPath(SearchExpressionContext c)
{
var dataPath = TaskEvaluatorManager.EvaluateMainThread(() => Application.dataPath);
yield return SearchExpression.CreateItem(dataPath ?? string.Empty, c.ResolveAlias("DataPath"));
}
static Dictionary<string, MethodInfo> s_EnvFunctions = null;
static object s_EnvFunctionsLock = new object();
[Description("Returns the value of one or more environment variables."), Category("Env")]
[SearchExpressionEvaluator(SearchExpressionEvaluationHints.ImplicitArgsLiterals)]
[SearchExpressionEvaluatorSignatureOverload( SearchExpressionType.Text | SearchExpressionType.Variadic)]
public static IEnumerable<SearchItem> Env(SearchExpressionContext c)
{
lock (s_EnvFunctionsLock)
{
if (s_EnvFunctions == null)
{
var searchExpressionEvaluators = TypeCache.GetMethodsWithAttribute<SearchExpressionEvaluatorAttribute>();
s_EnvFunctions = searchExpressionEvaluators.Where(mi =>
{
// Discard self
if (mi.Name == "Env")
return false;
var categories = mi.GetCustomAttributes<CategoryAttribute>();
return categories.Any(category => category.Category == "Env");
}).ToDictionary(mi => Utils.FastToLower(mi.Name));
}
string[] envNames = null;
if (c.args.Length == 0)
envNames = s_EnvFunctions.Keys.ToArray();
else
envNames = c.args.Select(exp => Utils.FastToLower(exp.innerText.ToString())).ToArray();
foreach (var envName in envNames)
{
if (!s_EnvFunctions.TryGetValue(envName, out var mi))
{
yield return null;
continue;
}
var searchItems = mi.Invoke(null, new object[] { c }) as IEnumerable<SearchItem>;
if (searchItems == null)
{
yield return null;
continue;
}
foreach (var searchItem in searchItems)
yield return searchItem;
}
}
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/EnvarEvaluators.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/EnvarEvaluators.cs",
"repo_id": "UnityCsReference",
"token_count": 3428
} | 440 |
// 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
{
static partial class Parsers
{
[SearchExpressionParser("named", BuiltinParserPriority.Named)]
internal static SearchExpression NamedParser(SearchExpressionParserArgs args)
{
var text = ParserUtils.SimplifyExpression(args.text);
if (text.IsNullOrEmpty())
return null;
var match = ParserUtils.namedExpressionStartRegex.Match(text.ToString());
if (!match.Success || match.Index != 0 || match.Groups["name"].Length == 0)
return null;
var expressionsStartAndLength = ParserUtils.GetExpressionsStartAndLength(text, out _, out _);
if (expressionsStartAndLength.Length != 1)
return null;
var expressionName = match.Groups["name"].Value;
if ((expressionName.Length + expressionsStartAndLength[0].length) != text.length)
return null;
var evaluator = EvaluatorManager.GetEvaluatorByNameDuringParsing(expressionName, text.Substring(0, expressionName.Length));
var parametersText = text.Substring(expressionName.Length, text.length - expressionName.Length);
var parametersPositions = ParserUtils.ExtractArguments(parametersText, expressionName);
var parameters = new List<SearchExpression>();
var argsWith = SearchExpressionParserFlags.None;
var argsWithout = SearchExpressionParserFlags.ImplicitLiterals;
ApplyEvaluatorHints(evaluator.hints, ref argsWith, ref argsWithout);
foreach (var paramText in parametersPositions)
{
parameters.Add(ParserManager.Parse(args.With(paramText, argsWith).Without(argsWithout)));
}
if (!evaluator.hints.HasFlag(SearchExpressionEvaluationHints.DoNotValidateSignature) &&
args.HasOption(SearchExpressionParserFlags.ValidateSignature))
{
var signatures = EvaluatorManager.GetSignaturesByName(expressionName);
if (signatures != null)
SearchExpressionValidator.ValidateExpressionArguments(evaluator, parameters.ToArray(), signatures, text);
}
var expressionText = ParserUtils.SimplifyExpression(expressionsStartAndLength[0].Substring(1, expressionsStartAndLength[0].length - 2));
return new SearchExpression(SearchExpressionType.Function, args.text, expressionText, evaluator, parameters.ToArray());
}
static void ApplyEvaluatorHints(SearchExpressionEvaluationHints hints, ref SearchExpressionParserFlags with, ref SearchExpressionParserFlags without)
{
if (hints.HasFlag(SearchExpressionEvaluationHints.ImplicitArgsLiterals))
{
with |= SearchExpressionParserFlags.ImplicitLiterals;
without &= ~SearchExpressionParserFlags.ImplicitLiterals;
}
if (hints.HasFlag(SearchExpressionEvaluationHints.DoNotValidateArgsSignature))
{
without |= SearchExpressionParserFlags.ValidateSignature;
}
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/NamedExpressionParser.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/NamedExpressionParser.cs",
"repo_id": "UnityCsReference",
"token_count": 1357
} | 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;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;
namespace UnityEditor.Search
{
/// <summary>
/// Indicates how the search item description needs to be formatted when presented to the user.
/// </summary>
[Flags]
public enum SearchItemOptions
{
/// <summary>Use default description.</summary>
None = 0,
/// <summary>If the description is too long truncate it and add an ellipsis.</summary>
Ellipsis = 1 << 0,
/// <summary>If the description is too long keep the right part.</summary>
RightToLeft = 1 << 1,
/// <summary>Highlight parts of the description that match the Search Query</summary>
Highlight = 1 << 2,
/// <summary>Highlight parts of the description that match the Fuzzy Search Query</summary>
FuzzyHighlight = 1 << 3,
/// <summary>Use Label instead of description for shorter display.</summary>
Compacted = 1 << 4,
/// <summary>Have the item description always refreshed.</summary>
AlwaysRefresh = 1 << 5,
/// <summary>Item description is being drawn in details view.</summary>
FullDescription = 1 << 6,
/// <summary>Indicates that this item acts as a system action.</summary>
CustomAction = 1 << 7,
}
internal enum SearchItemSorting
{
Id,
Label,
Description,
Score,
Complete,
Value,
Default = Id
}
/// <summary>
/// Search items are returned by the search provider when some results need to be shown to the user after a search is made.
/// The search item holds all the data that will be used to sort and present the search results.
/// </summary>
[DebuggerDisplay("{id} | {label} | {score}")]
public class SearchItem : IEquatable<SearchItem>, IComparable<SearchItem>, IComparable
{
private Dictionary<Type, UnityEngine.Object> m_Objects;
/// <summary>
/// Unique id of this item among this provider items.
/// </summary>
public readonly string id;
/// <summary>
/// The item score can affect how the item gets sorted within the same provider.
/// </summary>
public int score;
/// <summary>
/// Display name of the item
/// </summary>
public string label;
/// <summary>
/// If no description is provided, SearchProvider.fetchDescription will be called when the item is first displayed.
/// </summary>
public string description;
/// <summary>
/// Various flags that dictates how the search item is displayed and used.
/// </summary>
public SearchItemOptions options;
/// <summary>
/// If no thumbnail are provider, SearchProvider.fetchThumbnail will be called when the item is first displayed.
/// </summary>
public Texture2D thumbnail;
/// <summary>
/// Large preview of the search item. Usually cached by fetchPreview.
/// </summary>
public Texture2D preview;
/// <summary>
/// Search provider defined content. It can be used to transport any data to custom search provider handlers (i.e. `fetchDescription`).
/// </summary>
public object data;
/// <summary>
/// Used to map value to a search item
/// </summary>
public object value { get => m_Value ?? id; set => m_Value = value; }
private object m_Value = null;
/// <summary>
/// Back pointer to the provider.
/// </summary>
public SearchProvider provider;
/// <summary>
/// Context used to create that item.
/// </summary>
public SearchContext context;
private static readonly SearchProvider defaultProvider = new SearchProvider("default", "Default")
{
priority = int.MinValue,
toObject = (item, type) => null,
fetchLabel = (item, context) => item.label ?? item.id,
fetchThumbnail = (item, context) => item.thumbnail ?? Icons.logInfo,
actions = new List<SearchAction> { new SearchAction("select", "select", null, null, (SearchItem item) => {}) }
};
[Obsolete("Use SearchItem.clear instead.", error: false)] // 2022.2
public static readonly SearchItem none = new SearchItem(Guid.NewGuid().ToString())
{
label = "None",
score = int.MinValue,
provider = defaultProvider,
options = SearchItemOptions.CustomAction
};
/// <summary>
/// A search item representing none, usually used to clear the selection.
/// </summary>
private static SearchItem s_ClearItem;
public static SearchItem clear
{
get
{
if (s_ClearItem == null)
{
#pragma warning disable CS0618 // Type or member is obsolete
s_ClearItem = none;
#pragma warning restore CS0618 // Type or member is obsolete
}
if (s_ClearItem.thumbnail == null && UnityEditorInternal.InternalEditorUtility.CurrentThreadIsMainThread())
s_ClearItem.thumbnail = Icons.clear;
return s_ClearItem;
}
}
/// <summary>
/// Construct a search item. Minimally a search item need to have a unique id for a given search query.
/// </summary>
/// <param name="_id"></param>
public SearchItem(string _id)
{
id = _id;
provider = defaultProvider;
}
/// <summary>
/// Fetch and format label.
/// </summary>
/// <param name="context">Any search context for the item provider.</param>
/// <param name="stripHTML">True if any HTML tags should be dropped.</param>
/// <returns>The search item label</returns>
public string GetLabel(SearchContext context, bool stripHTML = false)
{
if (label == null)
label = provider?.fetchLabel?.Invoke(this, context);
if (!stripHTML || string.IsNullOrEmpty(label))
return label;
return Utils.StripHTML(label);
}
/// <summary>
/// Fetch and format description
/// </summary>
/// <param name="context">Any search context for the item provider.</param>
/// <param name="stripHTML">True if any HTML tags should be dropped.</param>
/// <returns>The search item description</returns>
public string GetDescription(SearchContext context, bool stripHTML = false)
{
var tempDescription = description;
if (options.HasAny(SearchItemOptions.Compacted | SearchItemOptions.FullDescription) && provider?.fetchDescription != null)
return provider?.fetchDescription?.Invoke(this, context);
if (description == null && provider?.fetchDescription != null)
{
tempDescription = provider.fetchDescription(this, context);
if (!options.HasAny(SearchItemOptions.AlwaysRefresh))
description = tempDescription;
}
if (tempDescription == null)
{
if (m_Value != null)
return value.ToString();
if (options.HasAny(SearchItemOptions.Compacted))
return GetLabel(context, stripHTML);
}
if (!stripHTML || string.IsNullOrEmpty(tempDescription))
return tempDescription;
return Utils.StripHTML(tempDescription);
}
/// <summary>
/// Fetch the item thumbnail.
/// </summary>
/// <param name="context"></param>
/// <param name="cacheThumbnail"></param>
/// <returns></returns>
public Texture2D GetThumbnail(SearchContext context, bool cacheThumbnail = false)
{
if (cacheThumbnail && thumbnail)
return thumbnail;
var tex = provider?.fetchThumbnail?.Invoke(this, context);
var textureValid = tex && tex.width > 0 && tex.height > 0;
if (cacheThumbnail && textureValid)
thumbnail = tex;
return textureValid ? tex : null;
}
/// <summary>
/// Fetch the item preview if any.
/// </summary>
/// <param name="context"></param>
/// <param name="size"></param>
/// <param name="options"></param>
/// <param name="cacheThumbnail"></param>
/// <returns></returns>
public Texture2D GetPreview(SearchContext context, Vector2 size, FetchPreviewOptions options = FetchPreviewOptions.Normal, bool cacheThumbnail = false)
{
if (cacheThumbnail && preview)
return preview;
var tex = provider?.fetchPreview?.Invoke(this, context, size, options);
var textureValid = tex && tex.width > 0 && tex.height > 0;
if (cacheThumbnail && textureValid)
preview = tex;
return textureValid ? tex : null;
}
/// <summary>
/// Check if 2 SearchItems have the same id.
/// </summary>
/// <param name="other"></param>
/// <returns>Returns true if SearchItem have the same id.</returns>
public int CompareTo(SearchItem other)
{
return Comparer.Compare(this, other, SearchItemSorting.Default);
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="sortBy"></param>
/// <returns></returns>
internal int CompareTo(SearchItem other, SearchItemSorting sortBy)
{
return Comparer.Compare(this, other, sortBy);
}
/// <summary>
/// Generic item compare.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public int CompareTo(object other)
{
return Comparer.Compare(this, (SearchItem)other);
}
/// <summary>
/// Check if 2 SearchItems have the same id.
/// </summary>
/// <param name="other"></param>
/// <returns>>Returns true if SearchItem have the same id.</returns>
public override bool Equals(object other)
{
return other is SearchItem l && Equals(l);
}
internal int GetInstanceId()
{
if (provider != null && provider.toInstanceId != null)
return provider.toInstanceId(this);
return id.GetHashCode();
}
/// <summary>
/// Default Hash of a SearchItem
/// </summary>
/// <returns>A hash code for the current SearchItem</returns>
public override int GetHashCode()
{
return id.GetHashCode();
}
/// <summary>
/// Check if 2 SearchItems have the same id.
/// </summary>
/// <param name="other"></param>
/// <returns>>Returns true if SearchItem have the same id.</returns>
public bool Equals(SearchItem other)
{
return string.Equals(id, other.id, StringComparison.Ordinal);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (string.IsNullOrEmpty(label))
return $"[{score}] {value}";
if (string.IsNullOrEmpty(description))
return $"[{score}] {label} | {value}";
return $"[{score}] {label} [{score}] | {value} ({description})";
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public UnityEngine.Object ToObject()
{
return ToObject(typeof(UnityEngine.Object));
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public UnityEngine.Object ToObject(Type type)
{
if (m_Objects == null)
m_Objects = new Dictionary<Type, UnityEngine.Object>();
if (!m_Objects.TryGetValue(type, out var obj))
{
obj = provider?.toObject?.Invoke(this, type);
m_Objects[type] = obj;
}
return obj;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T ToObject<T>() where T : UnityEngine.Object
{
return ToObject(typeof(T)) as T;
}
internal Type ToType(Type constraintedType = null)
{
var itemType = provider?.toType?.Invoke(this, constraintedType);
if (itemType != null)
{
if (typeof(GameObject) != itemType || constraintedType == null || !typeof(Component).IsAssignableFrom(constraintedType))
return itemType;
}
var itemObj = ToObject(constraintedType ?? typeof(UnityEngine.Object));
return itemObj?.GetType();
}
/// <summary>
/// Return a unique document key owning this object
/// </summary>
internal ulong key
{
get
{
if (provider.toKey != null)
return provider.toKey(this);
return id.GetHashCode64();
}
}
/// <summary>
/// Insert new search item keeping the list sorted and preventing duplicated.
/// </summary>
/// <param name="list"></param>
/// <param name="item"></param>
/// <param name="sortBy"></param>
/// <returns></returns>
internal static bool Insert(IList<SearchItem> list, SearchItem item, IComparer<SearchItem> comparer)
{
var insertAt = BinarySearch(list, item, comparer);
if (insertAt < 0)
{
list.Insert(~insertAt, item);
return true;
}
if (comparer.Compare(item, list[insertAt]) < 0)
list[insertAt] = item;
return false;
}
internal static bool Insert(IList<SearchItem> list, SearchItem item)
{
return Insert(list, item, DefaultComparer);
}
private static int BinarySearch(IList<SearchItem> list, SearchItem value, IComparer<SearchItem> comparer = null)
{
if (list == null)
throw new ArgumentNullException(nameof(list));
comparer = comparer ?? DefaultComparer;
int lower = 0;
int upper = list.Count - 1;
while (lower <= upper)
{
int middle = lower + (upper - lower) / 2;
int comparisonResult = comparer.Compare(value, list[middle]);
if (comparisonResult == 0)
return middle;
else if (comparisonResult < 0)
upper = middle - 1;
else
lower = middle + 1;
}
return ~lower;
}
internal static readonly Comparer DefaultComparer = new Comparer(SearchItemSorting.Id);
internal readonly struct Comparer : IComparer<SearchItem>
{
public readonly SearchItemSorting sortBy;
public Comparer(SearchItemSorting sortBy)
{
this.sortBy = sortBy;
}
public int Compare(SearchItem x, SearchItem y)
{
return Compare(x, y, sortBy);
}
public static int Compare(SearchItem x, SearchItem y, SearchItemSorting sortBy = SearchItemSorting.Default)
{
if (sortBy == SearchItemSorting.Id)
return string.CompareOrdinal(x.id, y.id);
if (sortBy == SearchItemSorting.Value)
return System.Collections.Comparer.DefaultInvariant.Compare(x.value, y.value);
if (sortBy == SearchItemSorting.Label)
return string.Compare(x.GetLabel(x.context, true), y.GetLabel(y.context, true), StringComparison.InvariantCulture);
if (sortBy == SearchItemSorting.Description)
return string.Compare(x.GetDescription(x.context, true), y.GetDescription(y.context, true), StringComparison.InvariantCulture);
if (sortBy == SearchItemSorting.Score)
{
int c = string.CompareOrdinal(x.id, y.id);
if (c != 0)
return c;
return x.score.CompareTo(y.score);
}
return string.CompareOrdinal(x.id, y.id);
}
}
private Dictionary<string, SearchField> m_Fields;
public void SetField(string name, object value)
{
SetField(name, null, value);
}
public void SetField(string name, string alias, object value)
{
if (m_Fields == null)
m_Fields = new Dictionary<string, SearchField>();
var f = new SearchField(name, alias, value);
m_Fields[name] = f;
}
public bool RemoveField(string name)
{
if (m_Fields == null)
return false;
return m_Fields.Remove(name);
}
public bool TryGetField(string name, out SearchField field)
{
if (m_Fields != null && m_Fields.TryGetValue(name, out field))
return true;
field = default;
return false;
}
public bool TryGetValue(string name, out SearchField field)
{
return TryGetValue(name, null, out field);
}
public bool TryGetValue(string name, SearchContext context, out SearchField field)
{
if (name == null)
{
field = new SearchField(name, m_Value);
return true;
}
if (TryGetField(name, out field))
return true;
if (string.Equals("id", name, StringComparison.Ordinal))
{
field = new SearchField(name, id);
return true;
}
if (string.Equals("value", name, StringComparison.Ordinal))
{
field = new SearchField(name, m_Value);
return true;
}
if (string.Equals("label", name, StringComparison.OrdinalIgnoreCase))
{
options |= SearchItemOptions.Compacted;
field = new SearchField(name, GetLabel(context ?? this.context, true));
options &= ~SearchItemOptions.Compacted;
return field.value != null;
}
if (string.Equals("description", name, StringComparison.OrdinalIgnoreCase))
{
options |= SearchItemOptions.Compacted;
field = new SearchField(name, GetDescription(context ?? this.context, true));
options &= ~SearchItemOptions.Compacted;
return field.value != null;
}
if (string.Equals("score", name, StringComparison.Ordinal))
{
field = new SearchField(name, score);
return true;
}
field = default;
return false;
}
public object GetValue(string name = null, SearchContext context = null)
{
if (TryGetValue(name, context, out var field))
return field.value;
return null;
}
public object this[string name] => GetValue(name);
public int GetFieldCount()
{
if (m_Fields == null)
return 0;
return m_Fields.Count;
}
public string[] GetFieldNames()
{
if (m_Fields == null)
return new string[0];
return m_Fields.Keys.ToArray();
}
public IEnumerable<SearchField> GetFields()
{
if (m_Fields == null)
return Enumerable.Empty<SearchField>();
return m_Fields.Values;
}
}
public readonly struct SearchField : IEquatable<SearchField>
{
public readonly string name;
public readonly string alias;
public readonly object value;
public string label => alias ?? name;
public SearchField(string name)
{
this.name = name;
this.alias = null;
this.value = null;
}
public SearchField(string name, object value)
{
this.name = name;
this.alias = null;
this.value = value;
}
public SearchField(string name, string alias, object value)
{
this.name = name;
this.alias = alias;
this.value = value;
}
public override string ToString() => $"{name}[{label}]={value}";
public override int GetHashCode()
{
unchecked
{
return name.GetHashCode();
}
}
public override bool Equals(object other)
{
return other is SearchIndexEntry l && Equals(l);
}
public bool Equals(SearchField other)
{
return string.Equals(name, other.name, StringComparison.Ordinal);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchItem.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchItem.cs",
"repo_id": "UnityCsReference",
"token_count": 9997
} | 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;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
public static class ItemSelectors
{
internal static class Styles
{
private static readonly RectOffset paddingNone = new RectOffset(0, 0, 0, 0);
public static readonly GUIStyle itemLabel = new GUIStyle(EditorStyles.label)
{
name = "quick-search-item-label",
richText = true,
wordWrap = false,
margin = new RectOffset(8, 4, 4, 2),
padding = paddingNone
};
public static readonly GUIStyle itemLabelLeftAligned = new GUIStyle(itemLabel)
{
alignment = TextAnchor.MiddleLeft,
padding = new RectOffset(2, 2, 0, 0)
};
public static readonly GUIStyle itemLabelCenterAligned = new GUIStyle(itemLabelLeftAligned) { alignment = TextAnchor.MiddleCenter };
public static readonly GUIStyle itemLabelrightAligned = new GUIStyle(itemLabelLeftAligned) { alignment = TextAnchor.MiddleRight };
}
[SearchSelector("id", priority: 1)] static object GetSearchItemID(SearchItem item) => item.id;
[SearchSelector("label", priority: 1)] static object GetSearchItemLabel(SearchItem item) => item.GetLabel(item.context);
[SearchSelector("description", priority: 1)] static object GetSearchItemDesc(SearchItem item) => item.GetDescription(item.context);
[SearchSelector("value", priority: 1)] static object GetSearchItemValue(SearchItem item) => item.value;
[SearchSelector("provider", priority: 9)] static object GetSearchItemProvider(SearchItem item) => item.provider?.name;
[SearchSelector("score", priority: 9)] static object GetSearchItemScore(SearchItem item) => item.score;
[SearchSelector("options", priority: 9)] static object GetSearchItemOptions(SearchItem item) => item.options;
[SearchSelector("data", priority: 9)] static object GetSearchItemData(SearchItem item) => item.data?.ToString();
[SearchSelector("thumbnail", priority: 9, cacheable = false)] static object GetSearchItemThumbnail(SearchItem item) => item.GetThumbnail(item.context, cacheThumbnail: false);
[SearchSelector("preview", priority: 9, cacheable = false)] static object GetSearchItemPreview(SearchItem item) => item.GetPreview(item.context, new Vector2(64, 64), FetchPreviewOptions.Normal, cacheThumbnail: false);
[SearchSelector("Field/(?<fieldName>.+)", priority: 9, printable: false)]
static object GetSearchItemFieldValue(SearchSelectorArgs args) => args.current.GetValue(args["fieldName"].ToString());
public static SearchColumn CreateColumn(string path, string selector = null, string provider = null, SearchColumnFlags options = SearchColumnFlags.Default)
{
var pname = SearchColumn.ParseName(path);
return new SearchColumn(path, selector ?? path, provider, new GUIContent(pname), options);
}
public static IEnumerable<SearchColumn> Enumerate(IEnumerable<SearchItem> items = null)
{
yield return CreateColumn("Label", null, "Name");
yield return CreateColumn("Description");
if (items != null)
{
yield return CreateColumn("ID");
yield return CreateColumn("Name", null, "Name");
yield return CreateColumn("Value");
yield return CreateColumn("Thumbnail", "thumbnail", "Texture2D");
yield return CreateColumn("Default/Path", "path");
yield return CreateColumn("Default/Type", "type");
yield return CreateColumn("Default/Provider", "provider");
yield return CreateColumn("Default/Score", "score");
yield return CreateColumn("Default/Options", "options");
yield return CreateColumn("Default/Data", "data");
var firstItem = items.FirstOrDefault();
if (firstItem != null && firstItem.GetFieldCount() > 0)
{
foreach (var f in firstItem.GetFields())
yield return CreateColumn($"Field/{f.label}", f.name);
}
}
}
private static object GetName(SearchColumnEventArgs args)
{
var value = args.column.SelectValue(args.item, args.item.context ?? args.context);
if (value is Object obj)
return obj;
return (value ?? args.value)?.ToString();
}
private static VisualElement CreateVisualElement(SearchColumn column)
{
var image = new Image();
var label = new Label { style = { unityTextAlign = GetItemTextAlignment(column) } };
var container = new VisualElement();
container.AddToClassList("search-table-cell__item-name");
container.Add(image);
container.Add(label);
return container;
}
private static void BindName(SearchColumnEventArgs args, VisualElement ve)
{
var text = string.Empty;
Texture2D thumbnail = null;
if (args.value is Object obj)
{
text = obj.name;
thumbnail = AssetPreview.GetMiniThumbnail(obj);
}
else if (args.value != null)
{
var item = args.item;
text = args.value.ToString();
thumbnail = item.GetThumbnail(item.context ?? args.context);
}
ve.Q<Label>().text = text;
ve.Q<Image>().image = thumbnail;
}
[SearchColumnProvider("Default")]
internal static void InitializeObjectPathColumn(SearchColumn column)
{
column.getter = SearchColumn.DefaultSelect;
column.setter = null;
column.drawer = null;
column.comparer = null;
column.binder = null;
column.cellCreator = null;
}
[SearchColumnProvider("Name")]
internal static void InitializeItemNameColumn(SearchColumn column)
{
column.getter = GetName;
column.cellCreator = CreateVisualElement;
column.binder = BindName;
}
public static GUIStyle GetItemContentStyle(SearchColumn column)
{
if (column.options.HasAny(SearchColumnFlags.TextAlignmentCenter))
return Styles.itemLabelCenterAligned;
if (column.options.HasAny(SearchColumnFlags.TextAlignmentRight))
return Styles.itemLabelrightAligned;
return Styles.itemLabelLeftAligned;
}
internal static TextAnchor GetItemTextAlignment(SearchColumn column)
{
if (column.options.HasAny(SearchColumnFlags.TextAlignmentCenter))
return TextAnchor.MiddleCenter;
if (column.options.HasAny(SearchColumnFlags.TextAlignmentRight))
return TextAnchor.MiddleRight;
return TextAnchor.MiddleLeft;
}
[SearchColumnProvider("size")]
internal static void InitializeItemSizeColumn(SearchColumn column)
{
column.binder = (SearchColumnEventArgs args, VisualElement ve) =>
{
var label = (TextElement)ve;
string text = string.Empty;
if (Utils.TryGetNumber(args.value, out var n))
text = Utils.FormatBytes((long)n);
else if (args.value != null)
text = args.value.ToString();
label.text = text;
};
}
[SearchColumnProvider("count")]
internal static void InitializeCountColumn(SearchColumn column)
{
column.binder = (SearchColumnEventArgs args, VisualElement ve) =>
{
var label = (TextElement)ve;
string text = string.Empty;
if (Utils.TryGetNumber(args.value, out var n))
text = Utils.FormatCount((ulong)n);
else if (args.value != null)
text = args.value.ToString();
label.text = text;
};
}
[SearchColumnProvider("selectable")]
internal static void InitializeSelectableColumn(SearchColumn column)
{
column.binder = (args, ve) =>
{
var label = (TextElement)ve;
label.text = args.value?.ToString() ?? string.Empty;
label.selection.isSelectable = true;
};
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/Selectors/ItemSelectors.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/Selectors/ItemSelectors.cs",
"repo_id": "UnityCsReference",
"token_count": 3847
} | 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.Concurrent;
namespace UnityEditor.Search
{
public static class Dispatcher
{
readonly struct Task
{
readonly Action handler;
readonly double delayInSeconds;
readonly long timestamp;
public bool valid => handler != null;
public bool expired => delayInSeconds == 0d || TimeSpan.FromTicks(DateTime.UtcNow.Ticks - timestamp).TotalSeconds >= delayInSeconds;
public Task(in Action handler, in double delayInSeconds)
{
this.handler = handler;
this.delayInSeconds = delayInSeconds;
timestamp = DateTime.UtcNow.Ticks;
}
public bool Invoke()
{
if (!expired)
return false;
handler?.Invoke();
return true;
}
}
private static readonly ConcurrentQueue<Task> s_ExecutionQueue = new ConcurrentQueue<Task>();
private static readonly SearchEventManager s_SearchEventManager = new SearchEventManager();
static Dispatcher()
{
Utils.tick += Update;
}
public static void Enqueue(Action action)
{
Enqueue(action, 0.0d);
}
public static void Enqueue(Action action, double delayInSeconds)
{
Enqueue(new Task(action, delayInSeconds));
}
private static void Enqueue(in Task task)
{
s_ExecutionQueue.Enqueue(task);
}
public static bool ProcessOne()
{
if (!UnityEditorInternal.InternalEditorUtility.CurrentThreadIsMainThread())
return false;
if (!s_ExecutionQueue.TryDequeue(out var task) && task.valid)
return false;
return Process(task);
}
static bool Process(in Task task)
{
var done = task.Invoke();
if (!done)
Enqueue(task);
return done;
}
static void Update()
{
if (s_ExecutionQueue.IsEmpty)
return;
while (s_ExecutionQueue.TryDequeue(out var task) && task.valid)
if (!Process(task))
break;
}
public static Action CallDelayed(EditorApplication.CallbackFunction callback, double seconds = 0)
{
return Utils.CallDelayed(callback, seconds);
}
internal static Action On(string eventName, SearchEventHandler handler)
{
return s_SearchEventManager.On(eventName, handler);
}
internal static Action On(string eventName, SearchEventHandler handler, int handlerHashCode)
{
return s_SearchEventManager.On(eventName, handler, handlerHashCode);
}
internal static Action OnOnce(string eventName, SearchEventHandler handler)
{
return s_SearchEventManager.OnOnce(eventName, handler);
}
internal static Action OnOnce(string eventName, SearchEventHandler handler, int handlerHashCode)
{
return s_SearchEventManager.OnOnce(eventName, handler, handlerHashCode);
}
internal static void Off(string eventName, SearchEventHandler handler)
{
s_SearchEventManager.Off(eventName, handler);
}
internal static void Off(string eventName, int handlerHashCode)
{
s_SearchEventManager.Off(eventName, handlerHashCode);
}
internal static void Emit(string eventName, SearchEventPayload payload)
{
s_SearchEventManager.Emit(eventName, payload);
}
internal static void Emit(string eventName, SearchEventPayload payload, SearchEventPrepareHandler onPrepare, SearchEventResultHandler onResolved)
{
s_SearchEventManager.Emit(eventName, payload, onPrepare, onResolved);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UI/Dispatcher.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UI/Dispatcher.cs",
"repo_id": "UnityCsReference",
"token_count": 1847
} | 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.Generic;
using System.Linq;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
static class SearchEvent
{
public const string ViewStateUpdated = "search-view-state-updated";
public const string SearchTextChanged = "search-text-changed";
public const string SearchContextChanged = "search-context-changed";
public const string SelectionHasChanged = "search-selection-has-changed";
public const string RefreshBuilder = "search-refresh-builder";
public const string BuilderRefreshed = "search-builder-refreshed";
public const string FilterToggled = "search-filter-toggled";
public const string ExecuteSearchQuery = "execute-search-query";
public const string SearchQueryItemCountUpdated = "search-query-item-count-updated";
public const string SaveUserQuery = "search-save-user-query";
public const string SaveProjectQuery = "search-save-project-query";
public const string UserQueryAdded = "search-user-query-added";
public const string UserQueryRemoved = "search-user-query-removed";
public const string ProjectQueryAdded = "search-project-query-added";
public const string ProjectQueryRemoved = "search-project-query-removed";
public const string ProjectQueryListChanged = "search-project-query-list-changed";
public const string ActiveQueryChanged = "search-active-query-changed";
public const string SaveActiveSearchQuery = "search-save-active-search-query";
public const string SearchQueryChanged = "search-query-changed";
public const string TogglePackages = "search-toggle-packages";
public const string ToggleWantsMore = "search-toggle-wants-more";
public const string RefreshContent = "search-refresh-content";
public const string DisplayModeChanged = "search-display-mode-changed";
public const string RequestResultViewButtons = "search-request-result-view-buttons";
public const string ItemFavoriteStateChanged = "search-item-favorite-state-changed";
public const string SearchFieldFocused = "search-field-focused";
public const string SearchIndexesChanged = "search-indexes-changed";
}
interface ISearchElement
{
SearchContext context { get; }
SearchViewState viewState { get; }
}
static class StringUtilsExtensions
{
public static string WithUssElement(this string blockName, string elementName) => blockName + "__" + elementName;
public static string WithUssModifier(this string blockName, string modifier) => blockName + "--" + modifier;
}
static class SearchVisualElementExtensions
{
public static void SetClassState(this VisualElement self, in bool enabled, params string[] classNames)
{
if (enabled)
{
foreach (var n in classNames)
self.AddToClassList(n);
}
else
{
foreach (var n in classNames)
self.RemoveFromClassList(n);
}
}
public static EditorWindow GetHostWindow(this VisualElement self)
{
if (self == null || self.elementPanel == null)
return null;
if (self.elementPanel.ownerObject is HostView hv)
return hv.actualView;
if (self.elementPanel.ownerObject is IEditorWindowModel ewm)
return ewm.window;
if (self.elementPanel.ownerObject is EditorWindow window)
return window;
return null;
}
public static ISearchWindow GetSearchHostWindow(this VisualElement self)
{
if (self?.elementPanel == null)
return null;
if (self.elementPanel.ownerObject is ISearchWindow sw)
return sw;
if (self.elementPanel.ownerObject is HostView hv && hv.actualView is ISearchWindow hvsw)
return hvsw;
if (self.elementPanel.ownerObject is IEditorWindowModel ewm && ewm.window is ISearchWindow ewmsw)
return ewmsw;
return null;
}
public static bool HostWindowHasFocus(this VisualElement self)
{
if (self?.elementPanel == null)
return false;
if (self.elementPanel.ownerObject is ISearchWindow sw)
return sw.HasFocus();
var hostWindow = self.GetHostWindow();
return hostWindow?.hasFocus ?? false;
}
public static void RegisterFireAndForgetCallback<TEventType>(this VisualElement self, EventCallback<TEventType> callback)
where TEventType : EventBase<TEventType>, new()
{
EventCallback<TEventType> outerCallback = null;
outerCallback = evt =>
{
try
{
callback?.Invoke(evt);
}
finally
{
self.UnregisterCallback<TEventType>(outerCallback);
}
};
self.RegisterCallback<TEventType>(outerCallback);
}
}
abstract class SearchElement : VisualElement, ISearchElement
{
private const string ussBasePath = "StyleSheets/QuickSearch";
private static readonly string ussPath = $"{ussBasePath}/SearchWindow.uss";
private static readonly string ussPathDark = $"{ussBasePath}/SearchWindow_Dark.uss";
private static readonly string ussPathLight = $"{ussBasePath}/SearchWindow_Light.uss";
public static readonly string baseIconButtonClassName = "search-icon-button";
protected readonly ISearchView m_ViewModel;
public virtual SearchContext context => m_ViewModel.context;
public virtual SearchViewState viewState => m_ViewModel.state;
public bool attachedToPanel { get; private set; }
public bool geometryRealized { get; private set; }
public SearchElement(ISearchView viewModel)
{
m_ViewModel = viewModel;
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
public SearchElement(string name, ISearchView viewModel, params string[] classes)
: this(viewModel)
{
this.name = name;
m_ViewModel = viewModel;
foreach (var c in classes)
AddToClassList(c);
}
protected virtual void OnAttachToPanel(AttachToPanelEvent evt)
{
attachedToPanel = true;
this.RegisterFireAndForgetCallback<GeometryChangedEvent>(OnGeometryChangedEvent);
}
protected virtual void OnDetachFromPanel(DetachFromPanelEvent evt)
{
attachedToPanel = false;
geometryRealized = false;
}
void OnGeometryChangedEvent(GeometryChangedEvent evt)
{
geometryRealized = true;
}
internal static void HideElements<T>(params T[] elements) where T : VisualElement
{
HideElements(elements.AsEnumerable());
}
internal static void HideElements<T>(IEnumerable<T> elements) where T : VisualElement
{
foreach (var e in elements)
e.style.display = DisplayStyle.None;
}
internal static void ShowElements<T>(params T[] elements) where T : VisualElement
{
foreach (var e in elements)
e.style.display = DisplayStyle.Flex;
}
internal static bool IsElementVisible(VisualElement e)
{
return e.style.display != DisplayStyle.None;
}
internal static bool IsPartOf<T>(in VisualElement e) where T : VisualElement
{
if (e == null)
return false;
if (e is T)
return true;
return IsPartOf<T>(e.parent);
}
internal static VisualElement Create(in string name, params string[] classNames)
{
return Create<VisualElement>(name, classNames);
}
internal static T Create<T>(in string name, params string[] classNames) where T : VisualElement, new()
{
var ve = new T { name = name };
foreach (var n in classNames)
ve.AddToClassList(n);
return ve;
}
internal static T Create<T, TEventType>(in string name, EventCallback<TEventType> handler, params string[] classes)
where T : VisualElement, new()
where TEventType : EventBase<TEventType>, new()
{
var ve = Create<T>(name, classes);
ve.RegisterCallback(handler);
return ve;
}
internal static Button CreateButton(in string name, in GUIContent content, Action handler, params string[] classNames)
{
var button = CreateButton(name, content.text, content.tooltip, handler, classNames);
button.Add(new Image() { image = content.image });
return button;
}
internal static Button CreateButton(in string name, in string text, in string tooltip, Action handler, params string[] classNames)
{
var button = Create<Button>(name, classNames);
button.clickable = new Clickable(handler);
button.text = text;
button.tooltip = tooltip;
return button;
}
internal static Button CreateButton(in string name, in string tooltip, Action handler, params string[] classNames)
{
return CreateButton(name, string.Empty, tooltip, handler, classNames);
}
internal static ToolbarToggle CreateToolbarToggle(in string name, in string tooltip, bool value, EventCallback<ChangeEvent<bool>> handler, params string[] classNames)
{
var btn = Create<ToolbarToggle, ChangeEvent<bool>>(name, handler, classNames);
btn.tooltip = tooltip;
btn.SetValueWithoutNotify(value);
return btn;
}
internal static Label CreateLabel(in string text, in string tooltip, PickingMode pickingMode, params string[] classNames)
{
var l = Create<Label>(null, classNames);
l.text = text;
l.tooltip = tooltip;
l.pickingMode = pickingMode;
return l;
}
internal static Label CreateLabel(in string text, in string tooltip, params string[] classNames)
{
return CreateLabel(text, tooltip, PickingMode.Position, classNames);
}
internal static Label CreateLabel(in string text, params string[] classNames)
{
return CreateLabel(text, null, classNames);
}
internal static Label CreateLabel(in string text, PickingMode pickingMode, params string[] classNames)
{
return CreateLabel(text, null, pickingMode, classNames);
}
internal static Label CreateLabel(in GUIContent content, params string[] classNames)
{
return CreateLabel(content.text, content.tooltip, classNames);
}
internal static Label CreateLabel(in GUIContent content, PickingMode pickingMode, params string[] classNames)
{
return CreateLabel(content.text, content.tooltip, pickingMode, classNames);
}
internal void Emit(string eventName, params object[] arguments)
{
Dispatcher.Emit(eventName, new SearchEventPayload(this, arguments));
}
internal void Emit(string eventName, SearchEventPrepareHandler onPrepare, SearchEventResultHandler onResolved, params object[] arguments)
{
Dispatcher.Emit(eventName, new SearchEventPayload(this, arguments), onPrepare, onResolved);
}
protected Action On(string eventName, SearchEventHandler handler)
{
return Dispatcher.On(eventName, evt =>
{
if (!IsEventFromSameView(evt))
return;
handler(evt);
}, SearchEventManager.GetSearchEventHandlerHashCode(handler));
}
protected Action OnAll(string eventName, SearchEventHandler handler)
{
return Dispatcher.On(eventName, handler, SearchEventManager.GetSearchEventHandlerHashCode(handler));
}
protected Action OnOther(string eventName, SearchEventHandler handler)
{
return Dispatcher.On(eventName, evt =>
{
if (IsEventFromSameView(evt))
return;
handler(evt);
}, SearchEventManager.GetSearchEventHandlerHashCode(handler));
}
protected void Off(string eventName, SearchEventHandler handler)
{
Dispatcher.Off(eventName, SearchEventManager.GetSearchEventHandlerHashCode(handler));
}
protected bool IsEventFromSameView(ISearchEvent evt)
{
return evt.sourceViewState == viewState;
}
protected Action RegisterGlobalEventHandler<T>(SearchGlobalEventHandler<T> eventHandler, int priority)
where T : EventBase
{
return viewState.globalEventManager.RegisterGlobalEventHandler(eventHandler, priority);
}
protected void UnregisterGlobalEventHandler<T>(SearchGlobalEventHandler<T> eventHandler)
where T : EventBase
{
viewState.globalEventManager.UnregisterGlobalEventHandler(eventHandler);
}
internal static void AppendStyleSheets(VisualElement ve)
{
if (!ve.HasStyleSheetPath(ussPath))
ve.AddStyleSheetPath(ussPath);
var themedUssPath = EditorGUIUtility.isProSkin ? ussPathDark : ussPathLight;
if (!ve.HasStyleSheetPath(themedUssPath))
ve.AddStyleSheetPath(themedUssPath);
}
internal static VisualElement FlexibleSpace()
{
var fspace = new VisualElement();
fspace.AddToClassList("flex-space");
return fspace;
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchElement.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchElement.cs",
"repo_id": "UnityCsReference",
"token_count": 5991
} | 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.Collections.Generic;
using System.Linq;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Search;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
class SearchToolbar : UIElements.Toolbar, ISearchElement
{
private static readonly string openSaveSearchesIconTooltip = L10n.Tr("Open Saved Searches Panel (F3)");
public static readonly string queryBuilderIconTooltip = L10n.Tr("Toggle Query Builder Mode (F1)");
public static readonly string previewInspectorButtonTooltip = L10n.Tr("Open Inspector (F4)");
public static readonly string saveQueryButtonTooltip = L10n.Tr("Save search query as an asset.");
public static readonly string pressToFilterTooltip = L10n.Tr("Press Tab \u21B9 to filter");
protected readonly ISearchView m_ViewModel;
protected readonly Toggle m_SearchQueryToggle;
protected readonly Toggle m_QueryBuilderToggle;
protected readonly Toggle m_InspectorToggle;
protected readonly SearchFieldElement m_SearchField;
private readonly ToolbarMenu s_SaveQueryDropdown;
public virtual SearchContext context => m_ViewModel.context;
public virtual SearchViewState viewState => m_ViewModel.state;
public SearchFieldElement searchField => m_SearchField;
internal QueryBuilder queryBuilder => m_SearchField.queryBuilder;
public new static readonly string ussClassName = "search-toolbar";
public static readonly string buttonClassName = ussClassName.WithUssElement("button");
public static readonly string dropdownClassName = ussClassName.WithUssElement("dropdown");
public static readonly string savedSearchesButtonClassName = ussClassName.WithUssElement("saved-searches-button");
public static readonly string queryBuilderButtonClassName = ussClassName.WithUssElement("query-builder-button");
public static readonly string inspectorButtonClassName = ussClassName.WithUssElement("inspector-button");
public static readonly string saveQueryButtonClassName = ussClassName.WithUssElement("save-query-button");
public SearchToolbar(string name, ISearchView viewModel)
{
this.name = name;
m_ViewModel = viewModel;
AddToClassList(ussClassName);
var window = viewModel as SearchWindow;
// Search query panel toggle
if (viewState.hasQueryPanel)
{
m_SearchQueryToggle = SearchElement.CreateToolbarToggle("SearchQueryPanelToggle", openSaveSearchesIconTooltip, viewState.flags.HasAny(SearchViewFlags.OpenLeftSidePanel), OnToggleSearchQueryPanel, buttonClassName, savedSearchesButtonClassName);
Add(m_SearchQueryToggle);
}
// Query builder toggle
if (viewState.hasQueryBuilderToggle)
{
m_QueryBuilderToggle = SearchElement.CreateToolbarToggle("SearchQueryBuilderToggle", queryBuilderIconTooltip, viewState.queryBuilderEnabled, OnToggleQueryBuilder, buttonClassName, queryBuilderButtonClassName);
Add(m_QueryBuilderToggle);
}
// Search field
m_SearchField = new SearchFieldElement(nameof(SearchFieldElement), viewModel, useSearchGlobalEventHandler:true);
Add(m_SearchField);
// Save query dropdown
if (viewState.hasQueryPanel)
{
s_SaveQueryDropdown = SearchElement.Create<ToolbarMenu, MouseUpEvent>("SearchSaveQueryMenu", OnSaveQueryDropdown, buttonClassName, dropdownClassName, saveQueryButtonClassName);
Add(s_SaveQueryDropdown);
UpdateSaveQueryButton();
}
// Details view panel toggle.
if (viewState.flags.HasNone(SearchViewFlags.DisableInspectorPreview))
{
m_InspectorToggle = SearchElement.CreateToolbarToggle("SearchInspectorToggle", previewInspectorButtonTooltip, viewState.flags.HasAny(SearchViewFlags.OpenInspectorPreview), OnToggleInspector, buttonClassName, inspectorButtonClassName);
Add(m_InspectorToggle);
}
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
void UpdateSaveQueryButton()
{
if (s_SaveQueryDropdown == null)
return;
s_SaveQueryDropdown.SetEnabled(!context.empty);
}
private void OnToggleQueryBuilder(ChangeEvent<bool> evt)
{
if (m_ViewModel is SearchWindow window)
window.ToggleQueryBuilder();
m_SearchField.ToggleQueryBuilder();
}
private void OnToggleSearchQueryPanel(ChangeEvent<bool> evt)
{
if (m_ViewModel is SearchWindow window)
window.TogglePanelView(SearchViewFlags.OpenLeftSidePanel);
}
private void OnToggleInspector(ChangeEvent<bool> evt)
{
if (m_ViewModel is SearchWindow window)
window.TogglePanelView(SearchViewFlags.OpenInspectorPreview);
}
private void OnSaveQuery(ISearchQueryView window)
{
var saveQueryMenu = new GenericMenu();
if (m_ViewModel.state.activeQuery != null)
{
saveQueryMenu.AddItem(new GUIContent($"Save {m_ViewModel.state.activeQuery.displayName}"), false, window.SaveActiveSearchQuery);
saveQueryMenu.AddSeparator("");
}
AddSaveQueryMenuItems(window, saveQueryMenu);
saveQueryMenu.ShowAsContext();
}
private void OnSaveQueryDropdown(MouseUpEvent evt)
{
if (m_ViewModel is ISearchQueryView window)
OnSaveQuery(window);
}
private void AddSaveQueryMenuItems(ISearchQueryView window, GenericMenu saveQueryMenu)
{
saveQueryMenu.AddItem(new GUIContent("Save User"), false, window.SaveUserSearchQuery);
saveQueryMenu.AddItem(new GUIContent("Save Project..."), false, window.SaveProjectSearchQuery);
if (!string.IsNullOrEmpty(context.searchText))
{
saveQueryMenu.AddSeparator("");
saveQueryMenu.AddItem(new GUIContent("Clipboard"), false, () => SaveQueryToClipboard(context.searchText));
}
}
private void SaveQueryToClipboard(in string query)
{
var trimmedQuery = Utils.TrimText(query);
Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, trimmedQuery);
EditorGUIUtility.systemCopyBuffer = Utils.TrimText(trimmedQuery);
}
private void OnAttachToPanel(AttachToPanelEvent evt)
{
Dispatcher.On(SearchEvent.ViewStateUpdated, OnViewFlagsUpdated);
Dispatcher.On(SearchEvent.SearchTextChanged, OnSearchQueryChanged);
Dispatcher.On(SearchEvent.SearchContextChanged, OnSearchQueryChanged);
}
private void OnDetachFromPanel(DetachFromPanelEvent evt)
{
Dispatcher.Off(SearchEvent.ViewStateUpdated, OnViewFlagsUpdated);
Dispatcher.Off(SearchEvent.SearchTextChanged, OnSearchQueryChanged);
Dispatcher.Off(SearchEvent.SearchContextChanged, OnSearchQueryChanged);
}
private void OnSearchQueryChanged(ISearchEvent evt)
{
UpdateSaveQueryButton();
}
private void OnViewFlagsUpdated(ISearchEvent evt)
{
if (evt.sourceViewState != viewState)
return;
m_QueryBuilderToggle?.SetValueWithoutNotify(evt.sourceViewState.queryBuilderEnabled);
m_SearchQueryToggle?.SetValueWithoutNotify(evt.sourceViewState.flags.HasAny(SearchViewFlags.OpenLeftSidePanel));
m_InspectorToggle?.SetValueWithoutNotify(evt.sourceViewState.flags.HasAny(SearchViewFlags.OpenInspectorPreview));
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchToolbar.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchToolbar.cs",
"repo_id": "UnityCsReference",
"token_count": 3309
} | 446 |
// 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.IMGUI.Controls;
using UnityEditor.Search;
using UnityEngine;
namespace UnityEditor.SceneTemplate
{
class ListSelectionWindow : AdvancedDropdown
{
Action<int> m_ElementSelectedHandler;
List<SearchProposition> m_Models;
ListSelectionWindow(Rect rect, List<SearchProposition> models, Action<int> elementSelectedHandler)
: base(new AdvancedDropdownState())
{
m_Models = models;
m_ElementSelectedHandler = elementSelectedHandler;
minimumSize = new Vector2(Mathf.Max(rect.width, 300f), 350f);
maximumSize = new Vector2(Mathf.Max(rect.width, 400f), 450f);
}
public static void Open(Rect rect, List<SearchProposition> models, Action<int> elementSelectedHandler)
{
var win = new ListSelectionWindow(rect, models, elementSelectedHandler);
win.Show(rect);
win.Bind();
}
void Bind()
{
m_WindowInstance.windowClosed += OnClose;
m_WindowInstance.selectionCanceled += OnSelectionCanceled;
}
void OnSelectionCanceled()
{
m_ElementSelectedHandler?.Invoke(-1);
}
void OnClose(AdvancedDropdownWindow win)
{
if (!win)
{
m_ElementSelectedHandler?.Invoke(-1);
return;
}
var selectedItem = win.GetSelectedItem();
m_ElementSelectedHandler?.Invoke(selectedItem.elementIndex);
}
protected override AdvancedDropdownItem BuildRoot()
{
var rootItem = new AdvancedDropdownItem("Browse types...");
for (var i = 0; i < m_Models.Count; ++i)
{
var p = m_Models[i];
var path = p.path;
var name = p.label;
var prefix = p.category;
if (name.LastIndexOf('/') != -1)
{
var ls = path.LastIndexOf('/');
name = path.Substring(ls+1);
prefix = path.Substring(0, ls);
}
var newItem = new AdvancedDropdownItem(path)
{
displayName = name,
icon = p.icon,
tooltip = p.help,
userData = p,
elementIndex = i
};
var parent = rootItem;
if (prefix != null)
parent = MakeParents(prefix, p, rootItem);
var fit = FindItem(name, parent);
if (fit == null)
parent.AddChild(newItem);
else if (p.icon)
fit.icon = p.icon;
}
return rootItem;
}
AdvancedDropdownItem FindItem(string path, AdvancedDropdownItem root)
{
var pos = path.IndexOf('/');
var name = pos == -1 ? path : path.Substring(0, pos);
var suffix = pos == -1 ? null : path.Substring(pos + 1);
foreach (var c in root.children)
{
if (suffix == null && string.Equals(c.name, name, StringComparison.Ordinal))
return c;
if (suffix == null)
continue;
var f = FindItem(suffix, c);
if (f != null)
return f;
}
return null;
}
AdvancedDropdownItem MakeParents(string prefix, in SearchProposition proposition, AdvancedDropdownItem parent)
{
var parts = prefix.Split('/');
foreach (var p in parts)
{
var f = FindItem(p, parent);
if (f != null)
{
if (f.icon == null)
f.icon = proposition.icon;
parent = f;
}
else
{
var newItem = new AdvancedDropdownItem(p) { icon = proposition.icon };
parent.AddChild(newItem);
parent = newItem;
}
}
return parent;
}
}
}
| UnityCsReference/Modules/SceneTemplateEditor/ListSelectionWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/SceneTemplateEditor/ListSelectionWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 2358
} | 447 |
// 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.Overlays;
using UnityEditor.ShortcutManagement;
using UnityEditor.Toolbars;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using static UnityEditor.CameraPreviewUtils;
namespace UnityEditor
{
class ViewpointNameComparer : IComparer<IViewpoint>
{
public int Compare(IViewpoint x, IViewpoint y)
{
return x.TargetObject.name.CompareTo(y.TargetObject.name);
}
}
sealed class CameraLookThrough : EditorToolbarDropdown
{
const string k_DropdownButtonUSSClass = "unity-cameras-overlay-selector";
static readonly string k_NoCameraFound = L10n.Tr("No camera found");
static readonly string k_Tooltip = L10n.Tr("Select a camera in the Scene.");
[SerializeField]
CamerasOverlay m_Overlay;
public CameraLookThrough(CamerasOverlay overlay) : base()
{
tooltip = k_Tooltip;
text = k_NoCameraFound;
// The button will always reflect the Viewpoint's gameobject name.
var textElement = this.Query<TextElement>().Children<TextElement>().First();
textElement.bindingPath = "m_Name";
m_Overlay = overlay;
m_Overlay.onViewpointSelected += OnViewpointSelected;
AddToClassList(k_DropdownButtonUSSClass);
RegisterCallback<ClickEvent>(ShowSelectionDropdown);
Initialize();
}
void Initialize()
{
SetCameraName();
}
void SetCameraName()
{
this.Unbind();
if (m_Overlay.viewpoint != null)
{
icon = ViewpointProxyTypeCache.GetIcon(m_Overlay.viewpoint);
this.Bind(new SerializedObject((m_Overlay.viewpoint.TargetObject as Component).gameObject));
}
else
{
icon = null;
text = k_NoCameraFound;
}
}
void ShowSelectionDropdown(ClickEvent evt)
{
var menu = new DropdownMenu();
foreach (var vp in m_Overlay.availableViewpoints)
{
var status = vp.TargetObject.Equals(m_Overlay.viewpoint.TargetObject) ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal;
menu.AppendAction(vp.TargetObject.name, (_) => { m_Overlay.viewpoint = vp; }, status);
}
menu.DoDisplayEditorMenu(worldBound);
}
void OnViewpointSelected(IViewpoint vp) => SetCameraName();
}
sealed class CameraInspectProperties : EditorToolbarButton
{
[SerializeField]
CamerasOverlay m_Overlay;
[SerializeField]
PropertyEditor m_ActiveEditor;
public CameraInspectProperties(CamerasOverlay overlay) : base()
{
icon = EditorGUIUtility.FindTexture("UnityEditor.InspectorWindow");
tooltip = L10n.Tr("Open camera component properties.");
m_Overlay = overlay;
RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
void OnAttachedToPanel(AttachToPanelEvent evt)
{
clicked += OnClicked;
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
clicked -= OnClicked;
}
void OnClicked()
{
if (m_Overlay.viewpoint == null)
return;
if (m_ActiveEditor != null)
{
m_ActiveEditor.Focus();
return;
}
m_ActiveEditor = PropertyEditor.OpenPropertyEditor(m_Overlay.viewpoint.TargetObject, true);
}
}
sealed class CameraOverscanSettingsWindow : OverlayPopupWindow
{
readonly string k_OverscanScaleTooltip = L10n.Tr("Configure size of overscan view guides.");
readonly string k_OverscanOpacityTooltip = L10n.Tr("Configure overscan opacity.");
protected override void OnEnable()
{
base.OnEnable();
var sceneView = SceneView.lastActiveSceneView;
var settings = sceneView.viewpoint.cameraOverscanSettings;
var scale = new Slider(L10n.Tr("Overscan"), SceneViewViewpoint.ViewpointSettings.minScale, SceneViewViewpoint.ViewpointSettings.maxScale, SliderDirection.Horizontal, 1f);
scale.tooltip = k_OverscanScaleTooltip;
scale.SetValueWithoutNotify(settings.scale);
scale.showInputField = true;
scale.RegisterValueChangedCallback(evt =>
{
settings.scale = evt.newValue;
sceneView.Repaint();
});
rootVisualElement.Add(scale);
var opacity = new SliderInt(L10n.Tr("Overscan Opacity"), SceneViewViewpoint.ViewpointSettings.minOpacity, SceneViewViewpoint.ViewpointSettings.maxOpacity, SliderDirection.Horizontal, 1);
opacity.tooltip = k_OverscanOpacityTooltip;
opacity.SetValueWithoutNotify(settings.opacity);
opacity.showInputField = true;
opacity.RegisterValueChangedCallback(evt =>
{
settings.opacity = evt.newValue;
sceneView.Repaint();
});
rootVisualElement.Add(opacity);
}
}
sealed class CameraViewToggle : EditorToolbarDropdownToggle
{
const string k_ShortcutIdPrefx = "Scene View/Camera View/";
const string k_IconPathNormal = "Overlays/Fullscreen";
const string k_IconPathActive = "Overlays/FullscreenOn";
readonly string k_TooltipNormal = L10n.Tr("Control the selected camera in first person.");
readonly string k_TooltipActive = L10n.Tr("Return to Scene Camera.");
[Shortcut(k_ShortcutIdPrefx + "Toggle Between Scene Camera and Last Controlled Camera", typeof(SceneView))]
static void ToggleViewWithLastViewpoint(ShortcutArguments args)
{
SceneView sv = SceneView.focusedWindow as SceneView;
if (sv.TryGetOverlay(CamerasOverlay.overlayId, out Overlay match))
{
var toggleInstance = match.contentRoot.Q<CameraViewToggle>();
if (toggleInstance == null)
return;
if (toggleInstance.canActivate)
toggleInstance.value = !toggleInstance.value;
}
}
[SerializeField]
CamerasOverlay m_Overlay;
SceneView sceneView => m_Overlay.containerWindow as SceneView;
bool canActivate => m_Overlay.viewpoint != null;
public CameraViewToggle(CamerasOverlay overlay) : base()
{
m_Overlay = overlay;
m_Overlay.onWillBeDestroyed += OnWillBeDestroyed;
m_Overlay.displayedChanged += OnDisplayChanged;
RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
Initialize();
}
void OnAttachedToPanel(AttachToPanelEvent evt)
{
this.RegisterValueChangedCallback(ValueChanged);
m_Overlay.onViewpointSelected += ViewpointChanged;
dropdownClicked += OnDropdownClicked;
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
this.UnregisterValueChangedCallback(ValueChanged);
m_Overlay.onViewpointSelected -= ViewpointChanged;
dropdownClicked -= OnDropdownClicked;
}
void OnDisplayChanged(bool display)
{
if (!display && value)
DisableCameraViewTool();
}
void OnWillBeDestroyed()
{
if (value)
DisableCameraViewTool();
m_Overlay.onWillBeDestroyed -= OnWillBeDestroyed;
m_Overlay.displayedChanged -= OnDisplayChanged;
}
void ValueChanged(ChangeEvent<bool> evt)
{
if (evt.newValue)
{
if (m_Overlay.viewpoint == null)
{
return;
}
EnableCameraViewTool();
}
else
{
DisableCameraViewTool();
}
}
void OnDropdownClicked()
{
OverlayPopupWindow.Show<CameraOverscanSettingsWindow>(this, new Vector2(300, 88));
}
void EnableCameraViewTool()
{
sceneView.viewpoint.SetViewpoint(m_Overlay.viewpoint);
UpdateStyling();
}
void DisableCameraViewTool()
{
sceneView.viewpoint.ClearViewpoint();
UpdateStyling();
}
void SwitchCamera()
{
EnableCameraViewTool();
}
void ViewpointChanged(IViewpoint viewpoint)
{
UpdateEnableState();
// If toggle is on, it means the SceneView is looking though a camera.
// In that case, switch camera.
if (viewpoint != null && value)
SwitchCamera();
}
void UpdateEnableState()
{
SetEnabled(m_Overlay.viewpoint != null);
}
void UpdateToggleValue()
{
SetValueWithoutNotify(sceneView.viewpoint.hasActiveViewpoint);
}
void UpdateStyling()
{
icon = EditorGUIUtility.FindTexture(value? k_IconPathActive : k_IconPathNormal);
tooltip = value? k_TooltipActive : k_TooltipNormal;
}
void Initialize()
{
UpdateEnableState();
UpdateToggleValue();
UpdateStyling();
}
}
sealed class CameraPreview : IMGUIContainer
{
readonly string k_NoCameraDisplayLabel = L10n.Tr("No camera selected");
CamerasOverlay m_Overlay;
public CameraPreview(CamerasOverlay overlay)
{
m_Overlay = overlay;
onGUIHandler += OnGUI;
}
void OnGUI()
{
if ((m_Overlay.containerWindow as SceneView).viewpoint.hasActiveViewpoint)
return;
if (m_Overlay.viewpoint == null || !m_Overlay.viewpoint.TargetObject || !(m_Overlay.viewpoint is ICameraLensData))
{
GUILayout.Label(k_NoCameraDisplayLabel, EditorStyles.centeredGreyMiniLabel);
return;
}
var sceneView = m_Overlay.containerWindow as SceneView;
var cameraRect = rect;
cameraRect.width = Mathf.Floor(cameraRect.width);
if (cameraRect.width < 1 || cameraRect.height < 1 || float.IsNaN(cameraRect.width) || float.IsNaN(cameraRect.height))
return;
if (Event.current.type == EventType.Repaint)
{
Vector2 previewSize = PlayModeView.GetMainPlayModeViewTargetSize();
if (previewSize.x < 0f)
{
// Fallback to Scene View if not a valid game view size
previewSize.x = sceneView.position.width;
previewSize.y = sceneView.position.height;
}
float rectAspect = cameraRect.width / cameraRect.height;
float previewAspect = previewSize.x / previewSize.y;
Rect previewRect = cameraRect;
if (rectAspect > previewAspect)
{
float stretch = previewAspect / rectAspect;
previewRect = new Rect(cameraRect.xMin + cameraRect.width * (1.0f - stretch) * .5f, cameraRect.yMin, stretch * cameraRect.width, cameraRect.height);
}
else
{
float stretch = rectAspect / previewAspect;
previewRect = new Rect(cameraRect.xMin, cameraRect.yMin + cameraRect.height * (1.0f - stretch) * .5f, cameraRect.width, stretch * cameraRect.height);
}
var settings = new PreviewSettings(new Vector2((int)previewRect.width, (int)previewRect.height));
settings.overrideSceneCullingMask = sceneView.overrideSceneCullingMask;
settings.scene = sceneView.customScene;
settings.useHDR = (m_Overlay.containerWindow as SceneView).SceneViewIsRenderingHDR();
var previewTexture = CameraPreviewUtils.GetPreview(m_Overlay.viewpoint, new CameraPreviewUtils.PreviewSettings(new Vector2((int)previewRect.width, (int)previewRect.height)));
Graphics.DrawTexture(previewRect, previewTexture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, EditorGUIUtility.GUITextureBlit2SRGBMaterial);
}
}
}
sealed class ViewpointUserData : VisualElement
{
const string k_USSClass = "unity-user-data";
CamerasOverlay m_Overlay;
VisualElement m_CachedVisualElement;
internal ViewpointUserData(CamerasOverlay overlay)
{
m_Overlay = overlay;
AddToClassList(k_USSClass);
RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel);
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
if ((m_Overlay.containerWindow as SceneView).viewpoint.hasActiveViewpoint)
ViewpointChanged((m_Overlay.containerWindow as SceneView).viewpoint.activeViewpoint);
}
void OnAttachedToPanel(AttachToPanelEvent evt)
{
m_Overlay.onViewpointSelected += ViewpointChanged;
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
m_Overlay.onViewpointSelected -= ViewpointChanged;
}
void ViewpointChanged(IViewpoint viewpoint)
{
if (m_CachedVisualElement != null && Contains(m_CachedVisualElement))
Remove(m_CachedVisualElement);
if (viewpoint == null)
return;
m_CachedVisualElement = viewpoint.CreateVisualElement();
Add(m_CachedVisualElement);
}
}
[Overlay(typeof(SceneView), overlayId, k_DisplayName, priority = (int)OverlayPriority.Cameras)]
[Icon("Icons/Overlays/CameraPreview.png")]
class CamerasOverlay : Overlay
{
const string k_USSFilePath = "StyleSheets/SceneView/CamerasOverlay/CamerasOverlay.uss";
const string k_CamerasOverlayUSSClass = "unity-cameras-overlay";
const string k_ReducedCamerasOverlayUSSClass = "unity-cameras-overlay--reduced";
const string k_DisplayName = "Cameras";
static readonly Vector2 k_DefaultOverlaySize = new (250, 180);
static readonly Vector2 k_DefaultMaxSize = new (4000, 4000);
internal const string overlayId = "SceneView/CamerasOverlay";
struct OverlaySavedState
{
public bool sizeWasOverriden;
public float previousHeight;
public OverlaySavedState()
{
sizeWasOverriden = false;
previousHeight = 0;
}
internal OverlaySavedState(bool sizeIsOverriden, float height)
{
sizeWasOverriden = sizeIsOverriden;
previousHeight = height;
}
}
OverlaySavedState m_SavedStateBeforeReduceMode = default;
float m_CurrentBaseHeight;
CameraPreview m_CameraPreview;
ViewpointUserData m_UserData;
List<IViewpoint> m_AvailableViewpoints = new List<IViewpoint>();
IViewpoint m_SelectedViewpoint;
VisualElement m_Root;
internal VisualElement root => m_Root;
internal IViewpoint viewpoint
{
get => m_SelectedViewpoint;
set
{
if (value == m_SelectedViewpoint)
return;
m_SelectedViewpoint = value;
onViewpointSelected?.Invoke(m_SelectedViewpoint);
}
}
internal IReadOnlyCollection<IViewpoint> availableViewpoints
{
get
{
UpdateViewpointInternalList();
return m_AvailableViewpoints;
}
}
internal Action<IViewpoint> onViewpointSelected;
internal event Action onWillBeDestroyed;
public CamerasOverlay()
{
minSize = defaultSize = k_DefaultOverlaySize;
maxSize = k_DefaultMaxSize;
}
public override VisualElement CreatePanelContent()
{
var styleSheet = EditorGUIUtility.Load(k_USSFilePath) as StyleSheet;
m_Root = new VisualElement();
m_Root.name = "Cameras Preview Overlay";
m_Root.styleSheets.Add(styleSheet);
m_Root.AddToClassList(k_CamerasOverlayUSSClass);
m_Root.Add(new CameraControlsToolbar(this));
m_CameraPreview = new CameraPreview(this);
m_Root.Add(m_CameraPreview);
m_UserData = new ViewpointUserData(this);
m_UserData.RegisterCallback<GeometryChangedEvent>(UpdateSizeBasedOnUserData);
m_Root.Add(m_UserData);
return m_Root;
}
public override void OnCreated()
{
EditorApplication.update += Update;
(containerWindow as SceneView).viewpoint.cameraLookThroughStateChanged += CameraViewStateChanged;
CameraViewStateChanged((containerWindow as SceneView).viewpoint.hasActiveViewpoint);
}
public override void OnWillBeDestroyed()
{
EditorApplication.update -= Update;
if (m_UserData != null)
m_UserData.UnregisterCallback<GeometryChangedEvent>(UpdateSizeBasedOnUserData);
(containerWindow as SceneView).viewpoint.cameraLookThroughStateChanged -= CameraViewStateChanged;
onWillBeDestroyed?.Invoke();
}
// When the camera view is enabled in the SceneView, we reduce the overlay to hide the preview
// render. User can still manually resize the width of the overlay.
// When the user exits camera view, the overlay expands back to its original height.
void CameraViewStateChanged(bool viewpointIsActive)
{
if (viewpointIsActive)
{
if (m_SavedStateBeforeReduceMode.previousHeight > 0)
return;
m_SavedStateBeforeReduceMode = new OverlaySavedState(sizeOverridden, size.y);
float delta = m_CameraPreview != null? m_CameraPreview.resolvedStyle.height : 0;
m_CurrentBaseHeight = resizeTarget.resolvedStyle.height - delta + 5f;
// Lock the height. User can't resize the Overlay vertically in reduce mode.
maxSize = new Vector2(maxSize.x, m_CurrentBaseHeight);
minSize = new Vector2(minSize.x, m_CurrentBaseHeight);
UpdateOverlayStyling(isInReducedView: true);
}
else
{
maxSize = k_DefaultMaxSize;
minSize = defaultSize;
size = defaultSize;
ResetSize();
// Restore the size used before this overlay got reduced.
if (m_SavedStateBeforeReduceMode.sizeWasOverriden || size.x != k_DefaultMaxSize.x)
size = new Vector2(size.x, m_SavedStateBeforeReduceMode.previousHeight);
m_SavedStateBeforeReduceMode = default;
UpdateOverlayStyling(isInReducedView: false);
}
}
void UpdateOverlayStyling(bool isInReducedView)
{
contentRoot.EnableInClassList(k_CamerasOverlayUSSClass, !isInReducedView);
contentRoot.EnableInClassList(k_ReducedCamerasOverlayUSSClass, isInReducedView);
}
// Adjust the size of the Overlay based on the size of the ViewpointUserData.
void UpdateSizeBasedOnUserData(GeometryChangedEvent evt)
{
if (!(containerWindow as SceneView).viewpoint.hasActiveViewpoint)
return;
var size = m_UserData.resolvedStyle.height;
float fixedHeight = m_CurrentBaseHeight + size;
// Lock the height. User can't resize the Overlay vertically in reduced mode.
maxSize = new Vector2(maxSize.x, fixedHeight);
minSize = new Vector2(minSize.x, fixedHeight);
}
void UpdateViewpointInternalList()
{
m_AvailableViewpoints.Clear();
var caches = ViewpointProxyTypeCache.caches;
foreach (var componentType in ViewpointProxyTypeCache.GetSupportedCameraComponents())
{
foreach (var cam in GameObject.FindObjectsByType(componentType.viewpointType, FindObjectsInactive.Include,
FindObjectsSortMode.None))
{
Type proxyType = ViewpointProxyTypeCache.GetTranslatorTypeForType(cam.GetType());
var proxyTypeCtor = proxyType.GetConstructor(new[] { cam.GetType() });
IViewpoint instance = proxyTypeCtor.Invoke(new object[] { cam }) as IViewpoint;
m_AvailableViewpoints.Add(instance);
}
}
m_AvailableViewpoints.Sort(new ViewpointNameComparer());
}
void Update()
{
if (viewpoint == null)
{
UpdateViewpointInternalList();
if (m_SelectedViewpoint == null && m_AvailableViewpoints.Count > 0)
m_SelectedViewpoint = m_AvailableViewpoints[0];
if (m_SelectedViewpoint != null)
onViewpointSelected?.Invoke(m_SelectedViewpoint);
}
else if (!viewpoint.TargetObject)
{
m_SelectedViewpoint = null;
onViewpointSelected?.Invoke(m_SelectedViewpoint);
}
// Enable the toolbar only when there is at least one camera in the scene.
contentRoot.SetEnabled(viewpoint != null);
}
// used in tests
internal void SelectViewpoint(Component targetObject)
{
var viewpointToSelect = GetViewpoint(targetObject);
if (viewpointToSelect != null)
viewpoint = viewpointToSelect;
}
// used in tests
internal IViewpoint GetViewpoint(Component targetObject)
{
return m_AvailableViewpoints.Find(vp => vp.TargetObject == targetObject);
}
}
class CameraControlsToolbar : OverlayToolbar
{
public CameraControlsToolbar(CamerasOverlay overlay)
{
Add(new CameraLookThrough(overlay));
Add(new CameraInspectProperties(overlay));
Add(new CameraViewToggle(overlay));
}
}
}
| UnityCsReference/Modules/SceneView/CameraOverlay.cs/0 | {
"file_path": "UnityCsReference/Modules/SceneView/CameraOverlay.cs",
"repo_id": "UnityCsReference",
"token_count": 10628
} | 448 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Bindings;
namespace UnityEditor.ShaderFoundry
{
[NativeHeader("Modules/ShaderFoundry/Public/CustomizationPointImplementation.h")]
internal struct CustomizationPointImplementationInternal : IInternalType<CustomizationPointImplementationInternal>
{
internal FoundryHandle m_CustomizationPointHandle;
internal FoundryHandle m_BlockSequenceElementListHandle;
internal extern static CustomizationPointImplementationInternal Invalid();
internal extern bool IsValid();
// IInternalType
CustomizationPointImplementationInternal IInternalType<CustomizationPointImplementationInternal>.ConstructInvalid() => Invalid();
}
[FoundryAPI]
internal readonly struct CustomizationPointImplementation : IEquatable<CustomizationPointImplementation>, IPublicType<CustomizationPointImplementation>
{
// data members
readonly ShaderContainer container;
readonly internal FoundryHandle handle;
readonly CustomizationPointImplementationInternal customizationPointImplementation;
// IPublicType
ShaderContainer IPublicType.Container => Container;
bool IPublicType.IsValid => IsValid;
FoundryHandle IPublicType.Handle => handle;
CustomizationPointImplementation IPublicType<CustomizationPointImplementation>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new CustomizationPointImplementation(container, handle);
// public API
public ShaderContainer Container => container;
public bool IsValid => (container != null && handle.IsValid);
public CustomizationPoint CustomizationPoint => new CustomizationPoint(container, customizationPointImplementation.m_CustomizationPointHandle);
public IEnumerable<BlockSequenceElement> BlockSequenceElements
{
get
{
return customizationPointImplementation.m_BlockSequenceElementListHandle.AsListEnumerable<BlockSequenceElement>(container,
(container, handle) => (new BlockSequenceElement(container, handle)));
}
}
// private
internal CustomizationPointImplementation(ShaderContainer container, FoundryHandle handle)
{
this.container = container;
this.handle = handle;
ShaderContainer.Get(container, handle, out customizationPointImplementation);
}
public static CustomizationPointImplementation Invalid => new CustomizationPointImplementation(null, FoundryHandle.Invalid());
// Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead.
public override bool Equals(object obj) => obj is CustomizationPointImplementation other && this.Equals(other);
public bool Equals(CustomizationPointImplementation other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container);
public override int GetHashCode() => (container, handle).GetHashCode();
public static bool operator==(CustomizationPointImplementation lhs, CustomizationPointImplementation rhs) => lhs.Equals(rhs);
public static bool operator!=(CustomizationPointImplementation lhs, CustomizationPointImplementation rhs) => !lhs.Equals(rhs);
public class Builder
{
ShaderContainer container;
CustomizationPoint customizationPoint = CustomizationPoint.Invalid;
List<BlockSequenceElement> blockSequenceElements;
public ShaderContainer Container => container;
public Builder(ShaderContainer container, CustomizationPoint customizationPoint)
{
this.container = container;
this.customizationPoint = customizationPoint;
}
public void AddBlockSequenceElement(BlockSequenceElement element)
{
if (blockSequenceElements == null)
blockSequenceElements = new List<BlockSequenceElement>();
blockSequenceElements.Add(element);
}
public CustomizationPointImplementation Build()
{
var customizationPointImplementationInternal = new CustomizationPointImplementationInternal()
{
m_CustomizationPointHandle = customizationPoint.handle,
};
customizationPointImplementationInternal.m_BlockSequenceElementListHandle = HandleListInternal.Build(container, blockSequenceElements, (e) => (e.handle));
var returnTypeHandle = container.Add(customizationPointImplementationInternal);
return new CustomizationPointImplementation(container, returnTypeHandle);
}
}
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/CustomizationPointImplementation.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/CustomizationPointImplementation.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1718
} | 449 |
// 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 UnityEditor.ShaderFoundry
{
[NativeHeader("Modules/ShaderFoundry/Public/Namespace.h")]
internal struct NamespaceInternal : IInternalType<NamespaceInternal>
{
internal FoundryHandle m_NameHandle;
internal FoundryHandle m_ContainingNamespaceHandle;
internal extern static NamespaceInternal Invalid();
internal extern bool IsValid();
// IInternalType
NamespaceInternal IInternalType<NamespaceInternal>.ConstructInvalid() => Invalid();
}
[FoundryAPI]
internal readonly struct Namespace : IEquatable<Namespace>, IPublicType<Namespace>
{
// data members
readonly ShaderContainer container;
readonly NamespaceInternal data;
internal readonly FoundryHandle handle;
// IPublicType
ShaderContainer IPublicType.Container => Container;
bool IPublicType.IsValid => IsValid;
FoundryHandle IPublicType.Handle => handle;
Namespace IPublicType<Namespace>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new Namespace(container, handle);
// public API
public ShaderContainer Container => container;
public bool IsValid => (container != null && data.IsValid());
public string Name => Container?.GetString(data.m_NameHandle) ?? string.Empty;
public Namespace ContainingNamespace => new Namespace(Container, data.m_ContainingNamespaceHandle);
// private
internal Namespace(ShaderContainer container, FoundryHandle handle)
{
this.container = container;
this.handle = handle;
ShaderContainer.Get(container, handle, out data);
}
public static Namespace Invalid => new Namespace(null, FoundryHandle.Invalid());
// Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead.
public override bool Equals(object obj) => obj is Namespace other && this.Equals(other);
public bool Equals(Namespace other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container);
public override int GetHashCode() => (container, handle).GetHashCode();
public static bool operator ==(Namespace lhs, Namespace rhs) => lhs.Equals(rhs);
public static bool operator !=(Namespace lhs, Namespace rhs) => !lhs.Equals(rhs);
public class Builder
{
ShaderContainer container;
public string name;
public Namespace containingNamespace = Namespace.Invalid;
public ShaderContainer Container => container;
public Builder(ShaderContainer container, string name)
: this(container, name, Namespace.Invalid)
{
}
public Builder(ShaderContainer container, string name, Namespace containingNamespace)
{
this.container = container;
this.name = name;
this.containingNamespace = containingNamespace;
}
public Namespace Build()
{
var data = new NamespaceInternal
{
m_NameHandle = container.AddString(name),
m_ContainingNamespaceHandle = containingNamespace.handle,
};
var resultHandle = container.Add(data);
return new Namespace(container, resultHandle);
}
}
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/Namespace.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/Namespace.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1414
} | 450 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Bindings;
namespace UnityEditor.ShaderFoundry
{
[NativeHeader("Modules/ShaderFoundry/Public/StructField.h")]
internal struct StructFieldInternal : IInternalType<StructFieldInternal>
{
// This enum must be kept in sync with the enum in StructField.h
[Flags]
internal enum Flags : UInt32
{
kNone = 0,
kInput = 1 << 0,
kOutput = 1 << 1
}
internal FoundryHandle m_NameHandle;
internal FoundryHandle m_TypeHandle;
internal FoundryHandle m_AttributeListHandle;
internal Flags m_Flags;
internal static extern StructFieldInternal Invalid();
internal extern bool IsValid { [NativeMethod("IsValid")] get; }
internal extern string GetName(ShaderContainer container);
internal IEnumerable<ShaderAttribute> Attributes(ShaderContainer container)
{
var list = new HandleListInternal(m_AttributeListHandle);
return list.Select<ShaderAttribute>(container, (handle) => (new ShaderAttribute(container, handle)));
}
internal extern static bool ValueEquals(ShaderContainer aContainer, FoundryHandle aHandle, ShaderContainer bContainer, FoundryHandle bHandle);
// IInternalType
StructFieldInternal IInternalType<StructFieldInternal>.ConstructInvalid() => Invalid();
}
[FoundryAPI]
internal readonly struct StructField : IEquatable<StructField>, IPublicType<StructField>
{
// data members
readonly ShaderContainer container;
internal readonly FoundryHandle handle;
readonly StructFieldInternal field;
// IPublicType
ShaderContainer IPublicType.Container => Container;
bool IPublicType.IsValid => IsValid;
FoundryHandle IPublicType.Handle => handle;
StructField IPublicType<StructField>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new StructField(container, handle);
// public API
public ShaderContainer Container => container;
public bool IsValid => (container != null) && handle.IsValid && (field.IsValid);
public string Name => field.GetName(container);
public ShaderType Type => new ShaderType(container, field.m_TypeHandle);
public IEnumerable<ShaderAttribute> Attributes => field.Attributes(container);
public bool IsInput => field.m_Flags.HasFlag(StructFieldInternal.Flags.kInput);
public bool IsOutput => field.m_Flags.HasFlag(StructFieldInternal.Flags.kOutput);
internal bool HasFlag(StructFieldInternal.Flags flags) => field.m_Flags.HasFlag(flags);
// private
internal StructField(ShaderContainer container, FoundryHandle handle)
{
this.container = container;
this.handle = handle;
ShaderContainer.Get(container, handle, out field);
}
public static StructField Invalid => new StructField(null, FoundryHandle.Invalid());
// Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead.
public override bool Equals(object obj) => obj is StructField other && this.Equals(other);
public bool Equals(StructField other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container);
public override int GetHashCode() => (container, handle).GetHashCode();
public static bool operator==(StructField lhs, StructField rhs) => lhs.Equals(rhs);
public static bool operator!=(StructField lhs, StructField rhs) => !lhs.Equals(rhs);
public bool ValueEquals(in StructField other)
{
return StructFieldInternal.ValueEquals(container, handle, other.container, other.handle);
}
public class Builder
{
internal ShaderContainer container;
internal string name;
internal ShaderType type = ShaderType.Invalid;
internal List<ShaderAttribute> attributes;
internal StructFieldInternal.Flags m_Flags = StructFieldInternal.Flags.kNone;
public Builder(ShaderContainer container, string name, ShaderType type)
{
this.container = container;
this.name = name;
this.type = type;
}
public Builder(ShaderContainer container, string name, ShaderType type, bool isInput, bool isOutput)
{
this.container = container;
this.name = name;
this.type = type;
IsInput = isInput;
IsOutput = isOutput;
}
public void AddAttribute(ShaderAttribute attribute)
{
if (attributes == null)
attributes = new List<ShaderAttribute>();
attributes.Add(attribute);
}
public bool IsInput
{
get { return m_Flags.HasFlag(StructFieldInternal.Flags.kInput); }
set { SetFlag(StructFieldInternal.Flags.kInput, value); }
}
public bool IsOutput
{
get { return m_Flags.HasFlag(StructFieldInternal.Flags.kOutput); }
set { SetFlag(StructFieldInternal.Flags.kOutput, value); }
}
void SetFlag(StructFieldInternal.Flags flag, bool state)
{
if (state)
m_Flags |= flag;
else
m_Flags &= ~flag;
}
public StructField Build()
{
var structFieldInternal = new StructFieldInternal();
structFieldInternal.m_NameHandle = container.AddString(name);
structFieldInternal.m_TypeHandle = type.handle;
structFieldInternal.m_AttributeListHandle = HandleListInternal.Build(container, attributes, (a) => (a.handle));
structFieldInternal.m_Flags = m_Flags;
var returnHandle = container.Add(structFieldInternal);
return new StructField(container, returnHandle);
}
}
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/StructField.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/StructField.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2584
} | 451 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEditor.ShortcutManagement
{
class Discovery : IDiscovery
{
IEnumerable<IDiscoveryShortcutProvider> m_ShortcutProviders;
IBindingValidator m_BindingValidator;
IDiscoveryInvalidShortcutReporter m_InvalidShortcutReporter;
internal const string k_MainMenuShortcutPrefix = "Main Menu/";
public Discovery(IEnumerable<IDiscoveryShortcutProvider> shortcutProviders, IBindingValidator bindingValidator, IDiscoveryInvalidShortcutReporter invalidShortcutReporter = null)
{
m_ShortcutProviders = shortcutProviders;
m_BindingValidator = bindingValidator;
m_InvalidShortcutReporter = invalidShortcutReporter;
}
public IEnumerable<ShortcutEntry> GetAllShortcuts()
{
var availableShortcuts = new List<ShortcutEntry>();
var identifier2ShortcutEntry = new HashSet<Identifier>();
var displayName2ShortcutEntry = new HashSet<string>();
foreach (var discoveryModule in m_ShortcutProviders)
{
var shortcuts = discoveryModule.GetDefinedShortcuts();
foreach (var discoveredEntry in shortcuts)
{
var shortcutEntry = discoveredEntry.GetShortcutEntry();
if (shortcutEntry.identifier.path != null && shortcutEntry.type != ShortcutType.Menu && shortcutEntry.identifier.path.StartsWith(k_MainMenuShortcutPrefix))
{
m_InvalidShortcutReporter?.ReportReservedIdentifierPrefixConflict(discoveredEntry, k_MainMenuShortcutPrefix);
continue;
}
if (shortcutEntry.displayName != null && shortcutEntry.type != ShortcutType.Menu && shortcutEntry.displayName.StartsWith(k_MainMenuShortcutPrefix))
{
m_InvalidShortcutReporter?.ReportReservedDisplayNamePrefixConflict(discoveredEntry, k_MainMenuShortcutPrefix);
continue;
}
if (identifier2ShortcutEntry.Contains(shortcutEntry.identifier))
{
m_InvalidShortcutReporter?.ReportIdentifierConflict(discoveredEntry);
continue;
}
if (displayName2ShortcutEntry.Contains(shortcutEntry.displayName))
{
m_InvalidShortcutReporter?.ReportDisplayNameConflict(discoveredEntry);
continue;
}
if (!ValidateContext(discoveredEntry))
{
m_InvalidShortcutReporter?.ReportInvalidContext(discoveredEntry);
continue;
}
string invalidBindingMessage;
if (!m_BindingValidator.IsBindingValid(shortcutEntry, out invalidBindingMessage))
{
m_InvalidShortcutReporter?.ReportInvalidBinding(discoveredEntry, invalidBindingMessage);
// Replace invalid binding with empty binding
var emptyBinding = Enumerable.Empty<KeyCombination>();
shortcutEntry = new ShortcutEntry(shortcutEntry.identifier, emptyBinding, shortcutEntry.action,
shortcutEntry.context, shortcutEntry.tag, shortcutEntry.type, null, shortcutEntry.priority);
}
identifier2ShortcutEntry.Add(shortcutEntry.identifier);
displayName2ShortcutEntry.Add(shortcutEntry.displayName);
availableShortcuts.Add(shortcutEntry);
}
}
return availableShortcuts;
}
static bool ValidateContext(IShortcutEntryDiscoveryInfo discoveredEntry)
{
var shortcutEntry = discoveredEntry.GetShortcutEntry();
var context = shortcutEntry.context;
if (context == ContextManager.globalContextType)
return true;
var isEditorWindow = typeof(EditorWindow).IsAssignableFrom(context);
var isIShortcutToolContext = typeof(IShortcutContext).IsAssignableFrom(context);
if (isEditorWindow)
{
if (context != typeof(EditorWindow) && !isIShortcutToolContext)
return true;
}
else if (isIShortcutToolContext && context != typeof(IShortcutContext))
return true;
return false;
}
}
}
| UnityCsReference/Modules/ShortcutManagerEditor/Discovery.cs/0 | {
"file_path": "UnityCsReference/Modules/ShortcutManagerEditor/Discovery.cs",
"repo_id": "UnityCsReference",
"token_count": 2250
} | 452 |
// 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;
namespace UnityEditor.ShortcutManagement
{
public enum ShortcutStage
{
Begin,
End
}
public struct ShortcutArguments
{
public object context;
public ShortcutStage stage;
}
enum ShortcutType
{
Action,
Clutch,
Menu
}
[Serializable]
struct Identifier
{
public string path;
public const string kPathSeparator = "/";
public Identifier(MethodInfo methodInfo, ShortcutAttribute attribute)
{
path = attribute.identifier;
}
public Identifier(string path)
{
this.path = path;
}
public override string ToString()
{
return path;
}
}
class ShortcutEntry
{
readonly Identifier m_Identifier;
readonly string m_DisplayName;
readonly List<KeyCombination> m_DefaultCombinations = new List<KeyCombination>();
List<KeyCombination> m_OverriddenCombinations;
readonly Action<ShortcutArguments> m_Action;
readonly Type m_Context;
readonly Type m_ClutchActivatedContext;
readonly string m_Tag;
readonly ShortcutType m_Type;
readonly int m_Priority;
public Identifier identifier => m_Identifier;
public string displayName => m_DisplayName;
public IList<KeyCombination> combinations => activeCombination;
public bool overridden => m_OverriddenCombinations != null;
public Action<ShortcutArguments> action => m_Action;
public Type context => m_Context;
public Type clutchContext => m_ClutchActivatedContext;
public string tag => m_Tag;
public ShortcutType type => m_Type;
public int priority => m_Priority;
internal ShortcutModifiers m_ReservedModifier;
internal ShortcutEntry(Identifier id, IEnumerable<KeyCombination> defaultCombination, Action<ShortcutArguments> action, Type context, ShortcutType type, string displayName = null, int priority = int.MaxValue)
: this(id, defaultCombination, action, context, null, type, displayName, priority) {}
internal ShortcutEntry(Identifier id, IEnumerable<KeyCombination> defaultCombination, Action<ShortcutArguments> action, Type context, string tag, ShortcutType type, string displayName = null, int priority = int.MaxValue)
{
m_Identifier = id;
m_DefaultCombinations = defaultCombination.ToList();
m_Context = context ?? ContextManager.globalContextType;
m_Tag = tag;
m_Action = action;
m_Type = type;
m_DisplayName = displayName ?? id.path;
m_Priority = ShortcutAttributeUtility.AssignPriority(context, priority);
if (typeof(IShortcutContext).IsAssignableFrom(m_Context))
foreach (var attribute in m_Context.GetCustomAttributes(typeof(ReserveModifiersAttribute), true))
m_ReservedModifier |= (attribute as ReserveModifiersAttribute).Modifiers;
if(m_Action != null)
foreach(var clutch in m_Action.Method.GetCustomAttributes<ClutchShortcutAttribute>())
if (clutch.clutchActivatedContext != null)
m_ClutchActivatedContext = clutch.clutchActivatedContext;
}
public override string ToString()
{
return $"{displayName} {string.Join(",", combinations.Select(c => c.ToString()).ToArray())} [{context?.Name}] {(!string.IsNullOrWhiteSpace(tag) ? $"[{tag}]" : "")}";
}
List<KeyCombination> activeCombination
{
get
{
if (m_OverriddenCombinations != null)
return m_OverriddenCombinations;
return m_DefaultCombinations;
}
}
public bool StartsWith(IList<KeyCombination> prefix, IEnumerable<KeyCode> keyCodes = null)
{
if (activeCombination.Count < prefix.Count)
return false;
if (prefix.Count == 0)
return true;
for (int i = 0; i < prefix.Count - 1; i++)
{
if (!prefix[i].Equals(activeCombination[i]))
return false;
}
var lastKeyCombination = prefix.Last();
var lastKeyCombinationActive = activeCombination[prefix.Count - 1];
if (m_ReservedModifier != 0)
{
lastKeyCombination = new KeyCombination(lastKeyCombination.keyCode,
lastKeyCombination.modifiers & ~m_ReservedModifier);
lastKeyCombinationActive = new KeyCombination(lastKeyCombinationActive.keyCode,
lastKeyCombinationActive.modifiers & ~m_ReservedModifier);
}
if (lastKeyCombination.Equals(lastKeyCombinationActive))
{
if (keyCodes != null)
{
var otherCombinationHasDesiredKeyCode = HasSpecifiedKeyCode(keyCodes, lastKeyCombination.keyCode);
var activeCombinationHasDesiredKeyCode = HasSpecifiedKeyCode(keyCodes, lastKeyCombinationActive.keyCode);
return otherCombinationHasDesiredKeyCode && activeCombinationHasDesiredKeyCode;
}
return true;
}
return false;
}
static bool HasSpecifiedKeyCode(IEnumerable<KeyCode> keyCodes, KeyCode currentKeyCode)
{
if (keyCodes == null)
return false;
foreach (var keyCode in keyCodes)
{
if (keyCode == currentKeyCode)
return true;
}
return false;
}
public bool FullyMatches(List<KeyCombination> other)
{
if (activeCombination.Count != other.Count)
return false;
return StartsWith(other);
}
internal void ResetToDefault()
{
m_OverriddenCombinations = null;
}
internal void SetOverride(IEnumerable<KeyCombination> newKeyCombinations)
{
m_OverriddenCombinations = newKeyCombinations.ToList();
if (m_Type == ShortcutType.Menu && m_Identifier.path.StartsWith(ShortcutManagerWindowViewController.k_MainMenu))
{
var newMenuKey = m_OverriddenCombinations.Any() ? m_OverriddenCombinations[0].ToMenuShortcutString() : "";
Menu.SetHotkey(m_Identifier.path.Substring(Discovery.k_MainMenuShortcutPrefix.Length), newMenuKey);
}
}
internal List<KeyCombination> GetDefaultCombinations()
{
return m_DefaultCombinations;
}
internal void ApplyOverride(SerializableShortcutEntry shortcutOverride)
{
SetOverride(shortcutOverride.combinations);
}
}
[Flags]
public enum ShortcutModifiers
{
None = 0,
Alt = 1,
Action = 2,
Shift = 4,
Control = 8
}
}
| UnityCsReference/Modules/ShortcutManagerEditor/ShortcutEntry.cs/0 | {
"file_path": "UnityCsReference/Modules/ShortcutManagerEditor/ShortcutEntry.cs",
"repo_id": "UnityCsReference",
"token_count": 3283
} | 453 |
// 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.U2D;
namespace UnityEditor.U2D
{
[CustomEditor(typeof(SpriteShapeRenderer))]
[CanEditMultipleObjects]
internal class SpriteShapeRendererInspector : RendererEditorBase
{
private SerializedProperty m_Color;
private SerializedProperty m_Material;
private SerializedProperty m_MaskInteraction;
private SerializedProperty m_SpriteSortPoint;
private static class Styles
{
public static readonly GUIContent fillMaterialLabel = EditorGUIUtility.TrTextContent("Fill Material", "Fill Material to be used by SpriteShapeRenderer");
public static readonly GUIContent edgeMaterialLabel = EditorGUIUtility.TrTextContent("Edge Material", "Edge Material to be used by SpriteShapeRenderer");
public static readonly GUIContent colorLabel = EditorGUIUtility.TrTextContent("Color", "Rendering color for the Sprite graphic");
public static readonly Texture2D warningIcon = EditorGUIUtility.LoadIcon("console.warnicon");
public static readonly string mainTexErrorText = L10n.Tr("Material does not have a _MainTex texture property. It is required for SpriteShapeRenderer.");
public static readonly string offsetScaleErrorText = L10n.Tr("Material texture property _MainTex has offset/scale set. It is incompatible with SpriteShapeRenderer.");
public static readonly GUIContent spriteSortPointLabel = EditorGUIUtility.TrTextContent("SpriteShape Sort Point", "Determines which position of the SpriteShape is used for sorting.");
}
public override void OnEnable()
{
base.OnEnable();
m_Color = serializedObject.FindProperty("m_Color");
m_Material = serializedObject.FindProperty("m_Materials.Array"); // Only allow to edit one material
m_MaskInteraction = serializedObject.FindProperty("m_MaskInteraction");
m_SpriteSortPoint = serializedObject.FindProperty("m_SpriteSortPoint");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUI.enabled = true;
EditorGUILayout.PropertyField(m_Color, Styles.colorLabel, true);
EditorGUILayout.PropertyField(m_MaskInteraction);
EditorGUILayout.PropertyField(m_SpriteSortPoint, Styles.spriteSortPointLabel);
EditorGUILayout.PropertyField(m_Material.GetArrayElementAtIndex(0), Styles.fillMaterialLabel, true);
EditorGUILayout.PropertyField(m_Material.GetArrayElementAtIndex(1), Styles.edgeMaterialLabel, true);
bool isTextureTiled;
if (!DoesFillMaterialHaveSpriteTexture(out isTextureTiled))
ShowError(Styles.mainTexErrorText);
else
{
if (isTextureTiled)
ShowError(Styles.offsetScaleErrorText);
}
Other2DSettingsGUI();
serializedObject.ApplyModifiedProperties();
}
private bool DoesFillMaterialHaveSpriteTexture(out bool tiled)
{
tiled = false;
Material material = (target as SpriteShapeRenderer).sharedMaterial;
if (material == null)
return true;
bool has = material.HasProperty("_MainTex");
if (has)
{
Vector2 offset = material.GetTextureOffset("_MainTex");
Vector2 scale = material.GetTextureScale("_MainTex");
if (offset.x != 0 || offset.y != 0 || scale.x != 1 || scale.y != 1)
tiled = true;
}
return material.HasProperty("_MainTex");
}
private static void ShowError(string error)
{
var c = new GUIContent(error) {image = Styles.warningIcon};
GUILayout.Space(5);
GUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(c, EditorStyles.wordWrappedMiniLabel);
GUILayout.EndVertical();
}
}
}
| UnityCsReference/Modules/SpriteShapeEditor/Managed/SpriteShapeRendererEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/SpriteShapeEditor/Managed/SpriteShapeRendererEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 1695
} | 454 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
/*
using scm=System.ComponentModel;
using uei=UnityEngine.Internal;
using RequiredByNativeCodeAttribute=UnityEngine.Scripting.RequiredByNativeCodeAttribute;
using UsedByNativeCodeAttribute=UnityEngine.Scripting.UsedByNativeCodeAttribute;
*/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections;
namespace UnityEngine
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
public enum ProceduralProcessorUsage
{
Unsupported = 0,
One = 1,
Half = 2,
All = 3
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
public enum ProceduralCacheSize
{
Tiny = 0,
Medium = 1,
Heavy = 2,
NoLimit = 3,
None = 4
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
public enum ProceduralLoadingBehavior
{
DoNothing = 0,
Generate = 1,
BakeAndKeep = 2,
BakeAndDiscard = 3,
Cache = 4,
DoNothingAndCache = 5
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
public enum ProceduralPropertyType
{
Boolean = 0,
Float = 1,
Vector2 = 2,
Vector3 = 3,
Vector4 = 4,
Color3 = 5,
Color4 = 6,
Enum = 7,
Texture = 8,
String = 9
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
public enum ProceduralOutputType
{
Unknown = 0,
Diffuse = 1,
Normal = 2,
Height = 3,
Emissive = 4,
Specular = 5,
Opacity = 6,
Smoothness = 7,
AmbientOcclusion = 8,
DetailMask = 9,
Metallic = 10,
Roughness = 11
}
[StructLayout(LayoutKind.Sequential)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
public sealed partial class ProceduralPropertyDescription
{
public string name;
public string label;
public string group;
public ProceduralPropertyType type;
public bool hasRange;
public float minimum;
public float maximum;
public float step;
public string[] enumOptions;
public string[] componentLabels;
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
[ExcludeFromPreset]
public sealed partial class ProceduralMaterial : Material
{
internal ProceduralMaterial()
: base((Material)null)
{
FeatureRemoved();
}
public ProceduralPropertyDescription[] GetProceduralPropertyDescriptions()
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public bool HasProceduralProperty(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public bool GetProceduralBoolean(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public bool IsProceduralPropertyVisible(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void SetProceduralBoolean(string inputName, bool value)
{
FeatureRemoved();
}
public float GetProceduralFloat(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void SetProceduralFloat(string inputName, float value)
{
FeatureRemoved();
}
public Vector4 GetProceduralVector(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void SetProceduralVector(string inputName, Vector4 value)
{
FeatureRemoved();
}
public Color GetProceduralColor(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void SetProceduralColor(string inputName, Color value)
{
FeatureRemoved();
}
public int GetProceduralEnum(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void SetProceduralEnum(string inputName, int value)
{
FeatureRemoved();
}
public Texture2D GetProceduralTexture(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void SetProceduralTexture(string inputName, Texture2D value)
{
FeatureRemoved();
}
public string GetProceduralString(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void SetProceduralString(string inputName, string value)
{
FeatureRemoved();
}
public bool IsProceduralPropertyCached(string inputName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public void CacheProceduralProperty(string inputName, bool value)
{
FeatureRemoved();
}
public void ClearCache()
{
FeatureRemoved();
}
public ProceduralCacheSize cacheSize
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
set { FeatureRemoved(); }
}
public int animationUpdateRate
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
set { FeatureRemoved(); }
}
public void RebuildTextures()
{
FeatureRemoved();
}
public void RebuildTexturesImmediately()
{
FeatureRemoved();
}
public bool isProcessing
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
}
public static void StopRebuilds()
{
FeatureRemoved();
}
public bool isCachedDataAvailable
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
}
public bool isLoadTimeGenerated
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
set { FeatureRemoved(); }
}
public ProceduralLoadingBehavior loadingBehavior
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
}
public static bool isSupported
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
}
public static ProceduralProcessorUsage substanceProcessorUsage
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
set { FeatureRemoved(); }
}
public string preset
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
set { FeatureRemoved(); }
}
public Texture[] GetGeneratedTextures()
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public ProceduralTexture GetGeneratedTexture(string textureName)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public bool isReadable
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
set { FeatureRemoved(); }
}
public void FreezeAndReleaseSourceData()
{
FeatureRemoved();
}
public bool isFrozen
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
}
}
[Obsolete("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.", true)]
[ExcludeFromPreset]
public sealed partial class ProceduralTexture : Texture
{
private ProceduralTexture()
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public ProceduralOutputType GetProceduralOutputType()
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
internal ProceduralMaterial GetProceduralMaterial()
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
public bool hasAlpha
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
}
public TextureFormat format
{
get { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); }
}
public Color32[] GetPixels32(int x, int y, int blockWidth, int blockHeight)
{
throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store.");
}
}
}
| UnityCsReference/Modules/Substance/SubstanceUtility.cs/0 | {
"file_path": "UnityCsReference/Modules/Substance/SubstanceUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 5201
} | 455 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
namespace UnityEngine
{
public static partial class SubsystemManager
{
[Obsolete("Use GetSubsystems instead. (UnityUpgradable) -> GetSubsystems<T>(*)", false)]
public static void GetInstances<T>(List<T> subsystems)
where T : ISubsystem
{
GetSubsystems(subsystems);
}
#pragma warning disable CS0618
internal static void AddDeprecatedSubsystem(Subsystem subsystem) => s_DeprecatedSubsystems.Add(subsystem);
internal static bool RemoveDeprecatedSubsystem(Subsystem subsystem) => s_DeprecatedSubsystems.Remove(subsystem);
internal static Subsystem FindDeprecatedSubsystemByDescriptor(SubsystemDescriptor descriptor)
{
foreach (var subsystem in s_DeprecatedSubsystems)
{
if (subsystem.m_SubsystemDescriptor == descriptor)
return subsystem;
}
return null;
}
#pragma warning restore CS0618
// event never invoked warning (invoked indirectly from native code)
#pragma warning disable CS0067
[Obsolete("Use beforeReloadSubsystems instead. (UnityUpgradable) -> beforeReloadSubsystems", false)]
public static event Action reloadSubsytemsStarted;
[Obsolete("Use afterReloadSubsystems instead. (UnityUpgradable) -> afterReloadSubsystems", false)]
public static event Action reloadSubsytemsCompleted;
#pragma warning restore CS0067
}
}
| UnityCsReference/Modules/Subsystems/SubsystemManager.deprecated.cs/0 | {
"file_path": "UnityCsReference/Modules/Subsystems/SubsystemManager.deprecated.cs",
"repo_id": "UnityCsReference",
"token_count": 615
} | 456 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Serialization;
namespace UnityEditor
{
[AssetFileNameExtension("brush")]
internal class Brush : ScriptableObject
{
[MenuItem("Assets/Create/Terrain/Brush", secondaryPriority = 1)]
public static void CreateNewDefaultBrush()
{
Brush b = CreateInstance(DefaultMask(), AnimationCurve.Linear(0, 0, 1, 1), 1.0f, false);
ProjectWindowUtil.CreateAsset(b, "New Brush.brush");
}
public void Reset()
{
m_Mask = DefaultMask();
m_Falloff = AnimationCurve.Linear(0, 0, 1, 1);
m_RadiusScale = 1.0f;
m_BlackWhiteRemapMin = 0.0f;
m_BlackWhiteRemapMax = 1.0f;
m_InvertRemapRange = false;
readOnly = false;
}
// Don't instantiate directly, use Brush.CreateInstance()
protected Brush() {}
internal const float sqrt2 = 1.414214f; // diagonal of a unit square
internal const float kMaxRadiusScale = sqrt2 + (sqrt2 * 0.05f); // take into account the smoothness from CreateBrush.shader ( circleFalloff = 1.0f - smoothstep(_BrushRadiusScale-0.05f, _BrushRadiusScale, dist) )
public Texture2D m_Mask;
public AnimationCurve m_Falloff;
[Range(1.0f, kMaxRadiusScale)]
public float m_RadiusScale = kMaxRadiusScale;
[Range(0.0f, 1.0f)]
public float m_BlackWhiteRemapMin = 0.0f;
[Range(0.0f, 1.0f)]
public float m_BlackWhiteRemapMax = 1.0f;
public bool m_InvertRemapRange = false;
Texture2D m_Texture = null;
Texture2D m_Thumbnail = null;
bool m_UpdateTexture = true;
bool m_UpdateThumbnail = true;
internal bool readOnly { get; set; } = false;
static Texture2D s_WhiteTexture = null;
static Material s_CreateBrushMaterial = null;
internal static Brush CreateInstance(Texture2D t, AnimationCurve f, float radiusScale, bool isReadOnly)
{
var b = ScriptableObject.CreateInstance<Brush>();
b.m_Mask = t;
b.m_Falloff = f;
b.m_RadiusScale = radiusScale;
b.m_BlackWhiteRemapMin = 0.0f;
b.m_BlackWhiteRemapMax = 1.0f;
b.m_InvertRemapRange = false;
b.readOnly = isReadOnly;
return b;
}
void UpdateTexture()
{
if (m_UpdateTexture || m_Texture == null)
{
if (m_Mask == null)
m_Mask = DefaultMask();
m_Texture = GenerateBrushTexture(m_Mask, m_Falloff, m_RadiusScale, m_BlackWhiteRemapMin, m_BlackWhiteRemapMax, m_InvertRemapRange, m_Mask.width, m_Mask.height);
m_Texture.name = $"Terrain Brush ({m_Mask.name})";
m_UpdateTexture = false;
}
}
void UpdateThumbnail()
{
if (m_UpdateThumbnail || m_Thumbnail == null)
{
if (m_Mask == null)
m_Mask = DefaultMask();
m_Thumbnail = GenerateBrushTexture(m_Mask, m_Falloff, m_RadiusScale, m_BlackWhiteRemapMin, m_BlackWhiteRemapMax, m_InvertRemapRange, 64, 64, true);
m_Thumbnail.name = $"Terrain Brush Thumbnail ({m_Mask.name})";
m_UpdateThumbnail = false;
}
}
public Texture2D texture { get { UpdateTexture(); return m_Texture; } }
public Texture2D thumbnail { get { UpdateThumbnail(); return m_Thumbnail; } }
public void SetDirty(bool isDirty)
{
m_UpdateTexture |= isDirty;
m_UpdateThumbnail |= isDirty;
}
internal static Texture2D DefaultMask()
{
if (s_WhiteTexture == null)
{
s_WhiteTexture = new Texture2D(64, 64, TextureFormat.Alpha8, false);
Color[] colors = new Color[64 * 64];
for (int i = 0; i < 64 * 64; i++)
colors[i] = new Color(1, 1, 1, 1);
s_WhiteTexture.SetPixels(colors);
s_WhiteTexture.filterMode = FilterMode.Bilinear;
s_WhiteTexture.Apply();
}
return s_WhiteTexture;
}
internal static Texture2D GenerateBrushTexture(Texture2D mask, AnimationCurve falloff, float radiusScale, float blackWhiteRemapMin, float blackWhiteRemapMax, bool invertRemapRange, int width, int height, bool isThumbnail = false)
{
if (s_CreateBrushMaterial == null)
s_CreateBrushMaterial = new Material(EditorGUIUtility.LoadRequired("Brushes/CreateBrush.shader") as Shader);
TextureFormat falloffFormat = TextureFormat.R16;
// fallback for old platforms (GLES2).. ugly quantization but approximately correct
if (!SystemInfo.SupportsTextureFormat(falloffFormat))
falloffFormat = TextureFormat.RGBA32;
int sampleCount = Mathf.Max(width, 1024);
Texture2D falloffTex = new Texture2D(sampleCount, 1, falloffFormat, false);
Color[] falloffPix = new Color[sampleCount];
for (int i = 0; i < sampleCount; i++)
{
float time = (float)i / (float)(sampleCount - 1);
float val = falloff.Evaluate(time);
falloffPix[sampleCount - i - 1].r = falloffPix[sampleCount - i - 1].g = falloffPix[sampleCount - i - 1].b = falloffPix[sampleCount - i - 1].a = val;
}
falloffTex.SetPixels(falloffPix);
falloffTex.wrapMode = TextureWrapMode.Clamp;
falloffTex.filterMode = FilterMode.Bilinear;
falloffTex.Apply();
RenderTexture oldRT = RenderTexture.active;
GraphicsFormat outputRenderFormat = isThumbnail ? SystemInfo.GetGraphicsFormat(DefaultFormat.LDR) : Terrain.heightmapFormat;
TextureFormat outputTexFormat = isThumbnail ? TextureFormat.ARGB32 : Terrain.heightmapTextureFormat;
// build brush texture
float blackRemap = invertRemapRange ? blackWhiteRemapMax : blackWhiteRemapMin;
float whiteRemap = invertRemapRange ? blackWhiteRemapMin : blackWhiteRemapMax;
Vector4 brushParams = new Vector4(radiusScale * 0.5f, mask.format != TextureFormat.Alpha8 ? 1.0f : 0.0f, blackRemap, whiteRemap);
RenderTexture tempRT = RenderTexture.GetTemporary(width, height, 0, outputRenderFormat);
s_CreateBrushMaterial.SetTexture("_BrushFalloff", falloffTex);
s_CreateBrushMaterial.SetVector("_BrushParams", brushParams);
Graphics.Blit(mask, tempRT, s_CreateBrushMaterial);
Texture2D previewTexture = new Texture2D(width, height, outputTexFormat, false);
RenderTexture.active = tempRT;
previewTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
previewTexture.Apply();
RenderTexture.ReleaseTemporary(tempRT);
tempRT = null;
RenderTexture.active = oldRT;
return previewTexture;
}
}
}
| UnityCsReference/Modules/TerrainEditor/Brush/Brush.cs/0 | {
"file_path": "UnityCsReference/Modules/TerrainEditor/Brush/Brush.cs",
"repo_id": "UnityCsReference",
"token_count": 3309
} | 457 |
// 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.TerrainTools;
using UnityEditor.ShortcutManagement;
namespace UnityEditor.TerrainTools
{
[FilePath("Library/TerrainTools/SetHeight", FilePathAttribute.Location.ProjectFolder)]
internal class SetHeightTool : TerrainPaintToolWithOverlays<SetHeightTool>
{
private enum HeightSpace
{
World,
Local
}
const string k_ToolName = "Set Height";
public override string OnIcon => "TerrainOverlays/SetHeight_On.png";
public override string OffIcon => "TerrainOverlays/SetHeight.png";
[SerializeField] HeightSpace m_HeightSpace;
[SerializeField] float m_TargetHeight;
[FormerlyPrefKeyAs("Terrain/Set Height", "f2")]
[Shortcut("Terrain/Set Height", typeof(TerrainToolShortcutContext), KeyCode.F2)]
static void SelectShortcut(ShortcutArguments args)
{
TerrainToolShortcutContext context = (TerrainToolShortcutContext)args.context;
context.SelectPaintToolWithOverlays<SetHeightTool>();
}
class Styles
{
public readonly GUIContent description = EditorGUIUtility.TrTextContent("Left click to set the height.\n\nHold shift and left click to sample the target height.");
public readonly GUIContent space = EditorGUIUtility.TrTextContent("Space", "The heightmap space in which the painting operates.");
public readonly GUIContent height = EditorGUIUtility.TrTextContent("Height", "You can set the Height property manually or you can shift-click on the terrain to sample the height at the mouse position (rather like the 'eyedropper' tool in an image editor).");
public readonly GUIContent flatten = EditorGUIUtility.TrTextContent("Flatten Tile", "The Flatten button levels the whole terrain to the chosen height.");
public readonly GUIContent flattenAll = EditorGUIUtility.TrTextContent("Flatten All", "If selected, it will traverse all neighbors and flatten them too");
}
private static Styles m_styles;
private Styles GetStyles()
{
if (m_styles == null)
{
m_styles = new Styles();
}
return m_styles;
}
public override int IconIndex
{
get { return (int) SculptIndex.SetHeight; }
}
public override TerrainCategory Category
{
get { return TerrainCategory.Sculpt; }
}
public override string GetName()
{
return k_ToolName;
}
public override string GetDescription()
{
return GetStyles().description.text;
}
public override bool HasToolSettings => true;
public override bool HasBrushMask => true;
public override bool HasBrushAttributes => true;
public override void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext)
{
// We're only doing painting operations, early out if it's not a repaint
if (Event.current.type != EventType.Repaint)
return;
if (editContext.hitValidTerrain)
{
BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f);
PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1);
Material material = TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial();
TerrainPaintUtilityEditor.DrawBrushPreview(paintContext, TerrainBrushPreviewMode.SourceRenderTexture, editContext.brushTexture, brushXform, material, 0);
// draw result preview
{
ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform, terrain);
// restore old render target
RenderTexture.active = paintContext.oldRenderTexture;
material.SetTexture("_HeightmapOrig", paintContext.sourceRenderTexture);
TerrainPaintUtilityEditor.DrawBrushPreview(paintContext, TerrainBrushPreviewMode.DestinationRenderTexture, editContext.brushTexture, brushXform, material, 1);
}
TerrainPaintUtility.ReleaseContextResources(paintContext);
}
}
private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform, Terrain terrain)
{
Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial();
float brushTargetHeight = Mathf.Clamp01((m_TargetHeight - paintContext.heightWorldSpaceMin) / paintContext.heightWorldSpaceSize);
Vector4 brushParams = new Vector4(brushStrength * 0.01f, PaintContext.kNormalizedHeightScale * brushTargetHeight, 0.0f, 0.0f);
mat.SetTexture("_BrushTex", brushTexture);
mat.SetVector("_BrushParams", brushParams);
TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat);
Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainBuiltinPaintMaterialPasses.SetHeights);
}
public override bool OnPaint(Terrain terrain, IOnPaint editContext)
{
if (Event.current.shift)
{
m_TargetHeight = terrain.terrainData.GetInterpolatedHeight(editContext.uv.x, editContext.uv.y) + terrain.GetPosition().y;
editContext.Repaint(RepaintFlags.UI);
return true;
}
BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f);
PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds());
ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform, terrain);
TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Set Height");
return true;
}
void Flatten(Terrain terrain)
{
Undo.RegisterCompleteObjectUndo(terrain.terrainData, terrain.gameObject.name);
float terrainHeight = Mathf.Clamp01((m_TargetHeight - terrain.transform.position.y) / terrain.terrainData.size.y);
int res = terrain.terrainData.heightmapResolution;
float[,] heights = new float[res, res];
for (int y = 0; y < res; y++)
{
for (int x = 0; x < res; x++)
{
heights[y, x] = terrainHeight;
}
}
terrain.terrainData.SetHeights(0, 0, heights);
}
void FlattenAll()
{
foreach (Terrain t in Terrain.activeTerrains)
{
Flatten(t);
}
}
public override void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext)
{
Styles styles = GetStyles();
EditorGUI.BeginChangeCheck();
{
m_HeightSpace = (HeightSpace)EditorGUILayout.EnumPopup(styles.space, m_HeightSpace);
}
if (EditorGUI.EndChangeCheck())
{
if (m_HeightSpace == HeightSpace.Local)
m_TargetHeight = Mathf.Clamp(m_TargetHeight, terrain.GetPosition().y, terrain.terrainData.size.y + terrain.GetPosition().y);
}
if (m_HeightSpace == HeightSpace.Local)
m_TargetHeight = EditorGUILayout.Slider(styles.height, m_TargetHeight - terrain.GetPosition().y, 0, terrain.terrainData.size.y) + terrain.GetPosition().y;
else
m_TargetHeight = EditorGUILayout.FloatField(styles.height, m_TargetHeight);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(styles.flatten, GUILayout.ExpandWidth(false)))
Flatten(terrain);
if (GUILayout.Button(styles.flattenAll, GUILayout.ExpandWidth(false)))
FlattenAll();
GUILayout.EndHorizontal();
}
public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext)
{
OnToolSettingsGUI(terrain, editContext);
// show built-in brushes
int textureRez = terrain.terrainData.heightmapResolution;
editContext.ShowBrushesGUI(5, BrushGUIEditFlags.All, textureRez);
}
}
}
| UnityCsReference/Modules/TerrainEditor/PaintTools/SetHeightTool.cs/0 | {
"file_path": "UnityCsReference/Modules/TerrainEditor/PaintTools/SetHeightTool.cs",
"repo_id": "UnityCsReference",
"token_count": 3738
} | 458 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine.Scripting;
using UnityEngine.Bindings;
using UnityEngine.Profiling;
namespace UnityEngine.TextCore.LowLevel
{
/// <summary>
/// Flags taken from freetype.h
/// </summary>
[UsedByNativeCode]
[Flags]
public enum GlyphLoadFlags
{
LOAD_DEFAULT = 0,
LOAD_NO_SCALE = 1 << 0,
LOAD_NO_HINTING = 1 << 1,
LOAD_RENDER = 1 << 2,
LOAD_NO_BITMAP = 1 << 3,
//LOAD_VERTICAL_LAYOUT = 1 << 4,
LOAD_FORCE_AUTOHINT = 1 << 5,
//LOAD_CROP_BITMAP = 1 << 6,
//LOAD_PEDANTIC = 1 << 7,
//LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH = 1 << 9,
//LOAD_NO_RECURSE = 1 << 10,
//LOAD_IGNORE_TRANSFORM = 1 << 11,
LOAD_MONOCHROME = 1 << 12,
//LOAD_LINEAR_DESIGN = 1 << 13,
LOAD_NO_AUTOHINT = 1 << 15,
/* Bits 16-19 are used by `LOAD_TARGET_' */
LOAD_COLOR = 1 << 20,
LOAD_COMPUTE_METRICS = 1 << 21,
LOAD_BITMAP_METRICS_ONLY = 1 << 22
}
/// <summary>
/// Rasterizing modes used by the Font Engine to raster glyphs.
/// </summary>
[Flags]
internal enum GlyphRasterModes
{
RASTER_MODE_8BIT = 0x1,
RASTER_MODE_MONO = 0x2,
RASTER_MODE_NO_HINTING = 0x4,
RASTER_MODE_HINTED = 0x8,
RASTER_MODE_BITMAP = 0x10,
RASTER_MODE_SDF = 0x20,
RASTER_MODE_SDFAA = 0x40,
// Reserved = 0x80,
RASTER_MODE_MSDF = 0x100,
RASTER_MODE_MSDFA = 0x200,
// Reserved = 0x400,
// Reserved = 0x800,
RASTER_MODE_1X = 0x1000,
RASTER_MODE_8X = 0x2000,
RASTER_MODE_16X = 0x4000,
RASTER_MODE_32X = 0x8000,
RASTER_MODE_COLOR = 0x10000,
}
/// <summary>
/// Error codes returned and relevant to the various FontEngine functions.
/// Source codes are located in fterrdef.h
/// </summary>
public enum FontEngineError
{
Success = 0x0,
// Font file structure, type or path related errors.
Invalid_File_Path = 0x1,
Invalid_File_Format = 0x2,
Invalid_File_Structure = 0x3,
Invalid_File = 0x4,
Invalid_Table = 0x8,
// Glyph related errors.
Invalid_Glyph_Index = 0x10,
Invalid_Character_Code = 0x11,
Invalid_Pixel_Size = 0x17,
//
Invalid_Library = 0x21,
// Font face related errors.
Invalid_Face = 0x23,
Invalid_Library_or_Face = 0x29,
// Font atlas generation and glyph rendering related errors.
Atlas_Generation_Cancelled = 0x64,
Invalid_SharedTextureData = 0x65,
// OpenType Layout related errors.
OpenTypeLayoutLookup_Mismatch = 0x74,
// Additional errors codes will be added as necessary to cover new FontEngine features and functionality.
}
/// <summary>
/// Rendering modes used by the Font Engine to render glyphs.
/// </summary>
[UsedByNativeCode]
public enum GlyphRenderMode
{
SMOOTH_HINTED = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X,
SMOOTH = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X,
COLOR_HINTED = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_COLOR | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X,
COLOR = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_COLOR | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X,
RASTER_HINTED = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X,
RASTER = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_BITMAP | GlyphRasterModes.RASTER_MODE_1X,
SDF = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_SDF | GlyphRasterModes.RASTER_MODE_1X,
SDF8 = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_SDF | GlyphRasterModes.RASTER_MODE_8X,
SDF16 = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_SDF | GlyphRasterModes.RASTER_MODE_16X,
SDF32 = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_MONO | GlyphRasterModes.RASTER_MODE_SDF | GlyphRasterModes.RASTER_MODE_32X,
SDFAA_HINTED = GlyphRasterModes.RASTER_MODE_HINTED | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_SDFAA | GlyphRasterModes.RASTER_MODE_1X,
SDFAA = GlyphRasterModes.RASTER_MODE_NO_HINTING | GlyphRasterModes.RASTER_MODE_8BIT | GlyphRasterModes.RASTER_MODE_SDFAA | GlyphRasterModes.RASTER_MODE_1X,
}
/// <summary>
/// The modes available when packing glyphs into an atlas texture.
/// </summary>
[UsedByNativeCode]
public enum GlyphPackingMode
{
BestShortSideFit = 0x0,
BestLongSideFit = 0x1,
BestAreaFit = 0x2,
BottomLeftRule = 0x3,
ContactPointRule = 0x4,
}
/// <summary>
/// A structure that contains information about a system font.
/// </summary>
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
[System.Diagnostics.DebuggerDisplay("{familyName} - {styleName}")]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal struct FontReference
{
/// <summary>
/// The family name of the font.
/// </summary>
public string familyName;
/// <summary>
/// The style name of the font face.
/// </summary>
public string styleName;
/// <summary>
/// The face index of the face face matching this style name.
/// </summary>
public int faceIndex;
/// <summary>
/// The file path of the font file.
/// </summary>
public string filePath;
}
[NativeHeader("Modules/TextCoreFontEngine/Native/FontEngine.h")]
public sealed class FontEngine
{
private static Glyph[] s_Glyphs = new Glyph[16];
private static uint[] s_GlyphIndexes_MarshallingArray_A;
private static uint[] s_GlyphIndexes_MarshallingArray_B;
private static GlyphMarshallingStruct[] s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[16];
private static GlyphMarshallingStruct[] s_GlyphMarshallingStruct_OUT = new GlyphMarshallingStruct[16];
private static GlyphRect[] s_FreeGlyphRects = new GlyphRect[16];
private static GlyphRect[] s_UsedGlyphRects = new GlyphRect[16];
private static GlyphAdjustmentRecord[] s_SingleAdjustmentRecords_MarshallingArray;
private static SingleSubstitutionRecord[] s_SingleSubstitutionRecords_MarshallingArray;
private static MultipleSubstitutionRecord[] s_MultipleSubstitutionRecords_MarshallingArray;
private static AlternateSubstitutionRecord[] s_AlternateSubstitutionRecords_MarshallingArray;
private static LigatureSubstitutionRecord[] s_LigatureSubstitutionRecords_MarshallingArray;
private static ContextualSubstitutionRecord[] s_ContextualSubstitutionRecords_MarshallingArray;
private static ChainingContextualSubstitutionRecord[] s_ChainingContextualSubstitutionRecords_MarshallingArray;
private static GlyphPairAdjustmentRecord[] s_PairAdjustmentRecords_MarshallingArray;
private static MarkToBaseAdjustmentRecord[] s_MarkToBaseAdjustmentRecords_MarshallingArray;
private static MarkToMarkAdjustmentRecord[] s_MarkToMarkAdjustmentRecords_MarshallingArray;
private static Dictionary<uint, Glyph> s_GlyphLookupDictionary = new Dictionary<uint, Glyph>();
/// <summary>
///
/// </summary>
internal FontEngine() {}
/// <summary>
/// Initialize the Font Engine and library.
/// </summary>
/// <returns>Returns a value of zero if the initialization of the Font Engine was successful.</returns>
public static FontEngineError InitializeFontEngine()
{
return (FontEngineError)InitializeFontEngine_Internal();
}
[NativeMethod(Name = "TextCore::FontEngine::InitFontEngine", IsFreeFunction = true)]
static extern int InitializeFontEngine_Internal();
/// <summary>
/// Destroy and unload resources used by the Font Engine.
/// </summary>
/// <returns>Returns a value of zero if the Font Engine and used resources were successfully released.</returns>
public static FontEngineError DestroyFontEngine()
{
return (FontEngineError)DestroyFontEngine_Internal();
}
[NativeMethod(Name = "TextCore::FontEngine::DestroyFontEngine", IsFreeFunction = true)]
static extern int DestroyFontEngine_Internal();
/// <summary>
/// Force the cancellation of any atlas or glyph rendering process.
/// Used primarily by the Font Asset Creator.
/// </summary>
internal static void SendCancellationRequest()
{
SendCancellationRequest_Internal();
}
[NativeMethod(Name = "TextCore::FontEngine::SendCancellationRequest", IsFreeFunction = true)]
static extern void SendCancellationRequest_Internal();
/// <summary>
/// Determines if the font engine is currently in the process of rendering and adding glyphs into an atlas texture.
/// Used primarily by the Font Asset Creator.
/// </summary>
internal static extern bool isProcessingDone
{
[NativeMethod(Name = "TextCore::FontEngine::GetIsProcessingDone", IsFreeFunction = true)]
get;
}
/// <summary>
/// Returns the generation progress on glyph packing and rendering.
/// Used primarily by the Font Asset Creator.
/// </summary>
internal static extern float generationProgress
{
[NativeMethod(Name = "TextCore::FontEngine::GetGenerationProgress", IsFreeFunction = true)]
get;
}
/// <summary>
/// Loads the source font file at the given file path.
/// </summary>
/// <param name="filePath">The file path of the source font file.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(string filePath)
{
return (FontEngineError)LoadFontFace_Internal(filePath);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_Internal(string filePath);
/// <summary>
/// Loads the font file at the given file path and set it size to the specified point size.
/// </summary>
/// <param name="filePath">The file path of the source font file.</param>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <returns>A value of zero if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(string filePath, int pointSize)
{
return (FontEngineError)LoadFontFace_With_Size_Internal(filePath, pointSize);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_With_Size_Internal(string filePath, int pointSize);
/// <summary>
/// Loads the font file at the given file path and set it size and face index to the specified values.
/// </summary>
/// <param name="filePath">The file path of the source font file.</param>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <param name="faceIndex">The face index of the font face to load. When the font file is a TrueType collection (.TTC), this specifies the face index of the font face to load. If the font file is a TrueType Font (.TTF) or OpenType Font (.OTF) file, the face index is always 0.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(string filePath, int pointSize, int faceIndex)
{
return (FontEngineError)LoadFontFace_With_Size_And_FaceIndex_Internal(filePath, pointSize, faceIndex);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_With_Size_And_FaceIndex_Internal(string filePath, int pointSize, int faceIndex);
/// <summary>
/// Loads the font file from the provided byte array.
/// </summary>
/// <param name="sourceFontFile">The byte array that contains the source font file.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(byte[] sourceFontFile)
{
if (sourceFontFile.Length == 0)
return FontEngineError.Invalid_File;
return (FontEngineError)LoadFontFace_FromSourceFontFile_Internal(sourceFontFile);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_FromSourceFontFile_Internal(byte[] sourceFontFile);
/// <summary>
/// Loads the font file from the provided byte array and set its size to the given point size.
/// </summary>
/// <param name="sourceFontFile">The byte array that contains the source font file.</param>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(byte[] sourceFontFile, int pointSize)
{
if (sourceFontFile.Length == 0)
return FontEngineError.Invalid_File;
return (FontEngineError)LoadFontFace_With_Size_FromSourceFontFile_Internal(sourceFontFile, pointSize);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_With_Size_FromSourceFontFile_Internal(byte[] sourceFontFile, int pointSize);
/// <summary>
/// Loads the font file from the provided byte array and set its size and face index to the specified values.
/// </summary>
/// <param name="sourceFontFile">The byte array that contains the source font file.</param>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <param name="faceIndex">The face index of the font face to load. When the font file is a TrueType collection (.TTC), this specifies the face index of the font face to load. If the font file is a TrueType Font (.TTF) or OpenType Font (.OTF) file, the face index is always 0.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(byte[] sourceFontFile, int pointSize, int faceIndex)
{
if (sourceFontFile.Length == 0)
return FontEngineError.Invalid_File;
return (FontEngineError)LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal(sourceFontFile, pointSize, faceIndex);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_With_Size_And_FaceIndex_FromSourceFontFile_Internal(byte[] sourceFontFile, int pointSize, int faceIndex);
/// <summary>
/// Loads the font file from the Unity font's internal font data. Note the Unity font must be set to Dynamic with Include Font Data enabled.
/// </summary>
/// <param name="font">The font from which to load the data.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(Font font)
{
return (FontEngineError)LoadFontFace_FromFont_Internal(font);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_FromFont_Internal(Font font);
/// <summary>
/// Loads the font file from the Unity font's internal font data. Note the Unity font must be set to Dynamic with Include Font Data enabled.
/// </summary>
/// <param name="font">The font from which to load the data.</param>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(Font font, int pointSize)
{
return (FontEngineError)LoadFontFace_With_Size_FromFont_Internal(font, pointSize);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_With_Size_FromFont_Internal(Font font, int pointSize);
/// <summary>
/// Loads the font file from the Unity font's internal font data. Note the Unity font must be set to Dynamic with Include Font Data enabled.
/// </summary>
/// <param name="font">The font from which to load the data.</param>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <param name="faceIndex">The face index of the font face to load. When the font file is a TrueType collection (.TTC), this specifies the face index of the font face to load. If the font file is a TrueType Font (.TTF) or OpenType Font (.OTF) file, the face index is always 0.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(Font font, int pointSize, int faceIndex)
{
return (FontEngineError)LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal(font, pointSize, faceIndex);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_With_Size_and_FaceIndex_FromFont_Internal(Font font, int pointSize, int faceIndex);
/// <summary>
/// Loads the font file from a potential system font by family and style name.
/// </summary>
/// <param name="familyName">The family name of the font face to load.</param>
/// <param name="styleName">The style name of the font face to load.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(string familyName, string styleName)
{
return (FontEngineError)LoadFontFace_by_FamilyName_and_StyleName_Internal(familyName, styleName);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_by_FamilyName_and_StyleName_Internal(string familyName, string styleName);
/// <summary>
/// Loads the font file from a potential system font by family and style name at the specified point size.
/// </summary>
/// <param name="familyName">The family name of the font face to load.</param>
/// <param name="styleName">The style name of the font face to load.</param>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <returns>A value of zero (0) if the font face was loaded successfully.</returns>
public static FontEngineError LoadFontFace(string familyName, string styleName, int pointSize)
{
return (FontEngineError)LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal(familyName, styleName, pointSize);
}
[NativeMethod(Name = "TextCore::FontEngine::LoadFontFace", IsFreeFunction = true)]
static extern int LoadFontFace_With_Size_by_FamilyName_and_StyleName_Internal(string familyName, string styleName, int pointSize);
/// <summary>
/// Unloads current font face and removes it from the cache.
/// </summary>
/// <returns>A value of zero (0) if the font face was successfully unloaded and removed from the cache.</returns>
public static FontEngineError UnloadFontFace()
{
return (FontEngineError)UnloadFontFace_Internal();
}
[NativeMethod(Name = "TextCore::FontEngine::UnloadFontFace", IsFreeFunction = true)]
static extern int UnloadFontFace_Internal();
/// <summary>
/// Unloads all currently loaded font faces and removes them from the cache.
/// </summary>
/// <returns>A value of zero (0) if the font faces were successfully unloaded and removed from the cache.</returns>
public static FontEngineError UnloadAllFontFaces()
{
return (FontEngineError)UnloadAllFontFaces_Internal();
}
[NativeMethod(Name = "TextCore::FontEngine::UnloadAllFontFaces", IsFreeFunction = true)]
static extern int UnloadAllFontFaces_Internal();
/// <summary>
/// Gets the family names and styles of the system fonts.
/// </summary>
/// <returns>Returns the names and styles of the system fonts.</returns>
public static string[] GetSystemFontNames()
{
string[] fontNames = GetSystemFontNames_Internal();
if (fontNames != null && fontNames.Length == 0)
return null;
return fontNames;
}
[NativeMethod(Name = "TextCore::FontEngine::GetSystemFontNames", IsThreadSafe = true, IsFreeFunction = true)]
static extern string[] GetSystemFontNames_Internal();
/// <summary>
/// Gets references to all system fonts.
/// </summary>
/// <returns>An array of font references for all system fonts.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetSystemFontReferences", IsThreadSafe = true, IsFreeFunction = true)]
internal static extern FontReference[] GetSystemFontReferences();
/// <summary>
/// Try finding and returning a reference to a system font for the given family name and style.
/// </summary>
/// <param name="familyName">The family name of the font.</param>
/// <param name="styleName">The style name of the font.</param>
/// <param name="fontRef">A FontReference to the matching system font.</param>
/// <returns>Returns true if a reference to the system font was found. Otherwise returns false.</returns>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static bool TryGetSystemFontReference(string familyName, string styleName, out FontReference fontRef)
{
return TryGetSystemFontReference_Internal(familyName, styleName, out fontRef);
}
[NativeMethod(Name = "TextCore::FontEngine::TryGetSystemFontReference", IsThreadSafe = true, IsFreeFunction = true)]
static extern bool TryGetSystemFontReference_Internal(string familyName, string styleName, out FontReference fontRef);
/// <summary>
/// Set the size of the currently loaded font face.
/// </summary>
/// <param name="pointSize">The point size used to scale the font face.</param>
/// <returns>Returns a value of zero if the font face was successfully scaled to the given point size.</returns>
public static FontEngineError SetFaceSize(int pointSize)
{
return (FontEngineError)SetFaceSize_Internal(pointSize);
}
[NativeMethod(Name = "TextCore::FontEngine::SetFaceSize", IsThreadSafe = true, IsFreeFunction = true)]
static extern int SetFaceSize_Internal(int pointSize);
/// <summary>
/// Get information about the currently loaded and sized font face.
/// </summary>
/// <returns>Returns the FaceInfo of the currently loaded font face.</returns>
public static FaceInfo GetFaceInfo()
{
FaceInfo faceInfo = new FaceInfo();
GetFaceInfo_Internal(ref faceInfo);
return faceInfo;
}
[NativeMethod(Name = "TextCore::FontEngine::GetFaceInfo", IsThreadSafe = true, IsFreeFunction = true)]
static extern int GetFaceInfo_Internal(ref FaceInfo faceInfo);
/// <summary>
/// Get the number of faces and styles for the currently loaded font.
/// </summary>
/// <returns>Returns the number of font faces and styles contained in the font.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetFaceCount", IsThreadSafe = true, IsFreeFunction = true)]
internal static extern int GetFaceCount();
/// <summary>
/// Get the font face(s) and style(s) for the currently loaded font.
/// </summary>
/// <returns>Array containing the names of the font faces and styles.</returns>
public static string[] GetFontFaces()
{
string[] faces = GetFontFaces_Internal();
if (faces != null && faces.Length == 0)
return null;
return faces;
}
[NativeMethod(Name = "TextCore::FontEngine::GetFontFaces", IsThreadSafe = true, IsFreeFunction = true)]
static extern string[] GetFontFaces_Internal();
/// <summary>
/// Get the index of the glyph for the given character Unicode as modified by the variant selector.
/// </summary>
/// <param name="unicode">The Unicode value of the character for which to lookup the glyph index.</param>
/// <param name="variantSelectorUnicode">The Unicode value of the variant selector.</param>
/// <returns>Returns the index of the glyph used by the character using the Unicode value as modified by the variant selector. Returns zero if no glyph variant exists for the given Unicode value.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetVariantGlyphIndex", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static extern uint GetVariantGlyphIndex(uint unicode, uint variantSelectorUnicode);
/// <summary>
/// Get the index of the glyph for the character mapped at Unicode value.
/// </summary>
/// <param name="unicode">The Unicode value of the character for which to lookup the glyph index.</param>
/// <returns>Returns the index of the glyph used by the character using the Unicode value. Returns zero if no glyph exists for the given Unicode value.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetGlyphIndex", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static extern uint GetGlyphIndex(uint unicode);
/// <summary>
/// Try to get the glyph index for the character at the given Unicode value.
/// </summary>
/// <param name="unicode">The unicode value of the character for which to lookup the glyph index.</param>
/// <param name="glyphIndex">The index of the glyph for the given unicode character or the .notdef glyph (index 0) if no glyph is available for the given Unicode value.</param>
/// <returns>Returns true if the given unicode has a glyph index.</returns>
[NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphIndex", IsThreadSafe = true, IsFreeFunction = true)]
public static extern bool TryGetGlyphIndex(uint unicode, out uint glyphIndex);
/// <summary>
/// Try loading a glyph for the given unicode value. If available, populates the glyph and returns true. Otherwise returns false and populates the glyph with the .notdef / missing glyph data.
/// </summary>
/// <param name="unicode">The Unicode value of the character whose glyph should be loaded.</param>
/// <param name="flags">The Load Flags.</param>
/// <param name="glyph">The glyph for the given character using the provided Unicode value or the .notdef glyph (index 0) if no glyph is available for the given Unicode value.</param>
/// <returns>Returns true if a glyph exists for the given unicode value. Otherwise returns false.</returns>
public static bool TryGetGlyphWithUnicodeValue(uint unicode, GlyphLoadFlags flags, out Glyph glyph)
{
GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct();
if (TryGetGlyphWithUnicodeValue_Internal(unicode, flags, ref glyphStruct))
{
glyph = new Glyph(glyphStruct);
return true;
}
// Set glyph to null if no glyph exists for the given unicode value.
glyph = null;
return false;
}
[NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphWithUnicodeValue", IsThreadSafe = true, IsFreeFunction = true)]
static extern bool TryGetGlyphWithUnicodeValue_Internal(uint unicode, GlyphLoadFlags loadFlags, ref GlyphMarshallingStruct glyphStruct);
/// <summary>
/// Try loading the glyph for the given index value and if available populate the glyph.
/// </summary>
/// <param name="glyphIndex">The index of the glyph that should be loaded.</param>
/// <param name="flags">The Load Flags.</param>
/// <param name="glyph">The glyph using the provided index or the .notdef glyph (index 0) if no glyph was found at that index.</param>
/// <returns>Returns true if a glyph exists at the given index. Otherwise returns false.</returns>
public static bool TryGetGlyphWithIndexValue(uint glyphIndex, GlyphLoadFlags flags, out Glyph glyph)
{
GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct();
if (TryGetGlyphWithIndexValue_Internal(glyphIndex, flags, ref glyphStruct))
{
glyph = new Glyph(glyphStruct);
return true;
}
// Set glyph to null if no glyph exists for the given unicode value.
glyph = null;
return false;
}
[NativeMethod(Name = "TextCore::FontEngine::TryGetGlyphWithIndexValue", IsThreadSafe = true, IsFreeFunction = true)]
static extern bool TryGetGlyphWithIndexValue_Internal(uint glyphIndex, GlyphLoadFlags loadFlags, ref GlyphMarshallingStruct glyphStruct);
/// <summary>
/// Try to pack the given glyph into the given texture width and height.
/// </summary>
/// <param name="glyph">The glyph to try to pack.</param>
/// <param name="padding">The padding between this glyph and other glyphs.</param>
/// <param name="packingMode">The packing algorithm used to pack the glyphs.</param>
/// <param name="renderMode">The glyph rendering mode.</param>
/// <param name="width">The width of the target atlas texture.</param>
/// <param name="height">The height of the target atlas texture.</param>
/// <param name="freeGlyphRects">List of GlyphRects representing the available space in the atlas.</param>
/// <param name="usedGlyphRects">List of GlyphRects representing the occupied space in the atlas.</param>
/// <returns></returns>
internal static bool TryPackGlyphInAtlas(Glyph glyph, int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height, List<GlyphRect> freeGlyphRects, List<GlyphRect> usedGlyphRects)
{
GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyph);
int freeGlyphRectCount = freeGlyphRects.Count;
int usedGlyphRectCount = usedGlyphRects.Count;
int totalGlyphRects = freeGlyphRectCount + usedGlyphRectCount;
// Make sure marshalling arrays allocations are appropriate.
if (s_FreeGlyphRects.Length < totalGlyphRects || s_UsedGlyphRects.Length < totalGlyphRects)
{
int newSize = Mathf.NextPowerOfTwo(totalGlyphRects + 1);
s_FreeGlyphRects = new GlyphRect[newSize];
s_UsedGlyphRects = new GlyphRect[newSize];
}
// Copy glyph rect data to marshalling arrays.
int glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount);
for (int i = 0; i < glyphRectCount; i++)
{
if (i < freeGlyphRectCount)
s_FreeGlyphRects[i] = freeGlyphRects[i];
if (i < usedGlyphRectCount)
s_UsedGlyphRects[i] = usedGlyphRects[i];
}
if (TryPackGlyphInAtlas_Internal(ref glyphStruct, padding, packingMode, renderMode, width, height, s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount))
{
// Copy new glyph position to source glyph.
glyph.glyphRect = glyphStruct.glyphRect;
freeGlyphRects.Clear();
usedGlyphRects.Clear();
// Copy marshalled glyph rect data
glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount);
for (int i = 0; i < glyphRectCount; i++)
{
if (i < freeGlyphRectCount)
freeGlyphRects.Add(s_FreeGlyphRects[i]);
if (i < usedGlyphRectCount)
usedGlyphRects.Add(s_UsedGlyphRects[i]);
}
return true;
}
return false;
}
[NativeMethod(Name = "TextCore::FontEngine::TryPackGlyph", IsThreadSafe = true, IsFreeFunction = true)]
extern static bool TryPackGlyphInAtlas_Internal(ref GlyphMarshallingStruct glyph, int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height,
[Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount);
/// <summary>
/// Pack glyphs in the given atlas size.
/// </summary>
/// <param name="glyphsToAdd">Glyphs to pack in atlas.</param>
/// <param name="glyphsAdded">Glyphs packed in atlas.</param>
/// <param name="padding">The padding between glyphs.</param>
/// <param name="packingMode">The packing algorithm used to pack the glyphs.</param>
/// <param name="renderMode">The glyph rendering mode.</param>
/// <param name="width">The width of the target atlas texture.</param>
/// <param name="height">The height of the target atlas texture.</param>
/// <param name="freeGlyphRects">List of GlyphRects representing the available space in the atlas.</param>
/// <param name="usedGlyphRects">List of GlyphRects representing the occupied space in the atlas.</param>
/// <returns></returns>
internal static bool TryPackGlyphsInAtlas(List<Glyph> glyphsToAdd, List<Glyph> glyphsAdded, int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height, List<GlyphRect> freeGlyphRects, List<GlyphRect> usedGlyphRects)
{
// Determine potential total allocations required for glyphs and glyph rectangles.
int glyphsToAddCount = glyphsToAdd.Count;
int glyphsAddedCount = glyphsAdded.Count;
int freeGlyphRectCount = freeGlyphRects.Count;
int usedGlyphRectCount = usedGlyphRects.Count;
int totalCount = glyphsToAddCount + glyphsAddedCount + freeGlyphRectCount + usedGlyphRectCount;
// Make sure marshaling arrays allocations are appropriate.
if (s_GlyphMarshallingStruct_IN.Length < totalCount || s_GlyphMarshallingStruct_OUT.Length < totalCount || s_FreeGlyphRects.Length < totalCount || s_UsedGlyphRects.Length < totalCount)
{
int newSize = Mathf.NextPowerOfTwo(totalCount + 1);
s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize];
s_GlyphMarshallingStruct_OUT = new GlyphMarshallingStruct[newSize];
s_FreeGlyphRects = new GlyphRect[newSize];
s_UsedGlyphRects = new GlyphRect[newSize];
}
s_GlyphLookupDictionary.Clear();
// Copy glyph data into appropriate marshaling array.
for (int i = 0; i < totalCount; i++)
{
if (i < glyphsToAddCount)
{
GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyphsToAdd[i]);
s_GlyphMarshallingStruct_IN[i] = glyphStruct;
// Add reference to glyph in lookup dictionary
if (s_GlyphLookupDictionary.ContainsKey(glyphStruct.index) == false)
s_GlyphLookupDictionary.Add(glyphStruct.index, glyphsToAdd[i]);
}
if (i < glyphsAddedCount)
{
GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyphsAdded[i]);
s_GlyphMarshallingStruct_OUT[i] = glyphStruct;
// Add reference to glyph in lookup dictionary
if (s_GlyphLookupDictionary.ContainsKey(glyphStruct.index) == false)
s_GlyphLookupDictionary.Add(glyphStruct.index, glyphsAdded[i]);
}
if (i < freeGlyphRectCount)
s_FreeGlyphRects[i] = freeGlyphRects[i];
if (i < usedGlyphRectCount)
s_UsedGlyphRects[i] = usedGlyphRects[i];
}
bool allGlyphsIncluded = TryPackGlyphsInAtlas_Internal(s_GlyphMarshallingStruct_IN, ref glyphsToAddCount, s_GlyphMarshallingStruct_OUT, ref glyphsAddedCount,
padding, packingMode, renderMode, width, height,
s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount);
// Clear lists and / or re-allocate arrays.
glyphsToAdd.Clear();
glyphsAdded.Clear();
freeGlyphRects.Clear();
usedGlyphRects.Clear();
// Copy marshaled glyph data back into the appropriate lists.
for (int i = 0; i < totalCount; i++)
{
if (i < glyphsToAddCount)
{
GlyphMarshallingStruct glyphStruct = s_GlyphMarshallingStruct_IN[i];
Glyph glyph = s_GlyphLookupDictionary[glyphStruct.index];
// Note: In theory, only new glyphRect x and y need to be copied.
glyph.metrics = glyphStruct.metrics;
glyph.glyphRect = glyphStruct.glyphRect;
glyph.scale = glyphStruct.scale;
glyph.atlasIndex = glyphStruct.atlasIndex;
glyphsToAdd.Add(glyph);
}
if (i < glyphsAddedCount)
{
GlyphMarshallingStruct glyphStruct = s_GlyphMarshallingStruct_OUT[i];
Glyph glyph = s_GlyphLookupDictionary[glyphStruct.index];
glyph.metrics = glyphStruct.metrics;
glyph.glyphRect = glyphStruct.glyphRect;
glyph.scale = glyphStruct.scale;
glyph.atlasIndex = glyphStruct.atlasIndex;
glyphsAdded.Add(glyph);
}
if (i < freeGlyphRectCount)
{
freeGlyphRects.Add(s_FreeGlyphRects[i]);
}
if (i < usedGlyphRectCount)
{
usedGlyphRects.Add(s_UsedGlyphRects[i]);
}
}
return allGlyphsIncluded;
}
[NativeMethod(Name = "TextCore::FontEngine::TryPackGlyphs", IsThreadSafe = true, IsFreeFunction = true)]
extern static bool TryPackGlyphsInAtlas_Internal([Out] GlyphMarshallingStruct[] glyphsToAdd, ref int glyphsToAddCount, [Out] GlyphMarshallingStruct[] glyphsAdded, ref int glyphsAddedCount,
int padding, GlyphPackingMode packingMode, GlyphRenderMode renderMode, int width, int height,
[Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount);
/// <summary>
/// Render and add glyph to the provided texture.
/// </summary>
/// <param name="glyph">The Glyph that should be added into the provided texture.</param>
/// <param name="padding">The padding value around the glyph.</param>
/// <param name="renderMode">The Rendering Mode for the Glyph.</param>
/// <param name="texture">The Texture to which the glyph should be added.</param>
/// <returns>Returns a value of zero if the glyph was successfully added to the texture.</returns>
internal static FontEngineError RenderGlyphToTexture(Glyph glyph, int padding, GlyphRenderMode renderMode, Texture2D texture)
{
GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyph);
return (FontEngineError)RenderGlyphToTexture_Internal(glyphStruct, padding, renderMode, texture);
}
[NativeMethod(Name = "TextCore::FontEngine::RenderGlyphToTexture", IsFreeFunction = true)]
extern static int RenderGlyphToTexture_Internal(GlyphMarshallingStruct glyphStruct, int padding, GlyphRenderMode renderMode, Texture2D texture);
/// <summary>
/// Render and add the glyphs in the provided list to the texture.
/// </summary>
/// <param name="glyphs">The list of glyphs to be rendered and added to the provided texture.</param>
/// <param name="padding">The padding value around the glyphs.</param>
/// <param name="renderMode">The rendering mode used to rasterize the glyphs.</param>
/// <param name="texture">Returns a value of zero if the glyphs were successfully added to the texture.</param>
/// <returns></returns>
internal static FontEngineError RenderGlyphsToTexture(List<Glyph> glyphs, int padding, GlyphRenderMode renderMode, Texture2D texture)
{
int glyphCount = glyphs.Count;
// Make sure marshaling arrays allocations are appropriate.
if (s_GlyphMarshallingStruct_IN.Length < glyphCount)
{
int newSize = Mathf.NextPowerOfTwo(glyphCount + 1);
s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize];
}
// Copy data to marshalling buffers
for (int i = 0; i < glyphCount; i++)
s_GlyphMarshallingStruct_IN[i] = new GlyphMarshallingStruct(glyphs[i]);
// Call extern function to render and add glyphs to texture.
int error = RenderGlyphsToTexture_Internal(s_GlyphMarshallingStruct_IN, glyphCount, padding, renderMode, texture);
return (FontEngineError)error;
}
[NativeMethod(Name = "TextCore::FontEngine::RenderGlyphsToTexture", IsFreeFunction = true)]
extern static int RenderGlyphsToTexture_Internal(GlyphMarshallingStruct[] glyphs, int glyphCount, int padding, GlyphRenderMode renderMode, Texture2D texture);
internal static FontEngineError RenderGlyphsToTexture(List<Glyph> glyphs, int padding, GlyphRenderMode renderMode, byte[] texBuffer, int texWidth, int texHeight)
{
int glyphCount = glyphs.Count;
// Make sure marshaling arrays allocations are appropriate.
if (s_GlyphMarshallingStruct_IN.Length < glyphCount)
{
int newSize = Mathf.NextPowerOfTwo(glyphCount + 1);
s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize];
}
// Copy data to marshalling buffers
for (int i = 0; i < glyphCount; i++)
s_GlyphMarshallingStruct_IN[i] = new GlyphMarshallingStruct(glyphs[i]);
int error = RenderGlyphsToTextureBuffer_Internal(s_GlyphMarshallingStruct_IN, glyphCount, padding, renderMode, texBuffer, texWidth, texHeight);
return (FontEngineError)error;
}
[NativeMethod(Name = "TextCore::FontEngine::RenderGlyphsToTextureBuffer", IsThreadSafe = true, IsFreeFunction = true)]
extern static int RenderGlyphsToTextureBuffer_Internal(GlyphMarshallingStruct[] glyphs, int glyphCount, int padding, GlyphRenderMode renderMode, [Out] byte[] texBuffer, int texWidth, int texHeight);
/// <summary>
/// Internal function used to render and add glyphs to the cached shared texture data from outside the main thread.
/// It is necessary to use SetSharedTextureData(texture) prior to calling this function.
/// </summary>
/// <param name="glyphs">The list of glyphs to be added into the provided texture.</param>
/// <param name="padding">The padding value around the glyphs.</param>
/// <param name="renderMode">The rendering mode used to rasterize the glyphs.</param>
/// <returns></returns>
internal static FontEngineError RenderGlyphsToSharedTexture(List<Glyph> glyphs, int padding, GlyphRenderMode renderMode)
{
int glyphCount = glyphs.Count;
// Make sure marshaling arrays allocations are appropriate.
if (s_GlyphMarshallingStruct_IN.Length < glyphCount)
{
int newSize = Mathf.NextPowerOfTwo(glyphCount + 1);
s_GlyphMarshallingStruct_IN = new GlyphMarshallingStruct[newSize];
}
// Copy data to marshalling buffers
for (int i = 0; i < glyphCount; i++)
s_GlyphMarshallingStruct_IN[i] = new GlyphMarshallingStruct(glyphs[i]);
int error = RenderGlyphsToSharedTexture_Internal(s_GlyphMarshallingStruct_IN, glyphCount, padding, renderMode);
return (FontEngineError)error;
}
[NativeMethod(Name = "TextCore::FontEngine::RenderGlyphsToSharedTexture", IsThreadSafe = true, IsFreeFunction = true)]
extern static int RenderGlyphsToSharedTexture_Internal(GlyphMarshallingStruct[] glyphs, int glyphCount, int padding, GlyphRenderMode renderMode);
/// <summary>
/// Internal function used to get a reference to the shared texture data which is required for accessing the texture data outside of the main thread.
/// </summary>
[NativeMethod(Name = "TextCore::FontEngine::SetSharedTextureData", IsFreeFunction = true)]
internal extern static void SetSharedTexture(Texture2D texture);
/// <summary>
/// Internal function used to release the shared texture data.
/// </summary>
[NativeMethod(Name = "TextCore::FontEngine::ReleaseSharedTextureData", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static void ReleaseSharedTexture();
/// <summary>
/// Internal function used to control if texture changes resulting from adding glyphs to an atlas texture will be uploaded to the graphic device immediately or delayed and batched.
/// </summary>
[NativeMethod(Name = "TextCore::FontEngine::SetTextureUploadMode", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal extern static void SetTextureUploadMode(bool shouldUploadImmediately);
/// <summary>
/// Internal function used to add glyph to atlas texture.
/// </summary>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static bool TryAddGlyphToTexture(uint glyphIndex, int padding, GlyphPackingMode packingMode, List<GlyphRect> freeGlyphRects, List<GlyphRect> usedGlyphRects, GlyphRenderMode renderMode, Texture2D texture, out Glyph glyph)
{
// Determine potential total allocations required for glyphs and glyph rectangles.
int freeGlyphRectCount = freeGlyphRects.Count;
int usedGlyphRectCount = usedGlyphRects.Count;
int totalGlyphRects = freeGlyphRectCount + usedGlyphRectCount;
// Make sure marshalling arrays allocations are appropriate.
if (s_FreeGlyphRects.Length < totalGlyphRects || s_UsedGlyphRects.Length < totalGlyphRects)
{
int newSize = Mathf.NextPowerOfTwo(totalGlyphRects + 1);
s_FreeGlyphRects = new GlyphRect[newSize];
s_UsedGlyphRects = new GlyphRect[newSize];
}
// Copy glyph rect data to marshalling arrays.
int glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount);
for (int i = 0; i < glyphRectCount; i++)
{
if (i < freeGlyphRectCount)
s_FreeGlyphRects[i] = freeGlyphRects[i];
if (i < usedGlyphRectCount)
s_UsedGlyphRects[i] = usedGlyphRects[i];
}
GlyphMarshallingStruct glyphStruct;
// Marshall data over to the native side.
if (TryAddGlyphToTexture_Internal(glyphIndex, padding, packingMode, s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount, renderMode, texture, out glyphStruct))
{
// Copy marshalled data over to new glyph.
glyph = new Glyph(glyphStruct);
freeGlyphRects.Clear();
usedGlyphRects.Clear();
// Copy marshalled free and used GlyphRect data over.
glyphRectCount = Mathf.Max(freeGlyphRectCount, usedGlyphRectCount);
for (int i = 0; i < glyphRectCount; i++)
{
if (i < freeGlyphRectCount)
freeGlyphRects.Add(s_FreeGlyphRects[i]);
if (i < usedGlyphRectCount)
usedGlyphRects.Add(s_UsedGlyphRects[i]);
}
return true;
}
glyph = null;
return false;
}
//
[NativeMethod(Name = "TextCore::FontEngine::TryAddGlyphToTexture", IsThreadSafe = true, IsFreeFunction = true)]
extern static bool TryAddGlyphToTexture_Internal(uint glyphIndex, int padding,
GlyphPackingMode packingMode, [Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount,
GlyphRenderMode renderMode, Texture2D texture, out GlyphMarshallingStruct glyph);
/// <summary>
/// Internal function used to add glyph to atlas texture.
/// </summary>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static bool TryAddGlyphsToTexture(List<Glyph> glyphsToAdd, List<Glyph> glyphsAdded, int padding, GlyphPackingMode packingMode, List<GlyphRect> freeGlyphRects, List<GlyphRect> usedGlyphRects, GlyphRenderMode renderMode, Texture2D texture)
{
Profiler.BeginSample("FontEngine.TryAddGlyphsToTexture");
int writeIndex = 0;
bool keepCopyingData;
int glyphsToAddCount = glyphsToAdd.Count;
int glyphsAddedCount = 0;
// Make sure marshalling arrays allocations are appropriate
if (s_GlyphMarshallingStruct_IN.Length < glyphsToAddCount || s_GlyphMarshallingStruct_OUT.Length < glyphsToAddCount)
{
int newSize = Mathf.NextPowerOfTwo(glyphsToAddCount + 1);
if (s_GlyphMarshallingStruct_IN.Length < glyphsToAddCount)
System.Array.Resize(ref s_GlyphMarshallingStruct_IN, newSize);
if (s_GlyphMarshallingStruct_OUT.Length < glyphsToAddCount)
System.Array.Resize(ref s_GlyphMarshallingStruct_OUT, newSize);
}
// Determine potential total allocations required for glyphs and glyph rectangles.
int freeGlyphRectCount = freeGlyphRects.Count;
int usedGlyphRectCount = usedGlyphRects.Count;
int totalGlyphRects = freeGlyphRectCount + usedGlyphRectCount + glyphsToAddCount;
// Make sure marshalling arrays allocations are appropriate
if (s_FreeGlyphRects.Length < totalGlyphRects || s_UsedGlyphRects.Length < totalGlyphRects)
{
int newSize = Mathf.NextPowerOfTwo(totalGlyphRects + 1);
if (s_FreeGlyphRects.Length < totalGlyphRects)
System.Array.Resize(ref s_FreeGlyphRects, newSize);
if (s_UsedGlyphRects.Length < totalGlyphRects)
System.Array.Resize(ref s_UsedGlyphRects, newSize);
}
s_GlyphLookupDictionary.Clear();
// Copy data to marshalling arrays
writeIndex = 0;
keepCopyingData = true;
while (keepCopyingData == true)
{
keepCopyingData = false;
if (writeIndex < glyphsToAddCount)
{
Glyph glyph = glyphsToAdd[writeIndex];
s_GlyphMarshallingStruct_IN[writeIndex] = new GlyphMarshallingStruct(glyph);
s_GlyphLookupDictionary.Add(glyph.index, glyph);
keepCopyingData = true;
}
if (writeIndex < freeGlyphRectCount)
{
s_FreeGlyphRects[writeIndex] = freeGlyphRects[writeIndex];
keepCopyingData = true;
}
if (writeIndex < usedGlyphRectCount)
{
s_UsedGlyphRects[writeIndex] = usedGlyphRects[writeIndex];
keepCopyingData = true;
}
writeIndex += 1;
}
bool allGlyphsAdded = TryAddGlyphsToTexture_Internal_MultiThread(s_GlyphMarshallingStruct_IN, ref glyphsToAddCount, s_GlyphMarshallingStruct_OUT, ref glyphsAddedCount, padding, packingMode, s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount, renderMode, texture);
// Clear inbound lists
glyphsToAdd.Clear();
glyphsAdded.Clear();
freeGlyphRects.Clear();
usedGlyphRects.Clear();
// Copy new data into appropriate data structure
writeIndex = 0;
keepCopyingData = true;
while (keepCopyingData == true)
{
keepCopyingData = false;
if (writeIndex < glyphsToAddCount)
{
uint glyphIndex = s_GlyphMarshallingStruct_IN[writeIndex].index;
glyphsToAdd.Add(s_GlyphLookupDictionary[glyphIndex]);
keepCopyingData = true;
}
if (writeIndex < glyphsAddedCount)
{
uint glyphIndex = s_GlyphMarshallingStruct_OUT[writeIndex].index;
Glyph glyph = s_GlyphLookupDictionary[glyphIndex];
glyph.atlasIndex = s_GlyphMarshallingStruct_OUT[writeIndex].atlasIndex;
glyph.scale = s_GlyphMarshallingStruct_OUT[writeIndex].scale;
glyph.glyphRect = s_GlyphMarshallingStruct_OUT[writeIndex].glyphRect;
glyph.metrics = s_GlyphMarshallingStruct_OUT[writeIndex].metrics;
glyphsAdded.Add(glyph);
keepCopyingData = true;
}
if (writeIndex < freeGlyphRectCount)
{
freeGlyphRects.Add(s_FreeGlyphRects[writeIndex]);
keepCopyingData = true;
}
if (writeIndex < usedGlyphRectCount)
{
usedGlyphRects.Add(s_UsedGlyphRects[writeIndex]);
keepCopyingData = true;
}
writeIndex += 1;
}
Profiler.EndSample();
return allGlyphsAdded;
}
[NativeMethod(Name = "TextCore::FontEngine::TryAddGlyphsToTexture", IsThreadSafe = true, IsFreeFunction = true)]
extern static bool TryAddGlyphsToTexture_Internal_MultiThread([Out] GlyphMarshallingStruct[] glyphsToAdd, ref int glyphsToAddCount, [Out] GlyphMarshallingStruct[] glyphsAdded, ref int glyphsAddedCount,
int padding, GlyphPackingMode packingMode, [Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount,
GlyphRenderMode renderMode, Texture2D texture);
/// <summary>
/// Internal function used to add multiple glyphs to atlas texture.
/// </summary>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static bool TryAddGlyphsToTexture(List<uint> glyphIndexes, int padding, GlyphPackingMode packingMode, List<GlyphRect> freeGlyphRects, List<GlyphRect> usedGlyphRects, GlyphRenderMode renderMode, Texture2D texture, out Glyph[] glyphs)
{
return TryAddGlyphsToTexture(glyphIndexes, padding, packingMode, freeGlyphRects, usedGlyphRects, renderMode, texture, out glyphs);
}
/// <summary>
/// Internal function used to add multiple glyphs to atlas texture.
/// Also returns the glyphsAddedCount, since glyphIndexes.Count might not be exact.
/// </summary>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static bool TryAddGlyphsToTexture(List<uint> glyphIndexes, int padding, GlyphPackingMode packingMode, List<GlyphRect> freeGlyphRects, List<GlyphRect> usedGlyphRects, GlyphRenderMode renderMode, Texture2D texture, out Glyph[] glyphs, out int glyphsAddedCount)
{
Profiler.BeginSample("FontEngine.TryAddGlyphsToTexture");
glyphs = null;
if (glyphIndexes == null || glyphIndexes.Count == 0)
{
Profiler.EndSample();
glyphsAddedCount = 0;
return false;
}
int glyphCount = glyphIndexes.Count;
// Make sure marshalling glyph index array allocations are appropriate.
if (s_GlyphIndexes_MarshallingArray_A == null || s_GlyphIndexes_MarshallingArray_A.Length < glyphCount)
s_GlyphIndexes_MarshallingArray_A = new uint[Mathf.NextPowerOfTwo(glyphCount + 1)];
// Determine potential total allocations required for glyphs and glyph rectangles.
int freeGlyphRectCount = freeGlyphRects.Count;
int usedGlyphRectCount = usedGlyphRects.Count;
int totalGlyphRects = freeGlyphRectCount + usedGlyphRectCount + glyphCount;
// Make sure marshalling array(s) allocations are appropriate.
if (s_FreeGlyphRects.Length < totalGlyphRects || s_UsedGlyphRects.Length < totalGlyphRects)
{
int newSize = Mathf.NextPowerOfTwo(totalGlyphRects + 1);
s_FreeGlyphRects = new GlyphRect[newSize];
s_UsedGlyphRects = new GlyphRect[newSize];
}
// Make sure marshaling array allocations are appropriate.
if (s_GlyphMarshallingStruct_OUT.Length < glyphCount)
{
int newSize = Mathf.NextPowerOfTwo(glyphCount + 1);
s_GlyphMarshallingStruct_OUT = new GlyphMarshallingStruct[newSize];
}
// Determine the max count
int glyphRectCount = FontEngineUtilities.MaxValue(freeGlyphRectCount, usedGlyphRectCount, glyphCount);
// Copy inbound data to Marshalling arrays.
for (int i = 0; i < glyphRectCount; i++)
{
if (i < glyphCount)
s_GlyphIndexes_MarshallingArray_A[i] = glyphIndexes[i];
if (i < freeGlyphRectCount)
s_FreeGlyphRects[i] = freeGlyphRects[i];
if (i < usedGlyphRectCount)
s_UsedGlyphRects[i] = usedGlyphRects[i];
}
// Marshall data over to the native side.
bool allGlyphsAdded = TryAddGlyphsToTexture_Internal(s_GlyphIndexes_MarshallingArray_A, padding, packingMode, s_FreeGlyphRects, ref freeGlyphRectCount, s_UsedGlyphRects, ref usedGlyphRectCount, renderMode, texture, s_GlyphMarshallingStruct_OUT, ref glyphCount);
// Make sure internal glyph array is properly sized.
if (s_Glyphs == null || s_Glyphs.Length <= glyphCount)
s_Glyphs = new Glyph[Mathf.NextPowerOfTwo(glyphCount + 1)];
s_Glyphs[glyphCount] = null;
freeGlyphRects.Clear();
usedGlyphRects.Clear();
// Determine the max count
glyphRectCount = FontEngineUtilities.MaxValue(freeGlyphRectCount, usedGlyphRectCount, glyphCount);
// Copy marshalled data back to their appropriate data structures.
for (int i = 0; i < glyphRectCount; i++)
{
if (i < glyphCount)
s_Glyphs[i] = new Glyph(s_GlyphMarshallingStruct_OUT[i]);
if (i < freeGlyphRectCount)
freeGlyphRects.Add(s_FreeGlyphRects[i]);
if (i < usedGlyphRectCount)
usedGlyphRects.Add(s_UsedGlyphRects[i]);
}
glyphs = s_Glyphs;
glyphsAddedCount = glyphCount;
Profiler.EndSample();
return allGlyphsAdded;
}
[NativeMethod(Name = "TextCore::FontEngine::TryAddGlyphsToTexture", IsThreadSafe = true, IsFreeFunction = true)]
extern static bool TryAddGlyphsToTexture_Internal(uint[] glyphIndex, int padding,
GlyphPackingMode packingMode, [Out] GlyphRect[] freeGlyphRects, ref int freeGlyphRectCount, [Out] GlyphRect[] usedGlyphRects, ref int usedGlyphRectCount,
GlyphRenderMode renderMode, Texture2D texture, [Out] GlyphMarshallingStruct[] glyphs, ref int glyphCount);
// ================================================
// OPENTYPE RELATED FEATURES AND FUNCTIONS
// ================================================
/// <summary>
/// Get the specified OpenType Layout table.
/// </summary>
/// <param name="type">The type of the table.</param>
/// <returns>The OpenType Layout table.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetOpenTypeLayoutTable", IsFreeFunction = true)]
internal extern static OTL_Table GetOpenTypeLayoutTable(OTL_TableType type);
/// <summary>
/// Get OpenType Layout scripts for the currently loaded font.
/// </summary>
/// <returns></returns>
[NativeMethod(Name = "TextCore::FontEngine::GetOpenTypeLayoutScripts", IsFreeFunction = true)]
internal extern static OTL_Script[] GetOpenTypeLayoutScripts();
/// <summary>
/// Get OpenType Layout features for the currently loaded font.
/// </summary>
/// <returns></returns>
[NativeMethod(Name = "TextCore::FontEngine::GetOpenTypeLayoutFeatures", IsFreeFunction = true)]
internal extern static OTL_Feature[] GetOpenTypeLayoutFeatures();
/// <summary>
/// Get OpenType Layout lookups for the currently loaded font.
/// </summary>
/// <returns></returns>
[NativeMethod(Name = "TextCore::FontEngine::GetOpenTypeLayoutLookups", IsFreeFunction = true)]
internal extern static OTL_Lookup[] GetOpenTypeLayoutLookups();
// Required to prevent compilation errors on TMP 3.20.0 Preview 3.
internal static OpenTypeFeature[] GetOpenTypeFontFeatureList() => throw new NotImplementedException();
// ================================================
// GSUB FONT FEATURES
// ================================================
#region SINGLE SUBSTITUTION
/// <summary>
/// Retrieve all single substitution records.
/// </summary>
/// <returns>An array that contains all single substitution records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllSingleSubstitutionRecords", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static SingleSubstitutionRecord[] GetAllSingleSubstitutionRecords();
/// <summary>
/// Internal function used to retrieve potential Single Substitution records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential subsitution records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the given glyph index.</returns>
internal static SingleSubstitutionRecord[] GetSingleSubstitutionRecords(int lookupIndex, uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetSingleSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve Single Substitution records for the given list of glyphs.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential substitution records.</param>
/// <param name="glyphIndexes">List of glyph indexes to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the provide list of glyph indexes.</returns>
internal static SingleSubstitutionRecord[] GetSingleSubstitutionRecords(int lookupIndex, List<uint> glyphIndexes)
{
// Copy source list data to array of same type.
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetSingleSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static SingleSubstitutionRecord[] GetSingleSubstitutionRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_SingleSubstitutionRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetSingleSubstitutionRecordsFromMarshallingArray(s_SingleSubstitutionRecords_MarshallingArray.AsSpan());
// Terminate last record to zero
s_SingleSubstitutionRecords_MarshallingArray[recordCount] = new SingleSubstitutionRecord();
return s_SingleSubstitutionRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateSingleSubstitutionRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateSingleSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetSingleSubstitutionRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetSingleSubstitutionRecordsFromMarshallingArray(Span<SingleSubstitutionRecord> singleSubstitutionRecords);
#endregion
#region MULTIPLE SUBSTITUTION
/// <summary>
/// Retrieve all MultipleSubstitution records.
/// </summary>
/// <returns>An array that contains all MultipleSubstitution records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllMultipleSubstitutionRecords", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static MultipleSubstitutionRecord[] GetAllMultipleSubstitutionRecords();
/// <summary>
/// Internal function used to retrieve potential MultipleSubstitution records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential subsitution records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the given glyph index.</returns>
internal static MultipleSubstitutionRecord[] GetMultipleSubstitutionRecords(int lookupIndex, uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetMultipleSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve MultipleSubstitution records for the given list of glyphs.
/// </summary>
/// <param name="glyphIndexes">List of glyph indexes to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the provide list of glyph indexes.</returns>
internal static MultipleSubstitutionRecord[] GetMultipleSubstitutionRecords(int lookupIndex, List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetMultipleSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static MultipleSubstitutionRecord[] GetMultipleSubstitutionRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_MultipleSubstitutionRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetMultipleSubstitutionRecordsFromMarshallingArray(s_MultipleSubstitutionRecords_MarshallingArray);
// Terminate last record to zero
s_MultipleSubstitutionRecords_MarshallingArray[recordCount] = new MultipleSubstitutionRecord();
return s_MultipleSubstitutionRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateMultipleSubstitutionRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateMultipleSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetMultipleSubstitutionRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetMultipleSubstitutionRecordsFromMarshallingArray([Out] MultipleSubstitutionRecord[] substitutionRecords);
#endregion
#region ALTERNATE SUBSTITUTION
/// <summary>
/// Retrieve all alternate substitution records.
/// </summary>
/// <returns>An array that contains all alternate substitution records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllAlternateSubstitutionRecords", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static AlternateSubstitutionRecord[] GetAllAlternateSubstitutionRecords();
/// <summary>
/// Internal function used to retrieve potential Alternate Substitution records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential subsitution records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the given glyph index.</returns>
internal static AlternateSubstitutionRecord[] GetAlternateSubstitutionRecords(int lookupIndex, uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetAlternateSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve Alternate Substitution records for the given list of glyphs.
/// </summary>
/// <param name="glyphIndexes">List of glyph indexes to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the provide list of glyph indexes.</returns>
internal static AlternateSubstitutionRecord[] GetAlternateSubstitutionRecords(int lookupIndex, List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetAlternateSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static AlternateSubstitutionRecord[] GetAlternateSubstitutionRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_AlternateSubstitutionRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetAlternateSubstitutionRecordsFromMarshallingArray(s_AlternateSubstitutionRecords_MarshallingArray);
// Terminate last record to zero
s_AlternateSubstitutionRecords_MarshallingArray[recordCount] = new AlternateSubstitutionRecord();
return s_AlternateSubstitutionRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateAlternateSubstitutionRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateAlternateSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetAlternateSubstitutionRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetAlternateSubstitutionRecordsFromMarshallingArray([Out] AlternateSubstitutionRecord[] singleSubstitutionRecords);
#endregion
#region LIGATURE
/// <summary>
/// Retrieve all ligature substitution records.
/// </summary>
/// <returns>An array that contains all ligature substitution records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllLigatureSubstitutionRecords", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal extern static LigatureSubstitutionRecord[] GetAllLigatureSubstitutionRecords();
/// <summary>
/// Internal function used to retrieve potential ligature substitution records for the given glyph index.
/// </summary>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the given glyph index.</returns>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static LigatureSubstitutionRecord[] GetLigatureSubstitutionRecords(uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetLigatureSubstitutionRecords(s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve potential ligature substitution records for the provided list of glyph indexes.
/// </summary>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the provided list of glyph indexes.</returns>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static LigatureSubstitutionRecord[] GetLigatureSubstitutionRecords(List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetLigatureSubstitutionRecords(s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve potential ligature substitution records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential subsitution records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the given glyph index.</returns>
internal static LigatureSubstitutionRecord[] GetLigatureSubstitutionRecords(int lookupIndex, uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetLigatureSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve potential ligature substitution records for the provided list of glyph indexes.
/// </summary>
/// <param name="lookupIndex">Index of the Lookup table from which to retrieve the potential subsitution records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the provided list of glyph indexes.</returns>
internal static LigatureSubstitutionRecord[] GetLigatureSubstitutionRecords(int lookupIndex, List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetLigatureSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static LigatureSubstitutionRecord[] GetLigatureSubstitutionRecords(uint[] glyphIndexes)
{
PopulateLigatureSubstitutionRecordMarshallingArray(glyphIndexes, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_LigatureSubstitutionRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetLigatureSubstitutionRecordsFromMarshallingArray(s_LigatureSubstitutionRecords_MarshallingArray);
// Terminate last record to zero
s_LigatureSubstitutionRecords_MarshallingArray[recordCount] = new LigatureSubstitutionRecord();
return s_LigatureSubstitutionRecords_MarshallingArray;
}
private static LigatureSubstitutionRecord[] GetLigatureSubstitutionRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_LigatureSubstitutionRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetLigatureSubstitutionRecordsFromMarshallingArray(s_LigatureSubstitutionRecords_MarshallingArray);
// Terminate last record to zero
s_LigatureSubstitutionRecords_MarshallingArray[recordCount] = new LigatureSubstitutionRecord();
return s_LigatureSubstitutionRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateLigatureSubstitutionRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateLigatureSubstitutionRecordMarshallingArray(uint[] glyphIndexes, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::PopulateLigatureSubstitutionRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateLigatureSubstitutionRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetLigatureSubstitutionRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetLigatureSubstitutionRecordsFromMarshallingArray([Out] LigatureSubstitutionRecord[] ligatureSubstitutionRecords);
#endregion
#region CONTEXTUAL SUBSTITUTION
/// <summary>
/// Retrieve all MultipleSubstitution records.
/// </summary>
/// <returns>An array that contains all MultipleSubstitution records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllContextualSubstitutionRecords", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static ContextualSubstitutionRecord[] GetAllContextualSubstitutionRecords();
/// <summary>
/// Internal function used to retrieve potential ContextualSubstitution records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential subsitution records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the given glyph index.</returns>
internal static ContextualSubstitutionRecord[] GetContextualSubstitutionRecords(int lookupIndex, uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetContextualSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve MultipleSubstitution records for the given list of glyphs.
/// </summary>
/// <param name="glyphIndexes">List of glyph indexes to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the provide list of glyph indexes.</returns>
internal static ContextualSubstitutionRecord[] GetContextualSubstitutionRecords(int lookupIndex, List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetContextualSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static ContextualSubstitutionRecord[] GetContextualSubstitutionRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_ContextualSubstitutionRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetContextualSubstitutionRecordsFromMarshallingArray(s_ContextualSubstitutionRecords_MarshallingArray);
// Terminate last record to zero
s_ContextualSubstitutionRecords_MarshallingArray[recordCount] = new ContextualSubstitutionRecord();
return s_ContextualSubstitutionRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateContextualSubstitutionRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetContextualSubstitutionRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetContextualSubstitutionRecordsFromMarshallingArray([Out] ContextualSubstitutionRecord[] substitutionRecords);
#endregion
#region CHAINING CONTEXTUAL SUBSTITUTION
/// <summary>
/// Retrieve all ChainingContextualSubstitution records.
/// </summary>
/// <returns>An array that contains all ChainingContextualSubstitution records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllChainingContextualSubstitutionRecords", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static ChainingContextualSubstitutionRecord[] GetAllChainingContextualSubstitutionRecords();
/// <summary>
/// Internal function used to retrieve potential ChainingContextualSubstitution records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential subsitution records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the given glyph index.</returns>
internal static ChainingContextualSubstitutionRecord[] GetChainingContextualSubstitutionRecords(int lookupIndex, uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetChainingContextualSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve ChainingContextualSubstitution records for the given list of glyphs.
/// </summary>
/// <param name="glyphIndexes">List of glyph indexes to check for potential substitution records.</param>
/// <returns>An array that contains the substitution records for the provide list of glyph indexes.</returns>
internal static ChainingContextualSubstitutionRecord[] GetChainingContextualSubstitutionRecords(int lookupIndex, List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetChainingContextualSubstitutionRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static ChainingContextualSubstitutionRecord[] GetChainingContextualSubstitutionRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_ChainingContextualSubstitutionRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetChainingContextualSubstitutionRecordsFromMarshallingArray(s_ChainingContextualSubstitutionRecords_MarshallingArray);
// Terminate last record to zero
s_ChainingContextualSubstitutionRecords_MarshallingArray[recordCount] = new ChainingContextualSubstitutionRecord();
return s_ChainingContextualSubstitutionRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateChainingContextualSubstitutionRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateChainingContextualSubstitutionRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetChainingContextualSubstitutionRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetChainingContextualSubstitutionRecordsFromMarshallingArray([Out] ChainingContextualSubstitutionRecord[] substitutionRecords);
#endregion
// ================================================
// POSITIONAL ADJUSTMENTS FROM KERN TABLE
// ================================================
#region POSITIONAL ADJUSTMENTS
/// <summary>
/// Internal function used to retrieve positional adjustments records for the given glyph indexes.
/// </summary>
/// <param name="glyphIndexes">Array of glyph indexes to check for potential positional adjustment records.</param>
/// <returns>Array containing the positional adjustments for pairs of glyphs.</returns>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentTable(uint[] glyphIndexes)
{
int recordCount;
PopulatePairAdjustmentRecordMarshallingArray_from_KernTable(glyphIndexes, out recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_PairAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetPairAdjustmentRecordsFromMarshallingArray(s_PairAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_PairAdjustmentRecords_MarshallingArray[recordCount] = new GlyphPairAdjustmentRecord();
return s_PairAdjustmentRecords_MarshallingArray;
}
/// <summary>
/// Internal function used to retrieve positional adjustments records for the given glyph indexes.
/// </summary>
/// <param name="glyphIndexes">List of glyph indexes to check for potential positional adjustment records.</param>
/// <param name="recordCount">The number of valid records in the returned array.</param>
/// <returns>Array containing the positional adjustments for pairs of glyphs.</returns>
internal static GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentRecords(List<uint> glyphIndexes, out int recordCount)
{
// Copy source list data to array of same type.
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
PopulatePairAdjustmentRecordMarshallingArray_from_KernTable(s_GlyphIndexes_MarshallingArray_A, out recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_PairAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetPairAdjustmentRecordsFromMarshallingArray(s_PairAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_PairAdjustmentRecords_MarshallingArray[recordCount] = new GlyphPairAdjustmentRecord();
return s_PairAdjustmentRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulatePairAdjustmentRecordMarshallingArrayFromKernTable", IsFreeFunction = true)]
extern static int PopulatePairAdjustmentRecordMarshallingArray_from_KernTable(uint[] glyphIndexes, out int recordCount);
/// <summary>
/// Internal function used to retrieve GlyphPairAdjustmentRecords for the given glyph index.
/// </summary>
/// <param name="glyphIndex">Index of the target glyph.</param>
/// <param name="recordCount">Number of glyph pair adjustment records using this glyph.</param>
/// <returns>Array containing the glyph pair adjustment records.</returns>
internal static GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentRecords(uint glyphIndex, out int recordCount)
{
PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex(glyphIndex, out recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_PairAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetPairAdjustmentRecordsFromMarshallingArray(s_PairAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_PairAdjustmentRecords_MarshallingArray[recordCount] = new GlyphPairAdjustmentRecord();
return s_PairAdjustmentRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulatePairAdjustmentRecordMarshallingArrayFromKernTable", IsFreeFunction = true)]
extern static int PopulatePairAdjustmentRecordMarshallingArray_from_GlyphIndex(uint glyphIndex, out int recordCount);
/// <summary>
/// Internal function used to retrieve GlyphPairAdjustmentRecords for the given list of glyph indexes.
/// </summary>
/// <param name="newGlyphIndexes">List containing the indexes of the newly added glyphs.</param>
/// <param name="allGlyphIndexes">List containing the indexes of all the glyphs including the indexes of those newly added glyphs.</param>
/// <returns></returns>
internal static GlyphPairAdjustmentRecord[] GetGlyphPairAdjustmentRecords(List<uint> newGlyphIndexes, List<uint> allGlyphIndexes)
{
// Copy source list data to array of same type.
GenericListToMarshallingArray(ref newGlyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
GenericListToMarshallingArray(ref allGlyphIndexes, ref s_GlyphIndexes_MarshallingArray_B);
int recordCount;
PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes(s_GlyphIndexes_MarshallingArray_A, s_GlyphIndexes_MarshallingArray_B, out recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_PairAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetPairAdjustmentRecordsFromMarshallingArray(s_PairAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_PairAdjustmentRecords_MarshallingArray[recordCount] = new GlyphPairAdjustmentRecord();
return s_PairAdjustmentRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulatePairAdjustmentRecordMarshallingArrayFromKernTable", IsFreeFunction = true)]
extern static int PopulatePairAdjustmentRecordMarshallingArray_for_NewlyAddedGlyphIndexes(uint[] newGlyphIndexes, uint[] allGlyphIndexes, out int recordCount);
/// <summary>
/// Internal function used to retrieve the potential PairAdjustmentRecord for the given pair of glyph indexes.
/// </summary>
/// <param name="firstGlyphIndex">The index of the first glyph.</param>
/// <param name="secondGlyphIndex">The index of the second glyph.</param>
/// <returns></returns>
[NativeMethod(Name = "TextCore::FontEngine::GetGlyphPairAdjustmentRecord", IsFreeFunction = true)]
internal extern static GlyphPairAdjustmentRecord GetGlyphPairAdjustmentRecord(uint firstGlyphIndex, uint secondGlyphIndex);
#endregion
// ================================================
// GPOS FONT FEATURES
// ================================================
#region SINGLE ADJUSTMENT
/// <summary>
/// Internal function used to retrieve potential adjustment records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential adjustment records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential adjustment records.</param>
/// <returns>An array that contains the adjustment records for the given glyph index.</returns>
internal static GlyphAdjustmentRecord[] GetSingleAdjustmentRecords(int lookupIndex, uint glyphIndex)
{
if (s_GlyphIndexes_MarshallingArray_A == null)
s_GlyphIndexes_MarshallingArray_A = new uint[8];
s_GlyphIndexes_MarshallingArray_A[0] = glyphIndex;
s_GlyphIndexes_MarshallingArray_A[1] = 0;
return GetSingleAdjustmentRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve adjustment records for the given list of glyphs.
/// </summary>
/// <param name="glyphIndexes">List of glyph indexes to check for potential adjustment records.</param>
/// <returns>An array that contains the adjustment records for the provide list of glyph indexes.</returns>
internal static GlyphAdjustmentRecord[] GetSingleAdjustmentRecords(int lookupIndex, List<uint> glyphIndexes)
{
// Copy source list data to array of same type.
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetSingleAdjustmentRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static GlyphAdjustmentRecord[] GetSingleAdjustmentRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_SingleAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetSingleAdjustmentRecordsFromMarshallingArray(s_SingleAdjustmentRecords_MarshallingArray.AsSpan());
// Terminate last record to zero
s_SingleAdjustmentRecords_MarshallingArray[recordCount] = new GlyphAdjustmentRecord();
return s_SingleAdjustmentRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateSingleAdjustmentRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateSingleAdjustmentRecordMarshallingArray_from_GlyphIndexes(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetSingleAdjustmentRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetSingleAdjustmentRecordsFromMarshallingArray(Span<GlyphAdjustmentRecord> singleSubstitutionRecords);
#endregion
#region PAIR ADJUSTMENTS
/// <summary>
/// Retrieve all potential glyph pair adjustment records for the given glyph.
/// </summary>
/// <param name="baseGlyphIndex">The index of the glyph.</param>
/// <returns>An array that contains the adjustment records for the given glyph.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetPairAdjustmentRecords", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal extern static GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(uint glyphIndex);
/// <summary>
/// Retrieve potential glyph pair adjustment record for the given pair of glyphs.
/// </summary>
/// <param name="firstGlyphIndex">The index of the first glyph.</param>
/// <param name="secondGlyphIndex">The index of the second glyph.</param>
/// <returns>The glyph pair adjustment record.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetPairAdjustmentRecord", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static GlyphPairAdjustmentRecord GetPairAdjustmentRecord(uint firstGlyphIndex, uint secondGlyphIndex);
/// <summary>
/// Retrieve all glyph pair adjustment records.
/// </summary>
/// <returns>An array that contains the adjustment records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllPairAdjustmentRecords", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal extern static GlyphPairAdjustmentRecord[] GetAllPairAdjustmentRecords();
/// <summary>
/// Internal function used to retrieve the potential glyph pair adjustment records for the given list of glyphs.
/// </summary>
/// <param name="glyphIndexes">List of glyph indexes to check for potential adjustment records.</param>
/// <returns>An array that contains the glyph pair adjustment records.</returns>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetPairAdjustmentRecords(s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve potential pair adjustment records for the given glyph index.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential adjustment records.</param>
/// <param name="glyphIndex">Index of the glyph to check for potential adjustment records.</param>
/// <returns>An array that contains the adjustment records for the given glyph index.</returns>
internal static GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(int lookupIndex, uint glyphIndex)
{
GlyphIndexToMarshallingArray(glyphIndex, ref s_GlyphIndexes_MarshallingArray_A);
return GetPairAdjustmentRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve the potential glyph pair adjustment records for the given list of glyphs.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential adjustment records.</param>
/// <param name="glyphIndexes">List of glyph indexes to check for potential adjustment records.</param>
/// <returns>An array that contains the glyph pair adjustment records.</returns>
internal static GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(int lookupIndex, List<uint> glyphIndexes)
{
// Copy source list data to array of same type.
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetPairAdjustmentRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(uint[] glyphIndexes)
{
PopulatePairAdjustmentRecordMarshallingArray(glyphIndexes, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_PairAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetPairAdjustmentRecordsFromMarshallingArray(s_PairAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_PairAdjustmentRecords_MarshallingArray[recordCount] = new GlyphPairAdjustmentRecord();
return s_PairAdjustmentRecords_MarshallingArray;
}
private static GlyphPairAdjustmentRecord[] GetPairAdjustmentRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_PairAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetPairAdjustmentRecordsFromMarshallingArray(s_PairAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_PairAdjustmentRecords_MarshallingArray[recordCount] = new GlyphPairAdjustmentRecord();
return s_PairAdjustmentRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulatePairAdjustmentRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulatePairAdjustmentRecordMarshallingArray(uint[] glyphIndexes, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::PopulatePairAdjustmentRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulatePairAdjustmentRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetGlyphPairAdjustmentRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetPairAdjustmentRecordsFromMarshallingArray(Span<GlyphPairAdjustmentRecord> glyphPairAdjustmentRecords);
#endregion
#region MARK TO BASE
/// <summary>
/// Retrieve all Mark-to-Base adjustment records for the currently loaded font.
/// </summary>
/// <returns>An array that contains the Mark-to-Base adjustment records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllMarkToBaseAdjustmentRecords", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal extern static MarkToBaseAdjustmentRecord[] GetAllMarkToBaseAdjustmentRecords();
/// <summary>
/// Retrieve all potential Mark-to-Base adjustment records for the given base mark glyph.
/// </summary>
/// <param name="baseGlyphIndex">The index of the base glyph.</param>
/// <returns>An array that contains the adjustment records for the given base glyph.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetMarkToBaseAdjustmentRecords", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static MarkToBaseAdjustmentRecord[] GetMarkToBaseAdjustmentRecords(uint baseGlyphIndex);
/// <summary>
/// Internal function used to retrieve the potential MarkToBaseAdjustmentRecord for the given pair of glyph indexes.
/// </summary>
/// <param name="baseGlyphIndex">The index of the base glyph.</param>
/// <param name="markGlyphIndex">The index of the mark glyph.</param>
/// <returns></returns>
[NativeMethod(Name = "TextCore::FontEngine::GetMarkToBaseAdjustmentRecord", IsFreeFunction = true)]
internal extern static MarkToBaseAdjustmentRecord GetMarkToBaseAdjustmentRecord(uint baseGlyphIndex, uint markGlyphIndex);
/// <summary>
/// Internal function used to retrieve the potential Mark-To-Base adjustment records for the given list of glyph indexes.
/// </summary>
/// <param name="glyphIndexes">The list of glyph indexes.</param>
/// <returns>An array that contains the adjustment records for the given list of glyph indexes.</returns>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static MarkToBaseAdjustmentRecord[] GetMarkToBaseAdjustmentRecords(List<uint> glyphIndexes)
{
// Copy source list data to array of same type.
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetMarkToBaseAdjustmentRecords(s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve the potential Mark-to-Base adjustment records for the given list of glyphs.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential adjustment records.</param>
/// <param name="glyphIndexes">List of glyph indexes to check for potential adjustment records.</param>
/// <returns>An array that contains the Mark-to-Base adjustment records.</returns>
internal static MarkToBaseAdjustmentRecord[] GetMarkToBaseAdjustmentRecords(int lookupIndex, List<uint> glyphIndexes)
{
// Copy source list data to array of same type.
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetMarkToBaseAdjustmentRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static MarkToBaseAdjustmentRecord[] GetMarkToBaseAdjustmentRecords(uint[] glyphIndexes)
{
PopulateMarkToBaseAdjustmentRecordMarshallingArray(glyphIndexes, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_MarkToBaseAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetMarkToBaseAdjustmentRecordsFromMarshallingArray(s_MarkToBaseAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_MarkToBaseAdjustmentRecords_MarshallingArray[recordCount] = new MarkToBaseAdjustmentRecord();
return s_MarkToBaseAdjustmentRecords_MarshallingArray;
}
private static MarkToBaseAdjustmentRecord[] GetMarkToBaseAdjustmentRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex(glyphIndexes, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_MarkToBaseAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetMarkToBaseAdjustmentRecordsFromMarshallingArray(s_MarkToBaseAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_MarkToBaseAdjustmentRecords_MarshallingArray[recordCount] = new MarkToBaseAdjustmentRecord();
return s_MarkToBaseAdjustmentRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateMarkToBaseAdjustmentRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateMarkToBaseAdjustmentRecordMarshallingArray(uint[] glyphIndexes, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::PopulateMarkToBaseAdjustmentRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateMarkToBaseAdjustmentRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetMarkToBaseAdjustmentRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetMarkToBaseAdjustmentRecordsFromMarshallingArray(Span<MarkToBaseAdjustmentRecord> adjustmentRecords);
#endregion
#region MARK TO MARK
/// <summary>
/// Retrieve all Mark-to-Mark adjustment records for the currently loaded font.
/// </summary>
/// <returns>An array that contains the Mark-to-Base adjustment records.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetAllMarkToMarkAdjustmentRecords", IsThreadSafe = true, IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal extern static MarkToMarkAdjustmentRecord[] GetAllMarkToMarkAdjustmentRecords();
/// <summary>
/// Retrieve all potential Mark-to-Mark adjustment records for the given base mark glyph.
/// </summary>
/// <param name="baseMarkGlyphIndex">The index of the base mark glyph.</param>
/// <returns>An array that contains the adjustment records for the given base mark glyph.</returns>
[NativeMethod(Name = "TextCore::FontEngine::GetMarkToMarkAdjustmentRecords", IsThreadSafe = true, IsFreeFunction = true)]
internal extern static MarkToMarkAdjustmentRecord[] GetMarkToMarkAdjustmentRecords(uint baseMarkGlyphIndex);
/// <summary>
/// Internal function used to retrieve the potential MarkToMarkAdjustmentRecord for the given pair of glyph indexes.
/// </summary>
/// <param name="firstGlyphIndex">The index of the first glyph.</param>
/// <param name="secondGlyphIndex">The index of the second glyph.</param>
/// <returns></returns>
[NativeMethod(Name = "TextCore::FontEngine::GetMarkToMarkAdjustmentRecord", IsFreeFunction = true)]
internal extern static MarkToMarkAdjustmentRecord GetMarkToMarkAdjustmentRecord(uint firstGlyphIndex, uint secondGlyphIndex);
/// <summary>
/// Internal function used to retrieve the potential Mark-To-Mark adjustment records for the given list of glyph indexes.
/// </summary>
/// <param name="glyphIndexes">The list of glyph indexes.</param>
/// <returns>An array that contains the adjustment records for the given list of glyph indexes.</returns>
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal static MarkToMarkAdjustmentRecord[] GetMarkToMarkAdjustmentRecords(List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetMarkToMarkAdjustmentRecords(s_GlyphIndexes_MarshallingArray_A);
}
/// <summary>
/// Internal function used to retrieve the potential Mark-to-Mark adjustment records for the given list of glyphs.
/// </summary>
/// <param name="lookupIndex">Index of the lookup table from which to retrieve the potential adjustment records.</param>
/// <param name="glyphIndexes">List of glyph indexes to check for potential adjustment records.</param>
/// <returns>An array that contains the Mark-to-Mark adjustment records.</returns>
internal static MarkToMarkAdjustmentRecord[] GetMarkToMarkAdjustmentRecords(int lookupIndex, List<uint> glyphIndexes)
{
GenericListToMarshallingArray(ref glyphIndexes, ref s_GlyphIndexes_MarshallingArray_A);
return GetMarkToMarkAdjustmentRecords(lookupIndex, s_GlyphIndexes_MarshallingArray_A);
}
private static MarkToMarkAdjustmentRecord[] GetMarkToMarkAdjustmentRecords(uint[] glyphIndexes)
{
PopulateMarkToMarkAdjustmentRecordMarshallingArray(s_GlyphIndexes_MarshallingArray_A, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_MarkToMarkAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetMarkToMarkAdjustmentRecordsFromMarshallingArray(s_MarkToMarkAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_MarkToMarkAdjustmentRecords_MarshallingArray[recordCount] = new MarkToMarkAdjustmentRecord();
return s_MarkToMarkAdjustmentRecords_MarshallingArray;
}
private static MarkToMarkAdjustmentRecord[] GetMarkToMarkAdjustmentRecords(int lookupIndex, uint[] glyphIndexes)
{
PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex(s_GlyphIndexes_MarshallingArray_A, lookupIndex, out int recordCount);
if (recordCount == 0)
return null;
// Make sure marshalling array allocation is appropriate.
SetMarshallingArraySize(ref s_MarkToMarkAdjustmentRecords_MarshallingArray, recordCount);
// Retrieve adjustment records already gathered by the GetPairAdjustmentRecordCount function.
GetMarkToMarkAdjustmentRecordsFromMarshallingArray(s_MarkToMarkAdjustmentRecords_MarshallingArray);
// Terminate last record to zero
s_MarkToMarkAdjustmentRecords_MarshallingArray[recordCount] = new MarkToMarkAdjustmentRecord();
return s_MarkToMarkAdjustmentRecords_MarshallingArray;
}
[NativeMethod(Name = "TextCore::FontEngine::PopulateMarkToMarkAdjustmentRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateMarkToMarkAdjustmentRecordMarshallingArray(uint[] glyphIndexes, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::PopulateMarkToMarkAdjustmentRecordMarshallingArray", IsFreeFunction = true)]
extern static int PopulateMarkToMarkAdjustmentRecordMarshallingArray_for_LookupIndex(uint[] glyphIndexes, int lookupIndex, out int recordCount);
[NativeMethod(Name = "TextCore::FontEngine::GetMarkToMarkAdjustmentRecordsFromMarshallingArray", IsFreeFunction = true)]
extern static int GetMarkToMarkAdjustmentRecordsFromMarshallingArray(Span<MarkToMarkAdjustmentRecord> adjustmentRecords);
#endregion
// ================================================
// Utility Methods
// ================================================
static void GlyphIndexToMarshallingArray(uint glyphIndex, ref uint[] dstArray)
{
if (dstArray == null || dstArray.Length == 1)
dstArray = new uint[8];
dstArray[0] = glyphIndex;
dstArray[1] = 0;
}
static void GenericListToMarshallingArray<T>(ref List<T> srcList, ref T[] dstArray)
{
int count = srcList.Count;
if (dstArray == null || dstArray.Length <= count)
{
int size = Mathf.NextPowerOfTwo(count + 1);
if (dstArray == null)
dstArray = new T[size];
else
Array.Resize(ref dstArray, size);
}
// Copy list data to marshalling array
for (int i = 0; i < count; i++)
dstArray[i] = srcList[i];
// Set marshalling array boundary / terminator to value of zero.
dstArray[count] = default(T);
}
/// <summary>
///
/// </summary>
static void SetMarshallingArraySize<T>(ref T[] marshallingArray, int recordCount)
{
if (marshallingArray == null || marshallingArray.Length <= recordCount)
{
int size = Mathf.NextPowerOfTwo(recordCount + 1);
if (marshallingArray == null)
marshallingArray = new T[size];
else
Array.Resize(ref marshallingArray, size);
}
}
// ================================================
// Experimental / Testing / Benchmarking Functions
// ================================================
/// <summary>
/// Internal function used to reset an atlas texture to black
/// </summary>
/// <param name="srcTexture"></param>
[NativeMethod(Name = "TextCore::FontEngine::ResetAtlasTexture", IsFreeFunction = true)]
[VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")]
internal extern static void ResetAtlasTexture(Texture2D texture);
/// <summary>
/// Internal function used for testing rasterizing of shapes and glyphs.
/// </summary>
/// <param name="srcTexture">Texture containing the source shape to raster.</param>
/// <param name="padding">Padding value.</param>
/// <param name="renderMode">The rendering mode.</param>
/// <param name="dstTexture">Texture containing the rastered shape.</param>
[NativeMethod(Name = "TextCore::FontEngine::RenderToTexture", IsFreeFunction = true)]
internal extern static void RenderBufferToTexture(Texture2D srcTexture, int padding, GlyphRenderMode renderMode, Texture2D dstTexture);
/*
[NativeMethod(Name = "TextCore::FontEngine::ModifyGlyph", IsFreeFunction = true)]
extern public static void ModifyGlyph([Out] Glyph glyph);
/// <summary>
///
/// </summary>
/// <param name="glyph"></param>
public static void ModifyGlyphStruct(Glyph glyph)
{
GlyphMarshallingStruct glyphStruct = new GlyphMarshallingStruct(glyph);
ModifyGlyph_Internal(ref glyphStruct);
glyph.metrics = glyphStruct.metrics;
glyph.glyphRect = glyphStruct.glyphRect;
glyph.scale = glyphStruct.scale;
glyph.atlasIndex = glyphStruct.atlasIndex;
}
[NativeMethod(Name = "TextCore::FontEngine::ModifyGlyph", IsThreadSafe = true, IsFreeFunction = true)]
extern static void ModifyGlyph_Internal(ref GlyphMarshallingStruct glyphs);
/// <summary>
///
/// </summary>
/// <param name="glyph"></param>
[NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphMarshallingStruct", IsFreeFunction = true)]
extern public static void ModifyGlyphMarshallingStruct(GlyphMarshallingStruct[] glyph);
/// <summary>
///
/// </summary>
/// <param name="glyph"></param>
[NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphMarshallingStruct", IsFreeFunction = true)]
extern public static void ModifyGlyphMarshallingStructArray(GlyphMarshallingStruct[] glyph);
/// <summary>
///
/// </summary>
/// <param name="glyph"></param>
[NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphs", IsFreeFunction = true)]
extern public static void ModifyGlyphStructArray([Out] GlyphMarshallingStruct[] glyph);
/// <summary>
///
/// </summary>
/// <param name="glyph"></param>
[NativeMethod(Name = "TextCore::FontEngine::ModifyGlyphs", IsFreeFunction = true)]
extern public static void ModifyGlyphArray([Out] Glyph[] glyph);
[NativeMethod(Name = "TextCore::FontEngine::AccessFont", IsFreeFunction = true)]
extern public static void AccessFont(Font font);
*/
}
internal struct FontEngineUtilities
{
internal static bool Approximately(float a, float b)
{
return Mathf.Abs(a - b) < 0.001f;
}
internal static int MaxValue(int a, int b, int c)
{
return a < b ? (b < c ? c : b) : (a < c ? c : a);
}
}
}
| UnityCsReference/Modules/TextCoreFontEngine/Managed/FontEngine.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreFontEngine/Managed/FontEngine.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 47835
} | 459 |
// 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 Unity.Jobs.LowLevel.Unsafe;
namespace UnityEngine.TextCore.Text
{
static class MaterialManager
{
static Dictionary<long, Material> s_FallbackMaterials = new Dictionary<long, Material>();
/// <summary>
/// This function returns a material instance using the material properties of a previous material but using the font atlas texture of the new font asset.
/// </summary>
/// <param name="sourceMaterial">The material containing the source material properties to be copied to the new material.</param>
/// <param name="targetMaterial">The font atlas texture that should be assigned to the new material.</param>
/// <returns></returns>
public static Material GetFallbackMaterial(Material sourceMaterial, Material targetMaterial)
{
bool isMainThread = !JobsUtility.IsExecutingJob;
int sourceId = sourceMaterial.GetHashCode();
int texId = targetMaterial.GetHashCode();
long key = (long)sourceId << 32 | (uint)texId;
Material fallbackMaterial;
if (s_FallbackMaterials.TryGetValue(key, out fallbackMaterial))
{
if (fallbackMaterial == null)
s_FallbackMaterials.Remove(key);
else
{
// If we're not on the main thread, take for granted materials haven't change since last check.
if (!isMainThread)
return fallbackMaterial;
// Check if source material properties have changed.
int sourceMaterialCRC = sourceMaterial.ComputeCRC();
int fallbackMaterialCRC = fallbackMaterial.ComputeCRC();
if (sourceMaterialCRC == fallbackMaterialCRC)
return fallbackMaterial;
CopyMaterialPresetProperties(sourceMaterial, fallbackMaterial);
return fallbackMaterial;
}
}
// Create new material from the source material and copy properties if using distance field shaders.
if (sourceMaterial.HasProperty(TextShaderUtilities.ID_GradientScale) && targetMaterial.HasProperty(TextShaderUtilities.ID_GradientScale))
{
Texture tex = targetMaterial.GetTexture(TextShaderUtilities.ID_MainTex);
fallbackMaterial = new Material(sourceMaterial);
fallbackMaterial.hideFlags = HideFlags.HideAndDontSave;
fallbackMaterial.name += " + " + tex.name;
fallbackMaterial.SetTexture(TextShaderUtilities.ID_MainTex, tex);
// Retain material properties unique to target material.
fallbackMaterial.SetFloat(TextShaderUtilities.ID_GradientScale, targetMaterial.GetFloat(TextShaderUtilities.ID_GradientScale));
fallbackMaterial.SetFloat(TextShaderUtilities.ID_TextureWidth, targetMaterial.GetFloat(TextShaderUtilities.ID_TextureWidth));
fallbackMaterial.SetFloat(TextShaderUtilities.ID_TextureHeight, targetMaterial.GetFloat(TextShaderUtilities.ID_TextureHeight));
fallbackMaterial.SetFloat(TextShaderUtilities.ID_WeightNormal, targetMaterial.GetFloat(TextShaderUtilities.ID_WeightNormal));
fallbackMaterial.SetFloat(TextShaderUtilities.ID_WeightBold, targetMaterial.GetFloat(TextShaderUtilities.ID_WeightBold));
}
else
{
fallbackMaterial = new Material(targetMaterial);
}
s_FallbackMaterials.Add(key, fallbackMaterial);
return fallbackMaterial;
}
public static Material GetFallbackMaterial(FontAsset fontAsset, Material sourceMaterial, int atlasIndex)
{
bool isMainThread = !JobsUtility.IsExecutingJob;
int sourceMaterialID = sourceMaterial.GetHashCode();
Texture tex = fontAsset.atlasTextures[atlasIndex];
int texID = tex.GetHashCode();
long key = (long)sourceMaterialID << 32 | (uint)texID;
Material fallbackMaterial;
if (s_FallbackMaterials.TryGetValue(key, out fallbackMaterial))
{
// If we're not on the main thread, we assume nothng has changed since the last comparison (which should have been in the frame)
if (!isMainThread)
{
return fallbackMaterial;
}
// Check if source material properties have changed.
int sourceMaterialCRC = sourceMaterial.ComputeCRC();
int fallbackMaterialCRC = fallbackMaterial.ComputeCRC();
if (sourceMaterialCRC == fallbackMaterialCRC)
return fallbackMaterial;
CopyMaterialPresetProperties(sourceMaterial, fallbackMaterial);
return fallbackMaterial;
}
// Create new material from the source material and assign relevant atlas texture
fallbackMaterial = new Material(sourceMaterial);
fallbackMaterial.SetTexture(TextShaderUtilities.ID_MainTex, tex);
fallbackMaterial.hideFlags = HideFlags.HideAndDontSave;
fallbackMaterial.name += " + " + tex.name;
s_FallbackMaterials.Add(key, fallbackMaterial);
return fallbackMaterial;
}
/// <summary>
/// Function to copy the properties of a source material preset to another while preserving the unique font asset properties of the destination material.
/// </summary>
/// <param name="source"></param>
/// <param name="destination"></param>
static void CopyMaterialPresetProperties(Material source, Material destination)
{
if (!source.HasProperty(TextShaderUtilities.ID_GradientScale) || !destination.HasProperty(TextShaderUtilities.ID_GradientScale))
return;
// Save unique material properties
Texture dst_texture = destination.GetTexture(TextShaderUtilities.ID_MainTex);
float dst_gradientScale = destination.GetFloat(TextShaderUtilities.ID_GradientScale);
float dst_texWidth = destination.GetFloat(TextShaderUtilities.ID_TextureWidth);
float dst_texHeight = destination.GetFloat(TextShaderUtilities.ID_TextureHeight);
float dst_weightNormal = destination.GetFloat(TextShaderUtilities.ID_WeightNormal);
float dst_weightBold = destination.GetFloat(TextShaderUtilities.ID_WeightBold);
// Make sure the same shader is used
destination.shader = source.shader;
// Copy all material properties
destination.CopyPropertiesFromMaterial(source);
// Copy shader keywords
destination.shaderKeywords = source.shaderKeywords;
// Restore unique material properties
destination.SetTexture(TextShaderUtilities.ID_MainTex, dst_texture);
destination.SetFloat(TextShaderUtilities.ID_GradientScale, dst_gradientScale);
destination.SetFloat(TextShaderUtilities.ID_TextureWidth, dst_texWidth);
destination.SetFloat(TextShaderUtilities.ID_TextureHeight, dst_texHeight);
destination.SetFloat(TextShaderUtilities.ID_WeightNormal, dst_weightNormal);
destination.SetFloat(TextShaderUtilities.ID_WeightBold, dst_weightBold);
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/MaterialManager.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/MaterialManager.cs",
"repo_id": "UnityCsReference",
"token_count": 3096
} | 460 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.TextCore.Text
{
public enum ColorGradientMode
{
Single,
HorizontalGradient,
VerticalGradient,
FourCornersGradient
}
[System.Serializable][ExcludeFromPresetAttribute][ExcludeFromObjectFactory]
public class TextColorGradient : ScriptableObject
{
public ColorGradientMode colorMode = ColorGradientMode.FourCornersGradient;
public Color topLeft;
public Color topRight;
public Color bottomLeft;
public Color bottomRight;
const ColorGradientMode k_DefaultColorMode = ColorGradientMode.FourCornersGradient;
static readonly Color k_DefaultColor = Color.white;
/// <summary>
/// Default Constructor which sets each of the colors as white.
/// </summary>
public TextColorGradient()
{
colorMode = k_DefaultColorMode;
topLeft = k_DefaultColor;
topRight = k_DefaultColor;
bottomLeft = k_DefaultColor;
bottomRight = k_DefaultColor;
}
/// <summary>
/// Constructor allowing to set the default color of the Color Gradient.
/// </summary>
/// <param name="color"></param>
public TextColorGradient(Color color)
{
colorMode = k_DefaultColorMode;
topLeft = color;
topRight = color;
bottomLeft = color;
bottomRight = color;
}
/// <summary>
/// The vertex colors at the corners of the characters.
/// </summary>
/// <param name="color0">Top left color.</param>
/// <param name="color1">Top right color.</param>
/// <param name="color2">Bottom left color.</param>
/// <param name="color3">Bottom right color.</param>
public TextColorGradient(Color color0, Color color1, Color color2, Color color3)
{
colorMode = k_DefaultColorMode;
this.topLeft = color0;
this.topRight = color1;
this.bottomLeft = color2;
this.bottomRight = color3;
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextColorGradient.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextColorGradient.cs",
"repo_id": "UnityCsReference",
"token_count": 963
} | 461 |
// 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.Profiling;
using UnityEngine.TextCore.LowLevel;
namespace UnityEngine.TextCore.Text
{
[VisibleToOtherModules("UnityEngine.UIElementsModule")]
internal partial class TextGenerator
{
public Vector2 GetPreferredValues(TextGenerationSettings settings, TextInfo textInfo)
{
if (settings.fontAsset == null || settings.fontAsset.characterLookupTable == null)
{
Debug.LogWarning("Can't Generate Mesh, No Font Asset has been assigned.");
return Vector2.zero;
}
Prepare(settings, textInfo);
return GetPreferredValuesInternal(settings, textInfo);
}
Vector2 GetPreferredValuesInternal(TextGenerationSettings generationSettings, TextInfo textInfo)
{
if (generationSettings.textSettings == null)
return Vector2.zero;
float fontSize = generationSettings.autoSize ? generationSettings.fontSizeMax : m_FontSize;
// Reset auto sizing point size bounds
m_MinFontSize = generationSettings.fontSizeMin;
m_MaxFontSize = generationSettings.fontSizeMax;
m_CharWidthAdjDelta = 0;
Vector2 margin = new Vector2(m_MarginWidth != 0 ? m_MarginWidth : TextGeneratorUtilities.largePositiveFloat, m_MarginHeight != 0 ? m_MarginHeight : TextGeneratorUtilities.largePositiveFloat);
TextWrappingMode wrapMode = generationSettings.wordWrap ? TextWrappingMode.Normal : TextWrappingMode.NoWrap;
m_AutoSizeIterationCount = 0;
return CalculatePreferredValues(ref fontSize, margin, generationSettings.autoSize, wrapMode, generationSettings, textInfo);
}
/// <summary>
/// Method to calculate the preferred width and height of the text object.
/// </summary>
/// <returns></returns>
protected virtual Vector2 CalculatePreferredValues(ref float fontSize, Vector2 marginSize, bool isTextAutoSizingEnabled, TextWrappingMode textWrapMode, TextGenerationSettings generationSettings, TextInfo textInfo)
{
Profiler.BeginSample("TextGenerator.CalculatePreferredValues");
// Early exit if no font asset was assigned. This should not be needed since LiberationSans SDF will be assigned by default.
if (generationSettings.fontAsset == null || generationSettings.fontAsset.characterLookupTable == null)
{
Debug.LogWarning("Can't Generate Mesh! No Font Asset has been assigned.");
return Vector2.zero;
}
// Early exit if we don't have any Text to generate.
if (m_TextProcessingArray == null || m_TextProcessingArray.Length == 0 || m_TextProcessingArray[0].unicode == (char)0)
{
Profiler.EndSample();
return Vector2.zero;
}
m_CurrentFontAsset = generationSettings.fontAsset;
m_CurrentMaterial = generationSettings.material;
m_CurrentMaterialIndex = 0;
m_MaterialReferenceStack.SetDefault(new MaterialReference(0, m_CurrentFontAsset, null, m_CurrentMaterial, m_Padding));
// Total character count is computed when the text is parsed.
int totalCharacterCount = m_TotalCharacterCount; // m_VisibleCharacters.Count;
if (m_InternalTextElementInfo == null || totalCharacterCount > m_InternalTextElementInfo.Length)
m_InternalTextElementInfo = new TextElementInfo[totalCharacterCount > 1024 ? totalCharacterCount + 256 : Mathf.NextPowerOfTwo(totalCharacterCount)];
// Calculate the scale of the font based on selected font size and sampling point size.
// baseScale is calculated using the font asset assigned to the text object.
float baseScale = (fontSize / generationSettings.fontAsset.faceInfo.pointSize * generationSettings.fontAsset.faceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f));
float currentElementScale = baseScale;
float currentEmScale = fontSize * 0.01f * (generationSettings.isOrthographic ? 1 : 0.1f);
m_FontScaleMultiplier = 1;
m_CurrentFontSize = fontSize;
m_SizeStack.SetDefault(m_CurrentFontSize);
float fontSizeDelta = 0;
m_FontStyleInternal = generationSettings.fontStyle; // Set the default style.
m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? TextFontWeight.Bold : generationSettings.fontWeight;
m_FontWeightStack.SetDefault(m_FontWeightInternal);
m_FontStyleStack.Clear();
m_LineJustification = generationSettings.textAlignment; // m_textAlignment; // Sets the line justification mode to match editor alignment.
m_LineJustificationStack.SetDefault(m_LineJustification);
m_BaselineOffset = 0; // Used by subscript characters.
m_BaselineOffsetStack.Clear();
m_FXScale = Vector3.one;
m_LineOffset = 0; // Amount of space between lines (font line spacing + m_linespacing).
m_LineHeight = k_FloatUnset;
float lineGap = m_CurrentFontAsset.faceInfo.lineHeight - (m_CurrentFontAsset.faceInfo.ascentLine - m_CurrentFontAsset.faceInfo.descentLine);
m_CSpacing = 0; // Amount of space added between characters as a result of the use of the <cspace> tag.
m_MonoSpacing = 0;
m_XAdvance = 0; // Used to track the position of each character.
m_TagLineIndent = 0; // Used for indentation of text.
m_TagIndent = 0;
m_IndentStack.SetDefault(0);
m_TagNoParsing = false;
m_CharacterCount = 0; // Total characters in the char[]
// Tracking of line information
m_FirstCharacterOfLine = 0;
m_MaxLineAscender = TextGeneratorUtilities.largeNegativeFloat;
m_MaxLineDescender = TextGeneratorUtilities.largePositiveFloat;
m_LineNumber = 0;
m_StartOfLineAscender = 0;
m_IsDrivenLineSpacing = false;
m_LastBaseGlyphIndex = int.MinValue;
bool kerning = generationSettings.fontFeatures.Contains(OTL_FeatureTag.kern);
bool markToBase = generationSettings.fontFeatures.Contains(OTL_FeatureTag.mark);
bool markToMark = generationSettings.fontFeatures.Contains(OTL_FeatureTag.mkmk);
TextSettings textSettings = generationSettings.textSettings;
float marginWidth = marginSize.x;
float marginHeight = marginSize.y;
m_MarginLeft = 0;
m_MarginRight = 0;
m_Width = -1;
float widthOfTextArea = marginWidth + 0.0001f - m_MarginLeft - m_MarginRight;
// Used by Unity's Auto Layout system.
float renderedWidth = 0;
float renderedHeight = 0;
float textWidth = 0;
m_IsCalculatingPreferredValues = true;
// Tracking of the highest Ascender
m_MaxCapHeight = 0;
m_MaxAscender = 0;
m_MaxDescender = 0;
float maxVisibleDescender = 0;
bool isMaxVisibleDescenderSet = false;
// Initialize struct to track states of word wrapping
bool isFirstWordOfLine = true;
m_IsNonBreakingSpace = false;
bool ignoreNonBreakingSpace = false;
CharacterSubstitution characterToSubstitute = new CharacterSubstitution(-1, 0);
bool isSoftHyphenIgnored = false;
WordWrapState internalWordWrapState = new WordWrapState();
WordWrapState internalLineState = new WordWrapState();
WordWrapState internalSoftLineBreak = new WordWrapState();
// Clear the previous truncated / ellipsed state
m_IsTextTruncated = false;
// Counter to prevent recursive lockup when computing preferred values.
m_AutoSizeIterationCount += 1;
// Parse through Character buffer to read HTML tags and begin creating mesh.
for (int i = 0; i < m_TextProcessingArray.Length && m_TextProcessingArray[i].unicode != 0; i++)
{
uint charCode = m_TextProcessingArray[i].unicode;
// Skip characters that have been substituted.
if (charCode == 0x1A)
continue;
// Parse Rich Text Tag
#region Parse Rich Text Tag
if (generationSettings.richText && charCode == k_LesserThan) // '<'
{
m_isTextLayoutPhase = true;
m_TextElementType = TextElementType.Character;
int endTagIndex;
// Check if Tag is valid. If valid, skip to the end of the validated tag.
if (ValidateHtmlTag(m_TextProcessingArray, i + 1, out endTagIndex, generationSettings, textInfo, out bool isThreadSuccess))
{
i = endTagIndex;
// Continue to next character or handle the sprite element
if (m_TextElementType == TextElementType.Character)
continue;
}
}
else
{
m_TextElementType = textInfo.textElementInfo[m_CharacterCount].elementType;
m_CurrentMaterialIndex = textInfo.textElementInfo[m_CharacterCount].materialReferenceIndex;
m_CurrentFontAsset = textInfo.textElementInfo[m_CharacterCount].fontAsset;
}
#endregion End Parse Rich Text Tag
int prevMaterialIndex = m_CurrentMaterialIndex;
bool isUsingAltTypeface = textInfo.textElementInfo[m_CharacterCount].isUsingAlternateTypeface;
m_isTextLayoutPhase = false;
// Handle potential character substitutions
#region Character Substitutions
bool isInjectedCharacter = false;
if (characterToSubstitute.index == m_CharacterCount)
{
charCode = characterToSubstitute.unicode;
m_TextElementType = TextElementType.Character;
isInjectedCharacter = true;
switch (charCode)
{
case k_EndOfText:
m_InternalTextElementInfo[m_CharacterCount].textElement = m_CurrentFontAsset.characterLookupTable[k_EndOfText];
m_IsTextTruncated = true;
break;
case k_HyphenMinus:
//
break;
case k_HorizontalEllipsis:
m_InternalTextElementInfo[m_CharacterCount].textElement = m_Ellipsis.character;
m_InternalTextElementInfo[m_CharacterCount].elementType = TextElementType.Character;
m_InternalTextElementInfo[m_CharacterCount].fontAsset = m_Ellipsis.fontAsset;
m_InternalTextElementInfo[m_CharacterCount].material = m_Ellipsis.material;
m_InternalTextElementInfo[m_CharacterCount].materialReferenceIndex = m_Ellipsis.materialIndex;
// Indicates the source parsing data has been modified.
m_IsTextTruncated = true;
// End Of Text
characterToSubstitute.index = m_CharacterCount + 1;
characterToSubstitute.unicode = k_EndOfText;
break;
}
}
#endregion
// When using Linked text, mark character as ignored and skip to next character.
#region Linked Text
if (m_CharacterCount < generationSettings.firstVisibleCharacter && charCode != k_EndOfText)
{
m_InternalTextElementInfo[m_CharacterCount].isVisible = false;
m_InternalTextElementInfo[m_CharacterCount].character = (char)k_ZeroWidthSpace;
m_InternalTextElementInfo[m_CharacterCount].lineNumber = 0;
m_CharacterCount += 1;
continue;
}
#endregion
// Handle Font Styles like LowerCase, UpperCase and SmallCaps.
#region Handling of LowerCase, UpperCase and SmallCaps Font Styles
float smallCapsMultiplier = 1.0f;
if (m_TextElementType == TextElementType.Character)
{
if ( /*(m_fontStyle & FontStyles.UpperCase) == FontStyles.UpperCase ||*/ (m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase)
{
// If this character is lowercase, switch to uppercase.
if (char.IsLower((char)charCode))
charCode = char.ToUpper((char)charCode);
}
else if ( /*(m_fontStyle & FontStyles.LowerCase) == FontStyles.LowerCase ||*/ (m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase)
{
// If this character is uppercase, switch to lowercase.
if (char.IsUpper((char)charCode))
charCode = char.ToLower((char)charCode);
}
else if ( /*(m_fontStyle & FontStyles.SmallCaps) == FontStyles.SmallCaps ||*/ (m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps)
{
if (char.IsLower((char)charCode))
{
smallCapsMultiplier = 0.8f;
charCode = char.ToUpper((char)charCode);
}
}
}
#endregion
// Look up Character Data from Dictionary and cache it.
#region Look up Character Data
float baselineOffset = 0;
float elementAscentLine = 0;
float elementDescentLine = 0;
if (m_TextElementType == TextElementType.Sprite)
{
// If a sprite is used as a fallback then get a reference to it and set the color to white.
SpriteCharacter sprite = (SpriteCharacter)textInfo.textElementInfo[m_CharacterCount].textElement;
m_CurrentSpriteAsset = sprite.textAsset as SpriteAsset;
m_SpriteIndex = (int)sprite.glyphIndex;
if (sprite == null) continue;
// Sprites are assigned in the E000 Private Area + sprite Index
if (charCode == k_LesserThan)
charCode = 57344 + (uint)m_SpriteIndex;
// The sprite scale calculations are based on the font asset assigned to the text object.
if (m_CurrentSpriteAsset.faceInfo.pointSize > 0)
{
float spriteScale = (m_CurrentFontSize / m_CurrentSpriteAsset.faceInfo.pointSize * m_CurrentSpriteAsset.faceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f));
currentElementScale = sprite.scale * sprite.glyph.scale * spriteScale;
elementAscentLine = m_CurrentSpriteAsset.faceInfo.ascentLine;
//baselineOffset = m_CurrentSpriteAsset.faceInfo.baseline * m_fontScale * m_FontScaleMultiplier * m_CurrentSpriteAsset.faceInfo.scale;
elementDescentLine = m_CurrentSpriteAsset.faceInfo.descentLine;
}
else
{
float spriteScale = (m_CurrentFontSize / m_CurrentFontAsset.faceInfo.pointSize * m_CurrentFontAsset.faceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f));
currentElementScale = m_CurrentFontAsset.faceInfo.ascentLine / sprite.glyph.metrics.height * sprite.scale * sprite.glyph.scale * spriteScale;
float scaleDelta = spriteScale / currentElementScale;
elementAscentLine = m_CurrentFontAsset.faceInfo.ascentLine * scaleDelta;
//baselineOffset = m_CurrentFontAsset.faceInfo.baseline * m_fontScale * m_FontScaleMultiplier * m_CurrentFontAsset.faceInfo.scale;
elementDescentLine = m_CurrentFontAsset.faceInfo.descentLine * scaleDelta;
}
m_CachedTextElement = sprite;
m_InternalTextElementInfo[m_CharacterCount].elementType = TextElementType.Sprite;
m_InternalTextElementInfo[m_CharacterCount].scale = currentElementScale;
m_CurrentMaterialIndex = prevMaterialIndex;
}
else if (m_TextElementType == TextElementType.Character)
{
m_CachedTextElement = textInfo.textElementInfo[m_CharacterCount].textElement;
if (m_CachedTextElement == null)
{
continue;
}
m_CurrentFontAsset = textInfo.textElementInfo[m_CharacterCount].fontAsset;
m_CurrentMaterial = textInfo.textElementInfo[m_CharacterCount].material;
m_CurrentMaterialIndex = textInfo.textElementInfo[m_CharacterCount].materialReferenceIndex;
float adjustedScale;
if (isInjectedCharacter && m_TextProcessingArray[i].unicode == 0x0A && m_CharacterCount != m_FirstCharacterOfLine)
adjustedScale = textInfo.textElementInfo[m_CharacterCount - 1].pointSize * smallCapsMultiplier / m_CurrentFontAsset.m_FaceInfo.pointSize * m_CurrentFontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f);
else
adjustedScale = m_CurrentFontSize * smallCapsMultiplier / m_CurrentFontAsset.m_FaceInfo.pointSize * m_CurrentFontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f);
// Special handling for injected Ellipsis
if (isInjectedCharacter && charCode == k_HorizontalEllipsis)
{
elementAscentLine = 0;
elementDescentLine = 0;
}
else
{
elementAscentLine = m_CurrentFontAsset.m_FaceInfo.ascentLine;
elementDescentLine = m_CurrentFontAsset.m_FaceInfo.descentLine;
}
currentElementScale = adjustedScale * m_FontScaleMultiplier * m_CachedTextElement.scale;
m_InternalTextElementInfo[m_CharacterCount].elementType = TextElementType.Character;
}
#endregion
// Handle Soft Hyphen
#region Handle Soft Hyphen
float currentElementUnmodifiedScale = currentElementScale;
if (charCode == k_SoftHyphen || charCode == k_EndOfText)
currentElementScale = 0;
#endregion
// Store some of the text object's information
m_InternalTextElementInfo[m_CharacterCount].character = (char)charCode;
m_InternalTextElementInfo[m_CharacterCount].style = m_FontStyleInternal;
if (m_FontWeightInternal == TextFontWeight.Bold)
{
m_InternalTextElementInfo[m_CharacterCount].style |= FontStyles.Bold;
}
// Cache glyph metrics
Glyph altGlyph = textInfo.textElementInfo[m_CharacterCount].alternativeGlyph;
GlyphMetrics currentGlyphMetrics = altGlyph == null ? m_CachedTextElement.m_Glyph.metrics : altGlyph.metrics;
// Optimization to avoid calling this more than once per character.
bool isWhiteSpace = charCode <= 0xFFFF && char.IsWhiteSpace((char)charCode);
// Handle Kerning if Enabled.
#region Handle Kerning
GlyphValueRecord glyphAdjustments = new GlyphValueRecord();
float characterSpacingAdjustment = generationSettings.characterSpacing;
if (kerning && m_TextElementType == TextElementType.Character)
{
GlyphPairAdjustmentRecord adjustmentPair;
uint baseGlyphIndex = m_CachedTextElement.m_GlyphIndex;
if (m_CharacterCount < totalCharacterCount - 1 && textInfo.textElementInfo[m_CharacterCount + 1].elementType == TextElementType.Character)
{
uint nextGlyphIndex = textInfo.textElementInfo[m_CharacterCount + 1].textElement.m_GlyphIndex;
uint key = nextGlyphIndex << 16 | baseGlyphIndex;
if (m_CurrentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.TryGetValue(key, out adjustmentPair))
{
glyphAdjustments = adjustmentPair.firstAdjustmentRecord.glyphValueRecord;
characterSpacingAdjustment = (adjustmentPair.featureLookupFlags & FontFeatureLookupFlags.IgnoreSpacingAdjustments) == FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment;
}
}
if (m_CharacterCount >= 1)
{
uint previousGlyphIndex = textInfo.textElementInfo[m_CharacterCount - 1].textElement.m_GlyphIndex;
uint key = baseGlyphIndex << 16 | previousGlyphIndex;
if (textInfo.textElementInfo[m_CharacterCount - 1].elementType == TextElementType.Character && m_CurrentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.TryGetValue(key, out adjustmentPair))
{
glyphAdjustments += adjustmentPair.secondAdjustmentRecord.glyphValueRecord;
characterSpacingAdjustment = (adjustmentPair.featureLookupFlags & FontFeatureLookupFlags.IgnoreSpacingAdjustments) == FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment;
}
}
m_InternalTextElementInfo[m_CharacterCount].adjustedHorizontalAdvance = glyphAdjustments.xAdvance;
}
#endregion
// Handle Diacritical Marks
#region Handle Diacritical Marks
bool isBaseGlyph = TextGeneratorUtilities.IsBaseGlyph((uint)charCode);
if (isBaseGlyph)
m_LastBaseGlyphIndex = m_CharacterCount;
if (m_CharacterCount > 0 && !isBaseGlyph)
{
// Check for potential Mark-to-Base lookup if previous glyph was a base glyph
if (m_LastBaseGlyphIndex != int.MinValue && m_LastBaseGlyphIndex == m_CharacterCount - 1)
{
Glyph baseGlyph = textInfo.textElementInfo[m_LastBaseGlyphIndex].textElement.glyph;
uint baseGlyphIndex = baseGlyph.index;
uint markGlyphIndex = m_CachedTextElement.glyphIndex;
uint key = markGlyphIndex << 16 | baseGlyphIndex;
if (m_CurrentFontAsset.fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.TryGetValue(key, out MarkToBaseAdjustmentRecord glyphAdjustmentRecord))
{
float advanceOffset = (m_InternalTextElementInfo[m_LastBaseGlyphIndex].origin - m_XAdvance) / currentElementScale;
glyphAdjustments.xPlacement = advanceOffset + glyphAdjustmentRecord.baseGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.markPositionAdjustment.xPositionAdjustment;
glyphAdjustments.yPlacement = glyphAdjustmentRecord.baseGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.markPositionAdjustment.yPositionAdjustment;
characterSpacingAdjustment = 0;
}
}
else
{
// Iterate from previous glyph to last base glyph checking for any potential Mark-to-Mark lookups to apply. Otherwise check for potential Mark-to-Base lookup between the current glyph and last base glyph
bool wasLookupApplied = false;
// Check for any potential Mark-to-Mark lookups
for (int characterLookupIndex = m_CharacterCount - 1; characterLookupIndex >= 0 && characterLookupIndex != m_LastBaseGlyphIndex; characterLookupIndex--)
{
// Handle any potential Mark-to-Mark lookup
Glyph baseMarkGlyph = textInfo.textElementInfo[characterLookupIndex].textElement.glyph;
uint baseGlyphIndex = baseMarkGlyph.index;
uint combiningMarkGlyphIndex = m_CachedTextElement.glyphIndex;
uint key = combiningMarkGlyphIndex << 16 | baseGlyphIndex;
if (m_CurrentFontAsset.fontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.TryGetValue(key, out MarkToMarkAdjustmentRecord glyphAdjustmentRecord))
{
float baseMarkOrigin = (textInfo.textElementInfo[characterLookupIndex].origin - m_XAdvance) / currentElementScale;
float currentBaseline = baselineOffset - m_LineOffset + m_BaselineOffset;
float baseMarkBaseline = (m_InternalTextElementInfo[characterLookupIndex].baseLine - currentBaseline) / currentElementScale;
glyphAdjustments.xPlacement = baseMarkOrigin + glyphAdjustmentRecord.baseMarkGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.combiningMarkPositionAdjustment.xPositionAdjustment;
glyphAdjustments.yPlacement = baseMarkBaseline + glyphAdjustmentRecord.baseMarkGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.combiningMarkPositionAdjustment.yPositionAdjustment;
characterSpacingAdjustment = 0;
wasLookupApplied = true;
break;
}
}
// If no Mark-to-Mark lookups were applied, check for potential Mark-to-Base lookup.
if (m_LastBaseGlyphIndex != int.MinValue && !wasLookupApplied)
{
// Handle lookup for Mark-to-Base
Glyph baseGlyph = textInfo.textElementInfo[m_LastBaseGlyphIndex].textElement.glyph;
uint baseGlyphIndex = baseGlyph.index;
uint markGlyphIndex = m_CachedTextElement.glyphIndex;
uint key = markGlyphIndex << 16 | baseGlyphIndex;
if (m_CurrentFontAsset.fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.TryGetValue(key, out MarkToBaseAdjustmentRecord glyphAdjustmentRecord))
{
float advanceOffset = (m_InternalTextElementInfo[m_LastBaseGlyphIndex].origin - m_XAdvance) / currentElementScale;
glyphAdjustments.xPlacement = advanceOffset + glyphAdjustmentRecord.baseGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.markPositionAdjustment.xPositionAdjustment;
glyphAdjustments.yPlacement = glyphAdjustmentRecord.baseGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.markPositionAdjustment.yPositionAdjustment;
characterSpacingAdjustment = 0;
}
}
}
}
// Adjust relevant text metrics
elementAscentLine += glyphAdjustments.yPlacement;
elementDescentLine += glyphAdjustments.yPlacement;
#endregion
// Initial Implementation for RTL support.
#region Handle Right-to-Left
//if (generationSettings.isRightToLeft)
//{
// m_XAdvance -= ((m_CachedTextElement.xAdvance * boldXAdvanceMultiplier + m_characterSpacing + generationSettings.wordSpacing + m_CurrentFontAsset.regularStyleSpacing) * currentElementScale + m_CSpacing) * (1 - m_CharWidthAdjDelta);
// if (char.IsWhiteSpace((char)charCode) || charCode == k_ZeroWidthSpace)
// m_XAdvance -= generationSettings.wordSpacing * currentElementScale;
//}
#endregion
// Handle Mono Spacing
#region Handle Mono Spacing
float monoAdvance = 0;
if (m_MonoSpacing != 0 && charCode != k_ZeroWidthSpace)
{
monoAdvance = (m_MonoSpacing / 2 - (m_CachedTextElement.glyph.metrics.width / 2 + m_CachedTextElement.glyph.metrics.horizontalBearingX) * currentElementScale) * (1 - m_CharWidthAdjDelta);
m_XAdvance += monoAdvance;
}
#endregion
// Set Padding based on selected font style
#region Handle Style Padding
float boldSpacingAdjustment = 0;
if (m_TextElementType == TextElementType.Character && !isUsingAltTypeface && ((m_InternalTextElementInfo[m_CharacterCount].style & FontStyles.Bold) == FontStyles.Bold)) // Checks for any combination of Bold Style.
boldSpacingAdjustment = m_CurrentFontAsset.boldStyleSpacing;
#endregion Handle Style Padding
m_InternalTextElementInfo[m_CharacterCount].origin = m_XAdvance + glyphAdjustments.xPlacement * currentElementScale;
m_InternalTextElementInfo[m_CharacterCount].baseLine = (baselineOffset - m_LineOffset + m_BaselineOffset) + glyphAdjustments.yPlacement * currentElementScale;
// Compute text metrics
#region Compute Ascender & Descender values
// Element Ascender in line space
float elementAscender = m_TextElementType == TextElementType.Character
? elementAscentLine * currentElementScale / smallCapsMultiplier + m_BaselineOffset
: elementAscentLine * currentElementScale + m_BaselineOffset;
// Element Descender in line space
float elementDescender = m_TextElementType == TextElementType.Character
? elementDescentLine * currentElementScale / smallCapsMultiplier + m_BaselineOffset
: elementDescentLine * currentElementScale + m_BaselineOffset;
float adjustedAscender = elementAscender;
float adjustedDescender = elementDescender;
// Max line ascender and descender in line space
bool isFirstCharacterOfLine = m_CharacterCount == m_FirstCharacterOfLine;
if (isFirstCharacterOfLine || isWhiteSpace == false)
{
// Special handling for Superscript and Subscript where we use the unadjusted line ascender and descender
if (m_BaselineOffset != 0)
{
adjustedAscender = Mathf.Max((elementAscender - m_BaselineOffset) / m_FontScaleMultiplier, adjustedAscender);
adjustedDescender = Mathf.Min((elementDescender - m_BaselineOffset) / m_FontScaleMultiplier, adjustedDescender);
}
m_MaxLineAscender = Mathf.Max(adjustedAscender, m_MaxLineAscender);
m_MaxLineDescender = Mathf.Min(adjustedDescender, m_MaxLineDescender);
}
// Element Ascender and Descender in object space
if (isFirstCharacterOfLine || isWhiteSpace == false)
{
m_InternalTextElementInfo[m_CharacterCount].adjustedAscender = adjustedAscender;
m_InternalTextElementInfo[m_CharacterCount].adjustedDescender = adjustedDescender;
m_InternalTextElementInfo[m_CharacterCount].ascender = elementAscender - m_LineOffset;
m_MaxDescender = m_InternalTextElementInfo[m_CharacterCount].descender = elementDescender - m_LineOffset;
}
else
{
m_InternalTextElementInfo[m_CharacterCount].adjustedAscender = m_MaxLineAscender;
m_InternalTextElementInfo[m_CharacterCount].adjustedDescender = m_MaxLineDescender;
m_InternalTextElementInfo[m_CharacterCount].ascender = m_MaxLineAscender - m_LineOffset;
m_MaxDescender = m_InternalTextElementInfo[m_CharacterCount].descender = m_MaxLineDescender - m_LineOffset;
}
// Max text object ascender and cap height
if (m_LineNumber == 0 || m_IsNewPage)
{
if (isFirstCharacterOfLine || isWhiteSpace == false)
{
m_MaxAscender = m_MaxLineAscender;
m_MaxCapHeight = Mathf.Max(m_MaxCapHeight, m_CurrentFontAsset.m_FaceInfo.capLine * currentElementScale / smallCapsMultiplier);
}
}
// Page ascender
if (m_LineOffset == 0)
{
if (!isWhiteSpace || m_CharacterCount == m_FirstCharacterOfLine)
m_PageAscender = m_PageAscender > elementAscender ? m_PageAscender : elementAscender;
}
#endregion
bool isJustifiedOrFlush = ((HorizontalAlignment)m_LineJustification & HorizontalAlignment.Flush) == HorizontalAlignment.Flush || ((HorizontalAlignment)m_LineJustification & HorizontalAlignment.Justified) == HorizontalAlignment.Justified;
// Setup Mesh for visible text elements. ie. not a SPACE / LINEFEED / CARRIAGE RETURN.
#region Handle Visible Characters
if (charCode == k_Tab || charCode == k_ZeroWidthSpace || ((textWrapMode == TextWrappingMode.PreserveWhitespace || textWrapMode == TextWrappingMode.PreserveWhitespaceNoWrap) && (isWhiteSpace || charCode == k_ZeroWidthSpace)) || (isWhiteSpace == false && charCode != k_ZeroWidthSpace && charCode != k_SoftHyphen && charCode != k_EndOfText) || (charCode == k_SoftHyphen && isSoftHyphenIgnored == false) || m_TextElementType == TextElementType.Sprite)
{
//float marginLeft = m_MarginLeft;
//float marginRight = m_MarginRight;
// Injected characters do not override margins
//if (isInjectedCharacter)
//{
// marginLeft = textInfo.lineInfo[m_LineNumber].marginLeft;
// marginRight = textInfo.lineInfo[m_LineNumber].marginRight;
//}
widthOfTextArea = m_Width != -1 ? Mathf.Min(marginWidth + 0.0001f - m_MarginLeft - m_MarginRight, m_Width) : marginWidth + 0.0001f - m_MarginLeft - m_MarginRight;
// Calculate the line breaking width of the text.
textWidth = Mathf.Abs(m_XAdvance) + currentGlyphMetrics.horizontalAdvance * (1 - m_CharWidthAdjDelta) * (charCode == k_SoftHyphen ? currentElementUnmodifiedScale : currentElementScale);
int testedCharacterCount = m_CharacterCount;
// Handling of Horizontal Bounds
#region Current Line Horizontal Bounds Check
if (isBaseGlyph && textWidth > widthOfTextArea * (isJustifiedOrFlush ? 1.05f : 1.0f))
{
// Handle Line Breaking (if still possible)
if (textWrapMode != TextWrappingMode.NoWrap && textWrapMode != TextWrappingMode.PreserveWhitespaceNoWrap && m_CharacterCount != m_FirstCharacterOfLine)
{
// Restore state to previous safe line breaking
i = RestoreWordWrappingState(ref internalWordWrapState, textInfo);
// Replace Soft Hyphen by Hyphen Minus 0x2D
#region Handle Soft Hyphenation
if (m_InternalTextElementInfo[m_CharacterCount - 1].character == k_SoftHyphen && isSoftHyphenIgnored == false && generationSettings.overflowMode == TextOverflowMode.Overflow)
{
characterToSubstitute.index = m_CharacterCount - 1;
characterToSubstitute.unicode = k_HyphenMinus;
i -= 1;
m_CharacterCount -= 1;
continue;
}
isSoftHyphenIgnored = false;
// Ignore Soft Hyphen to prevent it from wrapping
if (m_InternalTextElementInfo[m_CharacterCount].character == k_SoftHyphen)
{
isSoftHyphenIgnored = true;
continue;
}
#endregion
// Adjust character spacing before breaking up word if auto size is enabled
#region Handle Text Auto Size (if word wrapping is no longer possible)
if (isTextAutoSizingEnabled && isFirstWordOfLine)
{
// Handle Character Width Adjustments
#region Character Width Adjustments
if (m_CharWidthAdjDelta < generationSettings.charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
{
float adjustedTextWidth = textWidth;
// Determine full width of the text
if (m_CharWidthAdjDelta > 0)
adjustedTextWidth /= 1f - m_CharWidthAdjDelta;
float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f);
m_CharWidthAdjDelta += adjustmentDelta / adjustedTextWidth;
m_CharWidthAdjDelta = Mathf.Min(m_CharWidthAdjDelta, generationSettings.charWidthMaxAdj / 100);
Profiler.EndSample();
return Vector2.zero;
}
#endregion
// Handle Text Auto-sizing resulting from text exceeding vertical bounds.
#region Text Auto-Sizing (Text greater than vertical bounds)
if (fontSize > generationSettings.fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
{
m_MaxFontSize = fontSize;
float sizeDelta = Mathf.Max((fontSize - m_MinFontSize) / 2, 0.05f);
fontSize -= sizeDelta;
fontSize = Mathf.Max((int)(fontSize * 20 + 0.5f) / 20f, generationSettings.fontSizeMin);
// TODO: Need to investigate this value when moving it to a service as TMP might require this value to be zero.
// It's currently omitted as UITK expects the text height to be auto-increased if a word becomes longer
// and longer. User scenario: User enters a very long word with no spaces that spawns longer than it's container.
// return Vector2.zero;
}
#endregion Text Auto-Sizing
}
#endregion
// Adjust line spacing if necessary
float baselineAdjustmentDelta = m_MaxLineAscender - m_StartOfLineAscender;
if (m_LineOffset > 0 && Math.Abs(baselineAdjustmentDelta) > 0.01f && m_IsDrivenLineSpacing == false && !m_IsNewPage)
{
//AdjustLineOffset(m_FirstCharacterOfLine, m_CharacterCount, baselineAdjustmentDelta);
m_MaxDescender -= baselineAdjustmentDelta;
m_LineOffset += baselineAdjustmentDelta;
}
// Calculate line ascender and make sure if last character is superscript or subscript that we check that as well.
float lineAscender = m_MaxLineAscender - m_LineOffset;
float lineDescender = m_MaxLineDescender - m_LineOffset;
// Update maxDescender and maxVisibleDescender
m_MaxDescender = m_MaxDescender < lineDescender ? m_MaxDescender : lineDescender;
if (!isMaxVisibleDescenderSet)
maxVisibleDescender = m_MaxDescender;
if (generationSettings.useMaxVisibleDescender && (m_CharacterCount >= generationSettings.maxVisibleCharacters || m_LineNumber >= generationSettings.maxVisibleLines))
isMaxVisibleDescenderSet = true;
// Store first character of the next line.
m_FirstCharacterOfLine = m_CharacterCount;
m_LineVisibleCharacterCount = 0;
// Store the state of the line before starting on the new line.
SaveWordWrappingState(ref internalLineState, i, m_CharacterCount - 1, textInfo);
m_LineNumber += 1;
float ascender = m_InternalTextElementInfo[m_CharacterCount].adjustedAscender;
// Compute potential new line offset in the event a line break is needed.
if (m_LineHeight == k_FloatUnset)
{
m_LineOffset += 0 - m_MaxLineDescender + ascender + (lineGap + m_LineSpacingDelta) * baseScale + generationSettings.lineSpacing * currentEmScale;
m_IsDrivenLineSpacing = false;
}
else
{
m_LineOffset += m_LineHeight + generationSettings.lineSpacing * currentEmScale;
m_IsDrivenLineSpacing = true;
}
m_MaxLineAscender = TextGeneratorUtilities.largeNegativeFloat;
m_MaxLineDescender = TextGeneratorUtilities.largePositiveFloat;
m_StartOfLineAscender = ascender;
m_XAdvance = 0 + m_TagIndent;
//isStartOfNewLine = true;
isFirstWordOfLine = true;
continue;
}
}
#endregion
// Compute Preferred Width & Height
renderedWidth = Mathf.Max(renderedWidth, textWidth + m_MarginLeft + m_MarginRight);
renderedHeight = Mathf.Max(renderedHeight, m_MaxAscender - m_MaxDescender);
}
#endregion Handle Visible Characters
// Check if Line Spacing of previous line needs to be adjusted.
#region Adjust Line Spacing
if (m_LineOffset > 0 && !TextGeneratorUtilities.Approximately(m_MaxLineAscender, m_StartOfLineAscender) && m_IsDrivenLineSpacing == false && !m_IsNewPage)
{
float offsetDelta = m_MaxLineAscender - m_StartOfLineAscender;
//AdjustLineOffset(m_FirstCharacterOfLine, m_CharacterCount, offsetDelta);
m_MaxDescender -= offsetDelta;
m_LineOffset += offsetDelta;
m_StartOfLineAscender += offsetDelta;
internalWordWrapState.lineOffset = m_LineOffset;
internalWordWrapState.startOfLineAscender = m_StartOfLineAscender;
}
#endregion
// Handle xAdvance & Tabulation Stops. Tab stops at every 25% of Font Size.
#region XAdvance, Tabulation & Stops
if (charCode != k_ZeroWidthSpace)
{
if (charCode == k_Tab)
{
float tabSize = m_CurrentFontAsset.faceInfo.tabWidth * m_CurrentFontAsset.tabMultiple * currentElementScale;
float tabs = Mathf.Ceil(m_XAdvance / tabSize) * tabSize;
m_XAdvance = tabs > m_XAdvance ? tabs : m_XAdvance + tabSize;
}
else if (m_MonoSpacing != 0)
{
m_XAdvance += (m_MonoSpacing - monoAdvance + ((m_CurrentFontAsset.regularStyleSpacing + characterSpacingAdjustment) * currentEmScale) + m_CSpacing) * (1 - m_CharWidthAdjDelta);
if (isWhiteSpace || charCode == k_ZeroWidthSpace)
m_XAdvance += generationSettings.wordSpacing * currentEmScale;
}
else
{
m_XAdvance += ((currentGlyphMetrics.horizontalAdvance * m_FXScale.x + glyphAdjustments.xAdvance) * currentElementScale + (m_CurrentFontAsset.regularStyleSpacing + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_CSpacing) * (1 - m_CharWidthAdjDelta);
if (isWhiteSpace || charCode == k_ZeroWidthSpace)
m_XAdvance += generationSettings.wordSpacing * currentEmScale;
}
}
#endregion Tabulation & Stops
// Handle Carriage Return
#region Carriage Return
if (charCode == k_CarriageReturn)
{
m_XAdvance = 0 + m_TagIndent;
}
#endregion Carriage Return
// Handle Line Spacing Adjustments + Word Wrapping & special case for last line.
#region Check for Line Feed and Last Character
if (charCode == k_LineFeed || charCode == k_VerticalTab || charCode == k_EndOfText || charCode == k_LineSeparator || charCode == k_ParagraphSeparator || m_CharacterCount == totalCharacterCount - 1)
{
// Check if Line Spacing of previous line needs to be adjusted.
float baselineAdjustmentDelta = m_MaxLineAscender - m_StartOfLineAscender;
if (m_LineOffset > 0 && Math.Abs(baselineAdjustmentDelta) > 0.01f && m_IsDrivenLineSpacing == false && !m_IsNewPage)
{
m_MaxDescender -= baselineAdjustmentDelta;
m_LineOffset += baselineAdjustmentDelta;
}
m_IsNewPage = false;
// Calculate lineAscender & make sure if last character is superscript or subscript that we check that as well.
//float lineAscender = m_MaxLineAscender - m_LineOffset;
float lineDescender = m_MaxLineDescender - m_LineOffset;
// Update maxDescender and maxVisibleDescender
m_MaxDescender = m_MaxDescender < lineDescender ? m_MaxDescender : lineDescender;
// Add new line if not last lines or character.
if (charCode == k_LineFeed || charCode == k_VerticalTab || charCode == k_HyphenMinus || charCode == k_LineSeparator || charCode == k_ParagraphSeparator)
{
// Store the state of the line before starting on the new line.
SaveWordWrappingState(ref internalLineState, i, m_CharacterCount, textInfo);
// Store the state of the last Character before the new line.
SaveWordWrappingState(ref internalWordWrapState, i, m_CharacterCount, textInfo);
m_LineNumber += 1;
m_FirstCharacterOfLine = m_CharacterCount + 1;
float ascender = m_InternalTextElementInfo[m_CharacterCount].adjustedAscender;
// Apply Line Spacing with special handling for VT char(11)
if (m_LineHeight == k_FloatUnset)
{
float lineOffsetDelta = 0 - m_MaxLineDescender + ascender + (lineGap + m_LineSpacingDelta) * baseScale + (generationSettings.lineSpacing + (charCode == k_LineFeed || charCode == k_ParagraphSeparator ? generationSettings.paragraphSpacing : 0)) * currentEmScale;
m_LineOffset += lineOffsetDelta;
m_IsDrivenLineSpacing = false;
}
else
{
m_LineOffset += m_LineHeight + (generationSettings.lineSpacing + (charCode == k_LineFeed || charCode == k_ParagraphSeparator ? generationSettings.paragraphSpacing : 0)) * currentEmScale;
m_IsDrivenLineSpacing = true;
}
m_MaxLineAscender = TextGeneratorUtilities.largeNegativeFloat;
m_MaxLineDescender = TextGeneratorUtilities.largePositiveFloat;
m_StartOfLineAscender = ascender;
m_XAdvance = 0 + m_TagLineIndent + m_TagIndent;
m_CharacterCount += 1;
continue;
}
// If End of Text
if (charCode == k_EndOfText)
i = m_TextProcessingArray.Length;
}
#endregion Check for Linefeed or Last Character
// Save State of Mesh Creation for handling of Word Wrapping
#region Save Word Wrapping State
if ((textWrapMode != TextWrappingMode.NoWrap && textWrapMode != TextWrappingMode.PreserveWhitespaceNoWrap) || generationSettings.overflowMode == TextOverflowMode.Truncate || generationSettings.overflowMode == TextOverflowMode.Ellipsis)
{
bool shouldSaveHardLineBreak = false;
bool shouldSaveSoftLineBreak = false;
if ((isWhiteSpace || charCode == k_ZeroWidthSpace || charCode == k_HyphenMinus || charCode == k_SoftHyphen) && (!m_IsNonBreakingSpace || ignoreNonBreakingSpace) && charCode != k_NoBreakSpace && charCode != k_FigureSpace && charCode != k_NonBreakingHyphen && charCode != k_NarrowNoBreakSpace && charCode != k_WordJoiner)
{
// Ignore Hyphen (0x2D) when preceded by a whitespace
if ((charCode == k_HyphenMinus && m_CharacterCount > 0 && char.IsWhiteSpace((char)textInfo.textElementInfo[m_CharacterCount - 1].character)) == false)
{
isFirstWordOfLine = false;
shouldSaveHardLineBreak = true;
// Reset soft line breaking point since we now have a valid hard break point.
internalSoftLineBreak.previousWordBreak = -1;
}
}
// Handling for East Asian scripts
else if (m_IsNonBreakingSpace == false && (TextGeneratorUtilities.IsHangul((uint)charCode) && textSettings.lineBreakingRules.useModernHangulLineBreakingRules == false || TextGeneratorUtilities.IsCJK((uint)charCode)))
{
bool isCurrentLeadingCharacter = textSettings.lineBreakingRules.leadingCharactersLookup.Contains((uint)charCode);
bool isNextFollowingCharacter = m_CharacterCount < totalCharacterCount - 1 && textSettings.lineBreakingRules.leadingCharactersLookup.Contains(m_InternalTextElementInfo[m_CharacterCount + 1].character);
if (isCurrentLeadingCharacter == false)
{
if (isNextFollowingCharacter == false)
{
isFirstWordOfLine = false;
shouldSaveHardLineBreak = true;
}
if (isFirstWordOfLine)
{
// Special handling for non-breaking space and soft line breaks
if (isWhiteSpace)
shouldSaveSoftLineBreak = true;
shouldSaveHardLineBreak = true;
}
}
else
{
if (isFirstWordOfLine && isFirstCharacterOfLine)
{
// Special handling for non-breaking space and soft line breaks
if (isWhiteSpace)
shouldSaveSoftLineBreak = true;
shouldSaveHardLineBreak = true;
}
}
}
// Special handling for Latin characters followed by a CJK character.
else if (m_IsNonBreakingSpace == false && m_CharacterCount + 1 < totalCharacterCount && TextGeneratorUtilities.IsCJK(textInfo.textElementInfo[m_CharacterCount + 1].character))
{
shouldSaveHardLineBreak = true;
}
else if (isFirstWordOfLine)
{
// Special handling for non-breaking space and soft line breaks
if (isWhiteSpace && charCode != k_NoBreakSpace || (charCode == k_SoftHyphen && isSoftHyphenIgnored == false))
shouldSaveSoftLineBreak = true;
shouldSaveHardLineBreak = true;
}
// Save potential Hard lines break
if (shouldSaveHardLineBreak)
SaveWordWrappingState(ref internalWordWrapState, i, m_CharacterCount, textInfo);
// Save potential Soft line break
if (shouldSaveSoftLineBreak)
SaveWordWrappingState(ref internalSoftLineBreak, i, m_CharacterCount, textInfo);
}
#endregion Save Word Wrapping State
m_CharacterCount += 1;
}
// Check Auto Sizing and increase font size to fill text container.
#region Check Auto-Sizing (Upper Font Size Bounds)
fontSizeDelta = m_MaxFontSize - m_MinFontSize;
if (isTextAutoSizingEnabled && fontSizeDelta > 0.051f && fontSize < generationSettings.fontSizeMax && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount)
{
// Reset character width adjustment delta
if (m_CharWidthAdjDelta < generationSettings.charWidthMaxAdj / 100)
m_CharWidthAdjDelta = 0;
m_MinFontSize = fontSize;
float sizeDelta = Mathf.Max((m_MaxFontSize - fontSize) / 2, 0.05f);
fontSize += sizeDelta;
fontSize = Mathf.Min((int)(fontSize * 20 + 0.5f) / 20f, generationSettings.fontSizeMax);
Profiler.EndSample();
return Vector2.zero;
}
#endregion End Auto-sizing Check
m_IsCalculatingPreferredValues = false;
// Adjust Preferred Width and Height to account for Margins.
renderedWidth += generationSettings.margins.x > 0 ? generationSettings.margins.x : 0;
renderedWidth += generationSettings.margins.z > 0 ? generationSettings.margins.z : 0;
renderedHeight += generationSettings.margins.y > 0 ? generationSettings.margins.y : 0;
renderedHeight += generationSettings.margins.w > 0 ? generationSettings.margins.w : 0;
// Round Preferred Values to nearest 5/100.
renderedWidth = (int)(renderedWidth * 100 + 1f) / 100f;
renderedHeight = (int)(renderedHeight * 100 + 1f) / 100f;
Profiler.EndSample();
return new Vector2(renderedWidth, renderedHeight);
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorPreferredValues.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorPreferredValues.cs",
"repo_id": "UnityCsReference",
"token_count": 28331
} | 462 |
// 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.Globalization;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.TextCore.LowLevel;
using UnityEditor.TextCore.LowLevel;
using Object = UnityEngine.Object;
using TextAsset = UnityEngine.TextAsset;
using FaceInfo = UnityEngine.TextCore.FaceInfo;
using Glyph = UnityEngine.TextCore.Glyph;
using GlyphRect = UnityEngine.TextCore.GlyphRect;
using GlyphMetrics = UnityEngine.TextCore.GlyphMetrics;
namespace UnityEditor.TextCore.Text
{
public class FontAssetCreatorWindow : EditorWindow
{
[MenuItem("Window/Text/Font Asset Creator", false, 2025)]
internal static void ShowFontAtlasCreatorWindow()
{
var window = GetWindow<FontAssetCreatorWindow>();
window.titleContent = new GUIContent("Font Asset Creator");
window.Focus();
// Make sure TMP Essential Resources have been imported.
window.CheckEssentialResources();
}
public static void ShowFontAtlasCreatorWindow(Font font)
{
var window = GetWindow<FontAssetCreatorWindow>();
window.titleContent = new GUIContent("Font Asset Creator");
window.Focus();
window.ClearGeneratedData();
window.m_LegacyFontAsset = null;
window.m_SelectedFontAsset = null;
// Override selected font asset
window.m_SourceFont = font;
// Make sure TMP Essential Resources have been imported.
window.CheckEssentialResources();
}
public static void ShowFontAtlasCreatorWindow(FontAsset fontAsset)
{
var window = GetWindow<FontAssetCreatorWindow>();
window.titleContent = new GUIContent("Font Asset Creator");
window.Focus();
// Clear any previously generated data
window.ClearGeneratedData();
window.m_LegacyFontAsset = null;
// Load font asset creation settings if we have valid settings
if (string.IsNullOrEmpty(fontAsset.fontAssetCreationEditorSettings.sourceFontFileGUID) == false)
{
window.LoadFontCreationSettings(fontAsset.fontAssetCreationEditorSettings);
// Override settings to inject character list from font asset
// window.m_CharacterSetSelectionMode = 6;
// window.m_CharacterSequence = TextCoreEditorUtilities.GetUnicodeCharacterSequence(FontAsset.GetCharactersArray(fontAsset));
window.m_ReferencedFontAsset = fontAsset;
window.m_SavedFontAtlas = fontAsset.atlasTexture;
}
else
{
window.m_WarningMessage = "Font Asset [" + fontAsset.name + "] does not contain any previous \"Font Asset Creation Settings\". This usually means [" + fontAsset.name + "] was created before this new functionality was added.";
window.m_SourceFont = null;
window.m_LegacyFontAsset = fontAsset;
}
// Even if we don't have any saved generation settings, we still want to pre-select the source font file.
window.m_SelectedFontAsset = fontAsset;
// Make sure TMP Essential Resources have been imported.
window.CheckEssentialResources();
}
[System.Serializable]
class FontAssetCreationSettingsContainer
{
public List<FontAssetCreationEditorSettings> fontAssetCreationSettings;
}
FontAssetCreationSettingsContainer m_FontAssetCreationSettingsContainer;
//static readonly string[] m_FontCreationPresets = new string[] { "Recent 1", "Recent 2", "Recent 3", "Recent 4" };
int m_FontAssetCreationSettingsCurrentIndex = 0;
const string k_FontAssetCreationSettingsContainerKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.Container";
const string k_FontAssetCreationSettingsCurrentIndexKey = "TextMeshPro.FontAssetCreator.RecentFontAssetCreationSettings.CurrentIndex";
const float k_TwoColumnControlsWidth = 335f;
// Diagnostics
System.Diagnostics.Stopwatch m_StopWatch;
double m_GlyphPackingGenerationTime;
double m_GlyphRenderingGenerationTime;
string[] m_FontSizingOptions = { "Auto Sizing", "Custom Size" };
int m_PointSizeSamplingMode;
string[] m_FontResolutionLabels = { "8", "16", "32", "64", "128", "256", "512", "1024", "2048", "4096", "8192" };
int[] m_FontAtlasResolutions = { 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192 };
string[] m_FontCharacterSets = { "ASCII", "Extended ASCII", "ASCII Lowercase", "ASCII Uppercase", "Numbers + Symbols", "Custom Range", "Unicode Range (Hex)", "Custom Characters", "Characters from File" };
enum FontPackingModes { Fast = 0, Optimum = 4 };
FontPackingModes m_PackingMode = FontPackingModes.Fast;
int m_CharacterSetSelectionMode;
string m_CharacterSequence = "";
string m_OutputFeedback = "";
string m_WarningMessage;
int m_CharacterCount;
Vector2 m_ScrollPosition;
Vector2 m_OutputScrollPosition;
bool m_IsRepaintNeeded;
float m_AtlasGenerationProgress;
string m_AtlasGenerationProgressLabel = string.Empty;
bool m_IsGlyphPackingDone;
bool m_IsGlyphRenderingDone;
bool m_IsRenderingDone;
bool m_IsProcessing;
bool m_IsGenerationDisabled;
bool m_IsGenerationCancelled;
bool m_IsFontAtlasInvalid;
Font m_SourceFont;
int m_SourceFontFaceIndex;
private string[] m_SourceFontFaces = new string[0];
FontAsset m_SelectedFontAsset;
FontAsset m_LegacyFontAsset;
FontAsset m_ReferencedFontAsset;
TextAsset m_CharactersFromFile;
int m_PointSize;
float m_PaddingFieldValue = 10;
int m_Padding;
enum PaddingMode { Undefined = 0, Percentage = 1, Pixel = 2 };
string[] k_PaddingOptionLabels = { "%", "px" };
private PaddingMode m_PaddingMode = PaddingMode.Percentage;
GlyphRenderMode m_GlyphRenderMode = GlyphRenderMode.SDFAA;
int m_AtlasWidth = 512;
int m_AtlasHeight = 512;
byte[] m_AtlasTextureBuffer;
Texture2D m_FontAtlasTexture;
Texture2D m_GlyphRectPreviewTexture;
Texture2D m_SavedFontAtlas;
//
List<Glyph> m_FontGlyphTable = new List<Glyph>();
List<Character> m_FontCharacterTable = new List<Character>();
Dictionary<uint, uint> m_CharacterLookupMap = new Dictionary<uint, uint>();
Dictionary<uint, List<uint>> m_GlyphLookupMap = new Dictionary<uint, List<uint>>();
List<Glyph> m_GlyphsToPack = new List<Glyph>();
List<Glyph> m_GlyphsPacked = new List<Glyph>();
List<GlyphRect> m_FreeGlyphRects = new List<GlyphRect>();
List<GlyphRect> m_UsedGlyphRects = new List<GlyphRect>();
List<Glyph> m_GlyphsToRender = new List<Glyph>();
List<uint> m_AvailableGlyphsToAdd = new List<uint>();
List<uint> m_MissingCharacters = new List<uint>();
List<uint> m_ExcludedCharacters = new List<uint>();
private FaceInfo m_FaceInfo;
bool m_IncludeFontFeatures;
public void OnEnable()
{
// Used for Diagnostics
m_StopWatch = new System.Diagnostics.Stopwatch();
// Set Editor window size.
minSize = new Vector2(315, minSize.y);
// Initialize & Get shader property IDs.
TextShaderUtilities.GetShaderPropertyIDs();
// Load last selected preset if we are not already in the process of regenerating an existing font asset (via the Context menu)
if (EditorPrefs.HasKey(k_FontAssetCreationSettingsContainerKey))
{
if (m_FontAssetCreationSettingsContainer == null)
m_FontAssetCreationSettingsContainer = JsonUtility.FromJson<FontAssetCreationSettingsContainer>(EditorPrefs.GetString(k_FontAssetCreationSettingsContainerKey));
if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings != null && m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 0)
{
// Load Font Asset Creation Settings preset.
if (EditorPrefs.HasKey(k_FontAssetCreationSettingsCurrentIndexKey))
m_FontAssetCreationSettingsCurrentIndex = EditorPrefs.GetInt(k_FontAssetCreationSettingsCurrentIndexKey);
LoadFontCreationSettings(m_FontAssetCreationSettingsContainer.fontAssetCreationSettings[m_FontAssetCreationSettingsCurrentIndex]);
}
}
// Get potential font face and styles for the current font.
if (m_SourceFont != null)
m_SourceFontFaces = GetFontFaces();
ClearGeneratedData();
}
public void OnDisable()
{
//Debug.Log("TextMeshPro Editor Window has been disabled.");
// Destroy Engine only if it has been initialized already
FontEngine.DestroyFontEngine();
ClearGeneratedData();
// Remove Glyph Report if one was created.
if (File.Exists("Assets/TextMesh Pro/Glyph Report.txt"))
{
File.Delete("Assets/TextMesh Pro/Glyph Report.txt");
File.Delete("Assets/TextMesh Pro/Glyph Report.txt.meta");
AssetDatabase.Refresh();
}
// Save Font Asset Creation Settings Index
SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings());
EditorPrefs.SetInt(k_FontAssetCreationSettingsCurrentIndexKey, m_FontAssetCreationSettingsCurrentIndex);
// Unregister to event
TextEventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
Resources.UnloadUnusedAssets();
}
// Event received when TMP resources have been loaded.
void ON_RESOURCES_LOADED()
{
TextEventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
m_IsGenerationDisabled = false;
}
// Make sure TMP Essential Resources have been imported.
void CheckEssentialResources()
{
// TODO: Update this
// if (TMP_Settings.instance == null)
// {
// if (m_IsGenerationDisabled == false)
// TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
//
// m_IsGenerationDisabled = true;
// }
}
public void OnGUI()
{
GUILayout.BeginHorizontal();
DrawControls();
if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
DrawPreview();
GUILayout.EndHorizontal();
}
public void Update()
{
if (m_IsRepaintNeeded)
{
//Debug.Log("Repainting...");
m_IsRepaintNeeded = false;
Repaint();
}
// Update Progress bar is we are Rendering a Font.
if (m_IsProcessing)
{
m_AtlasGenerationProgress = FontEngine.generationProgress;
m_IsRepaintNeeded = true;
}
if (m_IsGlyphPackingDone)
{
UpdateRenderFeedbackWindow();
if (m_IsGenerationCancelled == false)
{
DrawGlyphRectPreviewTexture();
Debug.Log("Glyph packing completed in: " + m_GlyphPackingGenerationTime.ToString("0.000 ms."));
}
m_IsGlyphPackingDone = false;
}
if (m_IsGlyphRenderingDone)
{
Debug.Log("Font Atlas generation completed in: " + m_GlyphRenderingGenerationTime.ToString("0.000 ms."));
m_IsGlyphRenderingDone = false;
}
// Update Feedback Window & Create Font Texture once Rendering is done.
if (m_IsRenderingDone)
{
m_IsProcessing = false;
m_IsRenderingDone = false;
if (m_IsGenerationCancelled == false)
{
m_AtlasGenerationProgress = FontEngine.generationProgress;
m_AtlasGenerationProgressLabel = "Generation completed in: " + (m_GlyphPackingGenerationTime + m_GlyphRenderingGenerationTime).ToString("0.00 ms.");
UpdateRenderFeedbackWindow();
CreateFontAtlasTexture();
// If dynamic make readable ...
m_FontAtlasTexture.Apply(false, false);
}
Repaint();
}
}
/// <summary>
/// Method which returns the character corresponding to a decimal value.
/// </summary>
/// <param name="sequence"></param>
/// <returns></returns>
static uint[] ParseNumberSequence(string sequence)
{
List<uint> unicodeList = new List<uint>();
string[] sequences = sequence.Split(',');
foreach (string seq in sequences)
{
string[] s1 = seq.Split('-');
if (s1.Length == 1)
try
{
unicodeList.Add(uint.Parse(s1[0]));
}
catch
{
Debug.Log("No characters selected or invalid format.");
}
else
{
for (uint j = uint.Parse(s1[0]); j < uint.Parse(s1[1]) + 1; j++)
{
unicodeList.Add(j);
}
}
}
return unicodeList.ToArray();
}
/// <summary>
/// Method which returns the character (decimal value) from a hex sequence.
/// </summary>
/// <param name="sequence"></param>
/// <returns></returns>
static uint[] ParseHexNumberSequence(string sequence)
{
List<uint> unicodeList = new List<uint>();
string[] sequences = sequence.Split(',');
foreach (string seq in sequences)
{
string[] s1 = seq.Split('-');
if (s1.Length == 1)
try
{
unicodeList.Add(uint.Parse(s1[0], NumberStyles.AllowHexSpecifier));
}
catch
{
Debug.Log("No characters selected or invalid format.");
}
else
{
for (uint j = uint.Parse(s1[0], NumberStyles.AllowHexSpecifier); j < uint.Parse(s1[1], NumberStyles.AllowHexSpecifier) + 1; j++)
{
unicodeList.Add(j);
}
}
}
return unicodeList.ToArray();
}
void DrawControls()
{
GUILayout.Space(5f);
if (position.width > position.height && position.width > k_TwoColumnControlsWidth)
{
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition, GUILayout.Width(315));
}
else
{
m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition);
}
GUILayout.Space(5f);
GUILayout.Label(m_SelectedFontAsset != null ? string.Format("Font Settings [{0}]", m_SelectedFontAsset.name) : "Font Settings", EditorStyles.boldLabel);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUIUtility.labelWidth = 125f;
EditorGUIUtility.fieldWidth = 5f;
// Disable Options if already generating a font atlas texture.
EditorGUI.BeginDisabledGroup(m_IsProcessing);
{
// FONT SELECTION
EditorGUI.BeginChangeCheck();
m_SourceFont = EditorGUILayout.ObjectField("Source Font", m_SourceFont, typeof(Font), false) as Font;
if (EditorGUI.EndChangeCheck())
{
m_SelectedFontAsset = null;
m_IsFontAtlasInvalid = true;
m_SourceFontFaces = GetFontFaces();
m_SourceFontFaceIndex = 0;
}
// FONT FACE AND STYLE SELECTION
EditorGUI.BeginChangeCheck();
GUI.enabled = m_SourceFont != null;
m_SourceFontFaceIndex = EditorGUILayout.Popup("Font Face", m_SourceFontFaceIndex, m_SourceFontFaces);
if (EditorGUI.EndChangeCheck())
{
m_SelectedFontAsset = null;
m_IsFontAtlasInvalid = true;
}
GUI.enabled = true;
// FONT SIZING
EditorGUI.BeginChangeCheck();
if (m_PointSizeSamplingMode == 0)
{
m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions);
}
else
{
GUILayout.BeginHorizontal();
m_PointSizeSamplingMode = EditorGUILayout.Popup("Sampling Point Size", m_PointSizeSamplingMode, m_FontSizingOptions, GUILayout.Width(225));
m_PointSize = EditorGUILayout.IntField(m_PointSize);
GUILayout.EndHorizontal();
}
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
// FONT PADDING
GUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck();
m_PaddingFieldValue = EditorGUILayout.FloatField("Padding", m_PaddingFieldValue);
int selection = m_PaddingMode == PaddingMode.Undefined || m_PaddingMode == PaddingMode.Pixel ? 1 : 0;
selection = GUILayout.SelectionGrid(selection, k_PaddingOptionLabels, 2);
if (m_PaddingMode == PaddingMode.Percentage)
m_PaddingFieldValue = (int)(m_PaddingFieldValue + 0.5f);
if (EditorGUI.EndChangeCheck())
{
m_PaddingMode = (PaddingMode)selection + 1;
m_IsFontAtlasInvalid = true;
}
GUILayout.EndHorizontal();
// FONT PACKING METHOD SELECTION
EditorGUI.BeginChangeCheck();
m_PackingMode = (FontPackingModes)EditorGUILayout.EnumPopup("Packing Method", m_PackingMode);
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
// FONT ATLAS RESOLUTION SELECTION
GUILayout.BeginHorizontal();
GUI.changed = false;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PrefixLabel("Atlas Resolution");
m_AtlasWidth = EditorGUILayout.IntPopup(m_AtlasWidth, m_FontResolutionLabels, m_FontAtlasResolutions);
m_AtlasHeight = EditorGUILayout.IntPopup(m_AtlasHeight, m_FontResolutionLabels, m_FontAtlasResolutions);
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
GUILayout.EndHorizontal();
// FONT CHARACTER SET SELECTION
EditorGUI.BeginChangeCheck();
bool hasSelectionChanged = false;
m_CharacterSetSelectionMode = EditorGUILayout.Popup("Character Set", m_CharacterSetSelectionMode, m_FontCharacterSets);
if (EditorGUI.EndChangeCheck())
{
m_CharacterSequence = "";
hasSelectionChanged = true;
m_IsFontAtlasInvalid = true;
}
switch (m_CharacterSetSelectionMode)
{
case 0: // ASCII
//characterSequence = "32 - 126, 130, 132 - 135, 139, 145 - 151, 153, 155, 161, 166 - 167, 169 - 174, 176, 181 - 183, 186 - 187, 191, 8210 - 8226, 8230, 8240, 8242 - 8244, 8249 - 8250, 8252 - 8254, 8260, 8286";
m_CharacterSequence = "32 - 126, 160, 8203, 8230, 9633";
break;
case 1: // EXTENDED ASCII
m_CharacterSequence = "32 - 126, 160 - 255, 8192 - 8303, 8364, 8482, 9633";
// Could add 9632 for missing glyph
break;
case 2: // Lowercase
m_CharacterSequence = "32 - 64, 91 - 126, 160";
break;
case 3: // Uppercase
m_CharacterSequence = "32 - 96, 123 - 126, 160";
break;
case 4: // Numbers & Symbols
m_CharacterSequence = "32 - 64, 91 - 96, 123 - 126, 160";
break;
case 5: // Custom Range
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label("Enter a sequence of decimal values to define the characters to be included in the font asset or retrieve one from another font asset.", TM_EditorStyles.label);
GUILayout.Space(10f);
EditorGUI.BeginChangeCheck();
m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(FontAsset), false) as FontAsset;
if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
{
if (m_ReferencedFontAsset != null)
m_CharacterSequence = TextCoreEditorUtilities.GetDecimalCharacterSequence(FontAsset.GetCharactersArray(m_ReferencedFontAsset));
m_IsFontAtlasInvalid = true;
}
// Filter out unwanted characters.
char chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < ',' || chr > '-'))
{
Event.current.character = '\0';
}
GUILayout.Label("Character Sequence (Decimal)", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TM_EditorStyles.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
EditorGUILayout.EndVertical();
break;
case 6: // Unicode HEX Range
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label("Enter a sequence of Unicode (hex) values to define the characters to be included in the font asset or retrieve one from another font asset.", TM_EditorStyles.label);
GUILayout.Space(10f);
EditorGUI.BeginChangeCheck();
m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(FontAsset), false) as FontAsset;
if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
{
if (m_ReferencedFontAsset != null)
m_CharacterSequence = TextCoreEditorUtilities.GetUnicodeCharacterSequence(FontAsset.GetCharactersArray(m_ReferencedFontAsset));
m_IsFontAtlasInvalid = true;
}
// Filter out unwanted characters.
chr = Event.current.character;
if ((chr < '0' || chr > '9') && (chr < 'a' || chr > 'f') && (chr < 'A' || chr > 'F') && (chr < ',' || chr > '-'))
{
Event.current.character = '\0';
}
GUILayout.Label("Character Sequence (Hex)", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TM_EditorStyles.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
EditorGUILayout.EndVertical();
break;
case 7: // Characters from Font Asset
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label("Type the characters to be included in the font asset or retrieve them from another font asset.", TM_EditorStyles.label);
GUILayout.Space(10f);
EditorGUI.BeginChangeCheck();
m_ReferencedFontAsset = EditorGUILayout.ObjectField("Select Font Asset", m_ReferencedFontAsset, typeof(FontAsset), false) as FontAsset;
if (EditorGUI.EndChangeCheck() || hasSelectionChanged)
{
if (m_ReferencedFontAsset != null)
m_CharacterSequence = FontAsset.GetCharacters(m_ReferencedFontAsset);
m_IsFontAtlasInvalid = true;
}
EditorGUI.indentLevel = 0;
GUILayout.Label("Custom Character List", EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
m_CharacterSequence = EditorGUILayout.TextArea(m_CharacterSequence, TM_EditorStyles.textAreaBoxWindow, GUILayout.Height(120), GUILayout.ExpandWidth(true));
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
EditorGUILayout.EndVertical();
break;
case 8: // Character List from File
EditorGUI.BeginChangeCheck();
m_CharactersFromFile = EditorGUILayout.ObjectField("Character File", m_CharactersFromFile, typeof(TextAsset), false) as TextAsset;
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
if (m_CharactersFromFile != null)
{
Regex rx = new Regex(@"(?<!\\)(?:\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})");
m_CharacterSequence = rx.Replace(m_CharactersFromFile.text,
match =>
{
if (match.Value.StartsWith("\\U"))
return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\U", ""), NumberStyles.HexNumber));
return char.ConvertFromUtf32(int.Parse(match.Value.Replace("\\u", ""), NumberStyles.HexNumber));
});
}
break;
}
// FONT STYLE SELECTION
//GUILayout.BeginHorizontal();
//EditorGUI.BeginChangeCheck();
////m_FontStyle = (FaceStyles)EditorGUILayout.EnumPopup("Font Style", m_FontStyle, GUILayout.Width(225));
////m_FontStyleValue = EditorGUILayout.IntField((int)m_FontStyleValue);
//if (EditorGUI.EndChangeCheck())
//{
// m_IsFontAtlasInvalid = true;
//}
//GUILayout.EndHorizontal();
// Render Mode Selection
CheckForLegacyGlyphRenderMode();
EditorGUI.BeginChangeCheck();
m_GlyphRenderMode = (GlyphRenderMode)EditorGUILayout.EnumPopup("Render Mode", m_GlyphRenderMode);
if (EditorGUI.EndChangeCheck())
{
m_IsFontAtlasInvalid = true;
}
m_IncludeFontFeatures = EditorGUILayout.Toggle("Get Font Features", m_IncludeFontFeatures);
EditorGUILayout.Space();
}
EditorGUI.EndDisabledGroup();
if (!string.IsNullOrEmpty(m_WarningMessage))
{
EditorGUILayout.HelpBox(m_WarningMessage, MessageType.Warning);
}
GUI.enabled = m_SourceFont != null && !m_IsProcessing && !m_IsGenerationDisabled; // Enable Preview if we are not already rendering a font.
if (GUILayout.Button("Generate Font Atlas") && GUI.enabled)
{
if (!m_IsProcessing && m_SourceFont != null)
{
DestroyImmediate(m_FontAtlasTexture);
DestroyImmediate(m_GlyphRectPreviewTexture);
m_FontAtlasTexture = null;
m_SavedFontAtlas = null;
m_OutputFeedback = string.Empty;
// Initialize font engine
FontEngineError errorCode = FontEngine.InitializeFontEngine();
if (errorCode != FontEngineError.Success)
{
Debug.Log("Font Asset Creator - Error [" + errorCode + "] has occurred while Initializing the FreeType Library.");
}
if (errorCode == FontEngineError.Success)
{
errorCode = FontEngine.LoadFontFace(m_SourceFont, 0, m_SourceFontFaceIndex);
if (errorCode != FontEngineError.Success)
{
Debug.Log("Font Asset Creator - Error Code [" + errorCode + "] has occurred trying to load the [" + m_SourceFont.name + "] font file. This typically results from the use of an incompatible or corrupted font file.", m_SourceFont);
}
}
// Define an array containing the characters we will render.
if (errorCode == FontEngineError.Success)
{
uint[] characterSet = null;
// Get list of characters that need to be packed and rendered to the atlas texture.
if (m_CharacterSetSelectionMode == 7 || m_CharacterSetSelectionMode == 8)
{
// Ensure these characters are always added
List<uint> char_List = new List<uint>()
{
9, // Space
95 // Underline
};
for (int i = 0; i < m_CharacterSequence.Length; i++)
{
uint unicode = m_CharacterSequence[i];
// Handle surrogate pairs
if (i < m_CharacterSequence.Length - 1 && char.IsHighSurrogate((char)unicode) && char.IsLowSurrogate(m_CharacterSequence[i + 1]))
{
unicode = (uint)char.ConvertToUtf32(m_CharacterSequence[i], m_CharacterSequence[i + 1]);
i += 1;
}
// Check to make sure we don't include duplicates
if (char_List.FindIndex(item => item == unicode) == -1)
char_List.Add(unicode);
}
characterSet = char_List.ToArray();
}
else if (m_CharacterSetSelectionMode == 6)
{
characterSet = ParseHexNumberSequence(m_CharacterSequence);
}
else
{
characterSet = ParseNumberSequence(m_CharacterSequence);
}
m_CharacterCount = characterSet.Length;
m_AtlasGenerationProgress = 0;
m_IsProcessing = true;
m_IsGenerationCancelled = false;
GlyphLoadFlags glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_HINTED) == GlyphRasterModes.RASTER_MODE_HINTED
? GlyphLoadFlags.LOAD_RENDER
: GlyphLoadFlags.LOAD_RENDER | GlyphLoadFlags.LOAD_NO_HINTING;
glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_MONO) == GlyphRasterModes.RASTER_MODE_MONO
? glyphLoadFlags | GlyphLoadFlags.LOAD_MONOCHROME
: glyphLoadFlags;
glyphLoadFlags = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_COLOR) == GlyphRasterModes.RASTER_MODE_COLOR
? glyphLoadFlags | GlyphLoadFlags.LOAD_COLOR
: glyphLoadFlags;
//
AutoResetEvent autoEvent = new AutoResetEvent(false);
// Worker thread to pack glyphs in the given texture space.
ThreadPool.QueueUserWorkItem(PackGlyphs =>
{
// Start Stop Watch
m_StopWatch = System.Diagnostics.Stopwatch.StartNew();
// Clear the various lists used in the generation process.
m_AvailableGlyphsToAdd.Clear();
m_MissingCharacters.Clear();
m_ExcludedCharacters.Clear();
m_CharacterLookupMap.Clear();
m_GlyphLookupMap.Clear();
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
// Check if requested characters are available in the source font file.
for (int i = 0; i < characterSet.Length; i++)
{
uint unicode = characterSet[i];
uint glyphIndex;
if (FontEngine.TryGetGlyphIndex(unicode, out glyphIndex))
{
// Skip over potential duplicate characters.
if (m_CharacterLookupMap.ContainsKey(unicode))
continue;
// Add character to character lookup map.
m_CharacterLookupMap.Add(unicode, glyphIndex);
// Skip over potential duplicate glyph references.
if (m_GlyphLookupMap.ContainsKey(glyphIndex))
{
// Add additional glyph reference for this character.
m_GlyphLookupMap[glyphIndex].Add(unicode);
continue;
}
// Add glyph reference to glyph lookup map.
m_GlyphLookupMap.Add(glyphIndex, new List<uint>() { unicode });
// Add glyph index to list of glyphs to add to texture.
m_AvailableGlyphsToAdd.Add(glyphIndex);
}
else
{
// Add Unicode to list of missing characters.
m_MissingCharacters.Add(unicode);
}
}
// Pack available glyphs in the provided texture space.
if (m_AvailableGlyphsToAdd.Count > 0)
{
int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
if (m_PointSizeSamplingMode == 0) // Auto-Sizing Point Size Mode
{
// Estimate min / max range for auto sizing of point size.
int minPointSize = 0;
int maxPointSize = (int)Mathf.Sqrt((m_AtlasWidth * m_AtlasHeight) / m_AvailableGlyphsToAdd.Count) * 3;
m_PointSize = (maxPointSize + minPointSize) / 2;
bool optimumPointSizeFound = false;
for (int iteration = 0; iteration < 15 && optimumPointSizeFound == false && m_PointSize > 0; iteration++)
{
m_AtlasGenerationProgressLabel = "Packing glyphs - Pass (" + iteration + ")";
FontEngine.SetFaceSize(m_PointSize);
m_Padding = (int)(m_PaddingMode == PaddingMode.Percentage ? m_PointSize * m_PaddingFieldValue / 100f : m_PaddingFieldValue);
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
m_FreeGlyphRects.Clear();
m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
m_UsedGlyphRects.Clear();
for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
{
uint glyphIndex = m_AvailableGlyphsToAdd[i];
Glyph glyph;
if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
{
if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
{
m_GlyphsToPack.Add(glyph);
}
else
{
m_GlyphsPacked.Add(glyph);
}
}
}
FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
if (m_IsGenerationCancelled)
{
DestroyImmediate(m_FontAtlasTexture);
m_FontAtlasTexture = null;
return;
}
//Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
if (m_GlyphsToPack.Count > 0)
{
if (m_PointSize > minPointSize)
{
maxPointSize = m_PointSize;
m_PointSize = (m_PointSize + minPointSize) / 2;
//Debug.Log("Decreasing point size from [" + maxPointSize + "] to [" + m_PointSize + "].");
}
}
else
{
if (maxPointSize - minPointSize > 1 && m_PointSize < maxPointSize)
{
minPointSize = m_PointSize;
m_PointSize = (m_PointSize + maxPointSize) / 2;
//Debug.Log("Increasing point size from [" + minPointSize + "] to [" + m_PointSize + "].");
}
else
{
//Debug.Log("[" + iteration + "] iterations to find the optimum point size of : [" + m_PointSize + "].");
optimumPointSizeFound = true;
}
}
}
}
else // Custom Point Size Mode
{
m_AtlasGenerationProgressLabel = "Packing glyphs...";
// Set point size
FontEngine.SetFaceSize(m_PointSize);
m_Padding = (int)(m_PaddingMode == PaddingMode.Percentage ? m_PointSize * m_PaddingFieldValue / 100 : m_PaddingFieldValue);
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
m_FreeGlyphRects.Clear();
m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
m_UsedGlyphRects.Clear();
for (int i = 0; i < m_AvailableGlyphsToAdd.Count; i++)
{
uint glyphIndex = m_AvailableGlyphsToAdd[i];
Glyph glyph;
if (FontEngine.TryGetGlyphWithIndexValue(glyphIndex, glyphLoadFlags, out glyph))
{
if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
{
m_GlyphsToPack.Add(glyph);
}
else
{
m_GlyphsPacked.Add(glyph);
}
}
}
FontEngine.TryPackGlyphsInAtlas(m_GlyphsToPack, m_GlyphsPacked, m_Padding, (GlyphPackingMode)m_PackingMode, m_GlyphRenderMode, m_AtlasWidth, m_AtlasHeight, m_FreeGlyphRects, m_UsedGlyphRects);
if (m_IsGenerationCancelled)
{
DestroyImmediate(m_FontAtlasTexture);
m_FontAtlasTexture = null;
return;
}
//Debug.Log("Glyphs remaining to add [" + m_GlyphsToAdd.Count + "]. Glyphs added [" + m_GlyphsAdded.Count + "].");
}
}
else
{
int packingModifier = ((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
FontEngine.SetFaceSize(m_PointSize);
m_Padding = (int)(m_PaddingMode == PaddingMode.Percentage ? m_PointSize * m_PaddingFieldValue / 100 : m_PaddingFieldValue);
m_GlyphsToPack.Clear();
m_GlyphsPacked.Clear();
m_FreeGlyphRects.Clear();
m_FreeGlyphRects.Add(new GlyphRect(0, 0, m_AtlasWidth - packingModifier, m_AtlasHeight - packingModifier));
m_UsedGlyphRects.Clear();
}
//Stop StopWatch
m_StopWatch.Stop();
m_GlyphPackingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds;
m_IsGlyphPackingDone = true;
m_StopWatch.Reset();
m_FontCharacterTable.Clear();
m_FontGlyphTable.Clear();
m_GlyphsToRender.Clear();
// Handle Results and potential cancellation of glyph rendering
if (m_GlyphRenderMode == GlyphRenderMode.SDF32 && m_PointSize > 512 || m_GlyphRenderMode == GlyphRenderMode.SDF16 && m_PointSize > 1024 || m_GlyphRenderMode == GlyphRenderMode.SDF8 && m_PointSize > 2048)
{
int upSampling = 1;
switch (m_GlyphRenderMode)
{
case GlyphRenderMode.SDF8:
upSampling = 8;
break;
case GlyphRenderMode.SDF16:
upSampling = 16;
break;
case GlyphRenderMode.SDF32:
upSampling = 32;
break;
}
Debug.Log("Glyph rendering has been aborted due to sampling point size of [" + m_PointSize + "] x SDF [" + upSampling + "] up sampling exceeds 16,384 point size. Please revise your generation settings to make sure the sampling point size x SDF up sampling mode does not exceed 16,384.");
m_IsRenderingDone = true;
m_AtlasGenerationProgress = 0;
m_IsGenerationCancelled = true;
}
// Add glyphs and characters successfully added to texture to their respective font tables.
foreach (Glyph glyph in m_GlyphsPacked)
{
uint glyphIndex = glyph.index;
m_FontGlyphTable.Add(glyph);
// Add glyphs to list of glyphs that need to be rendered.
if (glyph.glyphRect.width > 0 && glyph.glyphRect.height > 0)
m_GlyphsToRender.Add(glyph);
foreach (uint unicode in m_GlyphLookupMap[glyphIndex])
{
// Create new Character
m_FontCharacterTable.Add(new Character(unicode, glyph));
}
}
//
foreach (Glyph glyph in m_GlyphsToPack)
{
foreach (uint unicode in m_GlyphLookupMap[glyph.index])
{
m_ExcludedCharacters.Add(unicode);
}
}
// Get the face info for the current sampling point size.
m_FaceInfo = FontEngine.GetFaceInfo();
autoEvent.Set();
});
// Worker thread to render glyphs in texture buffer.
ThreadPool.QueueUserWorkItem(RenderGlyphs =>
{
autoEvent.WaitOne();
if (m_IsGenerationCancelled == false)
{
// Start Stop Watch
m_StopWatch = System.Diagnostics.Stopwatch.StartNew();
m_IsRenderingDone = false;
// Allocate texture data
if (m_GlyphRenderMode == GlyphRenderMode.COLOR || m_GlyphRenderMode == GlyphRenderMode.COLOR_HINTED)
m_AtlasTextureBuffer = new byte[m_AtlasWidth * m_AtlasHeight * 4];
else
m_AtlasTextureBuffer = new byte[m_AtlasWidth * m_AtlasHeight];
m_AtlasGenerationProgressLabel = "Rendering glyphs...";
// Render and add glyphs to the given atlas texture.
if (m_GlyphsToRender.Count > 0)
{
FontEngine.RenderGlyphsToTexture(m_GlyphsToRender, m_Padding, m_GlyphRenderMode, m_AtlasTextureBuffer, m_AtlasWidth, m_AtlasHeight);
}
m_IsRenderingDone = true;
// Stop StopWatch
m_StopWatch.Stop();
m_GlyphRenderingGenerationTime = m_StopWatch.Elapsed.TotalMilliseconds;
m_IsGlyphRenderingDone = true;
m_StopWatch.Reset();
}
});
}
SaveCreationSettingsToEditorPrefs(SaveFontCreationSettings());
}
}
// FONT RENDERING PROGRESS BAR
GUILayout.Space(1);
Rect progressRect = EditorGUILayout.GetControlRect(false, 20);
GUI.enabled = true;
progressRect.width -= 22;
EditorGUI.ProgressBar(progressRect, Mathf.Max(0.01f, m_AtlasGenerationProgress), m_AtlasGenerationProgressLabel);
progressRect.x = progressRect.x + progressRect.width + 2;
progressRect.y -= 1;
progressRect.width = 20;
progressRect.height = 20;
GUI.enabled = m_IsProcessing;
if (GUI.Button(progressRect, "X"))
{
FontEngine.SendCancellationRequest();
m_AtlasGenerationProgress = 0;
m_IsProcessing = false;
m_IsGenerationCancelled = true;
}
GUILayout.Space(5);
// FONT STATUS & INFORMATION
GUI.enabled = true;
GUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.Height(200));
m_OutputScrollPosition = EditorGUILayout.BeginScrollView(m_OutputScrollPosition);
EditorGUILayout.LabelField(m_OutputFeedback, TM_EditorStyles.label);
EditorGUILayout.EndScrollView();
GUILayout.EndVertical();
// SAVE TEXTURE & CREATE and SAVE FONT XML FILE
GUI.enabled = m_FontAtlasTexture != null && !m_IsProcessing; // Enable Save Button if font_Atlas is not Null.
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Save") && GUI.enabled)
{
if (m_SelectedFontAsset == null)
{
if (m_LegacyFontAsset != null)
SaveNewFontAssetWithSameName(m_LegacyFontAsset);
else
SaveNewFontAsset(m_SourceFont);
}
else
{
// Save over exiting Font Asset
string filePath = Path.GetFullPath(AssetDatabase.GetAssetPath(m_SelectedFontAsset)).Replace('\\', '/');
if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
Save_Bitmap_FontAsset(filePath);
else
Save_SDF_FontAsset(filePath);
}
}
if (GUILayout.Button("Save as...") && GUI.enabled)
{
if (m_SelectedFontAsset == null)
{
SaveNewFontAsset(m_SourceFont);
}
else
{
SaveNewFontAssetWithSameName(m_SelectedFontAsset);
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
GUI.enabled = true; // Re-enable GUI
if (position.height > position.width || position.width < k_TwoColumnControlsWidth)
{
DrawPreview();
GUILayout.Space(5);
}
EditorGUILayout.EndScrollView();
if (m_IsFontAtlasInvalid)
ClearGeneratedData();
}
/// <summary>
/// Clear the previously generated data.
/// </summary>
void ClearGeneratedData()
{
m_IsFontAtlasInvalid = false;
if (m_FontAtlasTexture != null && !EditorUtility.IsPersistent(m_FontAtlasTexture))
{
DestroyImmediate(m_FontAtlasTexture);
m_FontAtlasTexture = null;
}
if (m_GlyphRectPreviewTexture != null)
{
DestroyImmediate(m_GlyphRectPreviewTexture);
m_GlyphRectPreviewTexture = null;
}
m_AtlasGenerationProgressLabel = string.Empty;
m_AtlasGenerationProgress = 0;
m_SavedFontAtlas = null;
m_OutputFeedback = string.Empty;
m_WarningMessage = string.Empty;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
string[] GetFontFaces()
{
FontEngine.LoadFontFace(m_SourceFont, 0, 0);
return FontEngine.GetFontFaces();
}
/// <summary>
/// Function to update the feedback window showing the results of the latest generation.
/// </summary>
void UpdateRenderFeedbackWindow()
{
m_PointSize = m_FaceInfo.pointSize;
string missingGlyphReport = string.Empty;
//string colorTag = m_FontCharacterTable.Count == m_CharacterCount ? "<color=#C0ffff>" : "<color=#ffff00>";
string colorTag2 = "<color=#C0ffff>";
missingGlyphReport = "Font: <b>" + colorTag2 + m_FaceInfo.familyName + "</color></b> Style: <b>" + colorTag2 + m_FaceInfo.styleName + "</color></b>";
missingGlyphReport += "\nPoint Size: <b>" + colorTag2 + m_FaceInfo.pointSize + "</color></b> Padding: <b>" + colorTag2 + m_Padding + "</color></b> SP/PD Ratio: <b>" + colorTag2 + ((float)m_Padding / m_FaceInfo.pointSize).ToString("0.0%" + "</color></b>");
missingGlyphReport += "\n\nCharacters included: <color=#ffff00><b>" + m_FontCharacterTable.Count + "/" + m_CharacterCount + "</b></color>";
missingGlyphReport += "\nMissing characters: <color=#ffff00><b>" + m_MissingCharacters.Count + "</b></color>";
missingGlyphReport += "\nExcluded characters: <color=#ffff00><b>" + m_ExcludedCharacters.Count + "</b></color>";
// Report characters missing from font file
missingGlyphReport += "\n\n<b><color=#ffff00>Characters missing from font file:</color></b>";
missingGlyphReport += "\n----------------------------------------";
m_OutputFeedback = missingGlyphReport;
for (int i = 0; i < m_MissingCharacters.Count; i++)
{
missingGlyphReport += "\nID: <color=#C0ffff>" + m_MissingCharacters[i] + "\t</color>Hex: <color=#C0ffff>" + m_MissingCharacters[i].ToString("X") + "\t</color>Char [<color=#C0ffff>" + (char)m_MissingCharacters[i] + "</color>]";
if (missingGlyphReport.Length < 16300)
m_OutputFeedback = missingGlyphReport;
}
// Report characters that did not fit in the atlas texture
missingGlyphReport += "\n\n<b><color=#ffff00>Characters excluded from packing:</color></b>";
missingGlyphReport += "\n----------------------------------------";
for (int i = 0; i < m_ExcludedCharacters.Count; i++)
{
missingGlyphReport += "\nID: <color=#C0ffff>" + m_ExcludedCharacters[i] + "\t</color>Hex: <color=#C0ffff>" + m_ExcludedCharacters[i].ToString("X") + "\t</color>Char [<color=#C0ffff>" + (char)m_ExcludedCharacters[i] + "</color>]";
if (missingGlyphReport.Length < 16300)
m_OutputFeedback = missingGlyphReport;
}
if (missingGlyphReport.Length > 16300)
m_OutputFeedback += "\n\n<color=#ffff00>Report truncated.</color>\n<color=#c0ffff>See</color> \"TextMesh Pro\\Glyph Report.txt\"";
// Save Missing Glyph Report file
if (Directory.Exists("Assets/TextMesh Pro"))
{
missingGlyphReport = System.Text.RegularExpressions.Regex.Replace(missingGlyphReport, @"<[^>]*>", string.Empty);
File.WriteAllText("Assets/TextMesh Pro/Glyph Report.txt", missingGlyphReport);
AssetDatabase.Refresh();
}
}
void DrawGlyphRectPreviewTexture()
{
if (m_GlyphRectPreviewTexture != null)
DestroyImmediate(m_GlyphRectPreviewTexture);
m_GlyphRectPreviewTexture = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.RGBA32, false, true);
FontEngine.ResetAtlasTexture(m_GlyphRectPreviewTexture);
foreach (Glyph glyph in m_GlyphsPacked)
{
GlyphRect glyphRect = glyph.glyphRect;
Color c = UnityEngine.Random.ColorHSV(0f, 1f, 0.5f, 0.5f, 1.0f, 1.0f);
int x0 = glyphRect.x;
int x1 = x0 + glyphRect.width;
int y0 = glyphRect.y;
int y1 = y0 + glyphRect.height;
// Draw glyph rectangle.
for (int x = x0; x < x1; x++)
{
for (int y = y0; y < y1; y++)
m_GlyphRectPreviewTexture.SetPixel(x, y, c);
}
}
m_GlyphRectPreviewTexture.Apply(false);
}
void CreateFontAtlasTexture()
{
if (m_FontAtlasTexture != null)
DestroyImmediate(m_FontAtlasTexture);
Color32[] colors = new Color32[m_AtlasWidth * m_AtlasHeight];
switch (m_GlyphRenderMode)
{
case GlyphRenderMode.COLOR:
case GlyphRenderMode.COLOR_HINTED:
m_FontAtlasTexture = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.RGBA32, false, true);
for (int i = 0; i < colors.Length; i++)
{
int readIndex = i * 4;
byte r = m_AtlasTextureBuffer[readIndex + 0];
byte g = m_AtlasTextureBuffer[readIndex + 1];
byte b = m_AtlasTextureBuffer[readIndex + 2];
byte a = m_AtlasTextureBuffer[readIndex + 3];
colors[i] = new Color32(r, g, b, a);
}
break;
default:
m_FontAtlasTexture = new Texture2D(m_AtlasWidth, m_AtlasHeight, TextureFormat.Alpha8, false, true);
for (int i = 0; i < colors.Length; i++)
{
byte c = m_AtlasTextureBuffer[i];
colors[i] = new Color32(c, c, c, c);
}
break;
}
// Clear allocation of
m_AtlasTextureBuffer = null;
if ((m_GlyphRenderMode & GlyphRenderMode.RASTER) == GlyphRenderMode.RASTER || (m_GlyphRenderMode & GlyphRenderMode.RASTER_HINTED) == GlyphRenderMode.RASTER_HINTED)
m_FontAtlasTexture.filterMode = FilterMode.Point;
m_FontAtlasTexture.SetPixels32(colors, 0);
m_FontAtlasTexture.Apply(false, false);
// Saving File for Debug
//var pngData = m_FontAtlasTexture.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug Font Texture.png", pngData);
}
/// <summary>
/// Open Save Dialog to provide the option save the font asset using the name of the source font file. This also appends SDF to the name if using any of the SDF Font Asset creation modes.
/// </summary>
/// <param name="sourceObject"></param>
void SaveNewFontAsset(Object sourceObject)
{
string filePath;
// Save new Font Asset and open save file requester at Source Font File location.
string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName;
if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
{
filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset");
if (filePath.Length == 0)
return;
Save_Bitmap_FontAsset(filePath);
}
else
{
filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name + " SDF", "asset");
if (filePath.Length == 0)
return;
Save_SDF_FontAsset(filePath);
}
}
/// <summary>
/// Open Save Dialog to provide the option to save the font asset under the same name.
/// </summary>
/// <param name="sourceObject"></param>
void SaveNewFontAssetWithSameName(Object sourceObject)
{
string filePath;
// Save new Font Asset and open save file requester at Source Font File location.
string saveDirectory = new FileInfo(AssetDatabase.GetAssetPath(sourceObject)).DirectoryName;
filePath = EditorUtility.SaveFilePanel("Save TextMesh Pro! Font Asset File", saveDirectory, sourceObject.name, "asset");
if (filePath.Length == 0)
return;
if (((GlyphRasterModes)m_GlyphRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP)
{
Save_Bitmap_FontAsset(filePath);
}
else
{
Save_SDF_FontAsset(filePath);
}
}
void Save_Bitmap_FontAsset(string filePath)
{
filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
string dataPath = Application.dataPath;
// if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1)
// {
// Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
// return;
// }
string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
// Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
FontAsset fontAsset = AssetDatabase.LoadAssetAtPath(tex_Path_NoExt + ".asset", typeof(FontAsset)) as FontAsset;
if (fontAsset == null)
{
//Debug.Log("Creating TextMeshPro font asset!");
fontAsset = ScriptableObject.CreateInstance<FontAsset>(); // Create new TextMeshPro Font Asset.
AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset");
// Set version number of font asset
fontAsset.version = "1.1.0";
//Set Font Asset Type
fontAsset.atlasRenderMode = m_GlyphRenderMode;
// Reference to the source font file GUID.
fontAsset.m_SourceFontFile_EditorRef = m_SourceFont;
fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFont));
// Add FaceInfo to Font Asset
fontAsset.faceInfo = m_FaceInfo;
// Add GlyphInfo[] to Font Asset
fontAsset.glyphTable = m_FontGlyphTable;
// Add CharacterTable[] to font asset.
fontAsset.characterTable = m_FontCharacterTable;
// Sort glyph and character tables.
fontAsset.SortAllTables();
// Get and Add Kerning Pairs to Font Asset
if (m_IncludeFontFeatures)
fontAsset.fontFeatureTable = GetAllFontFeatures();
// Add Font Atlas as Sub-Asset
fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
m_FontAtlasTexture.name = tex_FileName + " Atlas";
fontAsset.atlasWidth = m_AtlasWidth;
fontAsset.atlasHeight = m_AtlasHeight;
fontAsset.atlasPadding = m_Padding;
AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
// Create new Material and Add it as Sub-Asset
Shader default_Shader = TextShaderUtilities.ShaderRef_MobileBitmap;
Material tmp_material = new Material(default_Shader);
tmp_material.name = tex_FileName + " Material";
tmp_material.SetTexture(TextShaderUtilities.ID_MainTex, m_FontAtlasTexture);
fontAsset.material = tmp_material;
AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
}
else
{
// Find all Materials referencing this font atlas.
Material[] material_references = TextCoreEditorUtilities.FindMaterialReferences(fontAsset);
// Set version number of font asset
fontAsset.version = "1.1.0";
//Set Font Asset Type
fontAsset.atlasRenderMode = m_GlyphRenderMode;
// Add FaceInfo to Font Asset
fontAsset.faceInfo = m_FaceInfo;
// Add GlyphInfo[] to Font Asset
fontAsset.glyphTable = m_FontGlyphTable;
// Add CharacterTable[] to font asset.
fontAsset.characterTable = m_FontCharacterTable;
// Sort glyph and character tables.
fontAsset.SortAllTables();
// Get and Add Kerning Pairs to Font Asset
if (m_IncludeFontFeatures)
fontAsset.fontFeatureTable = GetAllFontFeatures();
// Destroy Assets that will be replaced.
if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0)
{
for (int i = 1; i < fontAsset.atlasTextures.Length; i++)
DestroyImmediate(fontAsset.atlasTextures[i], true);
}
fontAsset.m_AtlasTextureIndex = 0;
fontAsset.atlasWidth = m_AtlasWidth;
fontAsset.atlasHeight = m_AtlasHeight;
fontAsset.atlasPadding = m_Padding;
// Make sure remaining atlas texture is of the correct size
Texture2D tex = fontAsset.atlasTextures[0];
tex.name = tex_FileName + " Atlas";
// Make texture readable to allow resizing
bool isReadableState = tex.isReadable;
if (isReadableState == false)
FontEngineEditorUtilities.SetAtlasTextureIsReadable(tex, true);
if (tex.width != m_AtlasWidth || tex.height != m_AtlasHeight)
{
tex.Reinitialize(m_AtlasWidth, m_AtlasHeight);
tex.Apply(false);
}
// Copy new texture data to existing texture
Graphics.CopyTexture(m_FontAtlasTexture, tex);
// Apply changes to the texture.
tex.Apply(false);
// Special handling due to a bug in earlier versions of Unity.
m_FontAtlasTexture.hideFlags = HideFlags.None;
fontAsset.material.hideFlags = HideFlags.None;
// Update the Texture reference on the Material
//for (int i = 0; i < material_references.Length; i++)
//{
// material_references[i].SetFloat(TextShaderUtilities.ID_TextureWidth, tex.width);
// material_references[i].SetFloat(TextShaderUtilities.ID_TextureHeight, tex.height);
// int spread = m_Padding;
// material_references[i].SetFloat(TextShaderUtilities.ID_GradientScale, spread);
// material_references[i].SetFloat(TextShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
// material_references[i].SetFloat(TextShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
//}
}
// Set texture to non readable
if (fontAsset.atlasPopulationMode == AtlasPopulationMode.Static)
FontEngineEditorUtilities.SetAtlasTextureIsReadable(fontAsset.atlasTexture, false);
// Add list of GlyphRects to font asset.
fontAsset.freeGlyphRects = m_FreeGlyphRects;
fontAsset.usedGlyphRects = m_UsedGlyphRects;
// Save Font Asset creation settings
m_SelectedFontAsset = fontAsset;
m_LegacyFontAsset = null;
fontAsset.fontAssetCreationEditorSettings = SaveFontCreationSettings();
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version.
//EditorUtility.SetDirty(font_asset);
fontAsset.ReadFontAssetDefinition();
AssetDatabase.Refresh();
m_FontAtlasTexture = null;
// NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
TextEventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
}
void Save_SDF_FontAsset(string filePath)
{
filePath = filePath.Substring(0, filePath.Length - 6); // Trim file extension from filePath.
string dataPath = Application.dataPath;
// if (filePath.IndexOf(dataPath, System.StringComparison.InvariantCultureIgnoreCase) == -1)
// {
// Debug.LogError("You're saving the font asset in a directory outside of this project folder. This is not supported. Please select a directory under \"" + dataPath + "\"");
// return;
// }
string relativeAssetPath = filePath.Substring(dataPath.Length - 6);
string tex_DirName = Path.GetDirectoryName(relativeAssetPath);
string tex_FileName = Path.GetFileNameWithoutExtension(relativeAssetPath);
string tex_Path_NoExt = tex_DirName + "/" + tex_FileName;
// Check if TextMeshPro font asset already exists. If not, create a new one. Otherwise update the existing one.
FontAsset fontAsset = AssetDatabase.LoadAssetAtPath<FontAsset>(tex_Path_NoExt + ".asset");
if (fontAsset == null)
{
//Debug.Log("Creating TextMeshPro font asset!");
fontAsset = ScriptableObject.CreateInstance<FontAsset>(); // Create new TextMeshPro Font Asset.
AssetDatabase.CreateAsset(fontAsset, tex_Path_NoExt + ".asset");
// Set version number of font asset
fontAsset.version = "1.1.0";
// Reference to source font file GUID.
fontAsset.m_SourceFontFile_EditorRef = m_SourceFont;
fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFont));
//Set Font Asset Type
fontAsset.atlasRenderMode = m_GlyphRenderMode;
// Add FaceInfo to Font Asset
fontAsset.faceInfo = m_FaceInfo;
// Add GlyphInfo[] to Font Asset
fontAsset.glyphTable = m_FontGlyphTable;
// Add CharacterTable[] to font asset.
fontAsset.characterTable = m_FontCharacterTable;
// Sort glyph and character tables.
fontAsset.SortAllTables();
// Get and Add Kerning Pairs to Font Asset
if (m_IncludeFontFeatures)
fontAsset.fontFeatureTable = GetAllFontFeatures();
// Add Font Atlas as Sub-Asset
fontAsset.atlasTextures = new Texture2D[] { m_FontAtlasTexture };
m_FontAtlasTexture.name = tex_FileName + " Atlas";
fontAsset.atlasWidth = m_AtlasWidth;
fontAsset.atlasHeight = m_AtlasHeight;
fontAsset.atlasPadding = m_Padding;
AssetDatabase.AddObjectToAsset(m_FontAtlasTexture, fontAsset);
// Create new Material and Add it as Sub-Asset
Shader default_Shader = TextShaderUtilities.ShaderRef_MobileSDF;
Material tmp_material = new Material(default_Shader);
tmp_material.name = tex_FileName + " Material";
tmp_material.SetTexture(TextShaderUtilities.ID_MainTex, m_FontAtlasTexture);
tmp_material.SetFloat(TextShaderUtilities.ID_TextureWidth, m_FontAtlasTexture.width);
tmp_material.SetFloat(TextShaderUtilities.ID_TextureHeight, m_FontAtlasTexture.height);
int spread = m_Padding + 1;
tmp_material.SetFloat(TextShaderUtilities.ID_GradientScale, spread); // Spread = Padding for Brute Force SDF.
tmp_material.SetFloat(TextShaderUtilities.ID_WeightNormal, fontAsset.regularStyleWeight);
tmp_material.SetFloat(TextShaderUtilities.ID_WeightBold, fontAsset.boldStyleWeight);
fontAsset.material = tmp_material;
AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
}
else
{
// Find all Materials referencing this font atlas.
Material[] material_references = TextCoreEditorUtilities.FindMaterialReferences(fontAsset);
// Set version number of font asset
fontAsset.version = "1.1.0";
//Set Font Asset Type
fontAsset.atlasRenderMode = m_GlyphRenderMode;
// Add FaceInfo to Font Asset
fontAsset.faceInfo = m_FaceInfo;
// Add GlyphInfo[] to Font Asset
fontAsset.glyphTable = m_FontGlyphTable;
// Add CharacterTable[] to font asset.
fontAsset.characterTable = m_FontCharacterTable;
// Sort glyph and character tables.
fontAsset.SortAllTables();
// Get and Add Kerning Pairs to Font Asset
// TODO: Check and preserve existing adjustment pairs.
if (m_IncludeFontFeatures)
fontAsset.fontFeatureTable = GetAllFontFeatures();
// Destroy Assets that will be replaced.
if (fontAsset.atlasTextures != null && fontAsset.atlasTextures.Length > 0)
{
for (int i = 1; i < fontAsset.atlasTextures.Length; i++)
DestroyImmediate(fontAsset.atlasTextures[i], true);
}
fontAsset.m_AtlasTextureIndex = 0;
fontAsset.atlasWidth = m_AtlasWidth;
fontAsset.atlasHeight = m_AtlasHeight;
fontAsset.atlasPadding = m_Padding;
// Make sure remaining atlas texture is of the correct size
Texture2D tex = fontAsset.atlasTextures[0];
tex.name = tex_FileName + " Atlas";
// Make texture readable to allow resizing
bool isReadableState = tex.isReadable;
if (isReadableState == false)
FontEngineEditorUtilities.SetAtlasTextureIsReadable(tex, true);
if (tex.width != m_AtlasWidth || tex.height != m_AtlasHeight)
{
tex.Reinitialize(m_AtlasWidth, m_AtlasHeight);
tex.Apply(false);
}
// Copy new texture data to existing texture
Graphics.CopyTexture(m_FontAtlasTexture, tex);
// Apply changes to the texture.
tex.Apply(false);
// Special handling due to a bug in earlier versions of Unity.
m_FontAtlasTexture.hideFlags = HideFlags.None;
fontAsset.material.hideFlags = HideFlags.None;
// Update the Texture reference on the Material
for (int i = 0; i < material_references.Length; i++)
{
material_references[i].SetFloat(TextShaderUtilities.ID_TextureWidth, tex.width);
material_references[i].SetFloat(TextShaderUtilities.ID_TextureHeight, tex.height);
int spread = m_Padding + 1;
material_references[i].SetFloat(TextShaderUtilities.ID_GradientScale, spread);
material_references[i].SetFloat(TextShaderUtilities.ID_WeightNormal, fontAsset.regularStyleWeight);
material_references[i].SetFloat(TextShaderUtilities.ID_WeightBold, fontAsset.boldStyleWeight);
}
}
// Saving File for Debug
//var pngData = destination_Atlas.EncodeToPNG();
//File.WriteAllBytes("Assets/Textures/Debug Distance Field.png", pngData);
// Set texture to non readable
if (fontAsset.atlasPopulationMode == AtlasPopulationMode.Static)
FontEngineEditorUtilities.SetAtlasTextureIsReadable(fontAsset.atlasTexture, false);
// Add list of GlyphRects to font asset.
fontAsset.freeGlyphRects = m_FreeGlyphRects;
fontAsset.usedGlyphRects = m_UsedGlyphRects;
// Save Font Asset creation settings
m_SelectedFontAsset = fontAsset;
m_LegacyFontAsset = null;
fontAsset.fontAssetCreationEditorSettings = SaveFontCreationSettings();
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(fontAsset)); // Re-import font asset to get the new updated version.
fontAsset.ReadFontAssetDefinition();
AssetDatabase.Refresh();
m_FontAtlasTexture = null;
// NEED TO GENERATE AN EVENT TO FORCE A REDRAW OF ANY TEXTMESHPRO INSTANCES THAT MIGHT BE USING THIS FONT ASSET
TextEventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
}
/// <summary>
/// Internal method to save the Font Asset Creation Settings
/// </summary>
/// <returns></returns>
FontAssetCreationEditorSettings SaveFontCreationSettings()
{
FontAssetCreationEditorSettings settings = new FontAssetCreationEditorSettings();
//settings.sourceFontFileName = m_SourceFontFile.name;
settings.sourceFontFileGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_SourceFont));
settings.faceIndex = m_SourceFontFaceIndex;
settings.pointSizeSamplingMode = m_PointSizeSamplingMode;
settings.pointSize = m_PointSize;
settings.padding = m_Padding;
settings.paddingMode = (int)m_PaddingMode;
settings.packingMode = (int)m_PackingMode;
settings.atlasWidth = m_AtlasWidth;
settings.atlasHeight = m_AtlasHeight;
settings.characterSetSelectionMode = m_CharacterSetSelectionMode;
settings.characterSequence = m_CharacterSequence;
settings.referencedFontAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_ReferencedFontAsset));
settings.referencedTextAssetGUID = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(m_CharactersFromFile));
settings.renderMode = (int)m_GlyphRenderMode;
settings.includeFontFeatures = m_IncludeFontFeatures;
return settings;
}
/// <summary>
/// Internal method to load the Font Asset Creation Settings
/// </summary>
/// <param name="settings"></param>
void LoadFontCreationSettings(FontAssetCreationEditorSettings settings)
{
m_SourceFont = AssetDatabase.LoadAssetAtPath<Font>(AssetDatabase.GUIDToAssetPath(settings.sourceFontFileGUID));
m_SourceFontFaceIndex = settings.faceIndex;
m_SourceFontFaces = GetFontFaces();
m_PointSizeSamplingMode = settings.pointSizeSamplingMode;
m_PointSize = settings.pointSize;
m_Padding = settings.padding;
m_PaddingMode = settings.paddingMode == 0 ? PaddingMode.Pixel : (PaddingMode)settings.paddingMode;
m_PaddingFieldValue = m_PaddingMode == PaddingMode.Percentage ? (float)m_Padding / m_PointSize * 100 : m_Padding;
m_PackingMode = (FontPackingModes)settings.packingMode;
m_AtlasWidth = settings.atlasWidth;
m_AtlasHeight = settings.atlasHeight;
m_CharacterSetSelectionMode = settings.characterSetSelectionMode;
m_CharacterSequence = settings.characterSequence;
m_ReferencedFontAsset = AssetDatabase.LoadAssetAtPath<FontAsset>(AssetDatabase.GUIDToAssetPath(settings.referencedFontAssetGUID));
m_CharactersFromFile = AssetDatabase.LoadAssetAtPath<TextAsset>(AssetDatabase.GUIDToAssetPath(settings.referencedTextAssetGUID));
m_GlyphRenderMode = (GlyphRenderMode)settings.renderMode;
m_IncludeFontFeatures = settings.includeFontFeatures;
}
/// <summary>
/// Save the latest font asset creation settings to EditorPrefs.
/// </summary>
/// <param name="settings"></param>
void SaveCreationSettingsToEditorPrefs(FontAssetCreationEditorSettings settings)
{
// Create new list if one does not already exist
if (m_FontAssetCreationSettingsContainer == null)
{
m_FontAssetCreationSettingsContainer = new FontAssetCreationSettingsContainer();
m_FontAssetCreationSettingsContainer.fontAssetCreationSettings = new List<FontAssetCreationEditorSettings>();
}
// Add new creation settings to the list
m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Add(settings);
// Since list should only contain the most 4 recent settings, we remove the first element if list exceeds 4 elements.
if (m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count > 4)
m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.RemoveAt(0);
m_FontAssetCreationSettingsCurrentIndex = m_FontAssetCreationSettingsContainer.fontAssetCreationSettings.Count - 1;
// Serialize list to JSON
string serializedSettings = JsonUtility.ToJson(m_FontAssetCreationSettingsContainer, true);
EditorPrefs.SetString(k_FontAssetCreationSettingsContainerKey, serializedSettings);
}
void DrawPreview()
{
Rect pixelRect;
float ratioX = (position.width - k_TwoColumnControlsWidth) / m_AtlasWidth;
float ratioY = (position.height - 15) / m_AtlasHeight;
if (position.width < position.height)
{
ratioX = (position.width - 15) / m_AtlasWidth;
ratioY = (position.height - 485) / m_AtlasHeight;
}
if (ratioX < ratioY)
{
float width = m_AtlasWidth * ratioX;
float height = m_AtlasHeight * ratioX;
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.MaxWidth(width), GUILayout.MaxHeight(height));
pixelRect = GUILayoutUtility.GetRect(width - 5, height, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
}
else
{
float width = m_AtlasWidth * ratioY;
float height = m_AtlasHeight * ratioY;
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.MaxWidth(width), GUILayout.MaxHeight(height));
pixelRect = GUILayoutUtility.GetRect(width - 5, height, GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false));
}
if (m_FontAtlasTexture != null)
{
if (m_FontAtlasTexture.format == TextureFormat.Alpha8)
EditorGUI.DrawTextureAlpha(pixelRect, m_FontAtlasTexture, ScaleMode.StretchToFill);
else
EditorGUI.DrawPreviewTexture(pixelRect, m_FontAtlasTexture, null, ScaleMode.StretchToFill);
// Destroy GlyphRect preview texture
if (m_GlyphRectPreviewTexture != null)
{
DestroyImmediate(m_GlyphRectPreviewTexture);
m_GlyphRectPreviewTexture = null;
}
}
else if (m_GlyphRectPreviewTexture != null)
{
EditorGUI.DrawPreviewTexture(pixelRect, m_GlyphRectPreviewTexture, null, ScaleMode.StretchToFill);
}
else if (m_SavedFontAtlas != null)
{
EditorGUI.DrawTextureAlpha(pixelRect, m_SavedFontAtlas, ScaleMode.StretchToFill);
}
EditorGUILayout.EndVertical();
}
void CheckForLegacyGlyphRenderMode()
{
// Special handling for legacy glyph render mode
if ((int)m_GlyphRenderMode < 0x100)
{
switch ((int)m_GlyphRenderMode)
{
case 0:
m_GlyphRenderMode = GlyphRenderMode.SMOOTH_HINTED;
break;
case 1:
m_GlyphRenderMode = GlyphRenderMode.SMOOTH;
break;
case 2:
m_GlyphRenderMode = GlyphRenderMode.RASTER_HINTED;
break;
case 3:
m_GlyphRenderMode = GlyphRenderMode.RASTER;
break;
case 6:
case 7:
m_GlyphRenderMode = GlyphRenderMode.SDFAA;
break;
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
FontFeatureTable GetAllFontFeatures()
{
FontFeatureTable fontFeatureTable = new FontFeatureTable();
PopulateGlyphAdjustmentTable(fontFeatureTable);
PopulateLigatureTable(fontFeatureTable);
PopulateDiacriticalMarkAdjustmentTables(fontFeatureTable);
return fontFeatureTable;
}
void PopulateGlyphAdjustmentTable(FontFeatureTable fontFeatureTable)
{
GlyphPairAdjustmentRecord[] adjustmentRecords = FontEngine.GetPairAdjustmentRecords(m_AvailableGlyphsToAdd);
if (adjustmentRecords == null)
return;
float emScale = (float)m_FaceInfo.pointSize / m_FaceInfo.unitsPerEM;
for (int i = 0; i < adjustmentRecords.Length && adjustmentRecords[i].firstAdjustmentRecord.glyphIndex != 0; i++)
{
GlyphPairAdjustmentRecord record = adjustmentRecords[i];
// Adjust values currently in Units per EM to make them relative to Sampling Point Size.
GlyphValueRecord valueRecord = record.firstAdjustmentRecord.glyphValueRecord;
valueRecord.xAdvance *= emScale;
GlyphPairAdjustmentRecord newRecord = new GlyphPairAdjustmentRecord { firstAdjustmentRecord = new GlyphAdjustmentRecord { glyphIndex = record.firstAdjustmentRecord.glyphIndex, glyphValueRecord = valueRecord }, secondAdjustmentRecord = record.secondAdjustmentRecord };
fontFeatureTable.glyphPairAdjustmentRecords.Add(newRecord);
}
fontFeatureTable.SortGlyphPairAdjustmentRecords();
}
void PopulateLigatureTable(FontFeatureTable fontFeatureTable)
{
UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord[] ligatureRecords = FontEngine.GetLigatureSubstitutionRecords(m_AvailableGlyphsToAdd);
if (ligatureRecords != null)
AddLigatureRecords(fontFeatureTable, ligatureRecords);
}
void AddLigatureRecords(FontFeatureTable fontFeatureTable, LigatureSubstitutionRecord[] records)
{
for (int i = 0; i < records.Length; i++)
{
LigatureSubstitutionRecord record = records[i];
if (records[i].componentGlyphIDs == null || records[i].ligatureGlyphID == 0)
return;
uint firstComponentGlyphIndex = record.componentGlyphIDs[0];
LigatureSubstitutionRecord newRecord = new LigatureSubstitutionRecord() { componentGlyphIDs = record.componentGlyphIDs, ligatureGlyphID = record.ligatureGlyphID };
// Add new record to lookup
if (!fontFeatureTable.m_LigatureSubstitutionRecordLookup.ContainsKey(firstComponentGlyphIndex))
{
fontFeatureTable.m_LigatureSubstitutionRecordLookup.Add(firstComponentGlyphIndex, new List<LigatureSubstitutionRecord> { newRecord });
}
else
{
fontFeatureTable.m_LigatureSubstitutionRecordLookup[firstComponentGlyphIndex].Add(newRecord);
}
fontFeatureTable.m_LigatureSubstitutionRecords.Add(newRecord);
}
}
void PopulateDiacriticalMarkAdjustmentTables(FontFeatureTable fontFeatureTable)
{
MarkToBaseAdjustmentRecord[] markToBaseRecords = FontEngine.GetMarkToBaseAdjustmentRecords(m_AvailableGlyphsToAdd);
if (markToBaseRecords != null)
AddMarkToBaseAdjustmentRecords(fontFeatureTable, markToBaseRecords);
MarkToMarkAdjustmentRecord[] markToMarkRecords = FontEngine.GetMarkToMarkAdjustmentRecords(m_AvailableGlyphsToAdd);
if (markToMarkRecords != null)
AddMarkToMarkAdjustmentRecords(fontFeatureTable, markToMarkRecords);
}
void AddMarkToBaseAdjustmentRecords(FontFeatureTable fontFeatureTable, MarkToBaseAdjustmentRecord[] records)
{
float emScale = (float)m_FaceInfo.pointSize / m_FaceInfo.unitsPerEM;
for (int i = 0; i < records.Length; i++)
{
MarkToBaseAdjustmentRecord record = records[i];
uint key = record.markGlyphID << 16 | record.baseGlyphID;
if (fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.ContainsKey(key))
continue;
MarkToBaseAdjustmentRecord newRecord = new MarkToBaseAdjustmentRecord {
baseGlyphID = record.baseGlyphID,
baseGlyphAnchorPoint = new GlyphAnchorPoint { xCoordinate = record.baseGlyphAnchorPoint.xCoordinate * emScale, yCoordinate = record.baseGlyphAnchorPoint.yCoordinate * emScale },
markGlyphID = record.markGlyphID,
markPositionAdjustment = new MarkPositionAdjustment { xPositionAdjustment = record.markPositionAdjustment.xPositionAdjustment * emScale, yPositionAdjustment = record.markPositionAdjustment.yPositionAdjustment * emScale } };
fontFeatureTable.MarkToBaseAdjustmentRecords.Add(newRecord);
fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.Add(key, newRecord);
}
}
void AddMarkToMarkAdjustmentRecords(FontFeatureTable fontFeatureTable, MarkToMarkAdjustmentRecord[] records)
{
float emScale = (float)m_FaceInfo.pointSize / m_FaceInfo.unitsPerEM;
for (int i = 0; i < records.Length; i++)
{
MarkToMarkAdjustmentRecord record = records[i];
uint key = record.combiningMarkGlyphID << 16 | record.baseMarkGlyphID;
if (fontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.ContainsKey(key))
continue;
MarkToMarkAdjustmentRecord newRecord = new MarkToMarkAdjustmentRecord {
baseMarkGlyphID = record.baseMarkGlyphID,
baseMarkGlyphAnchorPoint = new GlyphAnchorPoint { xCoordinate = record.baseMarkGlyphAnchorPoint.xCoordinate * emScale, yCoordinate = record.baseMarkGlyphAnchorPoint.yCoordinate * emScale},
combiningMarkGlyphID = record.combiningMarkGlyphID,
combiningMarkPositionAdjustment = new MarkPositionAdjustment { xPositionAdjustment = record.combiningMarkPositionAdjustment.xPositionAdjustment * emScale, yPositionAdjustment = record.combiningMarkPositionAdjustment.yPositionAdjustment * emScale } };
fontFeatureTable.MarkToMarkAdjustmentRecords.Add(newRecord);
fontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.Add(key, newRecord);
}
}
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetCreatorWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetCreatorWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 49974
} | 463 |
// 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.TextCore.Text;
using UnityEngine.TextCore.LowLevel;
namespace UnityEditor.TextCore.Text
{
class SerializedPropertyHolder : ScriptableObject
{
public FontAsset fontAsset;
public uint firstCharacter;
public uint secondCharacter;
public GlyphPairAdjustmentRecord glyphPairAdjustmentRecord = new GlyphPairAdjustmentRecord(new GlyphAdjustmentRecord(), new GlyphAdjustmentRecord());
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SerializedPropertyHolder.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SerializedPropertyHolder.cs",
"repo_id": "UnityCsReference",
"token_count": 196
} | 464 |
// 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.TextCore.Text;
using UnityEditorInternal;
using System.Collections.Generic;
namespace UnityEditor.TextCore.Text
{
[CustomEditor(typeof(SpriteAsset))]
internal class TextSpriteAssetEditor : Editor
{
struct UI_PanelState
{
public static bool spriteAssetFaceInfoPanel = true;
public static bool spriteAtlasInfoPanel = true;
public static bool fallbackSpriteAssetPanel = true;
public static bool spriteCharacterTablePanel;
public static bool spriteGlyphTablePanel;
}
private static string[] s_UiStateLabel = new string[] { "<i>(Click to collapse)</i> ", "<i>(Click to expand)</i> " };
int m_moveToIndex;
int m_selectedElement = -1;
bool m_isCharacterSelected = false;
bool m_isSpriteSelected = false;
int m_CurrentCharacterPage;
int m_CurrentGlyphPage;
const string k_UndoRedo = "UndoRedoPerformed";
string m_CharacterSearchPattern;
List<int> m_CharacterSearchList;
bool m_IsCharacterSearchDirty;
string m_GlyphSearchPattern;
List<int> m_GlyphSearchList;
bool m_IsGlyphSearchDirty;
SerializedProperty m_FaceInfoProperty;
SerializedProperty m_PointSizeProperty;
SerializedProperty m_ScaleProperty;
SerializedProperty m_LineHeightProperty;
SerializedProperty m_AscentLineProperty;
SerializedProperty m_BaselineProperty;
SerializedProperty m_DescentLineProperty;
SerializedProperty m_spriteAtlas_prop;
SerializedProperty m_material_prop;
SerializedProperty m_SpriteCharacterTableProperty;
SerializedProperty m_SpriteGlyphTableProperty;
ReorderableList m_fallbackSpriteAssetList;
SpriteAsset m_SpriteAsset;
bool isAssetDirty;
float m_xOffset;
float m_yOffset;
float m_xAdvance;
float m_scale;
public void OnEnable()
{
m_SpriteAsset = target as SpriteAsset;
m_FaceInfoProperty = serializedObject.FindProperty("m_FaceInfo");
m_PointSizeProperty = m_FaceInfoProperty.FindPropertyRelative("m_PointSize");
m_ScaleProperty = m_FaceInfoProperty.FindPropertyRelative("m_Scale");
m_LineHeightProperty = m_FaceInfoProperty.FindPropertyRelative("m_LineHeight");
m_AscentLineProperty = m_FaceInfoProperty.FindPropertyRelative("m_AscentLine");
m_BaselineProperty = m_FaceInfoProperty.FindPropertyRelative("m_Baseline");
m_DescentLineProperty = m_FaceInfoProperty.FindPropertyRelative("m_DescentLine");
m_spriteAtlas_prop = serializedObject.FindProperty("m_SpriteAtlasTexture");
m_material_prop = serializedObject.FindProperty("m_Material");
m_SpriteCharacterTableProperty = serializedObject.FindProperty("m_SpriteCharacterTable");
m_SpriteGlyphTableProperty = serializedObject.FindProperty("m_SpriteGlyphTable");
// Fallback TMP Sprite Asset list
m_fallbackSpriteAssetList = new ReorderableList(serializedObject, serializedObject.FindProperty("fallbackSpriteAssets"), true, true, true, true);
m_fallbackSpriteAssetList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
var element = m_fallbackSpriteAssetList.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none);
};
m_fallbackSpriteAssetList.drawHeaderCallback = rect =>
{
EditorGUI.LabelField(rect, new GUIContent("Fallback Sprite Asset List", "Select the Sprite Assets that will be searched and used as fallback when a given sprite is missing from this sprite asset."));
};
// Clear glyph proxy lookups
TextCorePropertyDrawerUtilities.ClearGlyphProxyLookups();
}
public override void OnInspectorGUI()
{
//Debug.Log("OnInspectorGUI Called.");
Event currentEvent = Event.current;
string evt_cmd = currentEvent.commandName; // Get Current Event CommandName to check for Undo Events
serializedObject.Update();
// TEXTMESHPRO SPRITE INFO PANEL
#region Display Sprite Asset Face Info
Rect rect = EditorGUILayout.GetControlRect(false, 24);
GUI.Label(rect, new GUIContent("<b>Face Info</b> - v" + m_SpriteAsset.version), TM_EditorStyles.sectionHeader);
rect.x += rect.width - 132f;
rect.y += 2;
rect.width = 130f;
rect.height = 18f;
if (GUI.Button(rect, new GUIContent("Update Sprite Asset")))
{
SpriteAssetCreationMenu.UpdateSpriteAsset(m_SpriteAsset);
}
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(m_PointSizeProperty);
EditorGUILayout.PropertyField(m_ScaleProperty);
//EditorGUILayout.PropertyField(m_LineHeightProperty);
EditorGUILayout.PropertyField(m_AscentLineProperty);
EditorGUILayout.PropertyField(m_BaselineProperty);
EditorGUILayout.PropertyField(m_DescentLineProperty);
EditorGUILayout.Space();
#endregion
// ATLAS TEXTURE & MATERIAL
#region Display Atlas Texture and Material
rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Atlas & Material</b>"), TM_EditorStyles.sectionHeader))
UI_PanelState.spriteAtlasInfoPanel = !UI_PanelState.spriteAtlasInfoPanel;
GUI.Label(rect, (UI_PanelState.spriteAtlasInfoPanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.spriteAtlasInfoPanel)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_spriteAtlas_prop, new GUIContent("Sprite Atlas"));
if (EditorGUI.EndChangeCheck())
{
// Assign the new sprite atlas texture to the current material
Texture2D tex = m_spriteAtlas_prop.objectReferenceValue as Texture2D;
if (tex != null)
{
Material mat = m_material_prop.objectReferenceValue as Material;
if (mat != null)
mat.mainTexture = tex;
}
}
EditorGUILayout.PropertyField(m_material_prop, new GUIContent("Default Material"));
EditorGUILayout.Space();
}
#endregion
// FALLBACK SPRITE ASSETS
#region Display Sprite Fallbacks
rect = EditorGUILayout.GetControlRect(false, 24);
EditorGUI.indentLevel = 0;
if (GUI.Button(rect, new GUIContent("<b>Fallback Sprite Assets</b>", "Select the Sprite Assets that will be searched and used as fallback when a given sprite is missing from this sprite asset."), TM_EditorStyles.sectionHeader))
UI_PanelState.fallbackSpriteAssetPanel = !UI_PanelState.fallbackSpriteAssetPanel;
GUI.Label(rect, (UI_PanelState.fallbackSpriteAssetPanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.fallbackSpriteAssetPanel)
{
m_fallbackSpriteAssetList.DoLayoutList();
EditorGUILayout.Space();
}
#endregion
// SPRITE CHARACTER TABLE
#region Display Sprite Character Table
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Sprite Character Table</b>", "List of sprite characters contained in this sprite asset."), TM_EditorStyles.sectionHeader))
UI_PanelState.spriteCharacterTablePanel = !UI_PanelState.spriteCharacterTablePanel;
GUI.Label(rect, (UI_PanelState.spriteCharacterTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.spriteCharacterTablePanel)
{
int arraySize = m_SpriteCharacterTableProperty.arraySize;
int itemsPerPage = 10;
// Display Glyph Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.ExpandWidth(true));
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 110f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Sprite Search", m_CharacterSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_IsCharacterSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
//GUIUtility.keyboardControl = 0;
m_CharacterSearchPattern = searchPattern.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim();
// Search Glyph Table for potential matches
SearchCharacterTable(m_CharacterSearchPattern, ref m_CharacterSearchList);
}
else
m_CharacterSearchPattern = null;
m_IsCharacterSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_CharacterSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_CharacterSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_CharacterSearchPattern))
arraySize = m_CharacterSearchList.Count;
// Display Page Navigation
DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
if (arraySize > 0)
{
// Display each SpriteInfo entry using the SpriteInfo property drawer.
for (int i = itemsPerPage * m_CurrentCharacterPage; i < arraySize && i < itemsPerPage * (m_CurrentCharacterPage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_CharacterSearchPattern))
elementIndex = m_CharacterSearchList[i];
SerializedProperty spriteCharacterProperty = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
EditorGUI.BeginDisabledGroup(i != m_selectedElement || !m_isCharacterSelected);
{
EditorGUILayout.PropertyField(spriteCharacterProperty);
}
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_selectedElement == i)
{
m_selectedElement = -1;
m_isCharacterSelected = false;
}
else
{
m_selectedElement = i;
m_isCharacterSelected = true;
m_isSpriteSelected = false;
GUIUtility.keyboardControl = 0;
}
}
// Draw & Handle Section Area
if (m_selectedElement == i && m_isCharacterSelected)
{
// Draw selection highlight
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw options to MoveUp, MoveDown, Add or Remove Sprites
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
controlRect.width /= 8;
// Move sprite up.
bool guiEnabled = GUI.enabled;
if (i == 0) { GUI.enabled = false; }
if (GUI.Button(controlRect, "Up"))
{
SwapCharacterElements(i, i - 1);
}
GUI.enabled = guiEnabled;
// Move sprite down.
controlRect.x += controlRect.width;
if (i == arraySize - 1) { GUI.enabled = false; }
if (GUI.Button(controlRect, "Down"))
{
SwapCharacterElements(i, i + 1);
}
GUI.enabled = guiEnabled;
// Move sprite to new index
controlRect.x += controlRect.width * 2;
//if (i == arraySize - 1) { GUI.enabled = false; }
m_moveToIndex = EditorGUI.IntField(controlRect, m_moveToIndex);
controlRect.x -= controlRect.width;
if (GUI.Button(controlRect, "Goto"))
{
MoveCharacterToIndex(i, m_moveToIndex);
}
//controlRect.x += controlRect.width;
GUI.enabled = guiEnabled;
// Add new Sprite
controlRect.x += controlRect.width * 4;
if (GUI.Button(controlRect, "+"))
{
m_SpriteCharacterTableProperty.arraySize += 1;
int index = m_SpriteCharacterTableProperty.arraySize - 1;
SerializedProperty spriteInfo_prop = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(index);
// Copy properties of the selected element
CopyCharacterSerializedProperty(m_SpriteCharacterTableProperty.GetArrayElementAtIndex(elementIndex), ref spriteInfo_prop);
//spriteInfo_prop.FindPropertyRelative("m_Index").intValue = index;
serializedObject.ApplyModifiedProperties();
m_IsCharacterSearchDirty = true;
}
// Delete selected Sprite
controlRect.x += controlRect.width;
if (m_selectedElement == -1) GUI.enabled = false;
if (GUI.Button(controlRect, "-"))
{
m_SpriteCharacterTableProperty.DeleteArrayElementAtIndex(elementIndex);
m_selectedElement = -1;
serializedObject.ApplyModifiedProperties();
m_IsCharacterSearchDirty = true;
return;
}
}
}
}
DisplayPageNavigation(ref m_CurrentCharacterPage, arraySize, itemsPerPage);
EditorGUIUtility.labelWidth = 40f;
EditorGUIUtility.fieldWidth = 20f;
GUILayout.Space(5f);
// GLOBAL TOOLS
#region Global Tools
/*
GUI.enabled = true;
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
rect = EditorGUILayout.GetControlRect(false, 40);
float width = (rect.width - 75f) / 4;
EditorGUI.LabelField(rect, "Global Offsets & Scale", EditorStyles.boldLabel);
rect.x += 70;
bool old_ChangedState = GUI.changed;
GUI.changed = false;
m_xOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 0, rect.y + 20, width - 5f, 18), new GUIContent("OX:"), m_xOffset);
if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingX", m_xOffset);
m_yOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 1, rect.y + 20, width - 5f, 18), new GUIContent("OY:"), m_yOffset);
if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingY", m_yOffset);
m_xAdvance = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 2, rect.y + 20, width - 5f, 18), new GUIContent("ADV."), m_xAdvance);
if (GUI.changed) UpdateGlobalProperty("m_HorizontalAdvance", m_xAdvance);
m_scale = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 3, rect.y + 20, width - 5f, 18), new GUIContent("SF."), m_scale);
if (GUI.changed) UpdateGlobalProperty("m_Scale", m_scale);
EditorGUILayout.EndVertical();
GUI.changed = old_ChangedState;
*/
#endregion
}
#endregion
// SPRITE GLYPH TABLE
#region Display Sprite Glyph Table
EditorGUI.indentLevel = 0;
rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Sprite Glyph Table</b>", "A list of the SpriteGlyphs contained in this sprite asset."), TM_EditorStyles.sectionHeader))
UI_PanelState.spriteGlyphTablePanel = !UI_PanelState.spriteGlyphTablePanel;
GUI.Label(rect, (UI_PanelState.spriteGlyphTablePanel ? "" : s_UiStateLabel[1]), TM_EditorStyles.rightLabel);
if (UI_PanelState.spriteGlyphTablePanel)
{
int arraySize = m_SpriteGlyphTableProperty.arraySize;
int itemsPerPage = 10;
// Display Glyph Management Tools
EditorGUILayout.BeginVertical(EditorStyles.helpBox, GUILayout.ExpandWidth(true));
{
// Search Bar implementation
#region DISPLAY SEARCH BAR
EditorGUILayout.BeginHorizontal();
{
EditorGUIUtility.labelWidth = 110f;
EditorGUI.BeginChangeCheck();
string searchPattern = EditorGUILayout.TextField("Sprite Search", m_GlyphSearchPattern, "SearchTextField");
if (EditorGUI.EndChangeCheck() || m_IsGlyphSearchDirty)
{
if (string.IsNullOrEmpty(searchPattern) == false)
{
//GUIUtility.keyboardControl = 0;
m_GlyphSearchPattern = searchPattern.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim();
// Search Glyph Table for potential matches
SearchCharacterTable(m_GlyphSearchPattern, ref m_GlyphSearchList);
}
else
m_GlyphSearchPattern = null;
m_IsGlyphSearchDirty = false;
}
string styleName = string.IsNullOrEmpty(m_GlyphSearchPattern) ? "SearchCancelButtonEmpty" : "SearchCancelButton";
if (GUILayout.Button(GUIContent.none, styleName))
{
GUIUtility.keyboardControl = 0;
m_GlyphSearchPattern = string.Empty;
}
}
EditorGUILayout.EndHorizontal();
#endregion
// Display Page Navigation
if (!string.IsNullOrEmpty(m_GlyphSearchPattern))
arraySize = m_GlyphSearchList.Count;
// Display Page Navigation
DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage);
}
EditorGUILayout.EndVertical();
if (arraySize > 0)
{
// Display each SpriteInfo entry using the SpriteInfo property drawer.
for (int i = itemsPerPage * m_CurrentGlyphPage; i < arraySize && i < itemsPerPage * (m_CurrentGlyphPage + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
int elementIndex = i;
if (!string.IsNullOrEmpty(m_GlyphSearchPattern))
elementIndex = m_GlyphSearchList[i];
SerializedProperty spriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(elementIndex);
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
{
EditorGUI.BeginDisabledGroup(i != m_selectedElement || !m_isSpriteSelected);
{
EditorGUILayout.PropertyField(spriteGlyphProperty);
}
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.EndVertical();
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_selectedElement == i)
{
m_selectedElement = -1;
m_isSpriteSelected = false;
}
else
{
m_selectedElement = i;
m_isCharacterSelected = false;
m_isSpriteSelected = true;
GUIUtility.keyboardControl = 0;
}
}
// Draw & Handle Section Area
if (m_selectedElement == i && m_isSpriteSelected)
{
// Draw selection highlight
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
// Draw options to MoveUp, MoveDown, Add or Remove Sprites
Rect controlRect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight * 1f);
controlRect.width /= 8;
// Move sprite up.
bool guiEnabled = GUI.enabled;
if (i == 0) { GUI.enabled = false; }
if (GUI.Button(controlRect, "Up"))
{
SwapGlyphElements(i, i - 1);
}
GUI.enabled = guiEnabled;
// Move sprite down.
controlRect.x += controlRect.width;
if (i == arraySize - 1) { GUI.enabled = false; }
if (GUI.Button(controlRect, "Down"))
{
SwapGlyphElements(i, i + 1);
}
GUI.enabled = guiEnabled;
// Move sprite to new index
controlRect.x += controlRect.width * 2;
//if (i == arraySize - 1) { GUI.enabled = false; }
m_moveToIndex = EditorGUI.IntField(controlRect, m_moveToIndex);
controlRect.x -= controlRect.width;
if (GUI.Button(controlRect, "Goto"))
{
MoveGlyphToIndex(i, m_moveToIndex);
}
//controlRect.x += controlRect.width;
GUI.enabled = guiEnabled;
// Add new Sprite
controlRect.x += controlRect.width * 4;
if (GUI.Button(controlRect, "+"))
{
m_SpriteGlyphTableProperty.arraySize += 1;
int index = m_SpriteGlyphTableProperty.arraySize - 1;
SerializedProperty newSpriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(index);
// Copy properties of the selected element
CopyGlyphSerializedProperty(m_SpriteGlyphTableProperty.GetArrayElementAtIndex(elementIndex), ref newSpriteGlyphProperty);
newSpriteGlyphProperty.FindPropertyRelative("m_Index").intValue = index;
serializedObject.ApplyModifiedProperties();
m_IsGlyphSearchDirty = true;
//m_SpriteAsset.UpdateLookupTables();
}
// Delete selected Sprite
controlRect.x += controlRect.width;
if (m_selectedElement == -1) GUI.enabled = false;
if (GUI.Button(controlRect, "-"))
{
SerializedProperty selectedSpriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(elementIndex);
int selectedGlyphIndex = selectedSpriteGlyphProperty.FindPropertyRelative("m_Index").intValue;
m_SpriteGlyphTableProperty.DeleteArrayElementAtIndex(elementIndex);
// Remove all Sprite Characters referencing this glyph.
for (int j = 0; j < m_SpriteCharacterTableProperty.arraySize; j++)
{
int glyphIndex = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(j).FindPropertyRelative("m_GlyphIndex").intValue;
if (glyphIndex == selectedGlyphIndex)
{
// Remove character
m_SpriteCharacterTableProperty.DeleteArrayElementAtIndex(j);
}
}
m_selectedElement = -1;
serializedObject.ApplyModifiedProperties();
m_IsGlyphSearchDirty = true;
//m_SpriteAsset.UpdateLookupTables();
return;
}
}
}
}
DisplayPageNavigation(ref m_CurrentGlyphPage, arraySize, itemsPerPage);
EditorGUIUtility.labelWidth = 40f;
EditorGUIUtility.fieldWidth = 20f;
GUILayout.Space(5f);
// GLOBAL TOOLS
#region Global Tools
GUI.enabled = true;
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
rect = EditorGUILayout.GetControlRect(false, 40);
float width = (rect.width - 75f) / 4;
EditorGUI.LabelField(rect, "Global Offsets & Scale", EditorStyles.boldLabel);
rect.x += 70;
bool old_ChangedState = GUI.changed;
GUI.changed = false;
m_xOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 0, rect.y + 20, width - 5f, 18), new GUIContent("OX:"), m_xOffset);
if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingX", m_xOffset);
m_yOffset = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 1, rect.y + 20, width - 5f, 18), new GUIContent("OY:"), m_yOffset);
if (GUI.changed) UpdateGlobalProperty("m_HorizontalBearingY", m_yOffset);
m_xAdvance = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 2, rect.y + 20, width - 5f, 18), new GUIContent("ADV."), m_xAdvance);
if (GUI.changed) UpdateGlobalProperty("m_HorizontalAdvance", m_xAdvance);
m_scale = EditorGUI.FloatField(new Rect(rect.x + 5f + width * 3, rect.y + 20, width - 5f, 18), new GUIContent("SF."), m_scale);
if (GUI.changed) UpdateGlobalProperty("m_Scale", m_scale);
EditorGUILayout.EndVertical();
#endregion
GUI.changed = old_ChangedState;
}
#endregion
if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo || isAssetDirty)
{
if (m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty || evt_cmd == k_UndoRedo)
{
m_SpriteAsset.UpdateLookupTables();
TextResourceManager.RebuildFontAssetCache();
}
TextEventManager.ON_SPRITE_ASSET_PROPERTY_CHANGED(true, m_SpriteAsset);
isAssetDirty = false;
EditorUtility.SetDirty(target);
}
// Clear selection if mouse event was not consumed.
GUI.enabled = true;
if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
m_selectedElement = -1;
}
/// <summary>
///
/// </summary>
/// <param name="arraySize"></param>
/// <param name="itemsPerPage"></param>
void DisplayPageNavigation(ref int currentPage, int arraySize, int itemsPerPage)
{
Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
pagePos.width /= 3;
int shiftMultiplier = Event.current.shift ? 10 : 1; // Page + Shift goes 10 page forward
// Previous Page
GUI.enabled = currentPage > 0;
if (GUI.Button(pagePos, "Previous Page"))
{
currentPage -= 1 * shiftMultiplier;
//m_isNewPage = true;
}
// Page Counter
GUI.enabled = true;
pagePos.x += pagePos.width;
int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
GUI.Label(pagePos, "Page " + (currentPage + 1) + " / " + totalPages, TM_EditorStyles.centeredLabel);
// Next Page
pagePos.x += pagePos.width;
GUI.enabled = itemsPerPage * (currentPage + 1) < arraySize;
if (GUI.Button(pagePos, "Next Page"))
{
currentPage += 1 * shiftMultiplier;
//m_isNewPage = true;
}
// Clamp page range
currentPage = Mathf.Clamp(currentPage, 0, arraySize / itemsPerPage);
GUI.enabled = true;
}
/// <summary>
/// Method to update the properties of all sprites
/// </summary>
/// <param name="property"></param>
/// <param name="value"></param>
void UpdateGlobalProperty(string property, float value)
{
int arraySize = m_SpriteGlyphTableProperty.arraySize;
for (int i = 0; i < arraySize; i++)
{
// Get a reference to the sprite glyph.
SerializedProperty spriteGlyphProperty = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(i);
if (property == "m_Scale")
{
spriteGlyphProperty.FindPropertyRelative(property).floatValue = value;
}
else
{
SerializedProperty glyphMetricsProperty = spriteGlyphProperty.FindPropertyRelative("m_Metrics");
glyphMetricsProperty.FindPropertyRelative(property).floatValue = value;
}
}
GUI.changed = false;
}
// Check if any of the Style elements were clicked on.
private bool DoSelectionCheck(Rect selectionArea)
{
Event currentEvent = Event.current;
switch (currentEvent.type)
{
case EventType.MouseDown:
if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0)
{
currentEvent.Use();
return true;
}
break;
}
return false;
}
/// <summary>
/// Swap the sprite item at the currently selected array index to another index.
/// </summary>
/// <param name="selectedIndex">Selected index.</param>
/// <param name="newIndex">New index.</param>
void SwapCharacterElements(int selectedIndex, int newIndex)
{
m_SpriteCharacterTableProperty.MoveArrayElement(selectedIndex, newIndex);
m_selectedElement = newIndex;
m_IsCharacterSearchDirty = true;
m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
}
/// <summary>
/// Move Sprite Element at selected index to another index and reorder sprite list.
/// </summary>
/// <param name="selectedIndex"></param>
/// <param name="newIndex"></param>
void MoveCharacterToIndex(int selectedIndex, int newIndex)
{
int arraySize = m_SpriteCharacterTableProperty.arraySize;
if (newIndex >= arraySize)
newIndex = arraySize - 1;
m_SpriteCharacterTableProperty.MoveArrayElement(selectedIndex, newIndex);
m_selectedElement = newIndex;
m_IsCharacterSearchDirty = true;
m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
// TODO: Need to handle switching pages if the character or glyph is moved to a different page.
}
/// <summary>
///
/// </summary>
/// <param name="selectedIndex"></param>
/// <param name="newIndex"></param>
void SwapGlyphElements(int selectedIndex, int newIndex)
{
m_SpriteGlyphTableProperty.MoveArrayElement(selectedIndex, newIndex);
m_selectedElement = newIndex;
m_IsGlyphSearchDirty = true;
m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
}
/// <summary>
/// Move Sprite Element at selected index to another index and reorder sprite list.
/// </summary>
/// <param name="selectedIndex"></param>
/// <param name="newIndex"></param>
void MoveGlyphToIndex(int selectedIndex, int newIndex)
{
int arraySize = m_SpriteGlyphTableProperty.arraySize;
if (newIndex >= arraySize)
newIndex = arraySize - 1;
m_SpriteGlyphTableProperty.MoveArrayElement(selectedIndex, newIndex);
m_selectedElement = newIndex;
m_IsGlyphSearchDirty = true;
m_SpriteAsset.m_IsSpriteAssetLookupTablesDirty = true;
// TODO: Need to handle switching pages if the character or glyph is moved to a different page.
}
/// <summary>
///
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
void CopyCharacterSerializedProperty(SerializedProperty source, ref SerializedProperty target)
{
target.FindPropertyRelative("m_Name").stringValue = source.FindPropertyRelative("m_Name").stringValue;
target.FindPropertyRelative("m_Unicode").intValue = source.FindPropertyRelative("m_Unicode").intValue;
target.FindPropertyRelative("m_GlyphIndex").intValue = source.FindPropertyRelative("m_GlyphIndex").intValue;
target.FindPropertyRelative("m_Scale").floatValue = source.FindPropertyRelative("m_Scale").floatValue;
}
void CopyGlyphSerializedProperty(SerializedProperty srcGlyph, ref SerializedProperty dstGlyph)
{
// TODO : Should make a generic function which copies each of the properties.
// Index
dstGlyph.FindPropertyRelative("m_Index").intValue = srcGlyph.FindPropertyRelative("m_Index").intValue;
// GlyphMetrics
SerializedProperty srcGlyphMetrics = srcGlyph.FindPropertyRelative("m_Metrics");
SerializedProperty dstGlyphMetrics = dstGlyph.FindPropertyRelative("m_Metrics");
dstGlyphMetrics.FindPropertyRelative("m_Width").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Width").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_Height").floatValue = srcGlyphMetrics.FindPropertyRelative("m_Height").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingX").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalBearingY").floatValue;
dstGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue = srcGlyphMetrics.FindPropertyRelative("m_HorizontalAdvance").floatValue;
// GlyphRect
SerializedProperty srcGlyphRect = srcGlyph.FindPropertyRelative("m_GlyphRect");
SerializedProperty dstGlyphRect = dstGlyph.FindPropertyRelative("m_GlyphRect");
dstGlyphRect.FindPropertyRelative("m_X").intValue = srcGlyphRect.FindPropertyRelative("m_X").intValue;
dstGlyphRect.FindPropertyRelative("m_Y").intValue = srcGlyphRect.FindPropertyRelative("m_Y").intValue;
dstGlyphRect.FindPropertyRelative("m_Width").intValue = srcGlyphRect.FindPropertyRelative("m_Width").intValue;
dstGlyphRect.FindPropertyRelative("m_Height").intValue = srcGlyphRect.FindPropertyRelative("m_Height").intValue;
dstGlyph.FindPropertyRelative("m_Scale").floatValue = srcGlyph.FindPropertyRelative("m_Scale").floatValue;
dstGlyph.FindPropertyRelative("m_AtlasIndex").intValue = srcGlyph.FindPropertyRelative("m_AtlasIndex").intValue;
}
/// <summary>
///
/// </summary>
/// <param name="searchPattern"></param>
/// <returns></returns>
void SearchCharacterTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
int arraySize = m_SpriteCharacterTableProperty.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty sourceSprite = m_SpriteCharacterTableProperty.GetArrayElementAtIndex(i);
// Check for potential match against array index
if (i.ToString().Contains(searchPattern))
{
searchResults.Add(i);
continue;
}
// Check for potential match against decimal id
int id = sourceSprite.FindPropertyRelative("m_GlyphIndex").intValue;
if (id.ToString().Contains(searchPattern))
{
searchResults.Add(i);
continue;
}
// Check for potential match against name
string name = sourceSprite.FindPropertyRelative("m_Name").stringValue.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim();
if (name.Contains(searchPattern))
{
searchResults.Add(i);
continue;
}
}
}
void SearchGlyphTable(string searchPattern, ref List<int> searchResults)
{
if (searchResults == null) searchResults = new List<int>();
searchResults.Clear();
int arraySize = m_SpriteGlyphTableProperty.arraySize;
for (int i = 0; i < arraySize; i++)
{
SerializedProperty sourceSprite = m_SpriteGlyphTableProperty.GetArrayElementAtIndex(i);
// Check for potential match against array index
if (i.ToString().Contains(searchPattern))
{
searchResults.Add(i);
continue;
}
// Check for potential match against decimal id
int id = sourceSprite.FindPropertyRelative("m_GlyphIndex").intValue;
if (id.ToString().Contains(searchPattern))
{
searchResults.Add(i);
continue;
}
// Check for potential match against name
string name = sourceSprite.FindPropertyRelative("m_Name").stringValue.ToLower(System.Globalization.CultureInfo.InvariantCulture).Trim();
if (name.Contains(searchPattern))
{
searchResults.Add(i);
continue;
}
}
}
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextSpriteAssetEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextSpriteAssetEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 22509
} | 465 |
// 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 System;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using UnityEngine.U2D;
namespace UnityEngine.Tilemaps
{
[Flags]
public enum TileFlags
{
None = 0,
LockColor = 1 << 0,
LockTransform = 1 << 1,
InstantiateGameObjectRuntimeOnly = 1 << 2,
KeepGameObjectRuntimeOnly = 1 << 3,
LockAll = LockColor | LockTransform,
}
[Flags]
public enum TileAnimationFlags
{
None = 0,
LoopOnce = 1 << 0,
PauseAnimation = 1 << 1,
UpdatePhysics = 1 << 2,
UnscaledTime = 1 << 3,
}
[RequireComponent(typeof(Transform))]
[NativeHeader("Modules/Grid/Public/GridMarshalling.h")]
[NativeHeader("Modules/Grid/Public/Grid.h")]
[NativeHeader("Runtime/Graphics/SpriteFrame.h")]
[NativeHeader("Modules/Tilemap/Public/TilemapTile.h")]
[NativeHeader("Modules/Tilemap/Public/TilemapMarshalling.h")]
[NativeType(Header = "Modules/Tilemap/Public/Tilemap.h")]
public sealed partial class Tilemap : GridLayout
{
public enum Orientation
{
XY = 0,
XZ = 1,
YX = 2,
YZ = 3,
ZX = 4,
ZY = 5,
Custom = 6,
}
public extern Grid layoutGrid
{
[NativeMethod(Name = "GetAttachedGrid")]
get;
}
public Vector3 GetCellCenterLocal(Vector3Int position) { return CellToLocalInterpolated(position) + CellToLocalInterpolated(tileAnchor); }
public Vector3 GetCellCenterWorld(Vector3Int position) { return LocalToWorld(CellToLocalInterpolated(position) + CellToLocalInterpolated(tileAnchor)); }
public BoundsInt cellBounds
{
get
{
return new BoundsInt(origin, size);
}
}
[NativeProperty("TilemapBoundsScripting")]
public extern Bounds localBounds
{
get;
}
[NativeProperty("TilemapFrameBoundsScripting")]
internal extern Bounds localFrameBounds
{
get;
}
public extern float animationFrameRate
{
get;
set;
}
public extern Color color
{
get;
set;
}
public extern Vector3Int origin
{
get;
set;
}
public extern Vector3Int size
{
get;
set;
}
[NativeProperty(Name = "TileAnchorScripting")]
public extern Vector3 tileAnchor
{
get;
set;
}
public extern Orientation orientation
{
get;
set;
}
public extern Matrix4x4 orientationMatrix
{
[NativeMethod(Name = "GetTileOrientationMatrix")]
get;
[NativeMethod(Name = "SetOrientationMatrix")]
set;
}
internal extern Object GetTileAsset(Vector3Int position);
public TileBase GetTile(Vector3Int position) { return GetTileAsset(position) as TileBase; }
public T GetTile<T>(Vector3Int position) where T : TileBase { return GetTileAsset(position) as T; }
internal extern Object[] GetTileAssetsBlock(Vector3Int position, Vector3Int blockDimensions);
public TileBase[] GetTilesBlock(BoundsInt bounds)
{
var array = GetTileAssetsBlock(bounds.min, bounds.size);
var tiles = new TileBase[array.Length];
for (int i = 0; i < array.Length; ++i)
{
tiles[i] = (TileBase)array[i];
}
return tiles;
}
[FreeFunction(Name = "TilemapBindings::GetTileAssetsBlockNonAlloc", HasExplicitThis = true)]
internal extern int GetTileAssetsBlockNonAlloc(Vector3Int startPosition, Vector3Int endPosition, [Unmarshalled] Object[] tiles);
public int GetTilesBlockNonAlloc(BoundsInt bounds, TileBase[] tiles)
{
return GetTileAssetsBlockNonAlloc(bounds.min, bounds.size, tiles);
}
public extern int GetTilesRangeCount(Vector3Int startPosition, Vector3Int endPosition);
[FreeFunction(Name = "TilemapBindings::GetTileAssetsRangeNonAlloc", HasExplicitThis = true)]
internal extern int GetTileAssetsRangeNonAlloc(Vector3Int startPosition, Vector3Int endPosition, Vector3Int[] positions, [Unmarshalled] Object[] tiles);
public int GetTilesRangeNonAlloc(Vector3Int startPosition, Vector3Int endPosition, Vector3Int[] positions, TileBase[] tiles)
{
return GetTileAssetsRangeNonAlloc(startPosition, endPosition, positions, tiles);
}
internal extern void SetTileAsset(Vector3Int position, Object tile);
public void SetTile(Vector3Int position, TileBase tile) { SetTileAsset(position, tile); }
internal extern void SetTileAssets(Vector3Int[] positionArray, Object[] tileArray);
public void SetTiles(Vector3Int[] positionArray, TileBase[] tileArray) { SetTileAssets(positionArray, tileArray); }
[NativeMethod(Name = "SetTileAssetsBlock")]
private extern void INTERNAL_CALL_SetTileAssetsBlock(Vector3Int position, Vector3Int blockDimensions, Object[] tileArray);
public void SetTilesBlock(BoundsInt position, TileBase[] tileArray) { INTERNAL_CALL_SetTileAssetsBlock(position.min, position.size, tileArray); }
[NativeMethod(Name = "SetTileChangeData")]
public extern void SetTile(TileChangeData tileChangeData, bool ignoreLockFlags);
[NativeMethod(Name = "SetTileChangeDataArray")]
public extern void SetTiles(TileChangeData[] tileChangeDataArray, bool ignoreLockFlags);
public bool HasTile(Vector3Int position)
{
return GetTileAsset(position) != null;
}
[NativeMethod(Name = "RefreshTileAsset")]
public extern void RefreshTile(Vector3Int position);
[FreeFunction(Name = "TilemapBindings::RefreshTileAssetsNative", HasExplicitThis = true)]
internal extern unsafe void RefreshTilesNative(void* positions, int count);
[NativeMethod(Name = "RefreshAllTileAssets")]
public extern void RefreshAllTiles();
internal extern void SwapTileAsset(Object changeTile, Object newTile);
public void SwapTile(TileBase changeTile, TileBase newTile) { SwapTileAsset(changeTile, newTile); }
internal extern bool ContainsTileAsset(Object tileAsset);
public bool ContainsTile(TileBase tileAsset) { return ContainsTileAsset(tileAsset); }
public extern int GetUsedTilesCount();
public extern int GetUsedSpritesCount();
public int GetUsedTilesNonAlloc(TileBase[] usedTiles)
{
return Internal_GetUsedTilesNonAlloc(usedTiles);
}
public int GetUsedSpritesNonAlloc(Sprite[] usedSprites)
{
return Internal_GetUsedSpritesNonAlloc(usedSprites);
}
[FreeFunction(Name = "TilemapBindings::GetUsedTilesNonAlloc", HasExplicitThis = true)]
internal extern int Internal_GetUsedTilesNonAlloc([Unmarshalled] Object[] usedTiles);
[FreeFunction(Name = "TilemapBindings::GetUsedSpritesNonAlloc", HasExplicitThis = true)]
internal extern int Internal_GetUsedSpritesNonAlloc([Unmarshalled] Object[] usedSprites);
public extern Sprite GetSprite(Vector3Int position);
public extern Matrix4x4 GetTransformMatrix(Vector3Int position);
public extern void SetTransformMatrix(Vector3Int position, Matrix4x4 transform);
[NativeMethod(Name = "GetTileColor")]
public extern Color GetColor(Vector3Int position);
[NativeMethod(Name = "SetTileColor")]
public extern void SetColor(Vector3Int position, Color color);
public extern TileFlags GetTileFlags(Vector3Int position);
public extern void SetTileFlags(Vector3Int position, TileFlags flags);
public extern void AddTileFlags(Vector3Int position, TileFlags flags);
public extern void RemoveTileFlags(Vector3Int position, TileFlags flags);
[NativeMethod(Name = "GetTileInstantiatedObject")]
public extern GameObject GetInstantiatedObject(Vector3Int position);
[NativeMethod(Name = "GetTileObjectToInstantiate")]
public extern GameObject GetObjectToInstantiate(Vector3Int position);
[NativeMethod(Name = "SetTileColliderType")]
public extern void SetColliderType(Vector3Int position, Tile.ColliderType colliderType);
[NativeMethod(Name = "GetTileColliderType")]
public extern Tile.ColliderType GetColliderType(Vector3Int position);
[NativeMethod(Name = "GetTileAnimationFrameCount")]
public extern int GetAnimationFrameCount(Vector3Int position);
[NativeMethod(Name = "GetTileAnimationFrame")]
public extern int GetAnimationFrame(Vector3Int position);
[NativeMethod(Name = "SetTileAnimationFrame")]
public extern void SetAnimationFrame(Vector3Int position, int frame);
[NativeMethod(Name = "GetTileAnimationTime")]
public extern float GetAnimationTime(Vector3Int position);
[NativeMethod(Name = "SetTileAnimationTime")]
public extern void SetAnimationTime(Vector3Int position, float time);
public extern TileAnimationFlags GetTileAnimationFlags(Vector3Int position);
public extern void SetTileAnimationFlags(Vector3Int position, TileAnimationFlags flags);
public extern void AddTileAnimationFlags(Vector3Int position, TileAnimationFlags flags);
public extern void RemoveTileAnimationFlags(Vector3Int position, TileAnimationFlags flags);
public void FloodFill(Vector3Int position, TileBase tile)
{
FloodFillTileAsset(position, tile);
}
[NativeMethod(Name = "FloodFill")]
private extern void FloodFillTileAsset(Vector3Int position, Object tile);
public void BoxFill(Vector3Int position, TileBase tile, int startX, int startY, int endX, int endY)
{
BoxFillTileAsset(position, tile, startX, startY, endX, endY);
}
[NativeMethod(Name = "BoxFill")]
private extern void BoxFillTileAsset(Vector3Int position, Object tile, int startX, int startY, int endX, int endY);
public void InsertCells(Vector3Int position, Vector3Int insertCells)
{
InsertCells(position, insertCells.x, insertCells.y, insertCells.z);
}
public extern void InsertCells(Vector3Int position, int numColumns, int numRows, int numLayers);
public void DeleteCells(Vector3Int position, Vector3Int deleteCells)
{
DeleteCells(position, deleteCells.x, deleteCells.y, deleteCells.z);
}
public extern void DeleteCells(Vector3Int position, int numColumns, int numRows, int numLayers);
public extern void ClearAllTiles();
public extern void ResizeBounds();
public extern void CompressBounds();
public extern Vector3Int editorPreviewOrigin
{
[NativeMethod(Name = "GetRenderOrigin")]
get;
}
public extern Vector3Int editorPreviewSize
{
[NativeMethod(Name = "GetRenderSize")]
get;
}
internal extern Object GetAnyTileAsset(Vector3Int position);
internal TileBase GetAnyTile(Vector3Int position) { return GetAnyTileAsset(position) as TileBase; }
internal T GetAnyTile<T>(Vector3Int position) where T : TileBase { return GetAnyTile(position) as T; }
internal extern Object GetEditorPreviewTileAsset(Vector3Int position);
public TileBase GetEditorPreviewTile(Vector3Int position) { return GetEditorPreviewTileAsset(position) as TileBase; }
public T GetEditorPreviewTile<T>(Vector3Int position) where T : TileBase { return GetEditorPreviewTile(position) as T; }
internal extern void SetEditorPreviewTileAsset(Vector3Int position, Object tile);
public void SetEditorPreviewTile(Vector3Int position, TileBase tile) { SetEditorPreviewTileAsset(position, tile); }
public bool HasEditorPreviewTile(Vector3Int position)
{
return GetEditorPreviewTileAsset(position) != null;
}
public extern Sprite GetEditorPreviewSprite(Vector3Int position);
public extern Matrix4x4 GetEditorPreviewTransformMatrix(Vector3Int position);
public extern void SetEditorPreviewTransformMatrix(Vector3Int position, Matrix4x4 transform);
[NativeMethod(Name = "GetEditorPreviewTileColor")]
public extern Color GetEditorPreviewColor(Vector3Int position);
[NativeMethod(Name = "SetEditorPreviewTileColor")]
public extern void SetEditorPreviewColor(Vector3Int position, Color color);
public extern TileFlags GetEditorPreviewTileFlags(Vector3Int position);
public void EditorPreviewFloodFill(Vector3Int position, TileBase tile)
{
EditorPreviewFloodFillTileAsset(position, tile);
}
[NativeMethod(Name = "EditorPreviewFloodFill")]
private extern void EditorPreviewFloodFillTileAsset(Vector3Int position, Object tile);
public void EditorPreviewBoxFill(Vector3Int position, Object tile, int startX, int startY, int endX, int endY)
{
EditorPreviewBoxFillTileAsset(position, tile, startX, startY, endX, endY);
}
[NativeMethod(Name = "EditorPreviewBoxFill")]
private extern void EditorPreviewBoxFillTileAsset(Vector3Int position, Object tile, int startX, int startY, int endX, int endY);
[NativeMethod(Name = "ClearAllEditorPreviewTileAssets")]
public extern void ClearAllEditorPreviewTiles();
[RequiredByNativeCode]
internal void GetLoopEndedForTileAnimationCallbackSettings(ref bool hasEndLoopForTileAnimationCallback)
{
hasEndLoopForTileAnimationCallback = HasLoopEndedForTileAnimationCallback();
}
[RequiredByNativeCode]
private void DoLoopEndedForTileAnimationCallback(int count, IntPtr positionsIntPtr)
{
HandleLoopEndedForTileAnimationCallback(count, positionsIntPtr);
}
[RequiredByNativeCode]
public struct SyncTile
{
internal Vector3Int m_Position;
internal TileBase m_Tile;
internal TileData m_TileData;
public Vector3Int position
{
get { return m_Position; }
}
public TileBase tile
{
get { return m_Tile; }
}
public TileData tileData
{
get { return m_TileData; }
}
}
internal struct SyncTileCallbackSettings
{
internal bool hasSyncTileCallback;
internal bool hasPositionsChangedCallback;
internal bool isBufferSyncTile;
}
[RequiredByNativeCode]
internal void GetSyncTileCallbackSettings(ref SyncTileCallbackSettings settings)
{
settings.hasSyncTileCallback = HasSyncTileCallback();
settings.hasPositionsChangedCallback = HasPositionsChangedCallback();
settings.isBufferSyncTile = bufferSyncTile;
}
internal extern void SendAndClearSyncTileBuffer();
[RequiredByNativeCode]
private void DoSyncTileCallback(SyncTile[] syncTiles)
{
HandleSyncTileCallback(syncTiles);
}
[RequiredByNativeCode]
private void DoPositionsChangedCallback(int count, IntPtr positionsIntPtr)
{
HandlePositionsChangedCallback(count, positionsIntPtr);
}
}
[RequireComponent(typeof(Tilemap))]
[NativeHeader("Modules/Grid/Public/GridMarshalling.h")]
[NativeHeader("Modules/Tilemap/TilemapRendererJobs.h")]
[NativeHeader("Modules/Tilemap/Public/TilemapMarshalling.h")]
[NativeType(Header = "Modules/Tilemap/Public/TilemapRenderer.h")]
public sealed partial class TilemapRenderer : Renderer
{
public enum SortOrder
{
BottomLeft = 0,
BottomRight = 1,
TopLeft = 2,
TopRight = 3,
}
public enum Mode
{
Chunk = 0,
Individual = 1,
SRPBatch = 2,
}
public enum DetectChunkCullingBounds
{
Auto = 0,
Manual = 1,
}
public extern Vector3Int chunkSize
{
get;
set;
}
public extern Vector3 chunkCullingBounds
{
[FreeFunction("TilemapRendererBindings::GetChunkCullingBounds", HasExplicitThis = true)]
get;
[FreeFunction("TilemapRendererBindings::SetChunkCullingBounds", HasExplicitThis = true)]
set;
}
public extern int maxChunkCount
{
get;
set;
}
public extern int maxFrameAge
{
get;
set;
}
public extern SortOrder sortOrder
{
get;
set;
}
[NativeProperty("RenderMode")]
public extern Mode mode
{
get;
set;
}
public extern DetectChunkCullingBounds detectChunkCullingBounds
{
get;
set;
}
public extern SpriteMaskInteraction maskInteraction
{
get;
set;
}
[RequiredByNativeCode]
internal void RegisterSpriteAtlasRegistered()
{
SpriteAtlasManager.atlasRegistered += OnSpriteAtlasRegistered;
}
[RequiredByNativeCode]
internal void UnregisterSpriteAtlasRegistered()
{
SpriteAtlasManager.atlasRegistered -= OnSpriteAtlasRegistered;
}
internal extern void OnSpriteAtlasRegistered(SpriteAtlas atlas);
}
[RequiredByNativeCode]
[StructLayoutAttribute(LayoutKind.Sequential)]
[NativeType(Header = "Modules/Tilemap/TilemapScripting.h")]
public partial struct TileData
{
public Sprite sprite { get { return Object.ForceLoadFromInstanceID(m_Sprite) as Sprite; } set { m_Sprite = value != null ? value.GetInstanceID() : 0; } }
public Color color { get { return m_Color; } set { m_Color = value; } }
public Matrix4x4 transform { get { return m_Transform; } set { m_Transform = value; } }
public GameObject gameObject { get { return Object.ForceLoadFromInstanceID(m_GameObject) as GameObject; } set { m_GameObject = value != null ? value.GetInstanceID() : 0;; } }
public TileFlags flags { get { return m_Flags; } set { m_Flags = value; } }
public Tile.ColliderType colliderType { get { return m_ColliderType; } set { m_ColliderType = value; } }
private int m_Sprite;
private Color m_Color;
private Matrix4x4 m_Transform;
private int m_GameObject;
private TileFlags m_Flags;
private Tile.ColliderType m_ColliderType;
internal static readonly TileData Default = CreateDefault();
private static TileData CreateDefault()
{
TileData tileData = default;
tileData.color = Color.white;
tileData.transform = Matrix4x4.identity;
tileData.flags = default;
tileData.colliderType = default;
return tileData;
}
}
[RequiredByNativeCode]
[StructLayoutAttribute(LayoutKind.Sequential)]
[NativeType(Header = "Modules/Tilemap/TilemapScripting.h")]
internal partial struct TileDataNative
{
public int sprite { get { return m_Sprite; } set { m_Sprite = value; } }
public Color color { get { return m_Color; } set { m_Color = value; } }
public Matrix4x4 transform { get { return m_Transform; } set { m_Transform = value; } }
public int gameObject { get { return m_GameObject; } set { m_GameObject = value; } }
public TileFlags flags { get { return m_Flags; } set { m_Flags = value; } }
public Tile.ColliderType colliderType { get { return m_ColliderType; } set { m_ColliderType = value; } }
private int m_Sprite;
private Color m_Color;
private Matrix4x4 m_Transform;
private int m_GameObject;
private TileFlags m_Flags;
private Tile.ColliderType m_ColliderType;
public static implicit operator TileDataNative(TileData td)
{
TileDataNative tileDataNative = default;
tileDataNative.sprite = td.sprite != null ? td.sprite.GetInstanceID() : 0;
tileDataNative.color = td.color;
tileDataNative.transform = td.transform;
tileDataNative.gameObject = td.gameObject != null ? td.gameObject.GetInstanceID() : 0;
tileDataNative.flags = td.flags;
tileDataNative.colliderType = td.colliderType;
return tileDataNative;
}
}
[Serializable]
[RequiredByNativeCode]
[StructLayoutAttribute(LayoutKind.Sequential)]
[NativeType(Header = "Modules/Tilemap/TilemapScripting.h")]
public partial struct TileChangeData
{
public Vector3Int position { get { return m_Position; } set { m_Position = value; } }
public TileBase tile { get { return (TileBase)m_TileAsset; } set { m_TileAsset = value; } }
public Color color { get { return m_Color; } set { m_Color = value; } }
public Matrix4x4 transform { get { return m_Transform; } set { m_Transform = value; } }
[SerializeField]
private Vector3Int m_Position;
[SerializeField]
private Object m_TileAsset;
[SerializeField]
private Color m_Color;
[SerializeField]
private Matrix4x4 m_Transform;
public TileChangeData(Vector3Int position, TileBase tile, Color color, Matrix4x4 transform)
{
m_Position = position;
m_TileAsset = tile;
m_Color = color;
m_Transform = transform;
}
}
[RequiredByNativeCode]
[StructLayoutAttribute(LayoutKind.Sequential)]
[NativeType(Header = "Modules/Tilemap/TilemapScripting.h")]
public partial struct TileAnimationData
{
public Sprite[] animatedSprites { get { return m_AnimatedSprites; } set { m_AnimatedSprites = value; } }
public float animationSpeed { get { return m_AnimationSpeed; } set { m_AnimationSpeed = value; } }
public float animationStartTime { get { return m_AnimationStartTime; } set { m_AnimationStartTime = value; } }
public TileAnimationFlags flags { get { return m_Flags; } set { m_Flags = value; } }
private Sprite[] m_AnimatedSprites;
private float m_AnimationSpeed;
private float m_AnimationStartTime;
private TileAnimationFlags m_Flags;
}
[RequireComponent(typeof(Tilemap))]
[NativeType(Header = "Modules/Tilemap/Public/TilemapCollider2D.h")]
public sealed partial class TilemapCollider2D : Collider2D
{
// Get/Set Delaunay mesh usage.
extern public bool useDelaunayMesh { get; set; }
public extern uint maximumTileChangeCount
{
get;
set;
}
public extern float extrusionFactor
{
get;
set;
}
public extern bool hasTilemapChanges
{
[NativeMethod("HasTilemapChanges")]
get;
}
[NativeMethod(Name = "ProcessTileChangeQueue")]
public extern void ProcessTilemapChanges();
}
}
| UnityCsReference/Modules/Tilemap/ScriptBindings/Tilemap.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Tilemap/ScriptBindings/Tilemap.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 9775
} | 466 |
// 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.Profiling;
using UnityEditor;
namespace TreeEditor
{
//
// Leaf group
//
[System.Serializable]
public class TreeGroupLeaf : TreeGroup
{
public enum GeometryMode
{
PLANE = 0,
CROSS = 1,
TRI_CROSS = 2,
BILLBOARD = 3,
MESH = 4
}
static class Styles
{
public static string groupSeedString = LocalizationDatabase.GetLocalizedString("Group Seed|The seed for this group of leaves. Modify to vary procedural generation.");
public static string frequencyString = LocalizationDatabase.GetLocalizedString("Frequency|Adjusts the number of leaves created for each parent branch.");
public static string distributionModeString = LocalizationDatabase.GetLocalizedString("Distribution|Select the way the leaves are distributed along their parent.");
public static string twirlString = LocalizationDatabase.GetLocalizedString("Twirl|Twirl around the parent branch.");
public static string whorledStepString = LocalizationDatabase.GetLocalizedString("Whorled Step|Defines how many nodes are in each whorled step when using Whorled distribution. For real plants this is normally a Fibonacci number.");
public static string growthScaleString = LocalizationDatabase.GetLocalizedString("Growth Scale|Defines the scale of nodes along the parent node. Use the curve to adjust and the slider to fade the effect in and out.");
public static string growthAngleString = LocalizationDatabase.GetLocalizedString("Growth Angle|Defines the initial angle of growth relative to the parent. Use the curve to adjust and the slider to fade the effect in and out.");
public static string mainWindString = LocalizationDatabase.GetLocalizedString("Main Wind|Primary wind effect. Usually this should be kept as a low value to avoid leaves floating away from the parent branch.");
public static string mainTurbulenceString = LocalizationDatabase.GetLocalizedString("Main Turbulence|Secondary turbulence effect. For leaves this should usually be kept as a low value.");
public static string edgeTurbulenceString = LocalizationDatabase.GetLocalizedString("Edge Turbulence|Defines how much wind turbulence occurs along the edges of the leaves.");
}
internal static Dictionary<Texture, Vector2[]> s_TextureHulls;
internal static bool s_TextureHullsDirty;
//[field: TreeAttribute("Geometry", "category", 0.0f, 1.0f)]
//public bool showGeometryProps = true;
//[field: TreeAttribute("GeometryMode", "popup", "Plane,Cross,Tri-Cross,Billboard,Mesh")]
public int geometryMode = (int)GeometryMode.PLANE;
//[field: TreeAttribute("Material", "material", 0.0f, 1.0f, "primitiveGeometry")]
public Material materialLeaf = null;
//[field: TreeAttribute("Mesh", "mesh", 0.0f, 1.0f, "meshGeometry")]
public GameObject instanceMesh = null;
//[field: TreeAttribute("Shape", "category", 0.0f, 1.0f)]
//public bool showShapeProps = true;
//[field: TreeAttribute("Size", "minmaxslider", 0.1f, 10.0f)]
public Vector2 size = Vector2.one;
//[field: TreeAttribute("PerpendicularAlign", "slider", 0.0f, 1.0f)]
public float perpendicularAlign = 0.0f;
//[field: TreeAttribute("HorizontalAlign", "slider", 0.0f, 1.0f)]
public float horizontalAlign = 0.0f;
//
// Leaves cannot have children...
//
override public bool CanHaveSubGroups()
{
return false;
}
override internal bool HasExternalChanges()
{
string hash;
if (geometryMode == (int)GeometryMode.MESH)
{
hash = UnityEditorInternal.InternalEditorUtility.CalculateHashForObjectsAndDependencies(new Object[] { instanceMesh });
}
else
{
hash = UnityEditorInternal.InternalEditorUtility.CalculateHashForObjectsAndDependencies(new Object[] { materialLeaf });
}
if (hash != m_Hash)
{
m_Hash = hash;
return true;
}
return false;
}
override public void UpdateParameters()
{
if (lockFlags == 0)
{
for (int n = 0; n < nodes.Count; n++)
{
TreeNode node = nodes[n];
Random.InitState(node.seed);
for (int x = 0; x < 5; x++)
{
node.scale *= size.x + ((size.y - size.x) * Random.value);
}
for (int x = 0; x < 5; x++)
{
float rx = (Random.value - 0.5f) * 180.0f * (1.0f - perpendicularAlign);
float ry = (Random.value - 0.5f) * 180.0f * (1.0f - perpendicularAlign);
float rz = 0.0f;
node.rotation = Quaternion.Euler(rx, ry, rz);
}
}
}
UpdateMatrix();
// Update child groups..
base.UpdateParameters();
}
override public void UpdateMatrix()
{
if (parentGroup == null)
{
for (int n = 0; n < nodes.Count; n++)
{
TreeNode node = nodes[n];
node.matrix = Matrix4x4.identity;
}
}
else
{
TreeGroupRoot tgr = parentGroup as TreeGroupRoot;
for (int n = 0; n < nodes.Count; n++)
{
TreeNode node = nodes[n];
Vector3 pos = new Vector3();
Quaternion rot = new Quaternion();
float rad = 0.0f;
float surfaceAngle = 0.0f;
if (tgr != null)
{
// attached to root node
float dist = node.offset * GetRootSpread();
float ang = node.angle * Mathf.Deg2Rad;
pos = new Vector3(Mathf.Cos(ang) * dist, -tgr.groundOffset, Mathf.Sin(ang) * dist);
rot = Quaternion.Euler(node.pitch * -Mathf.Sin(ang), 0, node.pitch * Mathf.Cos(ang)) * Quaternion.Euler(0, node.angle, 0);
}
else
{
// attached to branch node
node.parent.GetPropertiesAtTime(node.offset, out pos, out rot, out rad);
surfaceAngle = node.parent.GetSurfaceAngleAtTime(node.offset);
}
Quaternion angle = Quaternion.Euler(90.0f, node.angle, 0.0f);
Matrix4x4 aog = Matrix4x4.TRS(Vector3.zero, angle, Vector3.one);
// pitch matrix
Matrix4x4 pit = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(node.pitch + surfaceAngle, 0.0f, 0.0f), Vector3.one);
node.matrix = node.parent.matrix * Matrix4x4.TRS(pos, rot, Vector3.one) * aog * pit;
// spin
node.matrix *= Matrix4x4.TRS(new Vector3(0, 0, 0), node.rotation, new Vector3(1, 1, 1));
// horizontalize
if (horizontalAlign > 0.0f)
{
Vector4 opos = node.matrix.GetColumn(3);
Quaternion targetQuat = Quaternion.Euler(90.0f, node.angle, 0.0f);
Quaternion newQuat = Quaternion.Slerp(MathUtils.QuaternionFromMatrix(node.matrix), targetQuat,
horizontalAlign);
node.matrix = Matrix4x4.TRS(Vector3.zero, newQuat, Vector3.one);
node.matrix.SetColumn(3, opos);
}
Vector3 off;
if (geometryMode == (int)GeometryMode.MESH)
{
off = node.matrix.MultiplyPoint(new Vector3(0, rad, 0));
node.matrix = node.matrix * Matrix4x4.Scale(new Vector3(node.scale, node.scale, node.scale));
}
else
{
off = node.matrix.MultiplyPoint(new Vector3(0, rad + node.scale, 0));
}
node.matrix.m03 = off.x;
node.matrix.m13 = off.y;
node.matrix.m23 = off.z;
}
}
// Update child groups..
base.UpdateMatrix();
}
override public void BuildAOSpheres(List<TreeAOSphere> aoSpheres)
{
if (visible)
{
float scaleFactor = 0.75f;
for (int n = 0; n < nodes.Count; n++)
{
TreeNode node = nodes[n];
if (!node.visible) continue;
Vector3 pos = node.matrix.MultiplyPoint(new Vector3(0, 0, 0));
float rad = node.scale * scaleFactor;
aoSpheres.Add(new TreeAOSphere(pos, rad, 0.5f));
}
}
// Update child groups..
base.BuildAOSpheres(aoSpheres);
}
private static Mesh cloneMesh;
private static MeshFilter cloneMeshFilter;
private static Vector3[] cloneVerts;
private static Vector3[] cloneNormals;
private static Vector2[] cloneUVs;
private static Vector4[] cloneTangents;
override public void UpdateMesh(List<TreeMaterial> materials, List<TreeVertex> verts, List<TreeTriangle> tris, List<TreeAOSphere> aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity)
{
if (geometryMode == (int)GeometryMode.MESH)
{
// Skip if no instance mesh is selected
if (instanceMesh != null)
{
cloneMeshFilter = instanceMesh.GetComponent<MeshFilter>();
if (cloneMeshFilter != null)
{
cloneMesh = cloneMeshFilter.sharedMesh;
if (cloneMesh != null)
{
Vector3 meshSize = cloneMesh.bounds.extents;
float meshScale = Mathf.Max(meshSize.x, meshSize.z) * 0.5f;
cloneVerts = cloneMesh.vertices;
cloneNormals = cloneMesh.normals;
cloneUVs = cloneMesh.uv;
cloneTangents = cloneMesh.tangents;
// rescale to fit with size of the planes we're making..
for (int i = 0; i < cloneVerts.Length; i++)
{
cloneVerts[i].x /= meshScale;
cloneVerts[i].y /= meshScale;
cloneVerts[i].z /= meshScale;
}
}
}
if (instanceMesh.GetComponent<Renderer>() != null)
{
Material[] sharedMaterials = instanceMesh.GetComponent<Renderer>().sharedMaterials;
for (int i = 0; i < sharedMaterials.Length; i++)
{
GetMaterialIndex(sharedMaterials[i], materials, false);
}
}
}
}
else
{
GetMaterialIndex(materialLeaf, materials, false);
}
for (int n = 0; n < nodes.Count; n++)
{
UpdateNodeMesh(nodes[n], materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity);
}
// cloneRenderer = null;
cloneMesh = null;
cloneMeshFilter = null;
cloneVerts = null;
cloneNormals = null;
cloneUVs = null;
cloneTangents = null;
// Update child groups..
base.UpdateMesh(materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity);
}
private static TreeVertex CreateBillboardVertex(TreeNode node, Quaternion billboardRotation, Vector3 normalBase, float normalFix, Vector3 tangentBase, Vector2 uv)
{
TreeVertex vertex = new TreeVertex();
vertex.pos = node.matrix.MultiplyPoint(Vector3.zero);
vertex.uv0 = uv;
uv = 2.0f * uv - Vector2.one;
// Store billboard spread in the normal,
// normal will be reconstructed in the vertex shader.
vertex.nor = (billboardRotation * (new Vector3(uv.x * node.scale, uv.y * node.scale, 0.0f)));
vertex.nor.z = normalFix;
// normal
Vector3 normal = (billboardRotation * (new Vector3(uv.x * normalBase.x, uv.y * normalBase.y, normalBase.z))).normalized;
// calculate tangent from the normal
vertex.tangent = (tangentBase - normal * Vector3.Dot(tangentBase, normal)).normalized;
vertex.tangent.w = 0.0f;
return vertex;
}
private Vector2[] GetPlaneHullVertices(Material mat)
{
if (mat == null)
return null;
if (!mat.HasProperty("_MainTex"))
return null;
Texture tex = mat.mainTexture;
if (!tex)
return null;
if (s_TextureHulls == null || s_TextureHullsDirty)
{
s_TextureHulls = new Dictionary<Texture, Vector2[]>();
s_TextureHullsDirty = false;
}
if (s_TextureHulls.ContainsKey(tex))
return s_TextureHulls[tex];
Vector2[] textureHull = UnityEditor.MeshUtility.ComputeTextureBoundingHull(tex, 4);
Vector2 tmp = textureHull[1];
textureHull[1] = textureHull[3];
textureHull[3] = tmp;
s_TextureHulls.Add(tex, textureHull);
return textureHull;
}
private void UpdateNodeMesh(TreeNode node, List<TreeMaterial> materials, List<TreeVertex> verts, List<TreeTriangle> tris, List<TreeAOSphere> aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity)
{
node.triStart = tris.Count;
node.triEnd = tris.Count;
node.vertStart = verts.Count;
node.vertEnd = verts.Count;
// Check for visibility..
if (!node.visible || !visible) return;
Profiler.BeginSample("TreeGroupLeaf.UpdateNodeMesh");
Vector2 windFactors = ComputeWindFactor(node, node.offset);
if (geometryMode == (int)GeometryMode.MESH)
{
// Exit if no instance mesh is selected
if (cloneMesh == null)
{
// Debug.LogError("No cloneMesh");
return;
}
if (cloneVerts == null)
{
// Debug.LogError("No cloneVerts");
return;
}
if (cloneNormals == null)
{
// Debug.LogError("No cloneNormals");
return;
}
if (cloneTangents == null)
{
// Debug.LogError("No cloneTangents");
return;
}
if (cloneUVs == null)
{
// Debug.LogError("No cloneUVs");
return;
}
Matrix4x4 cloneMatrix = instanceMesh.transform.localToWorldMatrix;
Matrix4x4 tformMatrix = node.matrix * cloneMatrix;
int vertOffset = verts.Count;
float dist = 5.0f;
// copy verts
for (int i = 0; i < cloneVerts.Length; i++)
{
TreeVertex v0 = new TreeVertex();
v0.pos = tformMatrix.MultiplyPoint(cloneVerts[i]);
v0.nor = tformMatrix.MultiplyVector(cloneNormals[i]).normalized;
v0.uv0 = new Vector2(cloneUVs[i].x, cloneUVs[i].y);
Vector3 tangent = tformMatrix.MultiplyVector(new Vector3(cloneTangents[i].x, cloneTangents[i].y, cloneTangents[i].z)).normalized;
v0.tangent = new Vector4(tangent.x, tangent.y, tangent.z, cloneTangents[i].w);
// wind
float windEdge = (cloneVerts[i].magnitude / dist) * animationEdge;
v0.SetAnimationProperties(windFactors.x, windFactors.y, windEdge, node.animSeed);
// AO
if ((buildFlags & (int)BuildFlag.BuildAmbientOcclusion) != 0)
{
v0.SetAmbientOcclusion(ComputeAmbientOcclusion(v0.pos, v0.nor, aoSpheres, aoDensity));
}
verts.Add(v0);
}
// copy tris
for (int s = 0; s < cloneMesh.subMeshCount; s++)
{
int[] instanceTris = cloneMesh.GetTriangles(s);
int materialIndex;
if (instanceMesh.GetComponent<Renderer>() != null && s < instanceMesh.GetComponent<Renderer>().sharedMaterials.Length)
{
materialIndex = GetMaterialIndex(instanceMesh.GetComponent<Renderer>().sharedMaterials[s], materials, false);
}
else
{
materialIndex = GetMaterialIndex(null, materials, false);
}
for (int i = 0; i < instanceTris.Length; i += 3)
{
TreeTriangle t0 = new TreeTriangle(materialIndex, instanceTris[i] + vertOffset, instanceTris[i + 1] + vertOffset, instanceTris[i + 2] + vertOffset);
tris.Add(t0);
}
}
}
else if (geometryMode == (int)GeometryMode.BILLBOARD)
{
// rotation
Vector3 eulerRot = node.rotation.eulerAngles;
eulerRot.z = eulerRot.x * 2.0f;
eulerRot.x = 0.0f;
eulerRot.y = 0.0f;
Quaternion billboardRotation = Quaternion.Euler(eulerRot);
// normal
Vector3 normalBase = new Vector3(GenerateBendBillboardNormalFactor, GenerateBendBillboardNormalFactor, 1.0f);
Vector3 tangentBase = billboardRotation * new Vector3(1, 0, 0);
float normalFix = node.scale / (GenerateBendBillboardNormalFactor * GenerateBendBillboardNormalFactor);
TreeVertex v0 = CreateBillboardVertex(node, billboardRotation, normalBase, normalFix, tangentBase, new Vector2(0, 1));
TreeVertex v1 = CreateBillboardVertex(node, billboardRotation, normalBase, normalFix, tangentBase, new Vector2(0, 0));
TreeVertex v2 = CreateBillboardVertex(node, billboardRotation, normalBase, normalFix, tangentBase, new Vector2(1, 0));
TreeVertex v3 = CreateBillboardVertex(node, billboardRotation, normalBase, normalFix, tangentBase, new Vector2(1, 1));
// wind
v0.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed);
v1.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed);
v2.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed);
v3.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed);
if ((buildFlags & (int)BuildFlag.BuildAmbientOcclusion) != 0)
{
// Vector3 pushU = Vector3.up * internalSize;
Vector3 pushR = Vector3.right * node.scale;
Vector3 pushF = Vector3.forward * node.scale;
float a = 0.0f; // ComputeAmbientOcclusion(partID, v0.pos + pushU, Vector3.up, aoSpheres);
//a += ComputeAmbientOcclusion(partID, v0.pos - pushU, -Vector3.up, aoSpheres);
a = ComputeAmbientOcclusion(v0.pos + pushR, Vector3.right, aoSpheres, aoDensity);
a += ComputeAmbientOcclusion(v0.pos - pushR, -Vector3.right, aoSpheres, aoDensity);
a += ComputeAmbientOcclusion(v0.pos + pushF, Vector3.forward, aoSpheres, aoDensity);
a += ComputeAmbientOcclusion(v0.pos - pushF, -Vector3.forward, aoSpheres, aoDensity);
a /= 4.0f;
v0.SetAmbientOcclusion(a);
v1.SetAmbientOcclusion(a);
v2.SetAmbientOcclusion(a);
v3.SetAmbientOcclusion(a);
}
int index0 = verts.Count;
verts.Add(v0);
verts.Add(v1);
verts.Add(v2);
verts.Add(v3);
int materialIndex = GetMaterialIndex(materialLeaf, materials, false);
tris.Add(new TreeTriangle(materialIndex, index0, index0 + 2, index0 + 1, true));
tris.Add(new TreeTriangle(materialIndex, index0, index0 + 3, index0 + 2, true));
}
else
{
// plane, cross, tri-cross
int planes = 0;
switch ((GeometryMode)geometryMode)
{
case GeometryMode.PLANE:
planes = 1;
break;
case GeometryMode.CROSS:
planes = 2;
break;
case GeometryMode.TRI_CROSS:
planes = 3;
break;
}
int materialIndex = GetMaterialIndex(materialLeaf, materials, false);
Vector2[] rawHull = new Vector2[]
{
new Vector2(0, 1),
new Vector2(0, 0),
new Vector2(1, 0),
new Vector2(1, 1)
};
Vector2[] textureHull = GetPlaneHullVertices(materialLeaf);
if (textureHull == null)
textureHull = rawHull;
float ns = node.scale;
Vector3[] positionsRaw = new Vector3[]
{
new Vector3(-ns, 0f, -ns),
new Vector3(-ns, 0f, ns),
new Vector3(ns, 0f, ns),
new Vector3(ns, 0f, -ns)
};
Vector3 normal = new Vector3(GenerateBendNormalFactor, 1.0f - GenerateBendNormalFactor, GenerateBendNormalFactor);
Vector3[] normalsRaw = new Vector3[]
{
new Vector3(-normal.x, normal.y, -normal.z).normalized,
new Vector3(-normal.x, normal.y, 0).normalized, // note z always 0
new Vector3(normal.x, normal.y, 0).normalized, // note z always 0
new Vector3(normal.x, normal.y, -normal.z).normalized
};
for (int ipl = 0; ipl < planes; ipl++)
{
Quaternion rot = Quaternion.Euler(new Vector3(90, 0, 0));
switch (ipl)
{
case 1:
rot = Quaternion.Euler(new Vector3(90, 90, 0));
break;
case 2:
rot = Quaternion.Euler(new Vector3(0, 90, 0));
break;
}
TreeVertex[] tv = new TreeVertex[8]
{
new TreeVertex(), new TreeVertex(), new TreeVertex(), new TreeVertex(), // initial quad
new TreeVertex(), new TreeVertex(), new TreeVertex(), new TreeVertex() // from bounding hull
};
for (int i = 0; i < 4; ++i)
{
tv[i].pos = node.matrix.MultiplyPoint(rot * positionsRaw[i]);
tv[i].nor = node.matrix.MultiplyVector(rot * normalsRaw[i]);
tv[i].tangent = CreateTangent(node, rot, tv[i].nor);
tv[i].uv0 = textureHull[i];
tv[i].SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed);
if ((buildFlags & (int)BuildFlag.BuildAmbientOcclusion) != 0)
{
tv[i].SetAmbientOcclusion(ComputeAmbientOcclusion(tv[i].pos, tv[i].nor, aoSpheres, aoDensity));
}
}
// now lerp positions into correct placed based on the bounding hull
for (int i = 0; i < 4; ++i)
{
tv[i + 4].Lerp4(tv, textureHull[i]);
tv[i + 4].uv0 = tv[i].uv0;
tv[i + 4].uv1 = tv[i].uv1;
tv[i + 4].flag = tv[i].flag;
}
int index0 = verts.Count;
for (int i = 0; i < 4; ++i)
verts.Add(tv[i + 4]);
tris.Add(new TreeTriangle(materialIndex, index0, index0 + 1, index0 + 2));
tris.Add(new TreeTriangle(materialIndex, index0, index0 + 2, index0 + 3));
Vector3 faceNormal = node.matrix.MultiplyVector(rot * new Vector3(0, 1, 0));
if (GenerateDoubleSidedGeometry)
{
// Duplicate vertices with mirrored normal and tangent
TreeVertex[] tv2 = new TreeVertex[8]
{
new TreeVertex(), new TreeVertex(), new TreeVertex(), new TreeVertex(), // initial quad
new TreeVertex(), new TreeVertex(), new TreeVertex(), new TreeVertex() // from bounding hull
};
for (int i = 0; i < 4; ++i)
{
tv2[i].pos = tv[i].pos;
tv2[i].nor = Vector3.Reflect(tv[i].nor, faceNormal);
tv2[i].tangent = Vector3.Reflect(tv[i].tangent, faceNormal);
tv2[i].tangent.w = -1;
tv2[i].uv0 = tv[i].uv0;
tv2[i].SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed);
if ((buildFlags & (int)BuildFlag.BuildAmbientOcclusion) != 0)
{
tv2[i].SetAmbientOcclusion(ComputeAmbientOcclusion(tv2[i].pos, tv2[i].nor, aoSpheres, aoDensity));
}
}
// now lerp positions into correct placed based on the bounding hull
for (int i = 0; i < 4; ++i)
{
tv2[i + 4].Lerp4(tv2, textureHull[i]);
tv2[i + 4].uv0 = tv2[i].uv0;
tv2[i + 4].uv1 = tv2[i].uv1;
tv2[i + 4].flag = tv2[i].flag;
}
int index4 = verts.Count;
for (int i = 0; i < 4; ++i)
verts.Add(tv2[i + 4]);
tris.Add(new TreeTriangle(materialIndex, index4, index4 + 2, index4 + 1));
tris.Add(new TreeTriangle(materialIndex, index4, index4 + 3, index4 + 2));
}
}
}
node.triEnd = tris.Count;
node.vertEnd = verts.Count;
Profiler.EndSample(); // TreeGroupLeaf.UpdateNodeMesh
}
internal override string GroupSeedString { get { return Styles.groupSeedString; } }
internal override string FrequencyString { get { return Styles.frequencyString; } }
internal override string DistributionModeString { get { return Styles.distributionModeString; } }
internal override string TwirlString { get { return Styles.twirlString; } }
internal override string WhorledStepString { get { return Styles.whorledStepString; } }
internal override string GrowthScaleString { get { return Styles.growthScaleString; } }
internal override string GrowthAngleString { get { return Styles.growthAngleString; } }
internal override string MainWindString { get { return Styles.mainWindString; } }
internal override string MainTurbulenceString { get { return Styles.mainTurbulenceString; } }
internal override string EdgeTurbulenceString { get { return Styles.edgeTurbulenceString; } }
}
}
| UnityCsReference/Modules/TreeEditor/Includes/TreeGroupLeaf.cs/0 | {
"file_path": "UnityCsReference/Modules/TreeEditor/Includes/TreeGroupLeaf.cs",
"repo_id": "UnityCsReference",
"token_count": 15816
} | 467 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace UnityEditor.UIAutomation
{
class ClickOverTime
{
public float numEventsPerSecond = 10;
float nextEventTime;
float startTime;
float endTime;
float secondsBetweenClicks;
List<Vector2> clickPositions;
int currentClickIndex;
public void Clicks(EditorWindow window, List<Vector2> clickPositions, float secondsBetweenClicks)
{
Clicks(window, clickPositions, secondsBetweenClicks, EventModifiers.None);
}
public void Clicks(EditorWindow window, List<Vector2> clickPositions, float secondsBetweenClicks, EventModifiers modifiers)
{
this.clickPositions = clickPositions;
this.secondsBetweenClicks = secondsBetweenClicks;
// First click immediately
EventUtility.Click(window, clickPositions[0]);
SetCurrentClickIndex(1);
}
void SetCurrentClickIndex(int clickIndex)
{
currentClickIndex = clickIndex;
startTime = (float)EditorApplication.timeSinceStartup;
endTime = startTime + secondsBetweenClicks;
nextEventTime = 0;
}
public bool Update(EditorWindow window)
{
return Update(window, EventModifiers.None);
}
public bool Update(EditorWindow window, EventModifiers modifiers)
{
if (currentClickIndex >= clickPositions.Count)
return false;
float curtime = (float)EditorApplication.timeSinceStartup;
if (curtime > nextEventTime)
{
// Dispatch fake drag and drop events
float frac = Mathf.Clamp01((curtime - startTime) / (endTime - startTime));
frac = Easing.Quadratic.InOut(frac);
var mouseStart = clickPositions[currentClickIndex - 1];
var mouseEnd = clickPositions[currentClickIndex];
Vector2 mousePosition = Vector2.Lerp(mouseStart, mouseEnd, frac);
EventUtility.UpdateMouseMove(window, mousePosition);
if (frac >= 1f)
{
SetCurrentClickIndex(currentClickIndex + 1);
EventUtility.Click(window, mousePosition);
}
nextEventTime = curtime + (1 / numEventsPerSecond);
window.Repaint();
bool shouldContinue = currentClickIndex < clickPositions.Count - 1;
return shouldContinue;
}
return true;
}
}
}
| UnityCsReference/Modules/UIAutomationEditor/ClickOverTime.cs/0 | {
"file_path": "UnityCsReference/Modules/UIAutomationEditor/ClickOverTime.cs",
"repo_id": "UnityCsReference",
"token_count": 1239
} | 468 |
// 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.IO;
using UnityEditor;
namespace Unity.UI.Builder
{
[Serializable]
class BuilderDocumentSettings
{
public string UxmlGuid;
public string UxmlPath;
public int CanvasX;
public int CanvasY;
public int CanvasWidth = (int)BuilderConstants.CanvasInitialWidth;
public int CanvasHeight = (int)BuilderConstants.CanvasInitialHeight;
public bool MatchGameView;
public float ZoomScale = BuilderConstants.ViewportInitialZoom;
public Vector2 PanOffset = BuilderConstants.ViewportInitialContentOffset;
public float ColorModeBackgroundOpacity = 1.0f;
public float ImageModeCanvasBackgroundOpacity = 1.0f;
public float CameraModeCanvasBackgroundOpacity = 1.0f;
public bool EnableCanvasBackground;
public BuilderCanvasBackgroundMode CanvasBackgroundMode = BuilderCanvasBackgroundMode.Color;
public Color CanvasBackgroundColor = new Color(0, 0, 0, 1f);
public Texture2D CanvasBackgroundImage;
public ScaleMode CanvasBackgroundImageScaleMode = ScaleMode.ScaleAndCrop;
public string CanvasBackgroundCameraName;
public static BuilderDocumentSettings CreateOrLoadSettingsObject(
BuilderDocumentSettings settings,
string uxmlPath)
{
if (settings != null)
return settings;
settings = new BuilderDocumentSettings();
var diskDataFound = settings.LoadSettingsFromDisk(uxmlPath);
if (diskDataFound)
return settings;
settings.UxmlGuid = AssetDatabase.AssetPathToGUID(uxmlPath);
settings.UxmlPath = uxmlPath;
return settings;
}
public bool LoadSettingsFromDisk(string uxmlPath)
{
var guid = AssetDatabase.AssetPathToGUID(uxmlPath);
if (string.IsNullOrEmpty(guid))
return false;
var folderPath = BuilderConstants.builderDocumentDiskSettingsJsonFolderAbsolutePath;
var fileName = guid + ".json";
var path = folderPath + "/" + fileName;
if (!File.Exists(path))
return false;
var json = File.ReadAllText(path);
EditorJsonUtility.FromJsonOverwrite(json, this);
return true;
}
public void SaveSettingsToDisk()
{
if (string.IsNullOrEmpty(UxmlGuid) || string.IsNullOrEmpty(UxmlPath))
return;
var json = EditorJsonUtility.ToJson(this, true);
var folderPath = BuilderConstants.builderDocumentDiskSettingsJsonFolderAbsolutePath;
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
var fileName = UxmlGuid + ".json";
var filePath = folderPath + "/" + fileName;
File.WriteAllText(filePath, json);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Document/BuilderDocumentSettings.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Document/BuilderDocumentSettings.cs",
"repo_id": "UnityCsReference",
"token_count": 1288
} | 469 |
// 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 Unity.UI.Builder
{
internal class BuilderStyleSheetsContextMenu : BuilderElementContextMenu
{
public BuilderStyleSheetsContextMenu(BuilderPaneWindow paneWindow, BuilderSelection selection)
: base(paneWindow, selection)
{}
public override void BuildElementContextualMenu(ContextualMenuPopulateEvent evt, VisualElement target)
{
base.BuildElementContextualMenu(evt, target);
var documentElement = target.GetProperty(BuilderConstants.ElementLinkedDocumentVisualElementVEPropertyName) as VisualElement;
var selectedStyleSheet = documentElement?.GetStyleSheet();
int selectedStyleSheetIndex = selectedStyleSheet == null ? -1 : (int)documentElement.GetProperty(BuilderConstants.ElementLinkedStyleSheetIndexVEPropertyName);
var isStyleSheet = documentElement != null && BuilderSharedStyles.IsStyleSheetElement(documentElement);
var styleSheetBelongsToParent = !string.IsNullOrEmpty(documentElement?.GetProperty(BuilderConstants.ExplorerItemLinkedUXMLFileName) as string);
if (isStyleSheet)
evt.StopImmediatePropagation();
evt.menu.AppendSeparator();
evt.menu.AppendAction(
BuilderConstants.ExplorerStyleSheetsPaneCreateNewUSSMenu,
a =>
{
BuilderStyleSheetsUtilities.CreateNewUSSAsset(paneWindow);
},
DropdownMenuAction.Status.Normal);
evt.menu.AppendAction(
BuilderConstants.ExplorerStyleSheetsPaneAddExistingUSSMenu,
a =>
{
BuilderStyleSheetsUtilities.AddExistingUSSToAsset(paneWindow);
},
DropdownMenuAction.Status.Normal);
evt.menu.AppendAction(
BuilderConstants.ExplorerStyleSheetsPaneRemoveUSSMenu,
a =>
{
BuilderStyleSheetsUtilities.RemoveUSSFromAsset(paneWindow, selection, documentElement);
},
isStyleSheet && !styleSheetBelongsToParent
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
evt.menu.AppendSeparator();
evt.menu.AppendAction(
BuilderConstants.ExplorerStyleSheetsPaneSetActiveUSS,
a =>
{
selection.Select(null, documentElement);
BuilderStyleSheetsUtilities.SetActiveUSS(selection, paneWindow, selectedStyleSheet);
},
isStyleSheet && !styleSheetBelongsToParent
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheetsContextMenu.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheetsContextMenu.cs",
"repo_id": "UnityCsReference",
"token_count": 1345
} | 470 |
// 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 Unity.UI.Builder
{
/// <summary>
/// Toggle in a completer that indicates whether only compatible results should be displayed in the completer.
/// </summary>
class ShowOnlyCompatibleResultsToggle : VisualElement
{
static readonly string s_UssClassName = "show-only-compatible-toggle";
private Toggle m_Toggle;
private Label m_RatioLabel;
public Toggle toggle => m_Toggle;
/// <summary>
/// Constructs a toggle
/// </summary>
public ShowOnlyCompatibleResultsToggle()
{
AddToClassList(s_UssClassName);
m_Toggle = new Toggle() { text = BuilderConstants.BindingWindowShowOnlyCompatibleMessage, value = true };
m_RatioLabel = new Label() { classList = { FieldSearchCompleterPopup.s_ResultLabelUssClassName } };
Add(m_Toggle);
Add(m_RatioLabel);
}
/// <summary>
/// Sets the number of compatible results and the number of all results
/// </summary>
/// <param name="compatibleResultCount">The number of compatible results</param>
/// <param name="maxResultCount">The number of all results</param>
public void SetCompatibleResultCount(int compatibleResultCount, int maxResultCount)
{
m_RatioLabel.text = $"{compatibleResultCount}/{maxResultCount}";
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/ShowOnlyCompatibleResultsToggle.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/ShowOnlyCompatibleResultsToggle.cs",
"repo_id": "UnityCsReference",
"token_count": 600
} | 471 |
// 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;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
class BuilderLibrary : BuilderPaneContent, IBuilderSelectionNotifier
{
public enum BuilderLibraryTab
{
Standard,
Project
}
public enum LibraryViewMode
{
IconTile,
TreeView
}
public enum DefaultVisualElementType
{
Styled = 0,
NoStyles = 1
}
const string k_UssClassName = "unity-builder-library";
const string k_ContentContainerName = "content";
readonly BuilderPaneWindow m_PaneWindow;
readonly VisualElement m_DocumentElement;
readonly BuilderSelection m_Selection;
readonly BuilderLibraryDragger m_Dragger;
readonly BuilderTooltipPreview m_TooltipPreview;
readonly ToggleButtonGroup m_HeaderButtonStrip;
readonly VisualElement m_LibraryContentContainer;
BuilderLibraryTreeView m_ProjectTreeView;
BuilderLibraryPlainView m_ControlsPlainView;
BuilderLibraryTreeView m_ControlsTreeView;
bool m_EditorExtensionMode;
[SerializeField] bool m_ShowPackageTemplates;
[SerializeField] LibraryViewMode m_ViewMode = LibraryViewMode.IconTile;
[SerializeField] BuilderLibraryTab m_ActiveTab = BuilderLibraryTab.Standard;
int defaultVisualElementType => EditorPrefs.GetInt(BuilderConstants.LibraryDefaultVisualElementType, (int)DefaultVisualElementType.Styled);
public BuilderLibrary(
BuilderPaneWindow paneWindow, BuilderViewport viewport,
BuilderSelection selection, BuilderLibraryDragger dragger,
BuilderTooltipPreview tooltipPreview)
{
m_PaneWindow = paneWindow;
m_DocumentElement = viewport.documentRootElement;
m_Selection = selection;
m_Dragger = dragger;
m_TooltipPreview = tooltipPreview;
viewDataKey = "unity-ui-builder-library";
// Load styles.
AddToClassList(k_UssClassName);
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.LibraryUssPathNoExt + ".uss"));
styleSheets.Add(EditorGUIUtility.isProSkin
? BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.LibraryUssPathNoExt + "Dark.uss")
: BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.LibraryUssPathNoExt + "Light.uss"));
var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(BuilderConstants.LibraryUssPathNoExt + ".uxml");
template.CloneTree(this);
m_EditorExtensionMode = paneWindow.document.fileSettings.editorExtensionMode;
m_LibraryContentContainer = this.Q<VisualElement>(k_ContentContainerName);
m_HeaderButtonStrip = this.Q<ToggleButtonGroup>();
var libraryItems = new[] { BuilderConstants.LibraryStandardControlsTabName, BuilderConstants.LibraryProjectTabName };
foreach (var item in libraryItems)
{
m_HeaderButtonStrip.Add(new Button() { name = item, text = item, tooltip = item.ToLower() });
}
m_HeaderButtonStrip.RegisterValueChangedCallback(e =>
{
var selected = e.newValue.GetActiveOptions(stackalloc int[m_HeaderButtonStrip.value.length]);
SwitchLibraryTab((BuilderLibraryTab)selected[0]);
});
AddFocusable(m_HeaderButtonStrip);
BuilderLibraryContent.RegenerateLibraryContent(true);
RegisterCallback<AttachToPanelEvent>(AttachToPanelCallback);
RegisterCallback<DetachFromPanelEvent>(DetachFromPanelCallback);
}
void AttachToPanelCallback(AttachToPanelEvent e)
{
BuilderLibraryContent.OnLibraryContentUpdated += RebuildView;
}
void DetachFromPanelCallback(DetachFromPanelEvent e)
{
BuilderLibraryContent.OnLibraryContentUpdated -= RebuildView;
}
void SwitchLibraryTab(BuilderLibraryTab newTab)
{
m_ActiveTab = newTab;
SaveViewData();
RefreshView();
}
protected override void InitEllipsisMenu()
{
base.InitEllipsisMenu();
if (pane == null)
return;
pane.AppendActionToEllipsisMenu(BuilderConstants.LibraryShowPackageFiles,
a => TogglePackageFilesVisibility(),
a => m_ShowPackageTemplates
? DropdownMenuAction.Status.Checked
: DropdownMenuAction.Status.Normal);
pane.AppendActionToEllipsisMenu(BuilderConstants.LibraryViewModeToggle,
a => SwitchControlsViewMode(),
a => m_ViewMode == LibraryViewMode.TreeView
? DropdownMenuAction.Status.Checked
: DropdownMenuAction.Status.Normal);
pane.AppendActionToEllipsisMenu(BuilderConstants.LibraryEditorExtensionsAuthoring,
a => ToggleEditorExtensionsAuthoring(),
a => m_PaneWindow.document.fileSettings.editorExtensionMode
? DropdownMenuAction.Status.Checked
: DropdownMenuAction.Status.Normal);
pane.AppendActionToEllipsisMenu(BuilderConstants.LibraryDefaultVisualElementType + "/" + BuilderConstants.LibraryDefaultVisualElementStyledName,
a => SwitchDefaultVisualElementType(),
a => defaultVisualElementType == (int)DefaultVisualElementType.Styled
? DropdownMenuAction.Status.Checked
: DropdownMenuAction.Status.Normal);
pane.AppendActionToEllipsisMenu(BuilderConstants.LibraryDefaultVisualElementType + "/" + BuilderConstants.LibraryDefaultVisualElementNoStylesName,
a => SwitchDefaultVisualElementType(),
a => defaultVisualElementType == (int)DefaultVisualElementType.NoStyles
? DropdownMenuAction.Status.Checked
: DropdownMenuAction.Status.Normal);
}
void ToggleEditorExtensionsAuthoring()
{
var newValue = !m_PaneWindow.document.fileSettings.editorExtensionMode;
m_PaneWindow.document.fileSettings.editorExtensionMode = newValue;
m_Selection.NotifyOfStylingChangePostStylingUpdate();
SwitchLibraryTab(BuilderLibraryTab.Standard);
if (newValue)
Builder.ShowWarning(BuilderConstants.InspectorEditorExtensionAuthoringActivated);
}
internal override void OnViewDataReady()
{
base.OnViewDataReady();
OverwriteFromViewData(this, viewDataKey);
RefreshView();
}
public void OnAfterBuilderDeserialize()
{
RebuildView();
}
void TogglePackageFilesVisibility()
{
m_ShowPackageTemplates = !m_ShowPackageTemplates;
SaveViewData();
RebuildView();
}
internal void SetViewMode(LibraryViewMode viewMode)
{
if (m_ViewMode == viewMode)
return;
m_ViewMode = viewMode;
SaveViewData();
RefreshView();
}
void SwitchControlsViewMode()
{
SetViewMode(m_ViewMode == LibraryViewMode.IconTile
? LibraryViewMode.TreeView
: LibraryViewMode.IconTile);
}
internal void SetDefaultVisualElementType(DefaultVisualElementType visualElementType)
{
if (defaultVisualElementType == (int)visualElementType)
return;
EditorPrefs.SetInt(BuilderConstants.LibraryDefaultVisualElementType, (int)visualElementType);
}
void SwitchDefaultVisualElementType()
{
SetDefaultVisualElementType(defaultVisualElementType == (int)DefaultVisualElementType.NoStyles
? DefaultVisualElementType.Styled
: DefaultVisualElementType.NoStyles);
}
BuilderLibraryTreeView controlsTreeView
{
get
{
if (m_ControlsTreeView != null)
return m_ControlsTreeView;
var controlsTree = m_EditorExtensionMode
? BuilderLibraryContent.standardControlsTree
: BuilderLibraryContent.standardControlsTreeNoEditor;
m_ControlsTreeView = new BuilderLibraryTreeView(controlsTree);
m_ControlsTreeView.viewDataKey = "unity-ui-builder-library-controls-tree";
SetUpLibraryView(m_ControlsTreeView);
return m_ControlsTreeView;
}
}
BuilderLibraryTreeView projectTreeView
{
get
{
if (m_ProjectTreeView != null)
return m_ProjectTreeView;
var projectContentTree = m_ShowPackageTemplates
? BuilderLibraryContent.projectContentTree
: BuilderLibraryContent.projectContentTreeNoPackages;
m_ProjectTreeView = new BuilderLibraryTreeView(projectContentTree);
m_ProjectTreeView.viewDataKey = "unity-ui-builder-library-project-view";
SetUpLibraryView(m_ProjectTreeView);
return m_ProjectTreeView;
}
}
BuilderLibraryPlainView controlsPlainView
{
get
{
if (m_ControlsPlainView != null)
return m_ControlsPlainView;
var controlsTree = m_EditorExtensionMode
? BuilderLibraryContent.standardControlsTree
: BuilderLibraryContent.standardControlsTreeNoEditor;
m_ControlsPlainView = new BuilderLibraryPlainView(controlsTree);
m_ControlsPlainView.viewDataKey = "unity-ui-builder-library-controls-plane";
SetUpLibraryView(m_ControlsPlainView);
return m_ControlsPlainView;
}
}
void SetUpLibraryView(BuilderLibraryView builderLibraryView)
{
builderLibraryView.SetupView(m_Dragger, m_TooltipPreview,
this, m_PaneWindow,
m_DocumentElement, m_Selection);
}
void RebuildView()
{
m_LibraryContentContainer.Clear();
m_ProjectTreeView = null;
m_ControlsPlainView = null;
m_ControlsTreeView = null;
RefreshView();
}
void RefreshView()
{
m_LibraryContentContainer.Clear();
var builderLibraryOptions = new ToggleButtonGroupState(0, Enum.GetNames(typeof(BuilderLibraryTab)).Length);
builderLibraryOptions[(int)m_ActiveTab] = true;
m_HeaderButtonStrip.SetValueWithoutNotify(builderLibraryOptions);
switch (m_ActiveTab)
{
case BuilderLibraryTab.Standard:
if (m_ViewMode == LibraryViewMode.TreeView)
SetActiveView(controlsTreeView);
else
SetActiveView(controlsPlainView);
break;
case BuilderLibraryTab.Project:
SetActiveView(projectTreeView);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
void SetActiveView(BuilderLibraryView builderLibraryView)
{
m_LibraryContentContainer.Add(builderLibraryView);
builderLibraryView.Refresh();
primaryFocusable = builderLibraryView.primaryFocusable;
}
public void ResetCurrentlyLoadedUxmlStyles()
{
RefreshView();
}
public void SelectionChanged() { }
public void HierarchyChanged(VisualElement element, BuilderHierarchyChangeType changeType) { }
public void StylingChanged(List<string> styles, BuilderStylingChangeType changeType)
{
if (m_EditorExtensionMode != m_PaneWindow.document.fileSettings.editorExtensionMode)
{
m_EditorExtensionMode = m_PaneWindow.document.fileSettings.editorExtensionMode;
RebuildView();
}
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibrary.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibrary.cs",
"repo_id": "UnityCsReference",
"token_count": 5721
} | 472 |
// 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;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
class BuilderTransformer : BuilderManipulator
{
[Serializable]
public new class UxmlSerializedData : BuilderManipulator.UxmlSerializedData
{
public override object CreateInstance() => new BuilderTransformer();
}
static readonly string s_UssClassName = "unity-builder-transformer";
static readonly string s_ActiveHandleClassName = "unity-builder-transformer--active";
public static readonly string s_DisabledHandleClassName = "unity-builder-transformer--disabled";
protected List<string> m_ScratchChangeList;
VisualElement m_DragHoverCoverLayer;
protected float m_TargetCorrectedBottomOnStartDrag;
protected float m_TargetCorrectedRightOnStartDrag;
protected Rect m_TargetRectOnStartDrag;
protected Rect m_ThisRectOnStartDrag;
public BuilderTransformer()
{
var builderTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(
BuilderConstants.UIBuilderPackagePath + "/Manipulators/BuilderTransformer.uxml");
builderTemplate.CloneTree(this);
AddToClassList(s_UssClassName);
m_ScratchChangeList = new List<string>();
m_DragHoverCoverLayer = this.Q("drag-hover-cover-layer");
}
protected void OnStartDrag(VisualElement handle)
{
bool isScaledOrRotated = !Mathf.Approximately(m_Target.computedStyle.rotate.angle.value, 0) || m_Target.computedStyle.scale != Scale.Initial();
if (isScaledOrRotated)
{
Builder.ShowWarning(BuilderConstants.CannotManipulateResizedOrScaledItemMessage);
}
m_TargetRectOnStartDrag = m_Target.layout;
m_ThisRectOnStartDrag = this.layout;
// Adjust for margins.
var targetMarginTop = m_Target.resolvedStyle.marginTop;
var targetMarginLeft = m_Target.resolvedStyle.marginLeft;
var targetMarginBottom = m_Target.resolvedStyle.marginBottom;
var targetMarginRight = m_Target.resolvedStyle.marginRight;
m_TargetRectOnStartDrag.y -= targetMarginTop;
m_TargetRectOnStartDrag.x -= targetMarginLeft;
// Adjust for parent borders.
var parentBorderTop = m_Target.parent.resolvedStyle.borderTopWidth;
var parentBorderLeft = m_Target.parent.resolvedStyle.borderLeftWidth;
var parentBorderBottom = m_Target.parent.resolvedStyle.borderBottomWidth;
var parentBorderRight = m_Target.parent.resolvedStyle.borderRightWidth;
m_TargetRectOnStartDrag.y -= parentBorderTop;
m_TargetRectOnStartDrag.x -= parentBorderLeft;
var parentRect = m_Target.parent.layout;
m_TargetCorrectedBottomOnStartDrag =
parentRect.height - m_TargetRectOnStartDrag.yMax - targetMarginTop - targetMarginBottom - parentBorderTop - parentBorderBottom;
m_TargetCorrectedRightOnStartDrag =
parentRect.width - m_TargetRectOnStartDrag.xMax - targetMarginLeft - targetMarginRight - parentBorderLeft - parentBorderRight;
// This is a bit of a hack since the base class constructor always runs before
// the child class' constructor, therefore, our hover overlay will be first
// in the parent, not last. We need to make it last the first time.
if (m_DragHoverCoverLayer.parent.IndexOf(m_DragHoverCoverLayer) != m_DragHoverCoverLayer.parent.childCount - 1)
m_DragHoverCoverLayer.BringToFront();
m_DragHoverCoverLayer.style.display = DisplayStyle.Flex;
m_DragHoverCoverLayer.style.cursor = handle.computedStyle.cursor;
}
protected virtual void OnEndDrag()
{
m_DragHoverCoverLayer.style.display = DisplayStyle.None;
m_DragHoverCoverLayer.RemoveFromClassList(s_ActiveClassName);
}
protected class Manipulator : PointerManipulator
{
Vector3 m_Start;
protected bool m_Active;
Action<VisualElement> m_StartDrag;
Action m_EndDrag;
Action<Vector2> m_DragAction;
public Manipulator(Action<VisualElement> startDrag, Action endDrag, Action<Vector2> dragAction)
{
m_StartDrag = startDrag;
m_EndDrag = endDrag;
m_DragAction = dragAction;
activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse });
m_Active = false;
}
protected override void RegisterCallbacksOnTarget()
{
target.RegisterCallback<PointerDownEvent>(OnPointerDown);
target.RegisterCallback<PointerMoveEvent>(OnPointerMove);
target.RegisterCallback<PointerUpEvent>(OnPointerUp);
}
protected override void UnregisterCallbacksFromTarget()
{
target.UnregisterCallback<PointerDownEvent>(OnPointerDown);
target.UnregisterCallback<PointerMoveEvent>(OnPointerMove);
target.UnregisterCallback<PointerUpEvent>(OnPointerUp);
}
protected void OnPointerDown(PointerDownEvent e)
{
if (m_Active || target.ClassListContains(s_DisabledHandleClassName))
{
e.StopImmediatePropagation();
return;
}
if (CanStartManipulation(e))
{
// Ignore double-click to allow text editing of the selected element
if (e.clickCount == 2)
return;
m_StartDrag(target);
m_Start = e.position;
m_Active = true;
target.CaptureMouse();
e.StopPropagation();
target.AddToClassList(s_ActiveHandleClassName);
}
}
protected void OnPointerMove(PointerMoveEvent e)
{
if (!m_Active || !target.HasMouseCapture())
return;
Vector2 diff = e.position - m_Start;
m_DragAction(diff);
e.StopPropagation();
}
protected void OnPointerUp(PointerUpEvent e)
{
if (!m_Active || !target.HasMouseCapture() || !CanStopManipulation(e))
return;
m_Active = false;
target.ReleaseMouse();
e.StopPropagation();
m_EndDrag();
target.RemoveFromClassList(s_ActiveHandleClassName);
}
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderTransformer.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderTransformer.cs",
"repo_id": "UnityCsReference",
"token_count": 3202
} | 473 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
// TODO: Hack. We need this because EditorGUIUtility.systemCopyBuffer is always empty on Mac in BatchMode.
static class BuilderEditorUtility
{
static string s_FakeSystemCopyBuffer = string.Empty;
public static string systemCopyBuffer
{
get
{
if (Application.isBatchMode && Application.platform == RuntimePlatform.OSXEditor)
return s_FakeSystemCopyBuffer;
return EditorGUIUtility.systemCopyBuffer;
}
set
{
if (Application.isBatchMode && Application.platform == RuntimePlatform.OSXEditor)
s_FakeSystemCopyBuffer = value;
else
EditorGUIUtility.systemCopyBuffer = value;
}
}
public static bool CopyBufferMatchesTarget(VisualElement target)
{
if (target == null)
return false;
var copyBuffer = systemCopyBuffer;
if (string.IsNullOrEmpty(copyBuffer))
return false;
if (IsUxml(copyBuffer) && (target.GetFirstOfType<BuilderHierarchy>() != null || target.GetFirstOfType<BuilderViewport>() != null))
return true;
if (IsUss(copyBuffer) && target.GetFirstOfType<BuilderStyleSheets>() != null)
return true;
// Unknown string.
return false;
}
public static bool IsUxml(string buffer)
{
if (string.IsNullOrEmpty(buffer))
return false;
var trimmedBuffer = buffer.Trim();
return trimmedBuffer.StartsWith("<") && trimmedBuffer.EndsWith(">");
}
public static bool IsUss(string buffer)
{
if (string.IsNullOrEmpty(buffer))
return false;
var trimmedBuffer = buffer.Trim();
return trimmedBuffer.EndsWith("}");
}
static int SearchCharSeq(string numAsText, char c, int minSeqCount)
{
// check if there is a decimal number separator
if (numAsText.Contains("."))
{
int lastIndex = numAsText.Length - 2; // ignore the last character as it is not relevant. E.g 0.1999992
int indexOffset = 0;
// search for the left most index of the sequence of characters
while (numAsText[lastIndex - indexOffset] == c)
{
indexOffset++;
}
// If the number of characters in the sequence is greater than the expected minimum then
// we assume a round off error.
bool hasRoundOffError = (indexOffset >= minSeqCount);
if (hasRoundOffError)
{
return lastIndex - indexOffset;
}
}
return -1;
}
public static float FixRoundOff(float value)
{
const int seqCount = 3;
string str = value.ToString();
// search a sequence of 9s at the end of the value
int seqIndex = SearchCharSeq(str, '9', seqCount);
// if there is no sequence of 9s then search sequence of 0s
if (seqIndex == -1)
seqIndex = SearchCharSeq(str, '0', seqCount);
if (seqIndex != -1)
{
return (float)Math.Round(value, seqIndex + 1);
}
return value;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderEditorUtility.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderEditorUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 1809
} | 474 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderUxmlIntAttributeFieldFactory : BuilderTypedUxmlAttributeFieldFactoryBase<int, BaseField<int>>
{
protected override BaseField<int> InstantiateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute)
{
if (attribute.name.Equals("value") && attributeOwner is LayerField)
{
return new LayerField();
}
if (attribute.name.Equals("value") && attributeOwner is LayerMaskField)
{
return new LayerMaskField();
}
if (attribute.name.Equals("fixed-item-height") &&
attributeOwner is BaseVerticalCollectionView)
{
var uiField = new IntegerField(BuilderNameUtilities.ConvertDashToHuman(attribute.name));
uiField.isDelayed = true;
uiField.RegisterCallback<InputEvent>(OnFixedHeightValueChangedImmediately);
uiField.labelElement.RegisterCallback<PointerMoveEvent>(OnFixedHeightValueChangedImmediately);
return uiField;
}
return new IntegerField();
}
public override void SetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, object value)
{
if (field is IntegerField && attribute.name.Equals("fixed-item-height") && attributeOwner is BaseVerticalCollectionView)
{
var styleRow = field.GetProperty(BuilderConstants.InspectorLinkedStyleRowVEPropertyName) as BuilderStyleRow;
styleRow?.contentContainer.AddToClassList(BuilderConstants.InspectorFixedItemHeightFieldClassName);
}
if (field is LayerField layerField)
{
var layerFieldAttributeOwner = attributeOwner as LayerField;
layerField.SetValueWithoutNotify(layerFieldAttributeOwner.value);
}
else if (field is LayerMaskField layerMaskField)
{
var layerMaskFieldAttributeOwner = attributeOwner as LayerMaskField;
layerMaskField.SetValueWithoutNotify(layerMaskFieldAttributeOwner.value);
}
else
{
if (value is float)
value = Convert.ToInt32(value);
base.SetFieldValue(field, attributeOwner, uxmlDocument, attributeUxmlOwner, attribute, value);
}
}
void OnFixedItemHeightValueChanged(ChangeEvent<int> evt, UxmlAttributeDescription attribute, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
var field = evt.currentTarget as IntegerField;
if (evt.newValue < 1)
{
SetNegativeFixedItemHeightHelpBoxEnabled(true,field);
field.SetValueWithoutNotify(1);
onValueChange?.Invoke(field, attribute, field.value, ValueToUxml.Convert(field.value));
return;
}
onValueChange?.Invoke(field, attribute, evt.newValue, ValueToUxml.Convert(evt.newValue));
}
void OnFixedHeightValueChangedImmediately(InputEvent evt)
{
var field = evt.currentTarget as BaseField<int>;
if (field == null)
return;
var newValue = evt.newData;
var valueResolved = UINumericFieldsUtils.TryConvertStringToLong(newValue, out var v);
var resolvedValue = valueResolved ? Mathf.ClampToInt(v) : field.value;
SetNegativeFixedItemHeightHelpBoxEnabled((newValue.Length != 0 && (resolvedValue < 1 || newValue.Equals("-"))), field);
}
void OnFixedHeightValueChangedImmediately(PointerMoveEvent evt)
{
if (evt.target is not Label labelElement)
return;
var field = labelElement.parent as TextInputBaseField<int>;
if (field == null)
return;
var valueResolved = UINumericFieldsUtils.TryConvertStringToLong(field.text, out var v);
var resolvedValue = valueResolved ? Mathf.ClampToInt(v) : field.value;
SetNegativeFixedItemHeightHelpBoxEnabled((resolvedValue < 1 || field.text.ToCharArray()[0].Equals('-')), field);
}
void SetNegativeFixedItemHeightHelpBoxEnabled(bool enabled, BaseField<int> field)
{
var negativeWarningHelpBox = field.parent.Q<UnityEngine.UIElements.HelpBox>();
if (enabled)
{
if (negativeWarningHelpBox == null)
{
negativeWarningHelpBox = new UnityEngine.UIElements.HelpBox(
L10n.Tr(BuilderConstants.HeightIntFieldValueCannotBeNegativeMessage), HelpBoxMessageType.Warning);
field.parent.Add(negativeWarningHelpBox);
negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorShownNegativeWarningMessageClassName, true);
}
else
{
negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorShownNegativeWarningMessageClassName, true);
negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorHiddenNegativeWarningMessageClassName, false);
}
return;
}
if (negativeWarningHelpBox == null)
return;
negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorHiddenNegativeWarningMessageClassName, true);
negativeWarningHelpBox.EnableInClassList(BuilderConstants.InspectorShownNegativeWarningMessageClassName, false);
}
protected override void NotifyValueChanged(ChangeEvent<int> evt, BaseField<int> field
, object attributeOwner
, UxmlAsset attributeUxmlOwner
, UxmlAttributeDescription attribute
, string uxmlValue
, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
if (attribute.name.Equals("fixed-item-height") &&
attributeOwner is BaseVerticalCollectionView)
{
OnFixedItemHeightValueChanged(evt, attribute, onValueChange);
return;
}
onValueChange?.Invoke(field, attribute, evt.newValue, uxmlValue);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlIntAttributeField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlIntAttributeField.cs",
"repo_id": "UnityCsReference",
"token_count": 2936
} | 475 |
// 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;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
using PopupWindow = UnityEditor.PopupWindow;
namespace Unity.UI.Builder
{
using Item = CategoryDropdownContent.Item;
using ItemType = CategoryDropdownContent.ItemType;
partial class CategoryDropdownField
{
class WindowContent : PopupWindowContent
{
const string k_UssPath = BuilderConstants.UtilitiesPath + "/CategoryDropdownField/CategoryDropdownContent.uss";
const string k_SelectionContextKey = "CategoryDropdownField.SelectionContext";
const string k_BaseClass = "unity-category-dropdown-field";
const string k_Category = k_BaseClass + "__category";
const string k_Item = k_BaseClass + "__item";
const string k_ItemInCategory = k_BaseClass + "__category-item";
const string k_Separator = k_BaseClass + "__separator";
const string k_SearchField = k_BaseClass + "__search-field";
class SelectionContext
{
public int index;
public Item item;
public WindowContent content;
}
static readonly UnityEngine.Pool.ObjectPool<TextElement> s_CategoryPool = new UnityEngine.Pool.ObjectPool<TextElement>(() =>
{
var category = new TextElement();
category.AddToClassList(k_Category);
return category;
}, null, te =>
{
te.style.display = DisplayStyle.Flex;
});
static readonly UnityEngine.Pool.ObjectPool<TextElement> s_ItemPool = new UnityEngine.Pool.ObjectPool<TextElement>(() =>
{
var value = new TextElement();
value.style.display = DisplayStyle.Flex;
value.AddToClassList(k_Item);
return value;
}, null, te =>
{
te.pseudoStates &= ~PseudoStates.Checked;
te.style.display = DisplayStyle.Flex;
te.RemoveFromClassList(k_ItemInCategory);
});
static readonly UnityEngine.Pool.ObjectPool<VisualElement> s_SeparatorPool = new UnityEngine.Pool.ObjectPool<VisualElement>(() =>
{
var separator = new VisualElement();
separator.AddToClassList(k_Separator);
return separator;
}, null, ve =>
{
ve.style.display = DisplayStyle.Flex;
});
readonly List<Item> m_Items = new List<Item>();
Vector2 m_Size;
string m_CurrentActiveValue;
int m_SelectedIndex = -1;
ScrollView m_ScrollView;
KeyboardNavigationManipulator m_NavigationManipulator;
public event Action<string> onSelectionChanged;
public void Show(Rect rect, string currentValue, IEnumerable<Item> items)
{
m_CurrentActiveValue = currentValue;
m_Items.Clear();
m_Items.AddRange(items);
m_Size = new Vector2(rect.width, 225);
PopupWindow.Show(rect, this);
}
public override void OnOpen()
{
var styleSheet = BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPath);
editorWindow.rootVisualElement.styleSheets.Add(styleSheet);
editorWindow.rootVisualElement.focusable = true;
editorWindow.rootVisualElement.AddToClassList(k_BaseClass);
editorWindow.rootVisualElement.AddManipulator(m_NavigationManipulator = new KeyboardNavigationManipulator(Apply));
var searchField = new ToolbarSearchField();
searchField.AddToClassList(k_SearchField);
searchField.RegisterCallback<AttachToPanelEvent>(evt =>
{
evt.elementTarget?.Focus();
});
searchField.RegisterCallback<KeyDownEvent>(evt =>
{
switch (evt.keyCode)
{
case KeyCode.UpArrow:
case KeyCode.DownArrow:
case KeyCode.PageDown:
case KeyCode.PageUp:
evt.StopPropagation();
m_ScrollView.Focus();
break;
case KeyCode.Return:
case KeyCode.KeypadEnter:
evt.StopPropagation();
if (string.IsNullOrWhiteSpace(searchField.value) || m_SelectedIndex < 0)
{
m_ScrollView.Focus();
return;
}
onSelectionChanged?.Invoke(m_Items[m_SelectedIndex].value);
editorWindow.Close();
break;
}
});
editorWindow.rootVisualElement.RegisterCallback<KeyDownEvent>(evt =>
{
searchField.Focus();
});
searchField.RegisterValueChangedCallback(OnSearchChanged);
editorWindow.rootVisualElement.Add(searchField);
m_ScrollView = new ScrollView();
m_ScrollView.RegisterCallback<GeometryChangedEvent, ScrollView>((evt, sv) =>
{
if (m_SelectedIndex >= 0)
sv.ScrollTo(sv[m_SelectedIndex]);
}, m_ScrollView);
var selectionWasSet = false;
for (var i = 0; i < m_Items.Count; ++i)
{
var property = m_Items[i];
var element = GetPooledItem(property, i);
m_ScrollView.Add(element);
if (selectionWasSet)
continue;
if (property.itemType != ItemType.Item || property.value != m_CurrentActiveValue)
continue;
m_SelectedIndex = i;
element.pseudoStates |= PseudoStates.Checked;
selectionWasSet = true;
}
editorWindow.rootVisualElement.RegisterCallback<KeyDownEvent>(evt =>
{
if (evt.keyCode == KeyCode.F && evt.actionKey)
{
searchField.Focus();
}
}, TrickleDown.TrickleDown);
editorWindow.rootVisualElement.Add(m_ScrollView);
}
public override void OnClose()
{
editorWindow.rootVisualElement.RemoveManipulator(m_NavigationManipulator);
// Return to pool
for (var i = 0; i < m_Items.Count; ++i)
{
switch(m_Items[i].itemType)
{
case ItemType.Category:
s_CategoryPool.Release((TextElement)m_ScrollView[i]);
break;
case ItemType.Separator:
s_SeparatorPool.Release(m_ScrollView[i]);
break;
case ItemType.Item:
s_ItemPool.Release((TextElement)m_ScrollView[i]);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
m_ScrollView.Clear();
}
bool SetSelection(int index)
{
if (index < 0 || index >= m_ScrollView.childCount)
{
if (m_SelectedIndex >= 0)
{
var previous = m_ScrollView[m_SelectedIndex];
previous.pseudoStates &= ~PseudoStates.Checked;
}
m_SelectedIndex = -1;
return false;
}
if (m_SelectedIndex >= 0)
{
var previous = m_ScrollView[m_SelectedIndex];
previous.pseudoStates &= ~PseudoStates.Checked;
}
m_SelectedIndex = index;
var next = m_ScrollView[m_SelectedIndex];
next.pseudoStates |= PseudoStates.Checked;
m_ScrollView.ScrollTo(next);
return true;
}
void ResetSearch()
{
for (var i = 0; i < m_ScrollView.childCount; ++i)
{
var element = m_ScrollView[i];
element.style.display = DisplayStyle.Flex;
}
}
void OnSearchChanged(ChangeEvent<string> evt)
{
var searchString = evt.newValue;
if (string.IsNullOrEmpty(searchString))
{
ResetSearch();
return;
}
for (var i = 0; i < m_Items.Count; ++i)
{
var item = m_Items[i];
var element = m_ScrollView[i];
switch (item.itemType)
{
case ItemType.Category:
{
var categoryIndex = i;
var shouldDisplayCategory = false;
// Manually iterate through the item of the current category
for (; i + 1 < m_Items.Count; ++i)
{
var sub = i + 1;
var categoryItem = m_Items[sub];
var categoryElement = m_ScrollView[sub];
if (categoryItem.itemType == ItemType.Item &&
categoryItem.categoryName == item.displayName)
{
if (categoryItem.displayName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 ||
categoryItem.value?.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
shouldDisplayCategory = true;
categoryElement.style.display = DisplayStyle.Flex;
}
else
{
categoryElement.style.display = DisplayStyle.None;
}
}
else
break;
}
m_ScrollView[categoryIndex].style.display = shouldDisplayCategory ? DisplayStyle.Flex : DisplayStyle.None;
break;
}
case ItemType.Item:
if (item.displayName.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0 ||
item.value?.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)
{
element.style.display = DisplayStyle.Flex;
}
else
{
element.style.display = DisplayStyle.None;
}
break;
case ItemType.Separator:
m_ScrollView[i].style.display = DisplayStyle.None;
break;
}
}
// Check if previous selection is still visible, otherwise select the first shown item
if (m_SelectedIndex >= 0 && m_ScrollView[m_SelectedIndex].style.display == DisplayStyle.Flex)
return;
if (!SelectFirstDisplayedItem())
SetSelection(-1);
}
VisualElement GetPooledItem(Item item, int index)
{
switch (item.itemType)
{
case ItemType.Category:
var category = s_CategoryPool.Get();
category.text = item.displayName;
return category;
case ItemType.Separator:
return s_SeparatorPool.Get();
case ItemType.Item:
var element = s_ItemPool.Get();
element.text = item.displayName;
element.tooltip = item.value;
var context = (SelectionContext)element.GetProperty(k_SelectionContextKey);
if (null == context)
{
context = new SelectionContext();
element.SetProperty(k_SelectionContextKey, context);
element.RegisterCallback<PointerUpEvent>(OnItemSelected);
}
context.index = index;
context.item = item;
context.content = this;
if (!string.IsNullOrWhiteSpace(item.categoryName))
element.AddToClassList(k_ItemInCategory);
return element;
default:
throw new ArgumentOutOfRangeException();
}
}
void OnItemSelected(PointerUpEvent evt)
{
var e = evt.elementTarget;
var ctx = (SelectionContext) e.GetProperty(k_SelectionContextKey);
// We must go through the context here, because the elements are pooled and the closure would bind on
// the previous time the element was used.
ctx.content.SetSelection(ctx.index);
ctx.content.onSelectionChanged?.Invoke(ctx.item.value);
ctx.content.editorWindow.Close();
}
bool SelectFirstDisplayedItem()
{
for (var i = 0; i < m_Items.Count; ++i)
{
if (m_Items[i].itemType == ItemType.Item && m_ScrollView[i].style.display == DisplayStyle.Flex)
return SetSelection(i);
}
return false;
}
bool SelectLastDisplayedItem()
{
for (var i = m_Items.Count - 1; i >= 0; --i)
{
if (m_Items[i].itemType == ItemType.Item && m_ScrollView[i].style.display == DisplayStyle.Flex)
return SetSelection(i);
}
return false;
}
bool SelectNextDisplayedItem(int offset = 1)
{
var current = m_SelectedIndex;
var initialIndex = Mathf.Clamp(m_SelectedIndex + offset, 0, m_Items.Count - 1);
for (var i = initialIndex; i < m_Items.Count; ++i)
{
if (m_Items[i].itemType == ItemType.Item &&
m_ScrollView[i].style.display == DisplayStyle.Flex
&& i != current)
return SetSelection(i);
}
return false;
}
bool SelectPreviousDisplayedItem(int offset = 1)
{
var current = m_SelectedIndex;
var initialIndex = Mathf.Clamp(m_SelectedIndex - offset, 0, m_Items.Count - 1);
for (var i = initialIndex; i >= 0; --i)
{
if (m_Items[i].itemType == ItemType.Item &&
m_ScrollView[i].style.display == DisplayStyle.Flex &&
i != current)
{
return SetSelection(i);
}
}
return false;
}
void Apply(KeyboardNavigationOperation op, EventBase sourceEvent)
{
if (!Apply(op))
return;
sourceEvent.StopImmediatePropagation();
}
bool Apply(KeyboardNavigationOperation op)
{
switch (op)
{
case KeyboardNavigationOperation.None:
case KeyboardNavigationOperation.SelectAll:
break;
case KeyboardNavigationOperation.Cancel:
editorWindow.Close();
break;
case KeyboardNavigationOperation.Submit:
if (m_SelectedIndex < 0)
return false;
onSelectionChanged?.Invoke(m_Items[m_SelectedIndex].value);
editorWindow.Close();
break;
case KeyboardNavigationOperation.Previous:
{
return SelectPreviousDisplayedItem() ||
SelectLastDisplayedItem();
}
case KeyboardNavigationOperation.Next:
{
return SelectNextDisplayedItem() ||
SelectFirstDisplayedItem();
}
case KeyboardNavigationOperation.PageUp:
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
return SelectPreviousDisplayedItem(10) ||
SelectFirstDisplayedItem() ||
true;
}
case KeyboardNavigationOperation.PageDown:
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
return SelectNextDisplayedItem(10) ||
SelectLastDisplayedItem() ||
true;
}
case KeyboardNavigationOperation.Begin:
{
SelectFirstDisplayedItem();
return true;
}
case KeyboardNavigationOperation.End:
{
SelectLastDisplayedItem();
return true;
}
}
return false;
}
public override void OnGUI(Rect rect)
{
// Intentionally left empty.
}
public override Vector2 GetWindowSize()
{
return m_Size;
}
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/CategoryDropdownField/CategoryDropdownField+WindowContent.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/CategoryDropdownField/CategoryDropdownField+WindowContent.cs",
"repo_id": "UnityCsReference",
"token_count": 11276
} | 476 |
// 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.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderVisualTreeAssetImporter : UXMLImporterImpl
{
public BuilderVisualTreeAssetImporter()
{
}
public override UnityEngine.Object DeclareDependencyAndLoad(string path)
{
return BuilderPackageUtilities.LoadAssetAtPath<UnityEngine.Object>(path);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/Importers/BuilderVisualTreeAssetImporter.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/Importers/BuilderVisualTreeAssetImporter.cs",
"repo_id": "UnityCsReference",
"token_count": 207
} | 477 |
// 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 Unity.UI.Builder
{
/// <summary>
/// Control that displays, using the appropriate icons, the status of a field based on the type, the value binding,
/// the value source of the underlying property. It also provides access to the field's contextual upon left click.
/// </summary>
class FieldStatusIndicator : VisualElement
{
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField, UxmlAttribute("field-name")] string targetFieldName;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags targetFieldName_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new FieldStatusIndicator();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
if (ShouldWriteAttributeValue(targetFieldName_UxmlAttributeFlags))
{
var e = (FieldStatusIndicator)obj;
e.targetFieldName = targetFieldName;
}
}
}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public static readonly string s_UssClassName = "unity-builder-field-status-indicator";
/// <summary>
/// Name of the content element.
/// </summary>
public static readonly string s_ContentElementName = "content-element";
/// <summary>
/// USS class name of content elements in elements of this type.
/// </summary>
public static readonly string s_ContentElementUSSClassName = s_UssClassName + "__content";
/// <summary>
/// Name of the icon element.
/// </summary>
public static readonly string s_IconElementName = "icon-element";
/// <summary>
/// USS class name of icon elements in elements of this type.
/// </summary>
public static readonly string s_IconElementUSSClassName = s_UssClassName + "__icon";
/// <summary>
/// Name of the property used to directly look up for the FieldStatusIndicator object associated to a given field.
/// </summary>
public static readonly string s_FieldStatusIndicatorVEPropertyName = "__unity-ui-builder-field-status-indicator";
VisualElement m_TargetField;
/// <summary>
/// Callback used to add menu items to the contextual menu of the associated field before it opens.
/// </summary>
public Action<DropdownMenu> populateMenuItems;
/// <summary>
/// The field associated with this FieldStatusIndicator.
/// </summary>
public VisualElement targetField
{
get => m_TargetField;
set
{
if (m_TargetField == value)
return;
if (m_TargetField != null)
m_TargetField.SetProperty(s_FieldStatusIndicatorVEPropertyName, null);
m_TargetField = value;
if (m_TargetField != null)
m_TargetField.SetProperty(s_FieldStatusIndicatorVEPropertyName, this);
}
}
/// <summary>
/// The name of the field to be associated to when the indicator is added to a StyleRow in UXML.
/// </summary>
public string targetFieldName { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
public FieldStatusIndicator()
: base()
{
AddToClassList(s_UssClassName);
var contextMenuManipulator = new ContextualMenuManipulator((evt) =>
{
populateMenuItems(evt.menu);
// stop immediately to not propagate the event to the row.
evt.StopImmediatePropagation();
});
// show menu also on left-click
contextMenuManipulator.activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse });
var contentElement = new VisualElement { name = s_ContentElementName };
contentElement.AddToClassList(s_ContentElementUSSClassName);
contentElement.AddManipulator(contextMenuManipulator);
var iconElement = new VisualElement()
{
name = s_IconElementName,
pickingMode = PickingMode.Ignore
};
iconElement.AddToClassList(s_IconElementUSSClassName);
contentElement.Add(iconElement);
Add(contentElement);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FieldStatusIndicator.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FieldStatusIndicator.cs",
"repo_id": "UnityCsReference",
"token_count": 2042
} | 478 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class StyleFieldPopupWindow : EditorWindow
{
VisualElement m_Content;
private float m_LastHeight;
public VisualElement content
{
get => m_Content;
set
{
if (m_Content == value)
return;
if (m_Content != null)
{
m_Content.RemoveFromHierarchy();
m_Content.UnregisterCallback<GeometryChangedEvent>(OnGeometryChanged);
}
m_Content = value;
m_LastHeight = 0;
if (m_Content != null)
{
rootVisualElement.Add(m_Content);
m_Content.style.position = Position.Relative;
m_Content.style.flexGrow = 0;
m_Content.style.flexShrink = 0;
m_Content.RegisterCallback<GeometryChangedEvent>(OnGeometryChanged);
ResizeToContent();
}
}
}
public event Action closed;
void OnGeometryChanged(GeometryChangedEvent evt)
{
if (m_Parent == null)
return;
ResizeToContent();
}
public void ResizeToContent()
{
if (m_Parent == null || m_Parent.window == null || float.IsNaN(content.layout.width) || float.IsNaN(content.layout.height))
return;
if (Mathf.Approximately(m_LastHeight, content.layout.height))
return;
m_LastHeight = content.layout.height;
rootVisualElement.schedule.Execute(() =>
{
var pos = m_Parent.window.position;
pos.height = content.layout.height;
position = pos;
});
}
private void OnDisable()
{
content = null;
closed?.Invoke();
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/StyleFieldPopupWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/StyleFieldPopupWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 1157
} | 479 |
// 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.Linq;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEngine.UIElements.StyleSheets;
namespace Unity.UI.Builder
{
internal static class StyleRuleExtensions
{
public static StyleProperty FindLastProperty(this StyleSheet styleSheet, StyleRule rule, string propertyName)
{
if (rule == null)
return null;
for (var i = rule.properties.Length - 1; i >= 0; --i)
{
var property = rule.properties[i];
if (property.name == propertyName)
return property;
}
return null;
}
public static StyleProperty AddProperty(
this StyleSheet styleSheet, StyleRule rule, string name,
string undoMessage = null)
{
// Undo/Redo
if (string.IsNullOrEmpty(undoMessage))
undoMessage = "Change UI Style Value";
Undo.RegisterCompleteObjectUndo(styleSheet, undoMessage);
var newProperty = new StyleProperty
{
name = name
};
// Create empty values array.
newProperty.values = new StyleValueHandle[0];
// Add property to selector's rule's properties.
var properties = rule.properties.ToList();
properties.Add(newProperty);
rule.properties = properties.ToArray();
styleSheet.UpdateContentHash();
StyleSheetCache.ClearCaches();
return newProperty;
}
public static void RemoveProperty(
this StyleSheet styleSheet, StyleRule rule, StyleProperty property, string undoMessage = null)
{
// Undo/Redo
if (string.IsNullOrEmpty(undoMessage))
undoMessage = BuilderConstants.ChangeUIStyleValueUndoMessage;
Undo.RegisterCompleteObjectUndo(styleSheet, undoMessage);
var properties = rule.properties.ToList();
properties.Remove(property);
rule.properties = properties.ToArray();
styleSheet.UpdateContentHash();
}
public static void RemoveProperty(this StyleSheet styleSheet, StyleRule rule,
string name, string undoMessage = null)
{
var property = styleSheet.FindLastProperty(rule, name);
if (property == null)
return;
styleSheet.RemoveProperty(rule, property, undoMessage);
}
public static IEnumerable<string> GetAllSetStyleProperties(this StyleRule styleRule)
{
foreach (var property in styleRule.properties)
{
if (StylePropertyUtil.propertyNameToStylePropertyId.ContainsKey(property.name))
yield return property.name;
}
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleRuleExtensions.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleRuleExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 1339
} | 480 |
// 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 Unity.UI.Builder
{
// HACK: We need a valid UIElement now that selection state is stored inside the live uxml
// asset that is potentially used elsewhere. This mock element will immediately remove
// itself from the hierarchy as soon as it's added.
// This should be removed once selection is moved to a separate object. See:
// https://unity3d.atlassian.net/browse/UIT-456
internal class UnityUIBuilderSelectionMarker : VisualElement
{
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new UnityUIBuilderSelectionMarker();
}
public UnityUIBuilderSelectionMarker() {}
[EventInterest(typeof(AttachToPanelEvent))]
protected override void HandleEventBubbleUp(EventBase evt)
{
base.HandleEventBubbleUp(evt);
if (evt.eventTypeId != AttachToPanelEvent.TypeId())
return;
RemoveFromHierarchy();
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/UnityUIBuilderSelectionMarker/UnityUIBuilderSelectionMarker.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/UnityUIBuilderSelectionMarker/UnityUIBuilderSelectionMarker.cs",
"repo_id": "UnityCsReference",
"token_count": 459
} | 481 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Properties;
namespace UnityEngine.UIElements
{
public partial struct BackgroundRepeat
{
internal class PropertyBag : ContainerPropertyBag<BackgroundRepeat>
{
class XProperty : Property<BackgroundRepeat, Repeat>
{
public override string Name { get; } = nameof(x);
public override bool IsReadOnly { get; } = false;
public override Repeat GetValue(ref BackgroundRepeat container) => container.x;
public override void SetValue(ref BackgroundRepeat container, Repeat value) => container.x = value;
}
class YProperty : Property<BackgroundRepeat, Repeat>
{
public override string Name { get; } = nameof(y);
public override bool IsReadOnly { get; } = false;
public override Repeat GetValue(ref BackgroundRepeat container) => container.y;
public override void SetValue(ref BackgroundRepeat container, Repeat value) => container.y = value;
}
public PropertyBag()
{
AddProperty(new XProperty());
AddProperty(new YProperty());
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/BackgroundRepeat.PropertyBag.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/BackgroundRepeat.PropertyBag.cs",
"repo_id": "UnityCsReference",
"token_count": 568
} | 482 |
// 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.Internal;
namespace UnityEngine.UIElements
{
// Important Note:
// Data binding uses the UxmlSerialization system and does not support UxmlTraits/UxmlFactories.
// <see cref="VisualElement"/>'s traits do not contain the binding attribute definition, only its uxml serialized data.
//
// This decision was made to avoid making the UxmlObject Traits/Factory public, just to remove them in a subsequent release.
// They were kept internal because we knew a new way for uxml support was coming, and now it's there.
// The only way to allow custom bindings in uxml with traits would be to expose UxmlObjectTraits, resulting in two
// code paths to maintain. So we decided to only support UxmlObject authoring from uxml serialization data.
[UxmlObject]
public partial class DataBinding
{
internal const string k_DataSourceTooltip = "A data source is a collection of information. By default, a binding will inherit the existing data source from the hierarchy. " +
"You can instead define another object here as the data source, or define the type of property it may be if the source is not yet available.";
internal const string k_DataSourcePathTooltip = "The path to the value in the data source used by this binding. To see resolved bindings in the UI Builder, define a path that is compatible with the target source property.";
internal const string k_BindingModeTooltip = "Controls how a binding is updated, which can include the direction in which data is written.";
internal const string k_SourceToUiConvertersTooltip = "Define one or more converter groups for this binding that will be used between the data source to the target UI.";
internal const string k_UiToSourceConvertersTooltip = "Define one or more converter groups for this binding that will be used between the target UI to the data source.";
[ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : Binding.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField, HideInInspector, UxmlAttribute("data-source-path")]
[Tooltip(k_DataSourcePathTooltip)]
string dataSourcePathString;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags dataSourcePathString_UxmlAttributeFlags;
[SerializeField, HideInInspector, DataSourceDrawer]
[Tooltip(k_DataSourceTooltip)]
Object dataSource;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags dataSource_UxmlAttributeFlags;
[UxmlAttribute("data-source-type")]
[SerializeField, HideInInspector, UxmlTypeReferenceAttribute(typeof(object))]
[Tooltip(k_DataSourceTooltip)]
string dataSourceTypeString;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags dataSourceTypeString_UxmlAttributeFlags;
[SerializeField, HideInInspector, BindingModeDrawer]
[Tooltip(k_BindingModeTooltip)]
BindingMode bindingMode;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags bindingMode_UxmlAttributeFlags;
[UxmlAttribute("source-to-ui-converters")]
[SerializeField, HideInInspector, ConverterDrawer(isConverterToSource = false)]
[Tooltip(k_SourceToUiConvertersTooltip)]
string sourceToUiConvertersString;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags sourceToUiConvertersString_UxmlAttributeFlags;
[UxmlAttribute("ui-to-source-converters")]
[SerializeField, HideInInspector, ConverterDrawer(isConverterToSource = true)]
[Tooltip(k_UiToSourceConvertersTooltip)]
string uiToSourceConvertersString;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags uiToSourceConvertersString_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new DataBinding();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
var e = (DataBinding) obj;
if (ShouldWriteAttributeValue(dataSourcePathString_UxmlAttributeFlags))
e.dataSourcePathString = dataSourcePathString;
if (ShouldWriteAttributeValue(dataSource_UxmlAttributeFlags))
e.dataSource = dataSource ? dataSource : null;
if (ShouldWriteAttributeValue(dataSourceTypeString_UxmlAttributeFlags))
e.dataSourceTypeString = dataSourceTypeString;
if (ShouldWriteAttributeValue(bindingMode_UxmlAttributeFlags))
e.bindingMode = bindingMode;
if (ShouldWriteAttributeValue(uiToSourceConvertersString_UxmlAttributeFlags))
e.uiToSourceConvertersString = uiToSourceConvertersString;
if (ShouldWriteAttributeValue(sourceToUiConvertersString_UxmlAttributeFlags))
e.sourceToUiConvertersString = sourceToUiConvertersString;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Bindings/DataBinding.Factory.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/DataBinding.Factory.cs",
"repo_id": "UnityCsReference",
"token_count": 1994
} | 483 |
// 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 Unity.Hierarchy;
using Unity.Profiling;
using UnityEngine.Bindings;
namespace UnityEngine.UIElements
{
internal class ReadOnlyHierarchyViewModelList : IList
{
readonly HierarchyViewModel m_HierarchyViewModel;
public bool IsFixedSize => true;
public bool IsReadOnly => true;
public int Count => m_HierarchyViewModel.Count;
public bool Contains(object value) => value is HierarchyNode node && m_HierarchyViewModel.Contains(node);
public int IndexOf(object value) => value is HierarchyNode node ? m_HierarchyViewModel.IndexOf(node) : BaseTreeView.invalidId;
public ReadOnlyHierarchyViewModelList(HierarchyViewModel viewModel)
{
m_HierarchyViewModel = viewModel;
}
public object this[int index]
{
get => m_HierarchyViewModel[index];
set => throw new NotSupportedException();
}
public void CopyTo(Array array, int index)
{
for (var i = index; i < m_HierarchyViewModel.Count; ++i)
array.SetValue(m_HierarchyViewModel[i], i - index);
}
public IEnumerator GetEnumerator() => new Enumerator(m_HierarchyViewModel);
public bool IsSynchronized => throw new NotSupportedException();
public object SyncRoot => throw new NotSupportedException();
public int Add(object value) => throw new NotSupportedException();
public void Clear() => throw new NotSupportedException();
public void Insert(int index, object value) => throw new NotSupportedException();
public void Remove(object value) => throw new NotSupportedException();
public void RemoveAt(int index) => throw new NotSupportedException();
struct Enumerator : IEnumerator
{
readonly HierarchyViewModel m_HierarchyViewModel;
HierarchyViewModel.Enumerator m_Enumerator;
public Enumerator(HierarchyViewModel hierarchyViewModel)
{
m_HierarchyViewModel = hierarchyViewModel;
m_Enumerator = hierarchyViewModel.GetEnumerator();
}
public object Current => m_Enumerator.Current;
public bool MoveNext() => m_Enumerator.MoveNext();
public void Reset() => m_Enumerator = m_HierarchyViewModel.GetEnumerator();
}
}
/// <summary>
/// Base collection tree view controller. View controllers of this type are meant to take care of data virtualized by any <see cref="BaseTreeView"/> inheritor.
/// </summary>
public abstract class BaseTreeViewController : CollectionViewController
{
private protected Hierarchy m_Hierarchy;
private protected HierarchyFlattened m_HierarchyFlattened;
private protected HierarchyViewModel m_HierarchyViewModel;
private protected Dictionary<int, HierarchyNode> m_IdToNodeDictionary = new();
private const string k_HierarchyPropertyName = "TreeViewDataProperty";
private IHierarchyProperty<int> m_TreeViewDataProperty;
// This Flag helps reduce the amount of C# bindings calls when RefreshItems() and Rebuild() are called.
private bool m_HierarchyHasPendingChanged;
/// <summary>
/// View for this controller, cast as a <see cref="BaseTreeView"/>.
/// </summary>
protected BaseTreeView baseTreeView => view as BaseTreeView;
internal event Action<TreeViewExpansionChangedArgs> itemExpandedChanged;
/// <summary>
/// Constructor for a BaseTreeViewController
/// </summary>
protected BaseTreeViewController()
{
hierarchy = new Hierarchy();
}
/// <summary>
/// Destructor for a BaseTreeViewController
/// </summary>
~BaseTreeViewController()
{
DisposeHierarchy();
}
private protected Hierarchy hierarchy
{
get => m_Hierarchy;
set
{
if (hierarchy == value)
return;
DisposeHierarchy();
if (value == null)
return;
m_Hierarchy = value;
m_HierarchyFlattened = new HierarchyFlattened(m_Hierarchy);
m_HierarchyViewModel = new HierarchyViewModel(m_HierarchyFlattened);
m_TreeViewDataProperty = m_Hierarchy.GetOrCreatePropertyUnmanaged<int>(k_HierarchyPropertyName);
}
}
internal void DisposeHierarchy()
{
if (m_HierarchyViewModel != null)
{
if (m_HierarchyViewModel.IsCreated)
m_HierarchyViewModel.Dispose();
m_HierarchyViewModel = null;
}
if (m_HierarchyFlattened != null)
{
if (m_HierarchyFlattened.IsCreated)
m_HierarchyFlattened.Dispose();
m_HierarchyFlattened = null;
}
if (m_Hierarchy != null)
{
if (m_Hierarchy.IsCreated)
m_Hierarchy.Dispose();
m_Hierarchy = null;
}
}
/// <summary>
/// Items for this tree. Contains items that are expanded in the tree.
/// </summary>
/// <remarks>It can only be accessed. Source is set when tree is rebuilt using <see cref="RebuildTree"/></remarks>
public override IList itemsSource
{
get => base.itemsSource;
set => throw new InvalidOperationException("Can't set itemsSource directly. Override this controller to manage tree data.");
}
/// <summary>
/// Rebuilds the tree item data and regenerates wrappers to fill the source.
/// </summary>
/// <remarks>This needs to be called when adding/removing/moving items.</remarks>
[Obsolete("RebuildTree is no longer supported and will be removed.", false)]
public void RebuildTree() {}
/// <summary>
/// Returns the root items of the tree, by IDs.
/// </summary>
/// <returns>The root item IDs.</returns>
public IEnumerable<int> GetRootItemIds()
{
var nodes = m_Hierarchy.EnumerateChildren(m_Hierarchy.Root);
foreach (var node in nodes)
{
yield return m_TreeViewDataProperty.GetValue(node);
}
}
/// <summary>
/// Returns all item IDs that can be found in the tree, optionally specifying root IDs from where to start.
/// </summary>
/// <param name="rootIds">Root IDs to start from. If null, will use the tree root ids.</param>
/// <returns>All items IDs in the tree, starting from the specified IDs.</returns>
public virtual IEnumerable<int> GetAllItemIds(IEnumerable<int> rootIds = null)
{
if (rootIds == null)
{
foreach (var flattenedNode in m_HierarchyFlattened)
{
if (flattenedNode.Node == m_Hierarchy.Root)
continue;
yield return m_TreeViewDataProperty.GetValue(flattenedNode.Node);
}
yield break;
}
foreach (var id in rootIds)
{
var flattenedNodeChildren = m_HierarchyFlattened.EnumerateChildren(m_IdToNodeDictionary[id]);
foreach (var node in flattenedNodeChildren)
yield return m_TreeViewDataProperty.GetValue(node);
yield return id;
}
}
/// <summary>
/// Returns the parent ID of an item, by ID.
/// </summary>
/// <param name="id">The ID of the item to fetch the parent from.</param>
/// <returns>The parent ID, or -1 if the item is at the root of the tree.</returns>
public virtual int GetParentId(int id)
{
var node = GetHierarchyNodeById(id);
if (node == HierarchyNode.Null || !m_Hierarchy.Exists(node))
return BaseTreeView.invalidId;
var parentNode = m_Hierarchy.GetParent(node);
if (parentNode == m_Hierarchy.Root)
return BaseTreeView.invalidId;
return m_TreeViewDataProperty.GetValue(parentNode);
}
/// <summary>
/// Get all children of a specific ID in the tree.
/// </summary>
/// <param name="id">The item ID.</param>
/// <returns>The children IDs.</returns>
public virtual IEnumerable<int> GetChildrenIds(int id)
{
var nodeById = GetHierarchyNodeById(id);
if (nodeById == HierarchyNode.Null || !m_Hierarchy.Exists(nodeById))
yield break;
var nodes = m_Hierarchy.EnumerateChildren(nodeById);
foreach (var node in nodes)
{
yield return m_TreeViewDataProperty.GetValue(node);
}
}
/// <summary>
/// Moves an item by ID, to a new parent and child index.
/// </summary>
/// <param name="id">The ID of the item to move.</param>
/// <param name="newParentId">The new parent ID. -1 if moved at the root.</param>
/// <param name="childIndex">The child index to insert at under the parent. -1 will add as the last child.</param>
/// <param name="rebuildTree">Whether we need to rebuild tree data. Set to false when doing multiple operations.</param>
public virtual void Move(int id, int newParentId, int childIndex = -1, bool rebuildTree = true)
{
if (id == newParentId)
return;
if (IsChildOf(newParentId, id))
return;
if (!m_IdToNodeDictionary.TryGetValue(id, out var node))
return;
var newParent = newParentId == BaseTreeView.invalidId ? m_Hierarchy.Root : GetHierarchyNodeById(newParentId);
var currentParent = m_Hierarchy.GetParent(node);
if (currentParent == newParent)
{
var index = GetChildIndexForId(id);
if (index < childIndex)
childIndex--;
}
else
{
m_Hierarchy.SetParent(node, newParent);
}
UpdateSortOrder(newParent, node, childIndex);
if (rebuildTree)
RaiseItemParentChanged(id, newParentId);
}
/// <summary>
/// Removes an item by id.
/// </summary>
/// <param name="id">The item id.</param>
/// <param name="rebuildTree">Whether we need to rebuild tree data. Set to <c>false</c> when doing multiple operations and call <see cref="TreeViewController.RebuildTree()"/>.</param>
/// <returns>Whether the item was successfully found and removed.</returns>
public abstract bool TryRemoveItem(int id, bool rebuildTree = true);
internal override void InvokeMakeItem(ReusableCollectionItem reusableItem)
{
if (reusableItem is ReusableTreeViewItem treeItem)
{
treeItem.Init(MakeItem());
PostInitRegistration(treeItem);
}
}
internal override void InvokeBindItem(ReusableCollectionItem reusableItem, int index)
{
if (reusableItem is ReusableTreeViewItem treeItem)
{
treeItem.Indent(GetIndentationDepthByIndex(index));
treeItem.SetExpandedWithoutNotify(IsExpandedByIndex(index));
treeItem.SetToggleVisibility(HasChildrenByIndex(index));
}
base.InvokeBindItem(reusableItem, index);
}
internal override void InvokeDestroyItem(ReusableCollectionItem reusableItem)
{
if (reusableItem is ReusableTreeViewItem treeItem)
{
treeItem.onPointerUp -= OnItemPointerUp;
treeItem.onToggleValueChanged -= OnToggleValueChanged;
}
base.InvokeDestroyItem(reusableItem);
}
internal void PostInitRegistration(ReusableTreeViewItem treeItem)
{
treeItem.onPointerUp += OnItemPointerUp;
treeItem.onToggleValueChanged += OnToggleValueChanged;
}
private void OnItemPointerUp(PointerUpEvent evt)
{
if ((evt.modifiers & EventModifiers.Alt) == 0)
return;
var target = evt.currentTarget as VisualElement;
var toggle = target.Q<Toggle>(BaseTreeView.itemToggleUssClassName);
var index = ((ReusableTreeViewItem)toggle.userData).index;
if (this is MultiColumnTreeViewController multiColumnTreeViewController)
{
index = multiColumnTreeViewController.columnController.GetSortedIndex(index);
}
if (!HasChildrenByIndex(index))
return;
var wasExpanded = IsExpandedByIndex(index);
if (IsViewDataKeyEnabled())
{
var id = GetIdForIndex(index);
var hashSet = new HashSet<int>(baseTreeView.expandedItemIds);
if (wasExpanded)
hashSet.Remove(id);
else
hashSet.Add(id);
var childrenIds = GetChildrenIdsByIndex(index);
foreach (var childId in GetAllItemIds(childrenIds))
{
if (HasChildren(childId))
{
if (wasExpanded)
hashSet.Remove(childId);
else
hashSet.Add(childId);
}
}
baseTreeView.expandedItemIds = new List<int>(hashSet);
}
if (wasExpanded)
m_HierarchyViewModel.ClearFlags(GetHierarchyNodeByIndex(index), HierarchyNodeFlags.Expanded, true);
else
m_HierarchyViewModel.SetFlags(GetHierarchyNodeByIndex(index), HierarchyNodeFlags.Expanded, true);
UpdateHierarchy();
baseTreeView.RefreshItems();
RaiseItemExpandedChanged(GetIdForIndex(index), !wasExpanded, true);
evt.StopPropagation();
}
private void RaiseItemExpandedChanged(int id, bool isExpanded, bool isAppliedToAllChildren)
{
itemExpandedChanged?.Invoke(new TreeViewExpansionChangedArgs
{
id = id,
isExpanded = isExpanded,
isAppliedToAllChildren = isAppliedToAllChildren
});
}
private void OnToggleValueChanged(ChangeEvent<bool> evt)
{
var toggle = evt.target as Toggle;
var index = ((ReusableTreeViewItem)toggle.userData).index;
if (this is MultiColumnTreeViewController multiColumnTreeViewController)
{
index = multiColumnTreeViewController.columnController.GetSortedIndex(index);
}
var isExpanded = IsExpandedByIndex(index);
if (isExpanded)
CollapseItemByIndex(index, false);
else
ExpandItemByIndex(index, false);
// To make sure our TreeView gets focus, we need to force this. :(
baseTreeView.scrollView.contentContainer.Focus();
}
/// <summary>
/// Get the number of items in the whole tree.
/// </summary>
/// <returns>The number of items in the tree.</returns>
/// <remarks>This is different from <see cref="CollectionViewController.GetItemsCount"/>, which will return the number of items in the source.</remarks>
public virtual int GetTreeItemsCount()
{
return m_Hierarchy.Count;
}
/// <summary>
/// Returns the index in the source of the item, by ID.
/// </summary>
/// <param name="id">The ID of the item to look for.</param>
/// <returns>The index of the item in the expanded items source. Returns -1 if the item is not visible.</returns>
public override int GetIndexForId(int id)
{
return m_IdToNodeDictionary.TryGetValue(id, out var node) ? m_HierarchyViewModel.IndexOf(node) : BaseTreeView.invalidId;
}
/// <summary>
/// Returns the ID for a specified index in the visible items source.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public override int GetIdForIndex(int index)
{
var availableNodeCount = m_HierarchyViewModel.Count;
if (index == availableNodeCount && availableNodeCount > 0)
return m_TreeViewDataProperty.GetValue(m_HierarchyViewModel[^1]);
return !IsIndexValid(index) ? BaseTreeView.invalidId : m_TreeViewDataProperty.GetValue(m_HierarchyViewModel[index]);
}
/// <summary>
/// Return whether the item with the specified ID has one or more child.
/// </summary>
/// <param name="id">The item id.</param>
/// <returns>Whether the item with the specified ID has one or more child.</returns>
public virtual bool HasChildren(int id)
{
if (m_IdToNodeDictionary.TryGetValue(id, out var node))
return m_Hierarchy.GetChildrenCount(node) > 0;
return false;
}
/// <summary>
/// Checks if an ID exists within this tree.
/// </summary>
/// <param name="id">The id to look for.</param>
/// <returns>Whether an item with this id exists in the tree.</returns>
public bool Exists(int id)
{
return m_IdToNodeDictionary.ContainsKey(id);
}
/// <summary>
/// Return whether the item with the specified index has one or more child.
/// </summary>
/// <param name="index">The item index.</param>
/// <returns>Whether the item with the specified ID has one or more child.</returns>
public bool HasChildrenByIndex(int index)
{
if (!IsIndexValid(index))
return false;
return m_HierarchyViewModel.GetChildrenCount(m_HierarchyViewModel[index]) > 0;
}
/// <summary>
/// Gets the children IDs of the item with the specified index.
/// </summary>
/// <param name="index">The item index.</param>
/// <returns>The children IDs.</returns>
public IEnumerable<int> GetChildrenIdsByIndex(int index)
{
if (!IsIndexValid(index))
yield break;
var nodes = m_Hierarchy.EnumerateChildren(m_HierarchyViewModel[index]);
foreach (var node in nodes)
{
yield return m_TreeViewDataProperty.GetValue(node);
}
}
/// <summary>
/// Gets the child index under the parent of the item with the specified ID.
/// </summary>
/// <param name="id">The item ID.</param>
/// <returns>The child index under the parent. Returns -1 if the item has no parent or doesn't exist in the tree.</returns>
public int GetChildIndexForId(int id)
{
if (m_IdToNodeDictionary.TryGetValue(id, out var node))
{
var parent = m_Hierarchy.GetParent(node);
if (parent == HierarchyNode.Null)
return BaseTreeView.invalidId;
var nodes = m_Hierarchy.EnumerateChildren(parent);
var index = 0;
foreach (var n in nodes)
{
if (n == node)
break;
index++;
}
return index;
}
return BaseTreeView.invalidId;
}
/// <summary>
/// Returns the depth of the element at that ID.
/// </summary>
/// <param name="id">The item ID.</param>
/// <returns>The depth of the element.</returns>
public int GetIndentationDepth(int id)
{
var depth = 0;
var parentId = GetParentId(id);
while (parentId != BaseTreeView.invalidId)
{
parentId = GetParentId(parentId);
depth++;
}
return depth;
}
/// <summary>
/// Return the depth of the element at that index.
/// </summary>
/// <param name="index">The item index.</param>
/// <returns>The depth of the element.</returns>
public int GetIndentationDepthByIndex(int index)
{
var id = GetIdForIndex(index);
return GetIndentationDepth(id);
}
/// <summary>
/// Determines whether the item with the specified ID can be expanded or collapsed.
/// </summary>
public virtual bool CanChangeExpandedState(int id)
{
return true;
}
/// <summary>
/// Return whether the item with the specified ID is expanded in the tree.
/// </summary>
/// <param name="id">The item ID</param>
/// <returns>Whether the item with the specified ID is expanded in the tree.</returns>
public bool IsExpanded(int id)
{
if (IsViewDataKeyEnabled())
return baseTreeView.expandedItemIds.Contains(id);
return m_IdToNodeDictionary.ContainsKey(id) && m_Hierarchy.Exists(m_IdToNodeDictionary[id]) && m_HierarchyViewModel.HasAllFlags(m_IdToNodeDictionary[id], HierarchyNodeFlags.Expanded);
}
/// <summary>
/// Return whether the item with the specified index is expanded in the tree.
/// </summary>
/// <param name="index">The item index</param>
/// <returns>Whether the item with the specified index is expanded in the tree. Will return false if the index is not valid.</returns>
public bool IsExpandedByIndex(int index)
{
if (!IsIndexValid(index))
return false;
return IsExpanded(GetIdForIndex(index));
}
static readonly ProfilerMarker K_ExpandItemByIndex = new ProfilerMarker(ProfilerCategory.Scripts, "BaseTreeViewController.ExpandItemByIndex");
/// <summary>
/// Expands the item with the specified index, making his children visible. Allows to expand the whole hierarchy under that item.
/// </summary>
/// <param name="index">The item index.</param>
/// <param name="expandAllChildren">Whether the whole hierarchy under that item will be expanded.</param>
/// <param name="refresh">Whether to refresh items or not. Set to false when doing multiple operations on the tree, to only do one RefreshItems once all operations are done.</param>
public void ExpandItemByIndex(int index, bool expandAllChildren, bool refresh = true)
{
using var marker = K_ExpandItemByIndex.Auto();
if (!HasChildrenByIndex(index))
return;
ExpandItemByNode(GetHierarchyNodeById(GetIdForIndex(index)), expandAllChildren, refresh);
}
/// <summary>
/// Expands the item with the specified ID, making its children visible. Allows to expand the whole hierarchy under that item.
/// </summary>
/// <param name="id">The item ID.</param>
/// <param name="expandAllChildren">Whether the whole hierarchy under that item will be expanded.</param>
/// <param name="refresh">Whether to refresh items or not. Set to false when doing multiple operations on the tree, to only do one RefreshItems once all operations are done. This is true by default.</param>
public void ExpandItem(int id, bool expandAllChildren, bool refresh = true)
{
if (!HasChildren(id) || !CanChangeExpandedState(id))
return;
if (m_IdToNodeDictionary.TryGetValue(id, out var node))
ExpandItemByNode(node, expandAllChildren, refresh);
}
/// <summary>
/// Collapses the item with the specified index, hiding its children. Allows to collapse the whole hierarchy under that item.
/// </summary>
/// <param name="index">The item index.</param>
/// <param name="collapseAllChildren">Whether the whole hierarchy under that item will be collapsed.</param>
/// <param name="refresh">Whether to refresh items or not. Set to false when doing multiple operations on the tree, to only do one RefreshItems once all operations are done. This is true by default.</param>
public void CollapseItemByIndex(int index, bool collapseAllChildren, bool refresh = true)
{
if (!HasChildrenByIndex(index))
return;
CollapseItemByNode(GetHierarchyNodeById(GetIdForIndex(index)), collapseAllChildren, refresh);
}
/// <summary>
/// Collapses the item with the specified ID, hiding its children. Allows to collapse the whole hierarchy under that item.
/// </summary>
/// <param name="id">The item ID.</param>
/// <param name="collapseAllChildren">Whether the whole hierarchy under that item will be collapsed.</param>
/// <param name="refresh">Whether to refresh items or not. Set to false when doing multiple operations on the tree, to only do one RefreshItems once all operations are done.</param>
public void CollapseItem(int id, bool collapseAllChildren, bool refresh = true)
{
if (!HasChildren(id) || !CanChangeExpandedState(id))
return;
if (m_IdToNodeDictionary.TryGetValue(id, out var node))
CollapseItemByNode(node, collapseAllChildren, refresh);
}
/// <summary>
/// Expands all items in the tree and refreshes the view.
/// </summary>
public void ExpandAll()
{
m_HierarchyViewModel.SetFlags(HierarchyNodeFlags.Expanded);
UpdateHierarchy();
if (IsViewDataKeyEnabled())
{
baseTreeView.expandedItemIds.Clear();
foreach (var node in m_HierarchyViewModel.EnumerateNodesWithAllFlags(HierarchyNodeFlags.Expanded))
baseTreeView.expandedItemIds.Add(m_TreeViewDataProperty.GetValue(node));
baseTreeView.SaveViewData();
}
baseTreeView.RefreshItems();
RaiseItemExpandedChanged(-1, true, true);
}
/// <summary>
/// Collapses all items in the tree and refreshes the view.
/// </summary>
public void CollapseAll()
{
m_HierarchyViewModel.ClearFlags(HierarchyNodeFlags.Expanded);
UpdateHierarchy();
if (IsViewDataKeyEnabled())
{
baseTreeView.expandedItemIds.Clear();
baseTreeView.SaveViewData();
}
baseTreeView.RefreshItems();
RaiseItemExpandedChanged(-1, false, true);
}
// Once we update the TreeView to be 100% Hierarchy, we can replace ExpandItemByIndex with this method. Or, we
// should at least provide some proper lookup for the node's index.
void ExpandItemByNode(in HierarchyNode node, bool expandAllChildren, bool refresh)
{
var id = m_TreeViewDataProperty.GetValue(node);
if (!CanChangeExpandedState(id))
return;
// Using a HashSet in order to prevent duplicates and it is faster than List.Contains(id)
m_HierarchyViewModel.SetFlags(node, HierarchyNodeFlags.Expanded, expandAllChildren);
m_HierarchyHasPendingChanged = true;
if (IsViewDataKeyEnabled())
{
var hashSet = new HashSet<int>(baseTreeView.expandedItemIds) { id };
// Required to update the expandedItemIds, can get rid of once we find a way to handle the serialized
// field for the viewDataKey
if (expandAllChildren)
{
// We need to refresh the view model in order the updated nodes
UpdateHierarchy();
var childrenIds = GetChildrenIds(id);
foreach (var childId in GetAllItemIds(childrenIds))
hashSet.Add(childId);
}
baseTreeView.expandedItemIds.Clear();
baseTreeView.expandedItemIds.AddRange(hashSet);
baseTreeView.SaveViewData();
}
if (refresh)
baseTreeView.RefreshItems();
RaiseItemExpandedChanged(id, true, expandAllChildren);
}
// Once we update the TreeView to be 100% Hierarchy, we can replace CollapseItemByIndex with this method. Or, we
// should at least provide some proper lookup for the node's index.
void CollapseItemByNode(in HierarchyNode node, bool collapseAllChildren, bool refresh)
{
var id = m_TreeViewDataProperty.GetValue(node);
if (!CanChangeExpandedState(id))
return;
if (IsViewDataKeyEnabled())
{
if (collapseAllChildren)
{
var childrenIds = GetChildrenIds(id);
foreach (var childId in GetAllItemIds(childrenIds))
baseTreeView.expandedItemIds.Remove(childId);
}
baseTreeView.expandedItemIds.Remove(id);
baseTreeView.SaveViewData();
}
m_HierarchyViewModel.ClearFlags(GetHierarchyNodeById(id), HierarchyNodeFlags.Expanded, collapseAllChildren);
m_HierarchyHasPendingChanged = true;
if (refresh)
baseTreeView.RefreshItems();
RaiseItemExpandedChanged(id, false, collapseAllChildren);
}
// Helps to determine which expandedItemsIds set to use (the serialized or the view model one).
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal void GetExpandedItemIds(List<int> list)
{
// This is just in case the function receives a list that contains old data. If so, we will clear the list
// since we want to get the expanded item ids from a clean slate.
if (list.Count > 0)
list.Clear();
if (IsViewDataKeyEnabled())
list.AddRange(baseTreeView.expandedItemIds);
// Otherwise we will populate the list with the expanded IDs from the view model
foreach (var node in m_HierarchyViewModel.EnumerateNodesWithAllFlags(HierarchyNodeFlags.Expanded))
list.Add(m_TreeViewDataProperty.GetValue(node));
}
// Used to check if it's a view data key path
internal bool IsViewDataKeyEnabled()
{
return baseTreeView.enableViewDataPersistence && !string.IsNullOrEmpty(baseTreeView.viewDataKey);
}
// For the use case of expanding all parents when interacting with a collapsed child.
internal void ExpandAncestorNodes(in HierarchyNode node)
{
var parentNode = m_Hierarchy.GetParent(node);
while (parentNode != m_Hierarchy.Root && (parentNode = GetHierarchyNodeById(m_TreeViewDataProperty.GetValue(parentNode))) != m_Hierarchy.Root)
{
var parentItemId = m_TreeViewDataProperty.GetValue(parentNode);
if (!m_HierarchyViewModel.HasAllFlags(parentNode, HierarchyNodeFlags.Expanded) && CanChangeExpandedState(parentItemId))
{
if (IsViewDataKeyEnabled())
baseTreeView.expandedItemIds.Add(parentItemId);
m_HierarchyViewModel.SetFlags(parentNode, HierarchyNodeFlags.Expanded);
m_HierarchyViewModel.Update();
}
parentNode = m_Hierarchy.GetParent(parentNode);
}
}
// A way for the view controller to request an update on the Hierarchy, HierarchyFlattened, and HierarchyViewModel.
internal override void PreRefresh()
{
if (!m_HierarchyHasPendingChanged)
return;
UpdateHierarchy();
}
// Returns the valid visible node
bool IsIndexValid(int index)
{
return index >= 0 && index < m_HierarchyViewModel.Count;
}
bool IsChildOf(int childId, int id)
{
if (childId == BaseTreeView.invalidId || id == BaseTreeView.invalidId)
return false;
HierarchyNode parentNode;
var childNode = GetHierarchyNodeById(childId);
var ancestorNode = GetHierarchyNodeById(id);
if (ancestorNode == childNode)
return true;
while ((parentNode = m_Hierarchy.GetParent(childNode)) != m_Hierarchy.Root)
{
if (ancestorNode == parentNode)
return true;
childNode = parentNode;
}
return false;
}
internal void RaiseItemParentChanged(int id, int newParentId)
{
RaiseItemIndexChanged(id, newParentId);
}
internal HierarchyNode CreateNode(in HierarchyNode parent)
{
return m_Hierarchy.Add(parent == HierarchyNode.Null ? m_Hierarchy.Root : parent);
}
internal void UpdateIdToNodeDictionary(int id, in HierarchyNode node, bool isAdd = true)
{
if (isAdd)
{
m_TreeViewDataProperty.SetValue(node, id);
m_IdToNodeDictionary[id] = node;
return;
}
m_IdToNodeDictionary.Remove(id);
}
// This can be removed once we drop support for the Dictionary in TreeDataController and this file. The goal of this
// function is to find all children associated to the node being passed and perform the callback that will remove
// from its collection.
internal void RemoveAllChildrenItemsFromCollections(in HierarchyNode node, Action<HierarchyNode, int> removeCallback)
{
if (node == HierarchyNode.Null)
return;
var nodeIndex = m_HierarchyFlattened.IndexOf(in node);
if (nodeIndex == -1)
return;
// We want to skip the current node's index since we only care about the children nodes.
var nextNodeIndex = nodeIndex + 1;
var count = m_HierarchyFlattened.GetChildrenCountRecursive(in node);
for (var i = nextNodeIndex; i < nextNodeIndex + count; ++i)
{
var item = m_HierarchyFlattened[i];
removeCallback(item.Node, m_TreeViewDataProperty.GetValue(item.Node));
}
}
internal void ClearIdToNodeDictionary()
{
m_IdToNodeDictionary.Clear();
}
internal void UpdateSortOrder(in HierarchyNode newParent, in HierarchyNode insertedNode, int insertedIndex)
{
Span<HierarchyNode> existingChildren = m_Hierarchy.GetChildren(newParent);
if (insertedIndex == -1)
insertedIndex = existingChildren.Length;
// If dragging from inside the view, it is possible that the dragged nodes are already children of the parent node.
// In that case, we need to skip them.
var currentSortIndex = 0;
for (var i = 0; i < insertedIndex && i < existingChildren.Length; ++i)
{
if (insertedNode == existingChildren[i])
continue;
m_Hierarchy.SetSortIndex(existingChildren[i], currentSortIndex++);
}
m_Hierarchy.SetSortIndex(insertedNode, insertedIndex);
if (insertedIndex == currentSortIndex)
currentSortIndex++;
for (var i = insertedIndex; i < existingChildren.Length; ++i)
{
if (insertedNode == existingChildren[i])
continue;
m_Hierarchy.SetSortIndex(existingChildren[i], currentSortIndex++);
}
m_Hierarchy.SortChildren(newParent);
UpdateHierarchy();
// Clear the node's sort indices otherwise the next time they will hold the wrong sort index value.
Span<HierarchyNode> newChildren = m_Hierarchy.GetChildren(newParent);
foreach (var node in newChildren)
{
m_Hierarchy.SetSortIndex(node, 0);
}
}
// Update the node's flags based on the serialized expandedItemsIds. This will not be called if it's not coming
// from the view data key path.
internal void OnViewDataReadyUpdateNodes()
{
foreach (var id in baseTreeView.expandedItemIds)
{
if (!m_IdToNodeDictionary.TryGetValue(id, out var node)) continue;
m_HierarchyViewModel.SetFlags(node, HierarchyNodeFlags.Expanded);
}
UpdateHierarchy();
}
internal void UpdateHierarchy()
{
if (m_Hierarchy.UpdateNeeded)
{
m_Hierarchy.Update();
}
if (m_HierarchyFlattened.UpdateNeeded)
{
m_HierarchyFlattened.Update();
}
if (m_HierarchyViewModel.UpdateNeeded)
{
m_HierarchyViewModel.Update();
}
// Clear the flag otherwise when the TreeView refreshes or rebuilds it will unnecessary call UpdateNeeded.
m_HierarchyHasPendingChanged = false;
}
internal HierarchyNode GetHierarchyNodeById(int id)
{
return m_IdToNodeDictionary.TryGetValue(id, out var node) ? node : HierarchyNode.Null;
}
internal HierarchyNode GetHierarchyNodeByIndex(int index)
{
if (!IsIndexValid(index))
return HierarchyNode.Null;
return m_HierarchyViewModel[index];
}
}
}
| UnityCsReference/Modules/UIElements/Core/Collections/Controllers/BaseTreeViewController.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Controllers/BaseTreeViewController.cs",
"repo_id": "UnityCsReference",
"token_count": 17196
} | 484 |
// 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.UIElements
{
class ReusableListViewItem : ReusableCollectionItem
{
static readonly string k_SortingDisablesReorderingTooltip = "Reordering is disabled when the collection is being sorted.";
VisualElement m_Container;
VisualElement m_DragHandle;
VisualElement m_ItemContainer;
public override VisualElement rootElement => m_Container ?? bindableElement;
public void Init(VisualElement item, bool usesAnimatedDragger)
{
base.Init(item);
var root = new VisualElement() { name = BaseListView.reorderableItemUssClassName };
UpdateHierarchy(root, bindableElement, usesAnimatedDragger);
}
protected void UpdateHierarchy(VisualElement root, VisualElement item, bool usesAnimatedDragger)
{
if (usesAnimatedDragger)
{
if (m_Container != null)
return;
m_Container = root;
m_Container.AddToClassList(BaseListView.reorderableItemUssClassName);
m_DragHandle = new VisualElement { name = BaseListView.reorderableItemHandleUssClassName };
m_DragHandle.AddToClassList(BaseListView.reorderableItemHandleUssClassName);
var handle1 = new VisualElement { name = BaseListView.reorderableItemHandleBarUssClassName };
handle1.AddToClassList(BaseListView.reorderableItemHandleBarUssClassName);
m_DragHandle.Add(handle1);
var handle2 = new VisualElement { name = BaseListView.reorderableItemHandleBarUssClassName };
handle2.AddToClassList(BaseListView.reorderableItemHandleBarUssClassName);
m_DragHandle.Add(handle2);
m_ItemContainer = new VisualElement { name = BaseListView.reorderableItemContainerUssClassName };
m_ItemContainer.AddToClassList(BaseListView.reorderableItemContainerUssClassName);
m_ItemContainer.Add(item);
m_Container.Add(m_DragHandle);
m_Container.Add(m_ItemContainer);
}
else
{
if (m_Container == null)
return;
m_Container.RemoveFromHierarchy();
m_Container = null;
}
}
public void UpdateDragHandle(bool needsDragHandle)
{
if (needsDragHandle)
{
if (m_DragHandle.parent == null)
{
rootElement.Insert(0, m_DragHandle);
rootElement.AddToClassList(BaseListView.reorderableItemUssClassName);
}
}
else
{
if (m_DragHandle?.parent != null)
{
m_DragHandle.RemoveFromHierarchy();
rootElement.RemoveFromClassList(BaseListView.reorderableItemUssClassName);
}
}
}
public void SetDragHandleEnabled(bool enabled)
{
if (m_DragHandle != null)
{
m_DragHandle.SetEnabled(enabled);
m_DragHandle.tooltip = enabled ? null : k_SortingDisablesReorderingTooltip;
}
}
public override void PreAttachElement()
{
base.PreAttachElement();
rootElement.AddToClassList(BaseListView.itemUssClassName);
}
public override void DetachElement()
{
base.DetachElement();
rootElement.RemoveFromClassList(BaseListView.itemUssClassName);
}
public override void SetDragGhost(bool dragGhost)
{
base.SetDragGhost(dragGhost);
if (m_DragHandle != null)
{
m_DragHandle.style.display = isDragGhost ? DisplayStyle.None : DisplayStyle.Flex;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableListViewItem.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableListViewItem.cs",
"repo_id": "UnityCsReference",
"token_count": 1944
} | 485 |
// 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.Scripting.APIUpdating;
namespace UnityEngine.UIElements
{
/// <summary>
/// A <see cref="BoundsInt"/> field. For more information, refer to [[wiki:UIE-uxml-element-BoundsIntField|UXML element BoundsIntField]].
/// </summary>
[MovedFrom(true, UpgradeConstants.EditorNamespace, UpgradeConstants.EditorAssembly)]
public class BoundsIntField : BaseField<BoundsInt>
{
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : BaseField<BoundsInt>.UxmlSerializedData, IUxmlSerializedDataCustomAttributeHandler
{
public override object CreateInstance() => new BoundsIntField();
void IUxmlSerializedDataCustomAttributeHandler.SerializeCustomAttributes(IUxmlAttributes bag, HashSet<string> handledAttributes)
{
// Its possible to only specify 1 attribute so we need to check them all and if we get at least 1 match then we can proceed.
int foundAttributeCounter = 0;
var px = UxmlUtility.TryParseIntAttribute("px", bag, ref foundAttributeCounter);
var py = UxmlUtility.TryParseIntAttribute("py", bag, ref foundAttributeCounter);
var pz = UxmlUtility.TryParseIntAttribute("pz", bag, ref foundAttributeCounter);
var sx = UxmlUtility.TryParseIntAttribute("sx", bag, ref foundAttributeCounter);
var sy = UxmlUtility.TryParseIntAttribute("sy", bag, ref foundAttributeCounter);
var sz = UxmlUtility.TryParseIntAttribute("sz", bag, ref foundAttributeCounter);
if (foundAttributeCounter > 0)
{
Value = new BoundsInt(new Vector3Int(px, py, pz), new Vector3Int(sx, sy, sz));
handledAttributes.Add("value");
if (bag is UxmlAsset uxmlAsset)
{
uxmlAsset.RemoveAttribute("px");
uxmlAsset.RemoveAttribute("py");
uxmlAsset.RemoveAttribute("pz");
uxmlAsset.RemoveAttribute("sx");
uxmlAsset.RemoveAttribute("sy");
uxmlAsset.RemoveAttribute("sz");
uxmlAsset.SetAttribute("value", UxmlUtility.ValueToString(Value));
}
}
}
}
/// <summary>
/// Instantiates a <see cref="BoundsIntField"/> 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<BoundsIntField, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="BoundsIntField"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : BaseField<BoundsInt>.UxmlTraits
{
UxmlIntAttributeDescription m_PositionXValue = new UxmlIntAttributeDescription { name = "px" };
UxmlIntAttributeDescription m_PositionYValue = new UxmlIntAttributeDescription { name = "py" };
UxmlIntAttributeDescription m_PositionZValue = new UxmlIntAttributeDescription { name = "pz" };
UxmlIntAttributeDescription m_SizeXValue = new UxmlIntAttributeDescription { name = "sx" };
UxmlIntAttributeDescription m_SizeYValue = new UxmlIntAttributeDescription { name = "sy" };
UxmlIntAttributeDescription m_SizeZValue = new UxmlIntAttributeDescription { name = "sz" };
/// <summary>
/// Initializes the <see cref="UxmlTraits"/> for the <see cref="BoundsIntField"/>.
/// </summary>
/// <param name="ve">The <see cref="VisualElement"/> to be initialized.</param>
/// <param name="bag">Bag of attributes.</param>
/// <param name="cc">CreationContext, unused.</param>
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
var f = (BoundsIntField)ve;
f.SetValueWithoutNotify(new BoundsInt(
new Vector3Int(m_PositionXValue.GetValueFromBag(bag, cc), m_PositionYValue.GetValueFromBag(bag, cc), m_PositionZValue.GetValueFromBag(bag, cc)),
new Vector3Int(m_SizeXValue.GetValueFromBag(bag, cc), m_SizeYValue.GetValueFromBag(bag, cc), m_SizeZValue.GetValueFromBag(bag, cc))));
}
}
private Vector3IntField m_PositionField;
private Vector3IntField m_SizeField;
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public new static readonly string ussClassName = "unity-bounds-int-field";
/// <summary>
/// USS class name of labels in elements of this type.
/// </summary>
public new static readonly string labelUssClassName = ussClassName + "__label";
/// <summary>
/// USS class name of input elements in elements of this type.
/// </summary>
public new static readonly string inputUssClassName = ussClassName + "__input";
/// <summary>
/// USS class name of position fields in elements of this type.
/// </summary>
public static readonly string positionUssClassName = ussClassName + "__position-field";
/// <summary>
/// USS class name of size fields in elements of this type.
/// </summary>
public static readonly string sizeUssClassName = ussClassName + "__size-field";
/// <summary>
/// Initializes and returns an instance of BoundsIntField.
/// </summary>
public BoundsIntField()
: this(null) {}
/// <summary>
/// Initializes and returns an instance of BoundsIntField.
/// </summary>
/// <param name="label">The text to use as a label.</param>
public BoundsIntField(string label)
: base(label, null)
{
delegatesFocus = false;
visualInput.focusable = false;
AddToClassList(ussClassName);
visualInput.AddToClassList(inputUssClassName);
labelElement.AddToClassList(labelUssClassName);
m_PositionField = new Vector3IntField("Position");
m_PositionField.name = "unity-m_Position-input";
m_PositionField.delegatesFocus = true;
m_PositionField.AddToClassList(positionUssClassName);
m_PositionField.RegisterValueChangedCallback(e =>
{
var current = value;
current.position = e.newValue;
value = current;
});
visualInput.hierarchy.Add(m_PositionField);
m_SizeField = new Vector3IntField("Size");
m_SizeField.name = "unity-m_Size-input";
m_SizeField.delegatesFocus = true;
m_SizeField.AddToClassList(sizeUssClassName);
m_SizeField.RegisterValueChangedCallback(e =>
{
var current = value;
current.size = e.newValue;
value = current;
});
visualInput.hierarchy.Add(m_SizeField);
}
public override void SetValueWithoutNotify(BoundsInt newValue)
{
base.SetValueWithoutNotify(newValue);
m_PositionField.SetValueWithoutNotify(rawValue.position);
m_SizeField.SetValueWithoutNotify(rawValue.size);
}
protected override void UpdateMixedValueContent()
{
m_PositionField.showMixedValue = showMixedValue;
m_SizeField.showMixedValue = showMixedValue;
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/BoundsIntField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/BoundsIntField.cs",
"repo_id": "UnityCsReference",
"token_count": 3467
} | 486 |
// 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.Properties;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEngine.UIElements
{
/// <summary>
/// A <see cref="VisualElement"/> representing a source texture.
///
/// **Note**: This is not related to the `UnityEngine.UI.Image` uGUI control. This is the Image control for the UI Toolkit framework.
/// </summary>
public class Image : VisualElement
{
internal static readonly BindingId imageProperty = nameof(image);
internal static readonly BindingId spriteProperty = nameof(sprite);
internal static readonly BindingId vectorImageProperty = nameof(vectorImage);
internal static readonly BindingId sourceRectProperty = nameof(sourceRect);
internal static readonly BindingId uvProperty = nameof(uv);
internal static readonly BindingId scaleModeProperty = nameof(scaleMode);
internal static readonly BindingId tintColorProperty = nameof(tintColor);
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
public override object CreateInstance() => new Image();
}
/// <summary>
/// Instantiates an <see cref="Image"/> 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<Image, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="Image"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : VisualElement.UxmlTraits
{
/// <summary>
/// Returns an empty enumerable, as images generally do not have children.
/// </summary>
public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
{
get { yield break; }
}
}
private ScaleMode m_ScaleMode;
private Texture m_Image;
private Sprite m_Sprite;
private VectorImage m_VectorImage;
private Rect m_UV;
private Color m_TintColor;
// Internal for tests
internal bool m_ImageIsInline;
private bool m_ScaleModeIsInline;
private bool m_TintColorIsInline;
/// <summary>
/// The texture to display in this image. If you assign a `Texture` or `Texture2D`, the Image element will resize and show the assigned texture.
/// </summary>
[CreateProperty]
public Texture image
{
get => m_Image;
set
{
if (m_Image == value && m_ImageIsInline)
return;
m_ImageIsInline = value != null;
SetProperty(value, ref m_Image, ref m_Sprite, ref m_VectorImage, imageProperty);
}
}
/// <summary>
/// The sprite to display in this image.
/// </summary>
[CreateProperty]
public Sprite sprite
{
get => m_Sprite;
set
{
if (m_Sprite == value && m_ImageIsInline)
return;
m_ImageIsInline = value != null;
SetProperty(value, ref m_Sprite, ref m_Image, ref m_VectorImage, spriteProperty);
}
}
/// <summary>
/// The <see cref="VectorImage"/> to display in this image.
/// </summary>
[CreateProperty]
public VectorImage vectorImage
{
get => m_VectorImage;
set
{
if (m_VectorImage == value && m_ImageIsInline)
return;
m_ImageIsInline = value != null;
SetProperty(value, ref m_VectorImage, ref m_Image, ref m_Sprite, vectorImageProperty);
}
}
/// <summary>
/// The source rectangle inside the texture relative to the top left corner.
/// </summary>
[CreateProperty]
public Rect sourceRect
{
get => GetSourceRect();
set
{
if (GetSourceRect() == value)
return;
if (sprite != null)
{
Debug.LogError("Cannot set sourceRect on a sprite image");
return;
}
CalculateUV(value);
NotifyPropertyChanged(sourceRectProperty);
}
}
/// <summary>
/// The base texture coordinates of the Image relative to the bottom left corner.
/// </summary>
[CreateProperty]
public Rect uv
{
get => m_UV;
set
{
if (m_UV == value)
return;
m_UV = value;
NotifyPropertyChanged(uvProperty);
}
}
/// <summary>
/// ScaleMode used to display the Image.
/// </summary>
[CreateProperty]
public ScaleMode scaleMode
{
get => m_ScaleMode;
set
{
if (m_ScaleMode == value && m_ScaleModeIsInline)
return;
m_ScaleModeIsInline = true;
SetScaleMode(value);
}
}
/// <summary>
/// Tinting color for this Image.
/// </summary>
[CreateProperty]
public Color tintColor
{
get => m_TintColor;
set
{
if (m_TintColor == value && m_TintColorIsInline)
return;
m_TintColorIsInline = true;
SetTintColor(value);
}
}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public static readonly string ussClassName = "unity-image";
/// <summary>
/// Constructor.
/// </summary>
public Image()
{
AddToClassList(ussClassName);
m_ScaleMode = ScaleMode.ScaleToFit;
m_TintColor = Color.white;
m_UV = new Rect(0, 0, 1, 1);
requireMeasureFunction = true;
RegisterCallback<CustomStyleResolvedEvent>(OnCustomStyleResolved);
generateVisualContent += OnGenerateVisualContent;
}
private Vector2 GetTextureDisplaySize(Texture texture)
{
var result = Vector2.zero;
if (texture != null)
{
result = new Vector2(texture.width, texture.height);
var t2d = texture as Texture2D;
if (t2d != null)
result = result / t2d.pixelsPerPoint;
}
return result;
}
private Vector2 GetTextureDisplaySize(Sprite sprite)
{
var result = Vector2.zero;
if (sprite != null)
{
float scale = UIElementsUtility.PixelsPerUnitScaleForElement(this, sprite);
result = (Vector2)(sprite.bounds.size * sprite.pixelsPerUnit) * scale;
}
return result;
}
protected internal override Vector2 DoMeasure(float desiredWidth, MeasureMode widthMode, float desiredHeight, MeasureMode heightMode)
{
float measuredWidth = float.NaN;
float measuredHeight = float.NaN;
if (image == null && sprite == null && vectorImage == null)
return new Vector2(measuredWidth, measuredHeight);
var sourceSize = Vector2.zero;
if (image != null)
sourceSize = GetTextureDisplaySize(image);
else if (sprite != null)
sourceSize = GetTextureDisplaySize(sprite);
else
sourceSize = vectorImage.size;
// covers the MeasureMode.Exactly case
Rect rect = sourceRect;
bool hasRect = rect != Rect.zero;
// UUM-17229: rect width/height can be negative (e.g. when the UVs are flipped)
measuredWidth = hasRect ? Mathf.Abs(rect.width) : sourceSize.x;
measuredHeight = hasRect ? Mathf.Abs(rect.height) : sourceSize.y;
if (widthMode == MeasureMode.AtMost)
{
measuredWidth = Mathf.Min(measuredWidth, desiredWidth);
}
if (heightMode == MeasureMode.AtMost)
{
measuredHeight = Mathf.Min(measuredHeight, desiredHeight);
}
return new Vector2(measuredWidth, measuredHeight);
}
private void OnGenerateVisualContent(MeshGenerationContext mgc)
{
if (image == null && sprite == null && vectorImage == null)
return;
var alignedRect = GUIUtility.AlignRectToDevice(contentRect);
var playModeTintColor = mgc.visualElement?.playModeTintColor ?? Color.white;
var rectParams = new UIR.MeshGenerator.RectangleParams();
if (image != null)
rectParams = UIR.MeshGenerator.RectangleParams.MakeTextured(alignedRect, uv, image, scaleMode, playModeTintColor);
else if (sprite != null)
{
var slices = Vector4.zero;
rectParams = UIR.MeshGenerator.RectangleParams.MakeSprite(alignedRect, uv, sprite, scaleMode, playModeTintColor, false, ref slices);
}
else if (vectorImage != null)
rectParams = UIR.MeshGenerator.RectangleParams.MakeVectorTextured(alignedRect, uv, vectorImage, scaleMode, playModeTintColor);
rectParams.color = tintColor;
mgc.meshGenerator.DrawRectangle(rectParams);
}
static CustomStyleProperty<Texture2D> s_ImageProperty = new CustomStyleProperty<Texture2D>("--unity-image");
static CustomStyleProperty<Sprite> s_SpriteProperty = new CustomStyleProperty<Sprite>("--unity-image");
static CustomStyleProperty<VectorImage> s_VectorImageProperty = new CustomStyleProperty<VectorImage>("--unity-image");
static CustomStyleProperty<string> s_ScaleModeProperty = new CustomStyleProperty<string>("--unity-image-size");
static CustomStyleProperty<Color> s_TintColorProperty = new CustomStyleProperty<Color>("--unity-image-tint-color");
private void OnCustomStyleResolved(CustomStyleResolvedEvent e)
{
// We should consider not exposing image as a style at all, since it's intimately tied to uv/sourceRect
ReadCustomProperties(e.customStyle);
}
private void ReadCustomProperties(ICustomStyle customStyleProvider)
{
if (!m_ImageIsInline)
{
if (customStyleProvider.TryGetValue(s_ImageProperty, out var textureValue))
{
SetProperty(textureValue, ref m_Image, ref m_Sprite, ref m_VectorImage, imageProperty);
}
else if (customStyleProvider.TryGetValue(s_SpriteProperty, out var spriteValue))
{
SetProperty(spriteValue, ref m_Sprite, ref m_Image, ref m_VectorImage, spriteProperty);
}
else if (customStyleProvider.TryGetValue(s_VectorImageProperty, out var vectorImageValue))
{
SetProperty(vectorImageValue, ref m_VectorImage, ref m_Image, ref m_Sprite, vectorImageProperty);
}
// If the value is not inline and none of the custom style properties are resolved, unset the value.
else
{
ClearProperty();
}
}
if (!m_ScaleModeIsInline && customStyleProvider.TryGetValue(s_ScaleModeProperty, out var scaleModeValue))
{
StylePropertyUtil.TryGetEnumIntValue(StyleEnumType.ScaleMode, scaleModeValue, out var intValue);
SetScaleMode((ScaleMode)intValue);
}
if (!m_TintColorIsInline )
{
if( customStyleProvider.TryGetValue(s_TintColorProperty, out var tintValue) )
SetTintColor(tintValue);
else
{
SetTintColor(Color.white);
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetProperty<T0, T1, T2>(T0 src, ref T0 dst, ref T1 alt0, ref T2 alt1, BindingId binding)
where T0 : Object where T1 : Object where T2 : Object
{
if (src == dst)
return;
dst = src;
if (dst != null)
{
alt0 = null;
alt1 = null;
}
if (dst == null)
{
uv = new Rect(0, 0, 1, 1);
ReadCustomProperties(customStyle);
}
IncrementVersion(VersionChangeType.Layout | VersionChangeType.Repaint);
NotifyPropertyChanged(binding);
}
private void ClearProperty()
{
if (m_ImageIsInline)
return;
image = null;
sprite = null;
vectorImage = null;
}
private void SetScaleMode(ScaleMode mode)
{
if (m_ScaleMode != mode)
{
m_ScaleMode = mode;
IncrementVersion(VersionChangeType.Repaint);
NotifyPropertyChanged(scaleModeProperty);
}
}
private void SetTintColor(Color color)
{
if (m_TintColor != color)
{
m_TintColor = color;
IncrementVersion(VersionChangeType.Repaint);
NotifyPropertyChanged(tintColorProperty);
}
}
private void CalculateUV(Rect srcRect)
{
m_UV = new Rect(0, 0, 1, 1);
var size = Vector2.zero;
Texture texture = image;
if (texture != null)
size = GetTextureDisplaySize(texture);
var vi = vectorImage;
if (vi != null)
size = vi.size;
if (size != Vector2.zero)
{
// Convert texture coordinates to UV
m_UV.x = srcRect.x / size.x;
m_UV.width = srcRect.width / size.x;
m_UV.height = srcRect.height / size.y;
m_UV.y = 1.0f - m_UV.height - (srcRect.y / size.y);
}
}
private Rect GetSourceRect()
{
Rect rect = Rect.zero;
var size = Vector2.zero;
var texture = image;
if (texture != null)
size = GetTextureDisplaySize(texture);
var vi = vectorImage;
if (vi != null)
size = vi.size;
if (size != Vector2.zero)
{
// Convert UV to texture coordinates
rect.x = uv.x * size.x;
rect.width = uv.width * size.x;
rect.y = (1.0f - uv.y - uv.height) * size.y;
rect.height = uv.height * size.y;
}
return rect;
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/Image.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/Image.cs",
"repo_id": "UnityCsReference",
"token_count": 7576
} | 487 |
// 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 UnityEngine.Internal;
namespace UnityEngine.UIElements
{
/// <summary>
/// Represents specific data of a header.
/// </summary>
internal enum ColumnsDataType
{
/// <summary>
/// Represents the primary column name of the header.
/// </summary>
PrimaryColumn,
/// <summary>
/// Represents the stretch mode of the header.
/// </summary>
StretchMode,
/// <summary>
/// Represents the ability for user to interactively reorder columns.
/// </summary>
Reorderable,
/// <summary>
/// Represents the ability for user to interactively resize columns.
/// </summary>
Resizable,
/// <summary>
/// Represents the value that indicates whether columns are resized as the user drags resize handles or only upon mouse release.
/// </summary>
ResizePreview,
}
/// <summary>
/// Represents a collection of columns.
/// </summary>
[UxmlObject]
public class Columns : ICollection<Column>
{
/// <summary>
/// Indicates how the size of a stretchable column in this collection should get automatically adjusted as other columns or its containing view get resized.
/// The default value is <see cref="StretchMode.Grow"/>.
/// </summary>
public enum StretchMode
{
/// <summary>
/// The size of stretchable columns is automatically and proportionally adjusted only as its container gets resized.
/// Unlike <see cref="StretchMode.GrowAndFill"/>, the size is not adjusted to fill any available space within its container when other columns are resized.
/// </summary>
Grow,
/// <summary>
/// The size of stretchable columns is automatically adjusted to fill the available space within its container when this container or other columns get resized
/// </summary>
GrowAndFill
}
[ExcludeFromDocs, Serializable]
public class UxmlSerializedData : UIElements.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField] string primaryColumnName;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags primaryColumnName_UxmlAttributeFlags;
[SerializeField] StretchMode stretchMode;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags stretchMode_UxmlAttributeFlags;
[SerializeField] bool reorderable;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags reorderable_UxmlAttributeFlags;
[SerializeField] bool resizable;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags resizable_UxmlAttributeFlags;
[SerializeField] bool resizePreview;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags resizePreview_UxmlAttributeFlags;
[SerializeReference, UxmlObjectReference] List<Column.UxmlSerializedData> columns;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags columns_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new Columns();
public override void Deserialize(object obj)
{
var e = (Columns)obj;
if (ShouldWriteAttributeValue(primaryColumnName_UxmlAttributeFlags))
e.primaryColumnName = primaryColumnName;
if (ShouldWriteAttributeValue(stretchMode_UxmlAttributeFlags))
e.stretchMode = stretchMode;
if (ShouldWriteAttributeValue(reorderable_UxmlAttributeFlags))
e.reorderable = reorderable;
if (ShouldWriteAttributeValue(resizable_UxmlAttributeFlags))
e.resizable = resizable;
if (ShouldWriteAttributeValue(resizePreview_UxmlAttributeFlags))
e.resizePreview = resizePreview;
if (ShouldWriteAttributeValue(columns_UxmlAttributeFlags) && columns != null)
{
foreach (var columnData in columns)
{
var column = (Column)columnData.CreateInstance();
columnData.Deserialize(column);
e.Add(column);
}
}
}
}
/// <summary>
/// Instantiates a <see cref="Columns"/> using the data read from a UXML file.
/// </summary>
[Obsolete("UxmlObjectFactory<T> is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
internal class UxmlObjectFactory<T> : UxmlObjectFactory<T, UxmlObjectTraits<T>> where T : Columns, new() {}
/// <summary>
/// Instantiates a <see cref="Columns"/> using the data read from a UXML file.
/// </summary>
[Obsolete("UxmlObjectFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
internal class UxmlObjectFactory : UxmlObjectFactory<Columns> {}
/// <summary>
/// Defines <see cref="UxmlObjectTraits{T}"/> for the <see cref="Columns"/>.
/// </summary>
[Obsolete("UxmlObjectTraits<T> is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
internal class UxmlObjectTraits<T> : UnityEngine.UIElements.UxmlObjectTraits<T> where T : Columns
{
readonly UxmlStringAttributeDescription m_PrimaryColumnName = new UxmlStringAttributeDescription { name = "primary-column-name" };
readonly UxmlEnumAttributeDescription<StretchMode> m_StretchMode = new UxmlEnumAttributeDescription<StretchMode> { name = "stretch-mode", defaultValue = StretchMode.GrowAndFill };
readonly UxmlBoolAttributeDescription m_Reorderable = new UxmlBoolAttributeDescription { name = "reorderable", defaultValue = true };
readonly UxmlBoolAttributeDescription m_Resizable = new UxmlBoolAttributeDescription { name = "resizable", defaultValue = true };
readonly UxmlBoolAttributeDescription m_ResizePreview = new UxmlBoolAttributeDescription { name = "resize-preview" };
readonly UxmlObjectListAttributeDescription<Column> m_Columns = new UxmlObjectListAttributeDescription<Column>();
public override void Init(ref T obj, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ref obj, bag, cc);
obj.primaryColumnName = m_PrimaryColumnName.GetValueFromBag(bag, cc);
obj.stretchMode = m_StretchMode.GetValueFromBag(bag, cc);
obj.reorderable = m_Reorderable.GetValueFromBag(bag, cc);
obj.resizable = m_Resizable.GetValueFromBag(bag, cc);
obj.resizePreview = m_ResizePreview.GetValueFromBag(bag, cc);
var columnList = m_Columns.GetValueFromBag(bag, cc);
if (columnList != null)
{
foreach (var column in columnList)
{
obj.Add(column);
}
}
}
}
IList<Column> m_Columns = new List<Column>();
List<Column> m_DisplayColumns;
List<Column> m_VisibleColumns;
bool m_VisibleColumnsDirty = true;
StretchMode m_StretchMode = StretchMode.GrowAndFill;
bool m_Reorderable = true;
bool m_Resizable = true;
bool m_ResizePreview;
string m_PrimaryColumnName;
internal IList<Column> columns => m_Columns;
/// <summary>
/// Indicates the column that needs to be considered as the primary column, by ID.
/// </summary>
/// <remarks>
/// Needs to match a <see cref="Column"/>'s id, otherwise will be ignored.
/// The primary column cannot be hidden and will contain the expand arrow for tree views.
/// </remarks>
public string primaryColumnName
{
get => m_PrimaryColumnName;
set
{
if (m_PrimaryColumnName == value)
return;
m_PrimaryColumnName = value;
NotifyChange(ColumnsDataType.PrimaryColumn);
}
}
/// <summary>
/// Indicates whether the columns can be reordered interactively by user.
/// </summary>
/// <remarks>
/// Reordering columns can be cancelled by pressing ESC key.
/// </remarks>
public bool reorderable
{
get => m_Reorderable;
set
{
if (m_Reorderable == value)
return;
m_Reorderable = value;
NotifyChange(ColumnsDataType.Reorderable);
}
}
/// <summary>
/// Indicates whether the columns can be resized interactively by user.
/// </summary>
/// <remarks>
/// The resize behaviour of a specific column in the column collection can be specified by setting <see cref="Column.resizable"/>.
/// A column is effectively resizable if both <see cref="Column.resizable"/> and <see cref="Columns.resizable"/> are both true.
/// </remarks>
public bool resizable
{
get => m_Resizable;
set
{
if (m_Resizable == value)
return;
m_Resizable = value;
NotifyChange(ColumnsDataType.Resizable);
}
}
/// <summary>
/// Indicates whether columns are resized as the user drags resize handles or only upon mouse release.
/// </summary>
/// <remarks>
/// When enabled, resizing can be cancelled by pressing ESC key.
/// </remarks>
public bool resizePreview
{
get => m_ResizePreview;
set
{
if (m_ResizePreview == value)
return;
m_ResizePreview = value;
NotifyChange(ColumnsDataType.ResizePreview);
}
}
/// <summary>
/// Returns the list of (visible and hidden) columns ordered by their display indexes.
/// </summary>
internal IEnumerable<Column> displayList
{
get
{
InitOrderColumns();
return m_DisplayColumns;
}
}
/// <summary>
/// Returns the list of visible columns.
/// </summary>
internal IEnumerable<Column> visibleList
{
get
{
UpdateVisibleColumns();
return m_VisibleColumns;
}
}
/// <summary>
/// Event sent whenever properties of the column collection change.
/// </summary>
internal event Action<ColumnsDataType> changed;
/// <summary>
/// Indicates how the size of columns in this collection is automatically adjusted as other columns or the containing view get resized.
/// The default value is <see cref="StretchMode.GrowAndFill"/>
/// </summary>
public StretchMode stretchMode
{
get => m_StretchMode;
set
{
if (m_StretchMode == value)
return;
m_StretchMode = value;
NotifyChange(ColumnsDataType.StretchMode);
}
}
/// <summary>
/// Event sent whenever a column is added to the collection at the specified index.
/// </summary>
internal event Action<Column, int> columnAdded;
/// <summary>
/// Event sent whenever a column is removed from the collection.
/// </summary>
internal event Action<Column> columnRemoved;
/// <summary>
/// Event sent whenever a column is changed, with the related data role that changed.
/// </summary>
internal event Action<Column, ColumnDataType> columnChanged;
/// <summary>
/// Event sent whenever a column is resized.
/// </summary>
internal event Action<Column> columnResized;
/// <summary>
/// Event sent whenever a column is moved from a display index to another.
/// </summary>
internal event Action<Column, int, int> columnReordered;
/// <summary>
/// Checks if the specified column is the primary one.
/// </summary>
/// <param name="column">The column to check.</param>
/// <returns>Whether or not the specified column is the primary one.</returns>
public bool IsPrimary(Column column)
{
return primaryColumnName == column.name || (string.IsNullOrEmpty(primaryColumnName) && column.visibleIndex == 0);
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<Column> GetEnumerator()
{
return m_Columns.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Adds a column at the end of the collection.
/// </summary>
/// <param name="item">The column to add.</param>
public void Add(Column item)
{
Insert(m_Columns.Count, item);
}
/// <summary>
/// Removes all columns from the collection.
/// </summary>
public void Clear()
{
while (m_Columns.Count > 0)
{
Remove(m_Columns[m_Columns.Count - 1]);
}
}
/// <inheritdoc />
public bool Contains(Column item)
{
return m_Columns.Contains(item);
}
/// <summary>
/// Whether the columns contain the specified name.
/// </summary>
/// <param name="name">The name of the column to look for.</param>
/// <returns>Whether a column with the given name exists or not.</returns>
public bool Contains(string name)
{
foreach (var column in m_Columns)
{
if (column.name == name)
return true;
}
return false;
}
/// <summary>
/// Copies the elements of the current collection to a Array, starting at the specified index.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="arrayIndex">The starting index.</param>
public void CopyTo(Column[] array, int arrayIndex)
{
m_Columns.CopyTo(array, arrayIndex);
}
/// <summary>
/// Removes the first occurence of a column from the collection.
/// </summary>
/// <param name="column">The column to remove.</param>
/// <returns>Whether it was removed or not.</returns>
public bool Remove(Column column)
{
if (column == null)
throw new ArgumentException("Cannot remove null column");
if (m_Columns.Remove(column))
{
m_DisplayColumns?.Remove(column);
m_VisibleColumns?.Remove(column);
column.collection = null;
column.changed -= OnColumnChanged;
column.resized -= OnColumnResized;
columnRemoved?.Invoke(column);
return true;
}
return false;
}
void OnColumnChanged(Column column, ColumnDataType type)
{
if (type == ColumnDataType.Visibility)
DirtyVisibleColumns();
columnChanged?.Invoke(column, type);
}
void OnColumnResized(Column column)
{
columnResized?.Invoke(column);
}
/// <summary>
/// Gets the number of columns in the collection.
/// </summary>
public int Count => m_Columns.Count;
/// <summary>
/// Gets a value indicating whether the collection is readonly.
/// </summary>
public bool IsReadOnly => m_Columns.IsReadOnly;
/// <summary>
/// Returns the index of the specified column if it is contained in the collection; returns -1 otherwise.
/// </summary>
/// <param name="column">The column to locate in the <see cref="Columns"/>.</param>
/// <returns>The index of the column if found in the collection; otherwise, -1.</returns>
public int IndexOf(Column column)
{
return m_Columns.IndexOf(column);
}
/// <summary>
/// Inserts a column into the current instance at the specified index.
/// </summary>
/// <param name="index">Index to insert to.</param>
/// <param name="column">The column to insert.</param>
public void Insert(int index, Column column)
{
if (column == null)
throw new ArgumentException("Cannot insert null column");
if (column.collection == this)
throw new ArgumentException("Already contains this column");
// Removes from the previous collection
if (column.collection != null)
column.collection.Remove(column);
m_Columns.Insert(index, column);
if (m_DisplayColumns != null)
{
m_DisplayColumns.Insert(index, column);
DirtyVisibleColumns();
}
column.collection = this;
column.changed += OnColumnChanged;
column.resized += OnColumnResized;
columnAdded?.Invoke(column, index);
}
/// <summary>
/// Removes the column at the specified index.
/// </summary>
/// <param name="index">The index of the column to remove.</param>
public void RemoveAt(int index)
{
Remove(m_Columns[index]);
}
/// <summary>
/// Returns the column at the specified index.
/// </summary>
/// <param name="index">The index of the colum to locate.</param>
/// <returns>The column at the specified index.</returns>
public Column this[int index]
{
get { return m_Columns[index]; }
}
/// <summary>
/// Returns the column with the specified name.
/// </summary>
/// <param name="name">The name of the column to locate.</param>
/// <returns>The column with the specified name.</returns>
/// <remarks>
/// Name must be unique in a column collection. Only the first with matching name will be returned.
/// </remarks>
public Column this[string name]
{
get
{
foreach (var column in m_Columns)
{
if (column.name == name)
return column;
}
return null;
}
}
/// <summary>
/// Reorders the display of a column at the specified source index, to the destination index.
/// </summary>
/// <remarks>
/// This does not change the order in the original columns data, only in columns being displayed.</remarks>
/// <param name="from">The display index of the column to move.</param>
/// <param name="to">The display index where the column will be moved to.</param>
public void ReorderDisplay(int from, int to)
{
InitOrderColumns();
var col = m_DisplayColumns[from];
m_DisplayColumns.RemoveAt(from);
m_DisplayColumns.Insert(to, col);
DirtyVisibleColumns();
columnReordered?.Invoke(col, from, to);
}
void InitOrderColumns()
{
if (m_DisplayColumns == null)
{
m_DisplayColumns = new List<Column>(this);
}
}
void DirtyVisibleColumns()
{
m_VisibleColumnsDirty = true;
if (m_VisibleColumns != null)
m_VisibleColumns.Clear();
}
void UpdateVisibleColumns()
{
if (m_VisibleColumnsDirty == false)
return;
InitOrderColumns();
if (m_VisibleColumns == null)
{
m_VisibleColumns = new List<Column>(m_Columns.Count);
}
m_VisibleColumns.AddRange(m_DisplayColumns.FindAll((c) => c.visible));
m_VisibleColumnsDirty = false;
}
void NotifyChange(ColumnsDataType type)
{
changed?.Invoke(type);
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/Columns.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/Columns.cs",
"repo_id": "UnityCsReference",
"token_count": 9435
} | 488 |
// 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.Properties;
namespace UnityEngine.UIElements
{
/// <summary>
/// A vertical or horizontal scrollbar. For more information, refer to [[wiki:UIE-uxml-element-scroller|UXML element Scroller]].
/// </summary>
public class Scroller : VisualElement
{
internal static readonly BindingId valueProperty = nameof(value);
internal static readonly BindingId lowValueProperty = nameof(lowValue);
internal static readonly BindingId highValueProperty = nameof(highValue);
internal static readonly BindingId directionProperty = nameof(direction);
class ScrollerSlider : Slider
{
public ScrollerSlider(float start, float end,
SliderDirection direction, float pageSize)
: base(start, end, direction, pageSize)
{
}
internal override float SliderNormalizeValue(float currentValue, float lowerValue, float higherValue)
{
// Ensure that the dragElement of the scrollbar never goes beyond the limits even when mouse wheel scrolling with
// elastic animation.
return Mathf.Clamp(base.SliderNormalizeValue(currentValue, lowerValue, higherValue), 0, 1);
}
}
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
#pragma warning disable 649
[UxmlAttribute("low-value", "lowValue")]
[SerializeField] float lowValue;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags lowValue_UxmlAttributeFlags;
[UxmlAttribute("high-value", "highValue")]
[SerializeField] float highValue;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags highValue_UxmlAttributeFlags;
[SerializeField] SliderDirection direction;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags direction_UxmlAttributeFlags;
[SerializeField] float value;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags value_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new Scroller();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
var e = (Scroller)obj;
if (ShouldWriteAttributeValue(lowValue_UxmlAttributeFlags))
e.slider.lowValue = lowValue;
if (ShouldWriteAttributeValue(highValue_UxmlAttributeFlags))
e.slider.highValue = highValue;
if (ShouldWriteAttributeValue(direction_UxmlAttributeFlags))
e.direction = direction;
if (ShouldWriteAttributeValue(value_UxmlAttributeFlags))
e.value = value;
}
}
/// <summary>
/// Instantiates a <see cref="Scroller"/> 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<Scroller, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="Scroller"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : VisualElement.UxmlTraits
{
UxmlFloatAttributeDescription m_LowValue = new UxmlFloatAttributeDescription { name = "low-value", obsoleteNames = new[] { "lowValue" } };
UxmlFloatAttributeDescription m_HighValue = new UxmlFloatAttributeDescription { name = "high-value", obsoleteNames = new[] { "highValue" } };
UxmlEnumAttributeDescription<SliderDirection> m_Direction = new UxmlEnumAttributeDescription<SliderDirection> { name = "direction", defaultValue = SliderDirection.Vertical};
UxmlFloatAttributeDescription m_Value = new UxmlFloatAttributeDescription { name = "value" };
/// <summary>
/// Returns an empty enumerable, as scrollers do not have children.
/// </summary>
public override IEnumerable<UxmlChildElementDescription> uxmlChildElementsDescription
{
get { yield break; }
}
/// <summary>
/// Initialize <see cref="Scroller"/> properties using values from the attribute bag.
/// </summary>
/// <param name="ve">The object to initialize.</param>
/// <param name="bag">The attribute bag.</param>
/// <param name="cc">The creation context; unused.</param>
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
Scroller scroller = ((Scroller)ve);
scroller.slider.lowValue = m_LowValue.GetValueFromBag(bag, cc);
scroller.slider.highValue = m_HighValue.GetValueFromBag(bag, cc);
scroller.direction = m_Direction.GetValueFromBag(bag, cc);
scroller.value = m_Value.GetValueFromBag(bag, cc);
}
}
// Usually set by the owner of the scroller
/// <summary>
/// Event sent when the slider value has changed.
/// </summary>
public event System.Action<float> valueChanged;
/// <summary>
/// The slider used by this scroller.
/// </summary>
public Slider slider { get; }
/// <summary>
/// Bottom or left scroll button.
/// </summary>
public RepeatButton lowButton { get; }
/// <summary>
/// Top or right scroll button.
/// </summary>
public RepeatButton highButton { get; }
/// <summary>
/// Value that defines the slider position. It lies between <see cref="lowValue"/> and <see cref="highValue"/>.
/// </summary>
[CreateProperty]
public float value
{
get { return slider.value; }
set
{
var previous = slider.value;
slider.value = value;
if (!Mathf.Approximately(previous, slider.value))
NotifyPropertyChanged(valueProperty);
}
}
/// <summary>
/// Minimum value.
/// </summary>
[CreateProperty]
public float lowValue
{
get { return slider.lowValue; }
set
{
var previous = slider.lowValue;
slider.lowValue = value;
if (!Mathf.Approximately(previous, slider.lowValue))
NotifyPropertyChanged(lowValueProperty);
}
}
/// <summary>
/// Maximum value.
/// </summary>
[CreateProperty]
public float highValue
{
get { return slider.highValue; }
set
{
var previous = slider.highValue;
slider.highValue = value;
if (!Mathf.Approximately(previous, slider.highValue))
NotifyPropertyChanged(highValueProperty);
}
}
/// <summary>
/// Direction of this scrollbar.
/// </summary>
[CreateProperty]
public SliderDirection direction
{
get { return resolvedStyle.flexDirection == FlexDirection.Row ? SliderDirection.Horizontal : SliderDirection.Vertical; }
set
{
var previous = slider.direction;
slider.direction = value;
// We want default behavior for vertical scrollers to be lowValue at the top and highValue at the bottom,
// instead of the default Slider behavior.
slider.inverted = value == SliderDirection.Vertical;
if (value == SliderDirection.Horizontal)
{
style.flexDirection = FlexDirection.Row;
AddToClassList(horizontalVariantUssClassName);
RemoveFromClassList(verticalVariantUssClassName);
}
else
{
style.flexDirection = FlexDirection.Column;
AddToClassList(verticalVariantUssClassName);
RemoveFromClassList(horizontalVariantUssClassName);
}
if (previous != slider.direction)
NotifyPropertyChanged(directionProperty);
}
}
internal const float kDefaultPageSize = 20.0f;
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public static readonly string ussClassName = "unity-scroller";
/// <summary>
/// USS class name of elements of this type, when they are displayed horizontally.
/// </summary>
public static readonly string horizontalVariantUssClassName = ussClassName + "--horizontal";
/// <summary>
/// USS class name of elements of this type, when they are displayed vertically.
/// </summary>
public static readonly string verticalVariantUssClassName = ussClassName + "--vertical";
/// <summary>
/// USS class name of slider elements in elements of this type.
/// </summary>
public static readonly string sliderUssClassName = ussClassName + "__slider";
/// <summary>
/// USS class name of low buttons in elements of this type.
/// </summary>
public static readonly string lowButtonUssClassName = ussClassName + "__low-button";
/// <summary>
/// USS class name of high buttons in elements of this type.
/// </summary>
public static readonly string highButtonUssClassName = ussClassName + "__high-button";
/// <summary>
/// Constructor.
/// </summary>
public Scroller()
: this(0, 0, null) {}
/// <summary>
/// Constructor.
/// </summary>
public Scroller(float lowValue, float highValue, System.Action<float> valueChanged, SliderDirection direction = SliderDirection.Vertical)
{
AddToClassList(ussClassName);
// Add children in correct order
slider = new ScrollerSlider(lowValue, highValue, direction, kDefaultPageSize) {name = "unity-slider", viewDataKey = "Slider"};
slider.AddToClassList(sliderUssClassName);
slider.RegisterValueChangedCallback(OnSliderValueChange);
lowButton = new RepeatButton(ScrollPageUp, ScrollWaitDefinitions.firstWait, ScrollWaitDefinitions.regularWait) { name = "unity-low-button" };
lowButton.AddToClassList(lowButtonUssClassName);
Add(lowButton);
highButton = new RepeatButton(ScrollPageDown, ScrollWaitDefinitions.firstWait, ScrollWaitDefinitions.regularWait) { name = "unity-high-button" };
highButton.AddToClassList(highButtonUssClassName);
Add(highButton);
Add(slider);
this.direction = direction;
this.valueChanged = valueChanged;
}
/// <summary>
/// Updates the slider element size as a ratio of total range. A value greater than or equal to 1 will disable the Scroller.
/// </summary>
/// <param name="factor">Slider size ratio.</param>
public void Adjust(float factor)
{
// Any factor smaller than 1f will enable the scroller (and its children)
SetEnabled(factor < 1f);
slider.AdjustDragElement(factor);
}
void OnSliderValueChange(ChangeEvent<float> evt)
{
value = evt.newValue;
valueChanged?.Invoke(slider.value);
this.IncrementVersion(VersionChangeType.Repaint);
}
/// <summary>
/// Will change the value according to the current slider pageSize.
/// </summary>
public void ScrollPageUp()
{
ScrollPageUp(1.0f);
}
/// <summary>
/// Will change the value according to the current slider pageSize.
/// </summary>
public void ScrollPageDown()
{
ScrollPageDown(1.0f);
}
/// <summary>
/// Will change the value according to the current slider pageSize.
/// </summary>
public void ScrollPageUp(float factor)
{
value -= factor * (slider.pageSize * (slider.lowValue < slider.highValue ? 1f : -1f));
}
/// <summary>
/// Will change the value according to the current slider pageSize.
/// </summary>
public void ScrollPageDown(float factor)
{
value += factor * (slider.pageSize * (slider.lowValue < slider.highValue ? 1f : -1f));
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/Scroller.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/Scroller.cs",
"repo_id": "UnityCsReference",
"token_count": 5702
} | 489 |
// 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.Globalization;
namespace UnityEngine.UIElements
{
/// <summary>
/// Makes a text field for entering an unsigned integer. For more information, refer to [[wiki:UIE-uxml-element-UnsignedIntegerField|UXML element UnsignedIntegerField]].
/// </summary>
public class UnsignedIntegerField : TextValueField<uint>
{
// This property to alleviate the fact we have to cast all the time
UnsignedIntegerInput integerInput => (UnsignedIntegerInput)textInputBase;
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : TextValueField<uint>.UxmlSerializedData
{
public override object CreateInstance() => new UnsignedIntegerField();
}
/// <summary>
/// Instantiates an <see cref="UnsignedIntegerField"/> 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<UnsignedIntegerField, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="UnsignedIntegerField"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : TextValueFieldTraits<uint, UxmlUnsignedIntAttributeDescription> {}
/// <summary>
/// Converts the given unsigned integer to a string.
/// </summary>
/// <param name="v">The unsigned integer to be converted to string.</param>
/// <returns>The unsigned integer as string.</returns>
protected override string ValueToString(uint v)
{
return v.ToString(formatString, CultureInfo.InvariantCulture.NumberFormat);
}
/// <summary>
/// Converts a string to an unsigned integer.
/// </summary>
/// <param name="str">The string to convert.</param>
/// <returns>The unsigned integer parsed from the string.</returns>
protected override uint StringToValue(string str)
{
var success = UINumericFieldsUtils.TryConvertStringToUInt(str, textInputBase.originalText, out var v);
return success ? v : rawValue;
}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public new static readonly string ussClassName = "unity-unsigned-integer-field";
/// <summary>
/// USS class name of labels in elements of this type.
/// </summary>
public new static readonly string labelUssClassName = ussClassName + "__label";
/// <summary>
/// USS class name of input elements in elements of this type.
/// </summary>
public new static readonly string inputUssClassName = ussClassName + "__input";
/// <summary>
/// Constructor.
/// </summary>
public UnsignedIntegerField()
: this((string)null) {}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="maxLength">Maximum number of characters the field can take.</param>
public UnsignedIntegerField(int maxLength)
: this(null, maxLength) {}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="maxLength">Maximum number of characters the field can take.</param>
public UnsignedIntegerField(string label, int maxLength = kMaxValueFieldLength)
: base(label, maxLength, new UnsignedIntegerInput())
{
AddToClassList(ussClassName);
labelElement.AddToClassList(labelUssClassName);
visualInput.AddToClassList(inputUssClassName);
AddLabelDragger<uint>();
}
internal override bool CanTryParse(string textString) => uint.TryParse(textString, out _);
/// <summary>
/// Applies the values of a 3D delta and a speed from an input device.
/// </summary>
/// <param name="delta">A vector used to compute the value change.</param>
/// <param name="speed">A multiplier for the value change.</param>
/// <param name="startValue">The start value.</param>
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, uint startValue)
{
integerInput.ApplyInputDeviceDelta(delta, speed, startValue);
}
class UnsignedIntegerInput : TextValueInput
{
UnsignedIntegerField parentUnsignedIntegerField => (UnsignedIntegerField)parent;
internal UnsignedIntegerInput()
{
formatString = UINumericFieldsUtils.k_IntFieldFormatString;
}
protected override string allowedCharacters => UINumericFieldsUtils.k_AllowedCharactersForInt;
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, uint startValue)
{
double sensitivity = NumericFieldDraggerUtility.CalculateIntDragSensitivity(startValue);
var acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow);
long v = StringToValue(text);
v += (long)Math.Round(NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity);
if (parentUnsignedIntegerField.isDelayed)
{
text = ValueToString(Mathf.ClampToUInt(v));
}
else
{
parentUnsignedIntegerField.value = Mathf.ClampToUInt(v);
}
}
protected override string ValueToString(uint v)
{
return v.ToString(formatString);
}
protected override uint StringToValue(string str)
{
UINumericFieldsUtils.TryConvertStringToUInt(str, originalText, out var v);
return v;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/UnsignedIntegerField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/UnsignedIntegerField.cs",
"repo_id": "UnityCsReference",
"token_count": 2492
} | 490 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace UnityEngine.UIElements
{
internal interface IDragAndDropController<in TArgs>
{
bool CanStartDrag(IEnumerable<int> itemIds);
StartDragArgs SetupDragAndDrop(IEnumerable<int> itemIds, bool skipText = false);
DragVisualMode HandleDragAndDrop(TArgs args);
void OnDrop(TArgs args);
void DragCleanup() { }
void HandleAutoExpand(ReusableCollectionItem item, Vector2 pointerPosition) { }
IEnumerable<int> GetSortedSelectedIds() => Enumerable.Empty<int>();
}
/// <summary>
/// The status of a drag-and-drop operation.
/// </summary>
public enum DragVisualMode
{
/// <summary>
/// The drag-and-drop is currently unhandled.
/// </summary>
None,
/// <summary>
/// The drag-and-drop handlers want to copy data.
/// </summary>
Copy,
/// <summary>
/// The drag-and-drop handlers want to move data.
/// </summary>
Move,
/// <summary>
/// The drag-and-drop operation is being rejected by the handlers.
/// </summary>
Rejected
}
/// <summary>
/// Information about a drag-and-drop operation that is about to start.
/// See <see cref="BaseVerticalCollectionView.canStartDrag"/>.
/// </summary>
public readonly struct CanStartDragArgs
{
/// <summary>
/// The element on which the drag operation is starting.
/// </summary>
public readonly VisualElement draggedElement;
/// <summary>
/// The ID of the dragged element.
/// </summary>
public readonly int id;
/// <summary>
/// The selected IDs in the source.
/// </summary>
public readonly IEnumerable<int> selectedIds;
internal CanStartDragArgs(VisualElement draggedElement, int id, IEnumerable<int> selectedIds)
{
this.draggedElement = draggedElement;
this.id = id;
this.selectedIds = selectedIds;
}
}
/// <summary>
/// Information about a drag-and-drop operation that just started.
/// You can use it to store generic data for the rest of the drag.
/// See <see cref="BaseVerticalCollectionView.setupDragAndDrop"/>.
/// </summary>
public readonly struct SetupDragAndDropArgs
{
/// <summary>
/// The element on which the drag operation started.
/// </summary>
public readonly VisualElement draggedElement;
/// <summary>
/// The selected IDs in the source.
/// </summary>
public readonly IEnumerable<int> selectedIds;
/// <summary>
/// Provides entry points to initialize data and visual of the new drag-and-drop operation.
/// </summary>
public readonly StartDragArgs startDragArgs;
internal SetupDragAndDropArgs(VisualElement draggedElement, IEnumerable<int> selectedIds, StartDragArgs startDragArgs)
{
this.draggedElement = draggedElement;
this.selectedIds = selectedIds;
this.startDragArgs = startDragArgs;
}
}
/// <summary>
/// Information about a drag-and-drop operation in progress.
/// See <see cref="BaseVerticalCollectionView.dragAndDropUpdate"/> and <see cref="BaseVerticalCollectionView.handleDrop"/>.
/// </summary>
public readonly struct HandleDragAndDropArgs
{
readonly DragAndDropArgs m_DragAndDropArgs;
/// <summary>
/// The world position of the pointer.
/// </summary>
public Vector2 position { get; }
/// <summary>
/// The target of the drop. There is only a target when hovering over an item. <see cref="DropPosition.OverItem"/>
/// </summary>
public object target => m_DragAndDropArgs.target;
/// <summary>
/// The index at which the drop operation wants to happen.
/// </summary>
public int insertAtIndex => m_DragAndDropArgs.insertAtIndex;
/// <summary>
/// The new parent targeted by the drag-and-drop operation. Used only for trees.
/// </summary>
/// <remarks>
/// Will always be -1 for drag-and-drop operations in list views.
/// </remarks>
public int parentId => m_DragAndDropArgs.parentId;
/// <summary>
/// The child index under the <see cref="parentId"/> that the drag-and-drop operation targets. Used only for trees.
/// </summary>
/// <remarks>
/// Will always be -1 for drag-and-drop operations in list views.
/// </remarks>
public int childIndex => m_DragAndDropArgs.childIndex;
/// <summary>
/// The type of drop position.
/// </summary>
public DragAndDropPosition dropPosition => m_DragAndDropArgs.dragAndDropPosition;
/// <summary>
/// Data stored for the drag-and-drop operation.
/// </summary>
public DragAndDropData dragAndDropData => m_DragAndDropArgs.dragAndDropData;
internal HandleDragAndDropArgs(Vector2 position, DragAndDropArgs dragAndDropArgs)
{
this.position = position;
m_DragAndDropArgs = dragAndDropArgs;
}
}
/// <summary>
/// Provides entry points to initialize the new drag-and-drop operation.
/// </summary>
public struct StartDragArgs
{
/// <summary>
/// Initializes a <see cref="StartDragArgs"/>.
/// </summary>
/// <param name="title">The text to use during the drag.</param>
/// <param name="visualMode">The visual mode the drag starts with.</param>
public StartDragArgs(string title, DragVisualMode visualMode)
{
this.title = title;
this.visualMode = visualMode;
genericData = null;
assetPaths = null;
unityObjectReferences = null;
}
// This API is used by com.unity.entities, we cannot remove it yet.
internal StartDragArgs(string title, object target)
{
this.title = title;
visualMode = DragVisualMode.Move;
genericData = null;
assetPaths = null;
unityObjectReferences = null;
SetGenericData(DragAndDropData.dragSourceKey, target);
}
/// <summary>
/// The title displayed near the pointer to identify what is being dragged.
/// Should be set during the <see cref="BaseVerticalCollectionView.setupDragAndDrop"/> callback.
/// </summary>
public string title { get; }
/// <summary>
/// The mode to use for this drag-and-drop operation.
/// </summary>
public DragVisualMode visualMode { get; }
internal Hashtable genericData { get; private set; }
internal IEnumerable<Object> unityObjectReferences { get; private set; }
internal string[] assetPaths { get; private set; }
/// <summary>
/// Sets data associated with the current drag-and-drop operation.
/// </summary>
/// <param name="key">The key for this entry.</param>
/// <param name="data">The data to store.</param>
public void SetGenericData(string key, object data)
{
genericData ??= new Hashtable();
genericData[key] = data;
}
/// <summary>
/// Sets Unity Objects associated with the current drag-and-drop operation.
/// </summary>
/// <param name="references">The Unity Object references.</param>
public void SetUnityObjectReferences(IEnumerable<Object> references)
{
unityObjectReferences = references;
}
/// <summary>
/// Stores an array of paths to assets being dragged during this drag-and-drop operation.
/// </summary>
/// <param name="paths">The asset paths.</param>
public void SetPaths(string[] paths)
{
assetPaths = paths;
}
}
}
| UnityCsReference/Modules/UIElements/Core/DragAndDrop/IDragAndDropController.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/DragAndDrop/IDragAndDropController.cs",
"repo_id": "UnityCsReference",
"token_count": 3246
} | 491 |
// 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 JetBrains.Annotations;
using UnityEngine.UIElements.Experimental;
namespace UnityEngine.UIElements
{
/// <summary>
/// The base class for all UIElements events. The class implements IDisposable to ensure proper release of the event from the pool and of any unmanaged resources, when necessary.
/// </summary>
public abstract class EventBase : IDisposable
{
private static long s_LastTypeId = 0;
/// <summary>
/// Registers an event class to the event type system.
/// </summary>
/// <returns>The type ID.</returns>
protected static long RegisterEventType() { return ++s_LastTypeId; }
/// <summary>
/// Retrieves the type ID for this event instance.
/// </summary>
public virtual long eventTypeId => - 1;
[Flags]
internal enum EventPropagation
{
None = 0,
Bubbles = 1,
TricklesDown = 2,
SkipDisabledElements = 4,
BubblesOrTricklesDown = Bubbles | TricklesDown,
}
[Flags]
enum LifeCycleStatus
{
None = 0,
PropagationStopped = 1,
ImmediatePropagationStopped = 2,
Dispatching = 4,
Pooled = 8,
IMGUIEventIsValid = 16,
PropagateToIMGUI = 32,
Dispatched = 64,
Processed = 128,
ProcessedByFocusController = 256,
}
internal int eventCategories { get; }
static ulong s_NextEventId = 0;
// Read-only state
/// <summary>
/// The time when the event was created, in milliseconds.
/// </summary>
/// <remarks>
/// This value is relative to the start time of the current application.
/// </remarks>
public long timestamp { get; private set; }
internal ulong eventId { get; private set; }
internal ulong triggerEventId { get; private set; }
internal void SetTriggerEventId(ulong id)
{
triggerEventId = id;
}
internal EventPropagation propagation { get; set; }
LifeCycleStatus lifeCycleStatus { get; set; }
/// <undoc/>
[Obsolete("Override PreDispatch(IPanel panel) instead.")]
protected virtual void PreDispatch() {}
/// <summary>
/// Allows subclasses to perform custom logic before the event is dispatched.
/// </summary>
/// <param name="panel">The panel where the event will be dispatched.</param>
protected internal virtual void PreDispatch(IPanel panel)
{
#pragma warning disable 618
PreDispatch();
#pragma warning restore 618
}
/// <undoc/>
[Obsolete("Override PostDispatch(IPanel panel) instead.")]
protected virtual void PostDispatch() {}
/// <summary>
/// Allows subclasses to perform custom logic after the event has been dispatched.
/// </summary>
/// <param name="panel">The panel where the event has been dispatched.</param>
protected internal virtual void PostDispatch(IPanel panel)
{
#pragma warning disable 618
PostDispatch();
#pragma warning restore 618
processed = true;
}
internal virtual void Dispatch([NotNull] BaseVisualElementPanel panel)
{
EventDispatchUtilities.DefaultDispatch(this, panel);
}
/// <summary>
/// Returns whether this event type bubbles up in the event propagation path.
/// </summary>
public bool bubbles
{
get { return (propagation & EventPropagation.Bubbles) != 0; }
protected set
{
if (value)
{
propagation |= EventPropagation.Bubbles;
}
else
{
propagation &= ~EventPropagation.Bubbles;
}
}
}
/// <summary>
/// Returns whether this event is sent down the event propagation path during the TrickleDown phase.
/// </summary>
public bool tricklesDown
{
get { return (propagation & EventPropagation.TricklesDown) != 0; }
protected set
{
if (value)
{
propagation |= EventPropagation.TricklesDown;
}
else
{
propagation &= ~EventPropagation.TricklesDown;
}
}
}
internal bool skipDisabledElements
{
get { return (propagation & EventPropagation.SkipDisabledElements) != 0; }
set
{
if (value)
{
propagation |= EventPropagation.SkipDisabledElements;
}
else
{
propagation &= ~EventPropagation.SkipDisabledElements;
}
}
}
internal bool bubblesOrTricklesDown => (propagation & EventPropagation.BubblesOrTricklesDown) != 0;
[Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal VisualElement elementTarget
{
get;
set;
}
/// <summary>
/// The target visual element that received this event. Unlike currentTarget, this target does not change when
/// the event is sent to other elements along the propagation path.
/// </summary>
public IEventHandler target
{
get => elementTarget;
set => elementTarget = value as VisualElement;
}
/// <summary>
/// Whether StopPropagation() was called for this event.
/// </summary>
public bool isPropagationStopped
{
get { return (lifeCycleStatus & LifeCycleStatus.PropagationStopped) != LifeCycleStatus.None; }
private set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.PropagationStopped;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.PropagationStopped;
}
}
}
/// <summary>
/// Stops propagating this event. The event is not sent to other elements along the propagation path.
/// This method does not prevent other event handlers from executing on the current target.
/// If this method is called during the TrickleDown propagation phase, it will prevent default actions
/// to be processed, such as an element getting focused as a result of a PointerDownEvent.
/// </summary>
public void StopPropagation()
{
isPropagationStopped = true;
}
/// <summary>
/// Indicates whether StopImmediatePropagation() was called for this event.
/// </summary>
public bool isImmediatePropagationStopped
{
get { return (lifeCycleStatus & LifeCycleStatus.ImmediatePropagationStopped) != LifeCycleStatus.None; }
private set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.ImmediatePropagationStopped;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.ImmediatePropagationStopped;
}
}
}
/// <summary>
/// Immediately stops the propagation of the event. The event isn't sent to other elements along the propagation path. This method prevents other event handlers from executing on the current target.
/// </summary>
public void StopImmediatePropagation()
{
isPropagationStopped = true;
isImmediatePropagationStopped = true;
}
/// <summary>
/// Returns true if the default actions should not be executed for this event.
/// </summary>
[Obsolete("Use isPropagationStopped. Before proceeding, make sure you understand the latest changes to " +
"UIToolkit event propagation rules by visiting Unity's manual page " +
"https://docs.unity3d.com/Manual/UIE-Events-Dispatching.html")]
public bool isDefaultPrevented => isPropagationStopped;
/// <summary>
/// Indicates whether the default actions are prevented from being executed for this event.
/// </summary>
[Obsolete("Use StopPropagation and/or FocusController.IgnoreEvent. Before proceeding, make sure you understand the latest changes to " +
"UIToolkit event propagation rules by visiting Unity's manual page " +
"https://docs.unity3d.com/Manual/UIE-Events-Dispatching.html")]
public void PreventDefault()
{
StopPropagation();
elementTarget?.focusController?.IgnoreEvent(this);
}
// Propagation state
/// <summary>
/// The current propagation phase for this event.
/// </summary>
public PropagationPhase propagationPhase { get; internal set; }
IEventHandler m_CurrentTarget;
/// <summary>
/// The current target of the event. This is the VisualElement, in the propagation path, for which event handlers are currently being executed.
/// </summary>
public virtual IEventHandler currentTarget
{
get { return m_CurrentTarget; }
internal set
{
m_CurrentTarget = value;
if (imguiEvent != null)
{
var element = currentTarget as VisualElement;
if (element != null)
{
imguiEvent.mousePosition = element.WorldToLocal(originalMousePosition);
}
else
{
imguiEvent.mousePosition = originalMousePosition;
}
}
}
}
/// <summary>
/// Indicates whether the event is being dispatched to a visual element. An event cannot be redispatched while it being dispatched. If you need to recursively dispatch an event, it is recommended that you use a copy of the event.
/// </summary>
public bool dispatch
{
get { return (lifeCycleStatus & LifeCycleStatus.Dispatching) != LifeCycleStatus.None; }
internal set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Dispatching;
dispatched = true;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Dispatching;
}
}
}
internal void MarkReceivedByDispatcher()
{
Debug.Assert(dispatched == false, "Events cannot be dispatched more than once.");
dispatched = true;
}
bool dispatched
{
get { return (lifeCycleStatus & LifeCycleStatus.Dispatched) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Dispatched;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Dispatched;
}
}
}
internal bool processed
{
get { return (lifeCycleStatus & LifeCycleStatus.Processed) != LifeCycleStatus.None; }
private set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Processed;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Processed;
}
}
}
internal bool processedByFocusController
{
get { return (lifeCycleStatus & LifeCycleStatus.ProcessedByFocusController) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.ProcessedByFocusController;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.ProcessedByFocusController;
}
}
}
internal bool propagateToIMGUI
{
get { return (lifeCycleStatus & LifeCycleStatus.PropagateToIMGUI) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.PropagateToIMGUI;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.PropagateToIMGUI;
}
}
}
private Event m_ImguiEvent;
// Since we recycle events (in their pools) and we do not free/reallocate a new imgui event
// at each recycling (m_ImguiEvent is never null), we use this flag to know whether m_ImguiEvent
// represents a valid Event.
bool imguiEventIsValid
{
get { return (lifeCycleStatus & LifeCycleStatus.IMGUIEventIsValid) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.IMGUIEventIsValid;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.IMGUIEventIsValid;
}
}
}
// We aim to make this internal.
/// <summary>
/// The IMGUIEvent at the source of this event. The source can be null since not all events are generated by IMGUI.
/// </summary>
public /*internal*/ Event imguiEvent
{
get { return imguiEventIsValid ? m_ImguiEvent : null; }
protected set
{
if (m_ImguiEvent == null)
{
m_ImguiEvent = new Event();
}
if (value != null)
{
m_ImguiEvent.CopyFrom(value);
imguiEventIsValid = true;
originalMousePosition = value.mousePosition; // when assigned, it is assumed that the imguievent is not touched and therefore in world coordinates.
}
else
{
imguiEventIsValid = false;
}
}
}
/// <summary>
/// The original mouse position of the IMGUI event, before it is transformed to the current target local coordinates.
/// </summary>
public Vector2 originalMousePosition { get; private set; }
internal EventDebugger eventLogger { get; set; }
internal bool log => eventLogger != null;
/// <summary>
/// Resets all event members to their initial values.
/// </summary>
protected virtual void Init()
{
LocalInit();
}
void LocalInit()
{
timestamp = Panel.TimeSinceStartupMs();
triggerEventId = 0;
eventId = s_NextEventId++;
propagation = EventPropagation.None;
elementTarget = null;
isPropagationStopped = false;
isImmediatePropagationStopped = false;
propagationPhase = default;
originalMousePosition = Vector2.zero;
m_CurrentTarget = null;
dispatch = false;
propagateToIMGUI = true;
dispatched = false;
processed = false;
processedByFocusController = false;
imguiEventIsValid = false;
pooled = false;
eventLogger = null;
}
/// <summary>
/// Constructor. Avoid creating new event instances. Instead, use GetPooled() to get an instance from a pool of reusable event instances.
/// </summary>
protected EventBase() : this(EventCategory.Default)
{
}
internal EventBase(EventCategory category)
{
eventCategories = 1 << (int) category;
m_ImguiEvent = null;
LocalInit();
}
/// <summary>
/// Whether the event is allocated from a pool of events.
/// </summary>
protected bool pooled
{
get { return (lifeCycleStatus & LifeCycleStatus.Pooled) != LifeCycleStatus.None; }
set
{
if (value)
{
lifeCycleStatus |= LifeCycleStatus.Pooled;
}
else
{
lifeCycleStatus &= ~LifeCycleStatus.Pooled;
}
}
}
internal abstract void Acquire();
/// <summary>
/// Implementation of IDisposable.
/// </summary>
public abstract void Dispose();
}
/// <summary>
/// Generic base class for events, implementing event pooling and automatic registration to the event type system.
/// </summary>
[EventCategory(EventCategory.Default)]
public abstract class EventBase<T> : EventBase where T : EventBase<T>, new()
{
static readonly long s_TypeId = RegisterEventType();
static readonly ObjectPool<T> s_Pool = new ObjectPool<T>(() => new T());
internal static void SetCreateFunction(Func<T> createMethod)
{
s_Pool.CreateFunc = createMethod;
}
int m_RefCount;
protected EventBase() : base(EventCategory)
{
m_RefCount = 0;
}
/// <summary>
/// Retrieves the type ID for this event instance.
/// </summary>
/// <returns>The type ID.</returns>
public static long TypeId()
{
return s_TypeId;
}
internal static readonly EventCategory EventCategory = EventInterestReflectionUtils.GetEventCategory(typeof(T));
/// <summary>
/// Resets all event members to their initial values.
/// </summary>
protected override void Init()
{
base.Init();
if (m_RefCount != 0)
{
Debug.Log("Event improperly released.");
m_RefCount = 0;
}
}
/// <summary>
/// Gets an event from the event pool. Use this function instead of creating new events. Events obtained using this method need to be released back to the pool. You can use `Dispose()` to release them.
/// </summary>
/// <returns>An initialized event.</returns>
public static T GetPooled()
{
T t = s_Pool.Get();
t.Init();
t.pooled = true;
t.Acquire();
return t;
}
internal static T GetPooled(EventBase e)
{
T t = GetPooled();
if (e != null)
{
t.SetTriggerEventId(e.eventId);
}
return t;
}
static void ReleasePooled(T evt)
{
if (evt.pooled)
{
// Reset the event before pooling to avoid leaking VisualElement
evt.Init();
s_Pool.Release(evt);
// To avoid double release from pool
evt.pooled = false;
}
}
internal override void Acquire()
{
m_RefCount++;
}
/// <summary>
/// Implementation of IDispose.
/// </summary>
/// <remarks>
/// If the event was instantiated from an event pool, the event is released when Dispose is called.
/// </remarks>
public sealed override void Dispose()
{
if (--m_RefCount == 0)
{
ReleasePooled((T)this);
}
}
/// <summary>
/// Retrieves the type ID for this event instance.
/// </summary>
public override long eventTypeId => s_TypeId;
}
}
| UnityCsReference/Modules/UIElements/Core/Events/EventBase.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Events/EventBase.cs",
"repo_id": "UnityCsReference",
"token_count": 9845
} | 492 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.UIElements
{
/// <summary>
/// Interface for all navigation events.
/// </summary>
public interface INavigationEvent
{
/// <summary>
/// Gets flags that indicate whether modifier keys (Alt, Ctrl, Shift, Windows/Cmd) are pressed.
/// </summary>
EventModifiers modifiers { get; }
/// <summary>
/// Describes the type of device this event was created from.
/// </summary>
/// <remarks>
/// The device type indicates whether there should be an KeyDownEvent observable before this navigation event.
/// </remarks>
internal NavigationDeviceType deviceType { get; }
/// <summary>
/// Gets a boolean value that indicates whether the Shift key is pressed. True means the Shift key is pressed.
/// False means it isn't.
/// </summary>
bool shiftKey { get; }
/// <summary>
/// Gets a boolean value that indicates whether the Ctrl key is pressed. True means the Ctrl key is pressed.
/// False means it isn't.
/// </summary>
bool ctrlKey { get; }
/// <summary>
/// Gets a boolean value that indicates whether the Windows/Cmd key is pressed. True means the Windows/Cmd key
/// is pressed. False means it isn't.
/// </summary>
bool commandKey { get; }
/// <summary>
/// Gets a boolean value that indicates whether the Alt key is pressed. True means the Alt key is pressed.
/// False means it isn't.
/// </summary>
bool altKey { get; }
/// <summary>
/// Gets a boolean value that indicates whether the platform-specific action key is pressed. True means the action
/// key is pressed. False means it isn't.
/// </summary>
/// <remarks>
/// The platform-specific action key is Cmd on macOS, and Ctrl on all other platforms.
/// </remarks>
bool actionKey { get; }
}
/// <summary>
/// Describes types of devices that can generate navigation events.
/// This can help avoid duplicated treatment of events when some controls react to keyboard input
/// using KeyDownEvent while others react to navigation events coming from the same keyboard input.
/// </summary>
internal enum NavigationDeviceType
{
/// <summary>
/// Indicates that no specific information is known about this device.
/// </summary>
/// <remarks>
/// Controls reacting to navigation events from an unknown device should react conservatively.
/// For example, if there is a conflict between a KeyDownEvent and a subsequent navigation event,
/// a control could assume that the device type is a keyboard and conservatively block the navigation event.
/// </remarks>
Unknown = 0,
/// <summary>
/// Indicates that this device is known to be a keyboard.
/// </summary>
/// <remarks>
/// This device should also send a KeyDownEvent immediately before any navigation event it generates.
/// </remarks>
Keyboard,
/// <summary>
/// Indicates that this device is anything else than a keyboard (it could be a Gamepad, for example).
/// </summary>
/// <remarks>
/// This device should not send a KeyDownEvent before the navigation events it generates.
/// </remarks>
NonKeyboard
}
/// <summary>
/// Navigation events abstract base class.
///
/// By default, navigation events trickle down and bubble up. Disabled elements won't receive these events.
/// </summary>
/// <typeparam name="T"></typeparam>
[EventCategory(EventCategory.Navigation)]
public abstract class NavigationEventBase<T> : EventBase<T>, INavigationEvent where T : NavigationEventBase<T>, new()
{
/// <summary>
/// Gets flags that indicate whether modifier keys (Alt, Ctrl, Shift, Windows/Cmd) are pressed.
/// </summary>
public EventModifiers modifiers { get; protected set; }
/// <summary>
/// Gets a boolean value that indicates whether the Shift key is pressed. True means the Shift key is pressed.
/// False means it isn't.
/// </summary>
public bool shiftKey
{
get { return (modifiers & EventModifiers.Shift) != 0; }
}
/// <summary>
/// Gets a boolean value that indicates whether the Ctrl key is pressed. True means the Ctrl key is pressed.
/// False means it isn't.
/// </summary>
public bool ctrlKey
{
get { return (modifiers & EventModifiers.Control) != 0; }
}
/// <summary>
/// Gets a boolean value that indicates whether the Windows/Cmd key is pressed. True means the Windows/Cmd key
/// is pressed. False means it isn't.
/// </summary>
public bool commandKey
{
get { return (modifiers & EventModifiers.Command) != 0; }
}
/// <summary>
/// Gets a boolean value that indicates whether the Alt key is pressed. True means the Alt key is pressed.
/// False means it isn't.
/// </summary>
public bool altKey
{
get { return (modifiers & EventModifiers.Alt) != 0; }
}
/// <summary>
/// Gets a boolean value that indicates whether the platform-specific action key is pressed. True means the action
/// key is pressed. False means it isn't.
/// </summary>
/// <remarks>
/// The platform-specific action key is Cmd on macOS, and Ctrl on all other platforms.
/// </remarks>
public bool actionKey
{
get
{
if (Application.platform == RuntimePlatform.OSXEditor ||
Application.platform == RuntimePlatform.OSXPlayer)
{
return commandKey;
}
else
{
return ctrlKey;
}
}
}
/// <summary>
/// Describes the type of device this event was created from.
/// </summary>
/// <remarks>
/// The device type indicates whether there should be an KeyDownEvent observable before this navigation event.
/// </remarks>
NavigationDeviceType INavigationEvent.deviceType => deviceType;
internal NavigationDeviceType deviceType { get; private set; }
/// <summary>
/// Constructor.
/// </summary>
protected NavigationEventBase()
{
LocalInit();
}
protected override void Init()
{
base.Init();
LocalInit();
}
void LocalInit()
{
propagation = EventPropagation.Bubbles | EventPropagation.TricklesDown |
EventPropagation.SkipDisabledElements;
modifiers = EventModifiers.None;
deviceType = NavigationDeviceType.Unknown;
}
/// <summary>
/// Gets an event from the event pool and initializes it with the given values.
/// Use this function instead of creating new events.
/// Events obtained from this method should be released back to the pool using Dispose().
/// </summary>
/// <param name="modifiers">The modifier keys held down during the event.</param>
/// <param name="deviceType">The type of device this event was created from.</param>
/// <returns>An initialized navigation event.</returns>
public static T GetPooled(EventModifiers modifiers = EventModifiers.None)
{
T e = EventBase<T>.GetPooled();
e.modifiers = modifiers;
e.deviceType = NavigationDeviceType.Unknown;
return e;
}
internal static T GetPooled(NavigationDeviceType deviceType, EventModifiers modifiers = EventModifiers.None)
{
T e = EventBase<T>.GetPooled();
e.modifiers = modifiers;
e.deviceType = deviceType;
return e;
}
internal override void Dispatch(BaseVisualElementPanel panel)
{
EventDispatchUtilities.DispatchToFocusedElementOrPanelRoot(this, panel);
}
}
/// <summary>
/// Event typically sent when the user presses the D-pad, moves a joystick or presses the arrow keys.
/// </summary>
public class NavigationMoveEvent : NavigationEventBase<NavigationMoveEvent>
{
static NavigationMoveEvent()
{
SetCreateFunction(() => new NavigationMoveEvent());
}
/// <summary>
/// Move event direction.
/// </summary>
public enum Direction
{
/// <summary>
/// No specific direction.
/// </summary>
None,
/// <summary>
/// Left.
/// </summary>
Left,
/// <summary>
/// Up.
/// </summary>
Up,
/// <summary>
/// Right.
/// </summary>
Right,
/// <summary>
/// Down.
/// </summary>
Down,
/// <summary>
/// Forwards, toward next element.
/// </summary>
Next,
/// <summary>
/// Backwards, toward previous element.
/// </summary>
Previous,
}
internal static Direction DetermineMoveDirection(float x, float y, float deadZone = 0.6f)
{
// if vector is too small... just return
if (new Vector2(x, y).sqrMagnitude < deadZone * deadZone)
return Direction.None;
if (Mathf.Abs(x) > Mathf.Abs(y))
{
if (x > 0)
return Direction.Right;
return Direction.Left;
}
else
{
if (y > 0)
return Direction.Up;
return Direction.Down;
}
}
/// <summary>
/// The direction of the navigation.
/// </summary>
public Direction direction { get; private set; }
/// <summary>
/// The move vector, if applicable.
/// </summary>
/// <remarks>
/// This information is not guaranteed to be available through all input sources that can generate
/// NavigationMoveEvents. UI Toolkit standard controls should never depend on this value being set.
/// </remarks>
public Vector2 move { get; private set; }
/// <summary>
/// Gets an event from the event pool and initializes it with the given values.
/// Use this function instead of creating new events.
/// Events obtained from this method should be released back to the pool using Dispose().
/// </summary>
/// <param name="moveVector">The move vector.</param>
/// <param name="modifiers">The modifier keys held down during the event.</param>
/// <returns>An initialized navigation event.</returns>
public static NavigationMoveEvent GetPooled(Vector2 moveVector, EventModifiers modifiers = EventModifiers.None)
{
NavigationMoveEvent e = GetPooled(NavigationDeviceType.Unknown, modifiers);
e.direction = DetermineMoveDirection(moveVector.x, moveVector.y);
e.move = moveVector;
return e;
}
internal static NavigationMoveEvent GetPooled(Vector2 moveVector, NavigationDeviceType deviceType, EventModifiers modifiers = EventModifiers.None)
{
NavigationMoveEvent e = GetPooled(deviceType, modifiers);
e.direction = DetermineMoveDirection(moveVector.x, moveVector.y);
e.move = moveVector;
return e;
}
/// <summary>
/// Gets an event from the event pool and initializes it with the given values.
/// Use this function instead of creating new events.
/// Events obtained from this method should be released back to the pool using Dispose().
/// </summary>
/// <param name="direction">The logical direction of the navigation.</param>
/// <param name="modifiers">The modifier keys held down during the event.</param>
/// <returns>An initialized navigation event.</returns>
/// <remarks>
/// This method doesn't set any move vector. See other overload of the method for more information.
/// </remarks>
public static NavigationMoveEvent GetPooled(Direction direction, EventModifiers modifiers = EventModifiers.None)
{
NavigationMoveEvent e = GetPooled(NavigationDeviceType.Unknown, modifiers);
e.direction = direction;
e.move = Vector2.zero;
return e;
}
internal static NavigationMoveEvent GetPooled(Direction direction, NavigationDeviceType deviceType, EventModifiers modifiers = EventModifiers.None)
{
NavigationMoveEvent e = GetPooled(deviceType, modifiers);
e.direction = direction;
e.move = Vector2.zero;
return e;
}
/// <summary>
/// Initialize the event members.
/// </summary>
protected override void Init()
{
base.Init();
LocalInit();
}
/// <summary>
/// Constructor.
/// </summary>
public NavigationMoveEvent()
{
LocalInit();
}
void LocalInit()
{
direction = Direction.None;
move = Vector2.zero;
}
protected internal override void PostDispatch(IPanel panel)
{
panel.focusController.SwitchFocusOnEvent(panel.focusController.GetLeafFocusedElement(), this);
base.PostDispatch(panel);
}
}
/// <summary>
/// Event sent when the user presses the cancel button.
/// </summary>
public class NavigationCancelEvent : NavigationEventBase<NavigationCancelEvent>
{
static NavigationCancelEvent()
{
SetCreateFunction(() => new NavigationCancelEvent());
}
}
/// <summary>
/// Event sent when the user presses the submit button.
/// </summary>
public class NavigationSubmitEvent : NavigationEventBase<NavigationSubmitEvent>
{
static NavigationSubmitEvent()
{
SetCreateFunction(() => new NavigationSubmitEvent());
}
}
}
| UnityCsReference/Modules/UIElements/Core/Events/NavigationEvents.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Events/NavigationEvents.cs",
"repo_id": "UnityCsReference",
"token_count": 5966
} | 493 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.UIElements
{
/// <summary>
/// A collection of static methods that provide simple World, Screen, and Panel coordinate transformations.
/// </summary>
public static class RuntimePanelUtils
{
/// <summary>
/// Transforms a screen absolute position to its equivalent local coordinate on given panel.
/// </summary>
/// <param name="panel">The local coordinates reference panel.</param>
/// <param name="screenPosition">The screen position to transform.</param>
/// <returns>A position in panel coordinates that corresponds to the provided screen position.</returns>
public static Vector2 ScreenToPanel(IPanel panel, Vector2 screenPosition)
{
return ((BaseRuntimePanel)panel).ScreenToPanel(screenPosition);
}
/// <summary>
/// Transforms a world absolute position to its equivalent local coordinate on given panel,
/// using provided camera for internal WorldToScreen transformation.
/// </summary>
/// <param name="panel">The local coordinates reference panel.</param>
/// <param name="worldPosition">The world position to transform.</param>
/// <param name="camera">The Camera used for internal WorldToScreen transformation.</param>
/// <returns>A position in panel coordinates that corresponds to the provided world position.</returns>
public static Vector2 CameraTransformWorldToPanel(IPanel panel, Vector3 worldPosition, Camera camera)
{
Vector2 screenPoint = camera.WorldToScreenPoint(worldPosition);
screenPoint.y = Screen.height - screenPoint.y; // Flip y axis. TODO: add appropriate #if (if necessary)
return ((BaseRuntimePanel)panel).ScreenToPanel(screenPoint);
}
/// <summary>
/// Transforms a world position and size (in world units) to their equivalent local position and size
/// on given panel, using provided camera for internal WorldToScreen transformation.
/// </summary>
/// <param name="panel">The local coordinates reference panel.</param>
/// <param name="worldPosition">The world position to transform.</param>
/// <param name="worldSize">The world size to transform. The object in the panel will appear to have
/// that size when compared to other 3D objects at neighboring positions.</param>
/// <param name="camera">The Camera used for internal WorldToScreen transformation.</param>
/// <returns>A (position, size) Rect in panel coordinates that corresponds to the provided world position
/// and size.</returns>
public static Rect CameraTransformWorldToPanelRect(IPanel panel, Vector3 worldPosition, Vector2 worldSize, Camera camera)
{
worldSize.y = -worldSize.y; // BottomRight has negative y offset
Vector2 topLeftOnPanel = CameraTransformWorldToPanel(panel, worldPosition, camera);
Vector3 bottomRightInWorldFacingCam = worldPosition + camera.worldToCameraMatrix.MultiplyVector(worldSize);
Vector2 bottomRightOnPanel = CameraTransformWorldToPanel(panel, bottomRightInWorldFacingCam, camera);
return new Rect(topLeftOnPanel, bottomRightOnPanel - topLeftOnPanel);
}
/// <summary>
/// Resets the dynamic atlas of the panel. Textured elements will be repainted.
/// </summary>
public static void ResetDynamicAtlas(this IPanel panel)
{
var p = panel as BaseVisualElementPanel;
if (p == null)
return;
var atlas = p.atlas as DynamicAtlas;
atlas?.Reset();
}
/// <summary>
/// Notifies the dynamic atlas of the panel that the content of the provided texture has changed. If the dynamic
/// atlas contains the texture, it will update it.
/// </summary>
/// <param name="panel">The current panel</param>
/// <param name="texture">The texture whose content has changed.</param>
public static void SetTextureDirty(this IPanel panel, Texture2D texture)
{
var p = panel as BaseVisualElementPanel;
if (p == null)
return;
var atlas = p.atlas as DynamicAtlas;
atlas?.SetDirty(texture);
}
}
}
| UnityCsReference/Modules/UIElements/Core/GameObjects/RuntimePanelUtils.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/GameObjects/RuntimePanelUtils.cs",
"repo_id": "UnityCsReference",
"token_count": 1563
} | 494 |
// 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.UIElements
{
/// <summary>
/// Represents an operation that the user is trying to accomplish through a specific input mechanism.
/// </summary>
/// <remarks>
/// Tests the received callback value for <see cref="KeyboardNavigationManipulator"/> against the values of this enum to implement the operation in your UI.
/// </remarks>
public enum KeyboardNavigationOperation
{
/// <summary>
/// Default value. Indicates an uninitialized enum value.
/// </summary>
None,
/// <summary>
/// Selects all UI selectable elements or text.
/// </summary>
SelectAll,
/// <summary>
/// Cancels the current UI interaction.
/// </summary>
Cancel,
/// <summary>
/// Submits or concludes the current UI interaction.
/// </summary>
Submit,
/// <summary>
/// Moves up to the previous item.
/// </summary>
Previous,
/// <summary>
/// Moves down to the next item.
/// </summary>
Next,
/// <summary>
/// Moves to the right.
/// </summary>
MoveRight,
/// <summary>
/// Moves to the left.
/// </summary>
MoveLeft,
/// <summary>
/// Moves the selection up one page (in a list that has a scrollable area).
/// </summary>
PageUp,
/// <summary>
/// Moves the selection down one page (in a list that has a scrollable area).
/// </summary>
PageDown,
/// <summary>
/// Selects the first element.
/// </summary>
Begin,
/// <summary>
/// Selects the last element.
/// </summary>
End,
}
/// <summary>
/// Provides a default implementation for translating input device specific events to higher level navigation operations as commonly possible with a keyboard.
/// </summary>
public class KeyboardNavigationManipulator : Manipulator
{
readonly Action<KeyboardNavigationOperation, EventBase> m_Action;
/// <summary>
/// Initializes and returns an instance of KeyboardNavigationManipulator, configured to invoke the specified callback.
/// </summary>
/// <param name="action">This action is invoked when specific low level events are dispatched to the target <see cref="VisualElement"/>,
/// with a specific value of <see cref="KeyboardNavigationOperation"/> and a reference to the original low level event.</param>
public KeyboardNavigationManipulator(Action<KeyboardNavigationOperation, EventBase> action)
{
m_Action = action;
}
protected override void RegisterCallbacksOnTarget()
{
target.RegisterCallback<NavigationMoveEvent>(OnNavigationMove);
target.RegisterCallback<NavigationSubmitEvent>(OnNavigationSubmit);
target.RegisterCallback<NavigationCancelEvent>(OnNavigationCancel);
target.RegisterCallback<KeyDownEvent>(OnKeyDown);
}
protected override void UnregisterCallbacksFromTarget()
{
target.UnregisterCallback<NavigationMoveEvent>(OnNavigationMove);
target.UnregisterCallback<NavigationSubmitEvent>(OnNavigationSubmit);
target.UnregisterCallback<NavigationCancelEvent>(OnNavigationCancel);
target.UnregisterCallback<KeyDownEvent>(OnKeyDown);
}
internal void OnKeyDown(KeyDownEvent evt)
{
// At the moment these actions are not mapped dynamically in the InputSystemEventSystem component.
// When that becomes the case in the future, remove the following and use corresponding Navigation events.
KeyboardNavigationOperation GetOperation()
{
switch (evt.keyCode)
{
case KeyCode.A when evt.actionKey: return KeyboardNavigationOperation.SelectAll;
case KeyCode.Home: return KeyboardNavigationOperation.Begin;
case KeyCode.End: return KeyboardNavigationOperation.End;
case KeyCode.PageUp: return KeyboardNavigationOperation.PageUp;
case KeyCode.PageDown: return KeyboardNavigationOperation.PageDown;
// Workaround for navigation with arrow keys. It will trigger the sound of an incorrect key being pressed.
// Since we use navigation events, the input system should already prevent the sound. See case UUM-26264.
case KeyCode.DownArrow:
case KeyCode.UpArrow:
case KeyCode.LeftArrow:
case KeyCode.RightArrow:
evt.StopPropagation();
break;
}
return KeyboardNavigationOperation.None;
}
var op = GetOperation();
if (op != KeyboardNavigationOperation.None)
{
Invoke(op, evt);
}
}
void OnNavigationCancel(NavigationCancelEvent evt)
{
Invoke(KeyboardNavigationOperation.Cancel, evt);
}
void OnNavigationSubmit(NavigationSubmitEvent evt)
{
Invoke(KeyboardNavigationOperation.Submit, evt);
}
void OnNavigationMove(NavigationMoveEvent evt)
{
switch (evt.direction)
{
case NavigationMoveEvent.Direction.Up:
Invoke(KeyboardNavigationOperation.Previous, evt);
break;
case NavigationMoveEvent.Direction.Down:
Invoke(KeyboardNavigationOperation.Next, evt);
break;
case NavigationMoveEvent.Direction.Left:
Invoke(KeyboardNavigationOperation.MoveLeft, evt);
break;
case NavigationMoveEvent.Direction.Right:
Invoke(KeyboardNavigationOperation.MoveRight, evt);
break;
}
}
void Invoke(KeyboardNavigationOperation operation, EventBase evt)
{
m_Action?.Invoke(operation, evt);
}
}
}
| UnityCsReference/Modules/UIElements/Core/KeyboardNavigationManipulator.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/KeyboardNavigationManipulator.cs",
"repo_id": "UnityCsReference",
"token_count": 2750
} | 495 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
// ReSharper disable FieldCanBeMadeReadOnly.Local
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnityEngine.UIElements.Layout;
[StructLayout(LayoutKind.Sequential)]
unsafe struct FixedBuffer2<T> where T : unmanaged
{
T __0;
T __1;
public const int Length = 2;
public ref T this[int index]
{
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
get
{
if (index < 0 || index >= Length)
throw new IndexOutOfRangeException(nameof(index));
fixed (void* ptr = &this)
{
var p = (T*) ptr;
return ref p[index];
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct FixedBuffer4<T> where T : unmanaged
{
T __0;
T __1;
T __2;
T __3;
public FixedBuffer4(T x, T y, T z, T w)
{
__0 = x;
__1 = y;
__2 = z;
__3 = w;
}
public const int Length = 4;
public ref T this[int index]
{
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
get
{
if (index < 0 || index >= Length)
throw new IndexOutOfRangeException(nameof(index));
fixed (void* ptr = &this)
{
var p = (T*) ptr;
return ref p[index];
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct FixedBuffer6<T> where T : unmanaged
{
T __0;
T __1;
T __2;
T __3;
T __4;
T __5;
public const int Length = 6;
public ref T this[int index]
{
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
get
{
if (index < 0 || index >= Length)
throw new IndexOutOfRangeException(nameof(index));
fixed (void* ptr = &this)
{
var p = (T*) ptr;
return ref p[index];
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct FixedBuffer9<T> where T : unmanaged
{
T __0;
T __1;
T __2;
T __3;
T __4;
T __5;
T __6;
T __7;
T __8;
public const int Length = 9;
public ref T this[int index]
{
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
get
{
if (index is < 0 or >= Length)
throw new IndexOutOfRangeException(nameof(index));
fixed (void* ptr = &this)
{
var p = (T*) ptr;
return ref p[index];
}
}
}
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct FixedBuffer16<T> where T : unmanaged
{
T __0;
T __1;
T __2;
T __3;
T __4;
T __5;
T __6;
T __7;
T __8;
T __9;
T _10;
T _11;
T _12;
T _13;
T _14;
T _15;
public const int Length = 16;
public ref T this[int index]
{
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
get
{
if (index is < 0 or >= Length)
throw new IndexOutOfRangeException(nameof(index));
fixed (void* ptr = &this)
{
var p = (T*) ptr;
return ref p[index];
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Layout/Model/FixedBuffer.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Layout/Model/FixedBuffer.cs",
"repo_id": "UnityCsReference",
"token_count": 1763
} | 496 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Runtime.InteropServices;
namespace UnityEngine.UIElements.Layout;
[StructLayout(LayoutKind.Sequential)]
struct LayoutSize
{
public float width;
public float height;
public LayoutSize(float width, float height)
{
this.width = width;
this.height = height;
}
}
| UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutSize.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutSize.cs",
"repo_id": "UnityCsReference",
"token_count": 156
} | 497 |
// 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 Unity.Jobs;
namespace UnityEngine.UIElements.UIR
{
[NativeHeader("Modules/UIElements/Core/Native/Renderer/UIRendererJobProcessor.h")]
static class JobProcessor
{
internal extern static JobHandle ScheduleNudgeJobs(IntPtr buffer, int jobCount);
internal extern static JobHandle ScheduleConvertMeshJobs(IntPtr buffer, int jobCount);
internal extern static JobHandle ScheduleCopyMeshJobs(IntPtr buffer, int jobCount);
}
}
| UnityCsReference/Modules/UIElements/Core/Native/Renderer/UIRendererJobProcessor.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Native/Renderer/UIRendererJobProcessor.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 219
} | 498 |
// 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.UIElements.UIR
{
static class CommandManipulator
{
static bool IsParentOrAncestorOf(this VisualElement ve, VisualElement child)
{
// O(n) of tree depth, not very cool
while (child.hierarchy.parent != null)
{
if (child.hierarchy.parent == ve)
return true;
child = child.hierarchy.parent;
}
return false;
}
public static void ReplaceCommands(RenderChain renderChain, VisualElement ve, EntryProcessor processor)
{
if (processor.firstHeadCommand == null && processor.firstTailCommand == null && ve.renderChainData.firstHeadCommand != null)
{
ResetCommands(renderChain, ve);
return;
}
// Update head commands
// Retain our command insertion points if possible, to avoid paying the cost of finding them again
{
bool foundInsertionBounds = false;
RenderChainCommand prev = null;
RenderChainCommand next = null;
if (ve.renderChainData.firstHeadCommand != null)
{
prev = ve.renderChainData.firstHeadCommand.prev;
next = ve.renderChainData.lastHeadCommand.next;
RemoveChain(renderChain, ve.renderChainData.firstHeadCommand, ve.renderChainData.lastHeadCommand);
foundInsertionBounds = true;
}
// Do we have anything to insert?
if (processor.firstHeadCommand != null)
{
if (!foundInsertionBounds)
FindHeadCommandInsertionPoint(ve, out prev, out next);
if (prev != null)
{
processor.firstHeadCommand.prev = prev;
prev.next = processor.firstHeadCommand;
}
if (next != null)
{
processor.lastHeadCommand.next = next;
next.prev = processor.lastHeadCommand;
}
renderChain.OnRenderCommandAdded(processor.firstHeadCommand);
}
ve.renderChainData.firstHeadCommand = processor.firstHeadCommand;
ve.renderChainData.lastHeadCommand = processor.lastHeadCommand;
}
// Update tail commands
// Retain our command insertion points if possible, to avoid paying the cost of finding them again
{
bool foundInsertionBounds = false;
RenderChainCommand prev = null;
RenderChainCommand next = null;
if (ve.renderChainData.firstTailCommand != null)
{
prev = ve.renderChainData.firstTailCommand.prev;
next = ve.renderChainData.lastTailCommand.next;
RemoveChain(renderChain, ve.renderChainData.firstTailCommand, ve.renderChainData.lastTailCommand);
foundInsertionBounds = true;
}
// Do we have anything to insert?
if (processor.firstTailCommand != null)
{
if (!foundInsertionBounds)
FindTailCommandInsertionPoint(ve, out prev, out next);
if (prev != null)
{
processor.firstTailCommand.prev = prev;
prev.next = processor.firstTailCommand;
}
if (next != null)
{
processor.lastTailCommand.next = next;
next.prev = processor.lastTailCommand;
}
renderChain.OnRenderCommandAdded(processor.firstTailCommand);
}
ve.renderChainData.firstTailCommand = processor.firstTailCommand;
ve.renderChainData.lastTailCommand = processor.lastTailCommand;
}
}
static void FindHeadCommandInsertionPoint(VisualElement ve, out RenderChainCommand prev, out RenderChainCommand next)
{
VisualElement prevDrawingElem = ve.renderChainData.prev;
// This can be potentially O(n) of VE count
// It is ok to check against lastHeadCommand to mean the presence of tailCommand too, as we
// require that tail commands only exist if a head command exists too
while (prevDrawingElem != null && prevDrawingElem.renderChainData.lastHeadCommand == null)
prevDrawingElem = prevDrawingElem.renderChainData.prev;
if (prevDrawingElem != null && prevDrawingElem.renderChainData.lastHeadCommand != null)
{
// A previous drawing element can be:
// A) A previous sibling (O(1) check time)
// B) A parent/ancestor (O(n) of tree depth check time - meh)
// C) A child/grand-child of a previous sibling to an ancestor (lengthy check time, so it is left as the only choice remaining after the first two)
if (prevDrawingElem.hierarchy.parent == ve.hierarchy.parent) // Case A
prev = prevDrawingElem.renderChainData.lastTailOrHeadCommand;
else if (prevDrawingElem.IsParentOrAncestorOf(ve)) // Case B
prev = prevDrawingElem.renderChainData.lastHeadCommand;
else
{
// Case C, get the last command that isn't owned by us, this is to skip potential
// tail commands wrapped after the previous drawing element
var lastCommand = prevDrawingElem.renderChainData.lastTailOrHeadCommand;
for (; ; )
{
prev = lastCommand;
lastCommand = lastCommand.next;
if (lastCommand == null || (lastCommand.owner == ve) || !lastCommand.isTail) // Once again, we assume tail commands cannot exist without opening commands on the element
break;
if (lastCommand.owner.IsParentOrAncestorOf(ve))
break;
}
}
next = prev.next;
}
else
{
VisualElement nextDrawingElem = ve.renderChainData.next;
// This can be potentially O(n) of VE count, very bad.. must adjust
while (nextDrawingElem != null && nextDrawingElem.renderChainData.firstHeadCommand == null)
nextDrawingElem = nextDrawingElem.renderChainData.next;
next = nextDrawingElem?.renderChainData.firstHeadCommand;
prev = null;
Debug.Assert((next == null) || (next.prev == null));
}
}
static void FindTailCommandInsertionPoint(VisualElement ve, out RenderChainCommand prev, out RenderChainCommand next)
{
// Tail commands for a visual element come after the tail commands of the shallowest child
// If not found, then after the last command of the last deepest child
// If not found, then after the last command of self
VisualElement nextDrawingElem = ve.renderChainData.next;
// Depth first search for the first VE that has a command (i.e. non empty element).
// This can be potentially O(n) of VE count
// It is ok to check against lastHeadCommand to mean the presence of tailCommand too, as we
// require that tail commands only exist if a startup command exists too
while (nextDrawingElem != null && nextDrawingElem.renderChainData.firstHeadCommand == null)
nextDrawingElem = nextDrawingElem.renderChainData.next;
if (nextDrawingElem != null && nextDrawingElem.renderChainData.firstHeadCommand != null)
{
// A next drawing element can be:
// A) A next sibling of ve (O(1) check time)
// B) A child/grand-child of self (O(n) of tree depth check time - meh)
// C) A next sibling of a parent/ancestor (lengthy check time, so it is left as the only choice remaining after the first two)
if (nextDrawingElem.hierarchy.parent == ve.hierarchy.parent) // Case A
{
next = nextDrawingElem.renderChainData.firstHeadCommand;
prev = next.prev;
}
else if (ve.IsParentOrAncestorOf(nextDrawingElem)) // Case B
{
// Enclose the last deepest drawing child by our tail command
for (; ; )
{
prev = nextDrawingElem.renderChainData.lastTailOrHeadCommand;
nextDrawingElem = prev.next?.owner;
if (nextDrawingElem == null || !ve.IsParentOrAncestorOf(nextDrawingElem))
break;
}
next = prev.next;
}
else
{
// Case C, just wrap ourselves
prev = ve.renderChainData.lastHeadCommand;
next = prev.next;
}
}
else
{
prev = ve.renderChainData.lastHeadCommand;
next = prev.next; // prev should not be null since we don't support tail commands without opening commands too
}
}
static void RemoveChain(RenderChain renderChain, RenderChainCommand first, RenderChainCommand last)
{
Debug.Assert(first != null);
Debug.Assert(last != null);
renderChain.OnRenderCommandsRemoved(first, last);
// Fix the rest of the chain
if (first.prev != null)
first.prev.next = last.next;
if (last.next != null)
last.next.prev = first.prev;
// Free the inner chain
RenderChainCommand current = first;
RenderChainCommand prev;
do
{
RenderChainCommand next = current.next;
renderChain.FreeCommand(current);
prev = current;
current = next;
} while (prev != last);
}
public static void ResetCommands(RenderChain renderChain, VisualElement ve)
{
if (ve.renderChainData.firstHeadCommand != null)
renderChain.OnRenderCommandsRemoved(ve.renderChainData.firstHeadCommand, ve.renderChainData.lastHeadCommand);
var prev = ve.renderChainData.firstHeadCommand != null ? ve.renderChainData.firstHeadCommand.prev : null;
var next = ve.renderChainData.lastHeadCommand != null ? ve.renderChainData.lastHeadCommand.next : null;
Debug.Assert(prev == null || prev.owner != ve);
Debug.Assert(next == null || next == ve.renderChainData.firstTailCommand || next.owner != ve);
if (prev != null) prev.next = next;
if (next != null) next.prev = prev;
if (ve.renderChainData.firstHeadCommand != null)
{
var c = ve.renderChainData.firstHeadCommand;
while (c != ve.renderChainData.lastHeadCommand)
{
var nextC = c.next;
renderChain.FreeCommand(c);
c = nextC;
}
renderChain.FreeCommand(c); // Last head command
}
ve.renderChainData.firstHeadCommand = ve.renderChainData.lastHeadCommand = null;
prev = ve.renderChainData.firstTailCommand != null ? ve.renderChainData.firstTailCommand.prev : null;
next = ve.renderChainData.lastTailCommand != null ? ve.renderChainData.lastTailCommand.next : null;
Debug.Assert(prev == null || prev.owner != ve);
Debug.Assert(next == null || next.owner != ve);
if (prev != null) prev.next = next;
if (next != null) next.prev = prev;
if (ve.renderChainData.firstTailCommand != null)
{
renderChain.OnRenderCommandsRemoved(ve.renderChainData.firstTailCommand, ve.renderChainData.lastTailCommand);
var c = ve.renderChainData.firstTailCommand;
while (c != ve.renderChainData.lastTailCommand)
{
var nextC = c.next;
renderChain.FreeCommand(c);
c = nextC;
}
renderChain.FreeCommand(c); // Last tail command
}
ve.renderChainData.firstTailCommand = ve.renderChainData.lastTailCommand = null;
}
static void InjectCommandInBetween(RenderChain renderChain, RenderChainCommand cmd, RenderChainCommand prev, RenderChainCommand next)
{
if (prev != null)
{
cmd.prev = prev;
prev.next = cmd;
}
if (next != null)
{
cmd.next = next;
next.prev = cmd;
}
VisualElement ve = cmd.owner;
if (!cmd.isTail)
{
if (ve.renderChainData.firstHeadCommand == null || ve.renderChainData.firstHeadCommand == next)
ve.renderChainData.firstHeadCommand = cmd;
if (ve.renderChainData.lastHeadCommand == null || ve.renderChainData.lastHeadCommand == prev)
ve.renderChainData.lastHeadCommand = cmd;
}
else
{
if (ve.renderChainData.firstTailCommand == null || ve.renderChainData.firstTailCommand == next)
ve.renderChainData.firstTailCommand = cmd;
if (ve.renderChainData.lastTailCommand == null || ve.renderChainData.lastTailCommand == prev)
ve.renderChainData.lastTailCommand = cmd;
}
renderChain.OnRenderCommandAdded(cmd);
}
public static void DisableElementRendering(RenderChain renderChain, VisualElement ve, bool renderingDisabled)
{
if (!ve.renderChainData.isInChain)
return;
if (renderingDisabled)
{
if (ve.renderChainData.firstHeadCommand == null || ve.renderChainData.firstHeadCommand.type != CommandType.BeginDisable)
{
var cmd = renderChain.AllocCommand();
cmd.type = CommandType.BeginDisable;
cmd.owner = ve;
if (ve.renderChainData.firstHeadCommand == null)
{
FindHeadCommandInsertionPoint(ve, out var cmdPrev, out var cmdNext);
InjectCommandInBetween(renderChain, cmd, cmdPrev, cmdNext);
}
else
{
// Need intermediate variable to pass by reference as it is modified
var prev = ve.renderChainData.firstHeadCommand.prev;
var next = ve.renderChainData.firstHeadCommand;
var lastHeadCommand = ve.renderChainData.lastHeadCommand; // InjectCommandInBetween assumes we are adding the last command, witch is not the case now. Backup the value to restore after.
Debug.Assert(lastHeadCommand != null);
ve.renderChainData.firstHeadCommand = null; // will be replaced in InjectCommandInBetween
InjectCommandInBetween(renderChain, cmd, prev, next);
ve.renderChainData.lastHeadCommand = lastHeadCommand;
}
}
if (ve.renderChainData.lastTailCommand == null || ve.renderChainData.lastTailCommand.type != CommandType.EndDisable)
{
var cmd = renderChain.AllocCommand();
cmd.type = CommandType.EndDisable;
cmd.isTail = true;
cmd.owner = ve;
if (ve.renderChainData.lastTailCommand == null)
{
FindTailCommandInsertionPoint(ve, out var cmdPrev, out var cmdNext);
InjectCommandInBetween(renderChain, cmd, cmdPrev, cmdNext);
}
else
{
// Need intermediate variable to pass by reference as it is modified
var prev = ve.renderChainData.lastTailCommand;
var next = ve.renderChainData.lastTailCommand.next;
Debug.Assert(ve.renderChainData.firstTailCommand != null);
InjectCommandInBetween(renderChain, cmd, prev, next);
}
}
}
else
{
if (ve.renderChainData.firstHeadCommand != null && ve.renderChainData.firstHeadCommand.type == CommandType.BeginDisable)
RemoveSingleCommand(renderChain, ve, ve.renderChainData.firstHeadCommand);
if (ve.renderChainData.lastTailCommand != null && ve.renderChainData.lastTailCommand.type == CommandType.EndDisable)
RemoveSingleCommand(renderChain, ve, ve.renderChainData.lastTailCommand);
}
}
static void RemoveSingleCommand(RenderChain renderChain, VisualElement ve, RenderChainCommand cmd)
{
Debug.Assert(cmd != null);
Debug.Assert(cmd.owner == ve);
renderChain.OnRenderCommandsRemoved(cmd, cmd);
var prev = cmd.prev;
var next = cmd.next;
if (prev != null) prev.next = next;
if (next != null) next.prev = prev;
// Clean up renderChain head commands pointers in the VisualElement's renderChainData
if (ve.renderChainData.firstHeadCommand == cmd)
{
// is this the last Head command of the object
if (ve.renderChainData.firstHeadCommand == ve.renderChainData.lastHeadCommand)
{
// Last command removed: extra checks
Debug.Assert(cmd.prev?.owner != ve, "When removing the first head command, the command before this one in the queue should belong to an other parent");
Debug.Assert(cmd.next?.owner != ve || cmd.next == ve.renderChainData.firstTailCommand); // It could be valid that there is a closing command if they get removed after this call.
ve.renderChainData.firstHeadCommand = null;
ve.renderChainData.lastHeadCommand = null;
}
else
{
Debug.Assert(cmd.next.owner == ve);
Debug.Assert(ve.renderChainData.lastHeadCommand != null);
ve.renderChainData.firstHeadCommand = cmd.next;
}
}
else if (ve.renderChainData.lastHeadCommand == cmd)
{
Debug.Assert(cmd.prev.owner == ve);
Debug.Assert(ve.renderChainData.firstHeadCommand != null);
ve.renderChainData.lastHeadCommand = cmd.prev;
}
// Clean up renderChain Tail commands
if (ve.renderChainData.firstTailCommand == cmd)
{
//is this the last tailCommand?
if (ve.renderChainData.firstTailCommand == ve.renderChainData.lastTailCommand)
{
// Last command removed: extra checks
Debug.Assert(cmd.prev?.owner != ve || cmd.prev == ve.renderChainData.lastHeadCommand);
Debug.Assert(cmd.next?.owner != ve);
ve.renderChainData.firstTailCommand = null;
ve.renderChainData.lastTailCommand = null;
}
else
{
Debug.Assert(cmd.next.owner == ve);
Debug.Assert(ve.renderChainData.lastTailCommand != null);
ve.renderChainData.firstTailCommand = cmd.next;
}
}
else if (ve.renderChainData.lastTailCommand == cmd)
{
Debug.Assert(cmd.prev.owner == ve);
Debug.Assert(ve.renderChainData.firstTailCommand != null);
ve.renderChainData.lastTailCommand = cmd.prev;
}
renderChain.FreeCommand(cmd);
}
}
}
| UnityCsReference/Modules/UIElements/Core/Renderer/UIRCommandManipulator.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRCommandManipulator.cs",
"repo_id": "UnityCsReference",
"token_count": 10313
} | 499 |
// 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 System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs.LowLevel.Unsafe;
namespace UnityEngine.UIElements
{
using UIR;
/// <summary>
/// Contains a part of the draw sequence of a VisualElement. You can use it in a job to add nested draw calls.
/// </summary>
[NativeContainer]
public struct MeshGenerationNode
{
UnsafeMeshGenerationNode m_UnsafeNode;
internal UnsafeMeshGenerationNode unsafeNode { get { return m_UnsafeNode; } }
AtomicSafetyHandle m_Safety;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void Create(GCHandle handle, AtomicSafetyHandle safety, out MeshGenerationNode node)
{
node = new MeshGenerationNode { m_Safety = safety };
UnsafeMeshGenerationNode.Create(handle, out node.m_UnsafeNode );
}
/// <summary>
/// Records a draw command with the provided triangle-list indexed mesh.
/// </summary>
/// <param name="vertices">The vertices to be drawn. All referenced vertices must be initialized.</param>
/// <param name="indices">The triangle list indices. Must be a multiple of 3. All indices must be initialized.</param>
/// <param name="texture">An optional texture to be applied on the triangles. Pass null to rely on vertex colors only.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void DrawMesh(NativeSlice<Vertex> vertices, NativeSlice<ushort> indices, Texture texture = null)
{
AtomicSafetyHandle.CheckWriteAndThrow(m_Safety);
m_UnsafeNode.DrawMesh(vertices, indices, texture);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Entry GetParentEntry() => m_UnsafeNode.GetParentEntry();
}
struct UnsafeMeshGenerationNode
{
GCHandle m_Handle;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
MeshGenerationNodeImpl GetManaged() => (MeshGenerationNodeImpl)m_Handle.Target;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void Create(GCHandle handle, out UnsafeMeshGenerationNode node)
{
node = new UnsafeMeshGenerationNode { m_Handle = handle };
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void DrawMesh(NativeSlice<Vertex> vertices, NativeSlice<ushort> indices, Texture texture = null)
{
GetManaged().DrawMesh(vertices, indices, texture);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void DrawMeshInternal(NativeSlice<Vertex> vertices, NativeSlice<ushort> indices, Texture texture = null, bool skipAtlas = false)
{
GetManaged().DrawMesh(vertices, indices, texture, skipAtlas);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void DrawGradientsInternal(NativeSlice<Vertex> vertices, NativeSlice<ushort> indices, VectorImage gradientsOwner)
{
GetManaged().DrawGradients(vertices, indices, gradientsOwner);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Entry GetParentEntry() => GetManaged().GetParentEntry();
}
class MeshGenerationNodeImpl : IDisposable
{
GCHandle m_SelfHandle;
Entry m_ParentEntry;
EntryRecorder m_EntryRecorder;
static int s_StaticSafetyId;
AtomicSafetyHandle m_Safety;
bool m_Safe;
static MeshGenerationNodeImpl()
{
if (s_StaticSafetyId == 0)
s_StaticSafetyId = AtomicSafetyHandle.NewStaticSafetyId<MeshGenerationNode>();
}
public MeshGenerationNodeImpl()
{
m_SelfHandle = GCHandle.Alloc(this);
}
// Must not be called from a job
public void Init(Entry parentEntry, EntryRecorder entryRecorder, bool safe)
{
Debug.Assert(m_ParentEntry == null);
Debug.Assert(parentEntry != null);
Debug.Assert(entryRecorder != null);
m_ParentEntry = parentEntry;
m_EntryRecorder = entryRecorder;
m_Safe = safe;
if (m_Safe)
{
m_Safety = AtomicSafetyHandle.Create();
AtomicSafetyHandle.SetStaticSafetyId(ref m_Safety, s_StaticSafetyId);
}
}
// Must not be called from a job
public void Reset()
{
Debug.Assert(m_ParentEntry != null);
Debug.Assert(m_EntryRecorder != null);
if (m_Safe)
{
AtomicSafetyHandle.CheckDeallocateAndThrow(m_Safety);
AtomicSafetyHandle.Release(m_Safety);
}
m_ParentEntry = null;
m_EntryRecorder = null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetNode(out MeshGenerationNode node)
{
MeshGenerationNode.Create(m_SelfHandle, m_Safety, out node);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetUnsafeNode(out UnsafeMeshGenerationNode node)
{
UnsafeMeshGenerationNode.Create(m_SelfHandle, out node);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Entry GetParentEntry() => m_ParentEntry;
public void DrawMesh(NativeSlice<Vertex> vertices, NativeSlice<ushort> indices, Texture texture = null, bool skipAtlas = false)
{
if (vertices.Length == 0 || indices.Length == 0)
return;
m_EntryRecorder.DrawMesh(m_ParentEntry, vertices, indices, texture, skipAtlas);
}
public void DrawGradients(NativeSlice<Vertex> vertices, NativeSlice<ushort> indices, VectorImage gradientsOwner)
{
if (vertices.Length == 0 || indices.Length == 0 || gradientsOwner == null)
return;
m_EntryRecorder.DrawGradients(m_ParentEntry, vertices, indices, gradientsOwner);
}
#region Dispose Pattern
protected bool disposed { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
if (m_ParentEntry != null)
Reset();
m_SelfHandle.Free();
}
else DisposeHelper.NotifyMissingDispose(this);
disposed = true;
}
#endregion // Dispose Pattern
}
class MeshGenerationNodeManager : IDisposable
{
List<MeshGenerationNodeImpl> m_Nodes = new(8);
int m_UsedCounter;
EntryRecorder m_EntryRecorder;
public MeshGenerationNodeManager(EntryRecorder entryRecorder)
{
m_EntryRecorder = entryRecorder;
}
public void CreateNode(Entry parentEntry, out MeshGenerationNode node)
{
MeshGenerationNodeImpl nodeImpl = CreateImpl(parentEntry, true);
nodeImpl.GetNode(out node);
}
public void CreateUnsafeNode(Entry parentEntry, out UnsafeMeshGenerationNode node)
{
MeshGenerationNodeImpl nodeImpl = CreateImpl(parentEntry, false);
nodeImpl.GetUnsafeNode(out node);
}
MeshGenerationNodeImpl CreateImpl(Entry parentEntry, bool safe)
{
if (disposed)
{
DisposeHelper.NotifyDisposedUsed(this);
return null;
}
if (m_Nodes.Count == m_UsedCounter)
{
for(int i = 0 ; i < 200 ; ++i)
m_Nodes.Add(new MeshGenerationNodeImpl());
}
var nodeImpl = m_Nodes[m_UsedCounter++];
nodeImpl.Init(parentEntry, m_EntryRecorder, safe);
return nodeImpl;
}
public void ResetAll()
{
for (int i = 0; i < m_UsedCounter; ++i)
m_Nodes[i].Reset();
m_UsedCounter = 0;
}
#region Dispose Pattern
protected bool disposed { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
for (int i = 0, count = m_Nodes.Count; i < count; ++i)
m_Nodes[i].Dispose();
m_Nodes.Clear();
}
else DisposeHelper.NotifyMissingDispose(this);
disposed = true;
}
#endregion // Dispose Pattern
}
}
| UnityCsReference/Modules/UIElements/Core/Renderer/UIRMeshGenerationNode.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRMeshGenerationNode.cs",
"repo_id": "UnityCsReference",
"token_count": 4046
} | 500 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Runtime.CompilerServices;
namespace UnityEngine.UIElements.UIR
{
class TextureSlotManager
{
static TextureSlotManager()
{
k_SlotCount = 8;
slotIds = new int[k_SlotCount];
for (int i = 0; i < k_SlotCount; ++i)
slotIds[i] = Shader.PropertyToID($"_Texture{i}");
}
internal static readonly int k_SlotCount;
internal static readonly int k_SlotSize = 2; // Number of float4 per slot
internal static readonly int[] slotIds;
internal static readonly int textureTableId = Shader.PropertyToID("_TextureInfo");
TextureId[] m_Textures;
int[] m_Tickets;
int m_CurrentTicket;
int m_FirstUsedTicket;
Vector4[] m_GpuTextures; // Contains IDs to be transferred to the GPU.
public TextureSlotManager()
{
m_Textures = new TextureId[k_SlotCount];
m_Tickets = new int[k_SlotCount];
m_GpuTextures = new Vector4[k_SlotCount * k_SlotSize];
Reset();
}
// This must be called before each frame starts rendering.
public void Reset()
{
m_CurrentTicket = 0;
m_FirstUsedTicket = 0;
for (int i = 0; i < k_SlotCount; ++i)
{
m_Textures[i] = TextureId.invalid;
m_Tickets[i] = -1;
SetGpuData(i, TextureId.invalid, 1, 1, 0, 0);
}
}
// Mark all textures slots as unused. Does not unbind any texture.
public void StartNewBatch()
{
m_FirstUsedTicket = ++m_CurrentTicket;
FreeSlots = k_SlotCount;
}
// Returns the slot to which the texture is currently bound to.
public int IndexOf(TextureId id)
{
for (int i = 0; i < k_SlotCount; ++i)
if (m_Textures[i].index == id.index)
return i;
return -1;
}
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public void MarkUsed(int slotIndex)
{
int oldTicket = m_Tickets[slotIndex];
if (oldTicket < m_FirstUsedTicket)
--FreeSlots;
m_Tickets[slotIndex] = ++m_CurrentTicket;
}
// Number of slots that are not required by the current batch.
public int FreeSlots { get; private set; } = k_SlotCount;
public int FindOldestSlot()
{
int ticket = m_Tickets[0];
int slot = 0;
for (int i = 1; i < k_SlotCount; ++i)
{
if (m_Tickets[i] < ticket)
{
ticket = m_Tickets[i];
slot = i;
}
}
return slot;
}
public void Bind(TextureId id, float sdfScale, float sharpness, int slot, MaterialPropertyBlock mat, CommandList commandList = null)
{
Texture tex = textureRegistry.GetTexture(id);
if (tex == null) // Case 1364578: Texture may have been destroyed
tex = Texture2D.whiteTexture;
m_Textures[slot] = id;
MarkUsed(slot);
SetGpuData(slot, id, tex.width, tex.height, sdfScale, sharpness);
if (commandList == null)
{
mat.SetTexture(slotIds[slot], tex);
mat.SetVectorArray(textureTableId, m_GpuTextures);
}
else
{
int offset = slot * k_SlotSize;
commandList.SetTexture(slotIds[slot], tex, offset, m_GpuTextures[offset], m_GpuTextures[offset+1]);
}
}
public void SetGpuData(int slotIndex, TextureId id, int textureWidth, int textureHeight, float sdfScale, float sharpness)
{
int offset = slotIndex * k_SlotSize;
float texelWidth = 1f / textureWidth;
float texelHeight = 1f / textureHeight;
m_GpuTextures[offset + 0] = new Vector4(id.ConvertToGpu(), texelWidth, texelHeight, sdfScale);
m_GpuTextures[offset + 1] = new Vector4(textureWidth, textureHeight, sharpness, 0);
}
// Overridable for tests
internal TextureRegistry textureRegistry = TextureRegistry.instance;
}
}
| UnityCsReference/Modules/UIElements/Core/Renderer/UIRTextureSlotManager.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRTextureSlotManager.cs",
"repo_id": "UnityCsReference",
"token_count": 2162
} | 501 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.UIElements.Experimental;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEngine.UIElements
{
internal struct ComputedTransitionProperty
{
public StylePropertyId id;
public int durationMs;
public int delayMs;
public Func<float, float> easingCurve;
}
internal static class ComputedTransitionUtils
{
internal static void UpdateComputedTransitions(ref ComputedStyle computedStyle)
{
if (computedStyle.computedTransitions == null)
{
computedStyle.computedTransitions = GetOrComputeTransitionPropertyData(ref computedStyle);
}
}
internal static bool HasTransitionProperty(ref this ComputedStyle computedStyle, StylePropertyId id)
{
for (var i = computedStyle.computedTransitions.Length - 1; i >= 0; i--)
{
var t = computedStyle.computedTransitions[i];
if (t.id == id || StylePropertyUtil.IsMatchingShorthand(t.id, id))
return true;
}
return false;
}
internal static bool GetTransitionProperty(ref this ComputedStyle computedStyle, StylePropertyId id, out ComputedTransitionProperty result)
{
// See https://www.w3.org/TR/css-transitions-1/#matching-transition-property-value:
// If a property is specified multiple times in the value of transition-property (either on its own, via a
// shorthand that contains it, or via the all value), then the transition that starts uses the duration,
// delay, and timing function at the index corresponding to the last item in the value of
// transition-property that calls for animating that property.
for (var i = computedStyle.computedTransitions.Length - 1; i >= 0; i--)
{
var t = computedStyle.computedTransitions[i];
if (t.id == id || StylePropertyUtil.IsMatchingShorthand(t.id, id))
{
result = t;
return true;
}
}
result = default;
return false;
}
private static List<ComputedTransitionProperty> s_ComputedTransitionsBuffer = new List<ComputedTransitionProperty>();
private static ComputedTransitionProperty[] GetOrComputeTransitionPropertyData(ref ComputedStyle computedStyle)
{
int hash = GetTransitionHashCode(ref computedStyle);
if (!StyleCache.TryGetValue(hash, out ComputedTransitionProperty[] computedTransitions))
{
ComputeTransitionPropertyData(ref computedStyle, s_ComputedTransitionsBuffer);
computedTransitions = new ComputedTransitionProperty[s_ComputedTransitionsBuffer.Count];
s_ComputedTransitionsBuffer.CopyTo(computedTransitions);
s_ComputedTransitionsBuffer.Clear();
StyleCache.SetValue(hash, computedTransitions);
}
return computedTransitions;
}
private static int GetTransitionHashCode(ref ComputedStyle cs)
{
unchecked
{
int hashCode = 0;
foreach (var x in cs.transitionDelay) hashCode = (hashCode * 397) ^ x.GetHashCode();
foreach (var x in cs.transitionDuration) hashCode = (hashCode * 397) ^ x.GetHashCode();
foreach (var x in cs.transitionProperty) hashCode = (hashCode * 397) ^ x.GetHashCode();
foreach (var x in cs.transitionTimingFunction) hashCode = (hashCode * 397) ^ x.GetHashCode();
return hashCode;
}
}
internal static bool SameTransitionProperty(ref ComputedStyle x, ref ComputedStyle y)
{
if (x.computedTransitions == y.computedTransitions && x.computedTransitions != null)
return true;
return SameTransitionProperty(x.transitionProperty, y.transitionProperty) &&
SameTransitionProperty(x.transitionDuration, y.transitionDuration) &&
SameTransitionProperty(x.transitionDelay, y.transitionDelay);
}
private static bool SameTransitionProperty(List<StylePropertyName> a, List<StylePropertyName> b)
{
if (a == b) return true;
if (a == null || b == null) return false;
if (a.Count != b.Count) return false;
int n = a.Count;
for (int i = 0; i < n; i++)
if (a[i] != b[i])
return false;
return true;
}
private static bool SameTransitionProperty(List<TimeValue> a, List<TimeValue> b)
{
if (a == b) return true;
if (a == null || b == null) return false;
if (a.Count != b.Count) return false;
int n = a.Count;
for (int i = 0; i < n; i++)
if (a[i] != b[i])
return false;
return true;
}
private static void ComputeTransitionPropertyData(ref ComputedStyle computedStyle, List<ComputedTransitionProperty> outData)
{
var properties = computedStyle.transitionProperty;
if (properties == null || properties.Count == 0)
return;
var durations = computedStyle.transitionDuration;
var delays = computedStyle.transitionDelay;
var timingFunctions = computedStyle.transitionTimingFunction;
// See https://developer.mozilla.org/en-US/docs/Web/CSS/transition-duration
// You may specify multiple durations; each duration will be applied to the corresponding property
// as specified by the transition-property property, which acts as a master list. If there are fewer
// durations specified than in the master list, the user agent repeat the list of durations. If there are
// more durations, the list is truncated to the right size. In both case the CSS declaration stays valid.
int nProperties = properties.Count;
for (var i = 0; i < nProperties; i++)
{
var id = properties[i].id;
// Remove properties that aren't animatable.
if (id == StylePropertyId.Unknown || !StylePropertyUtil.IsAnimatable(id))
continue;
// Remove properties with non-positive combined duration.
var durationMs = ConvertTransitionTime(GetWrappingTransitionData(durations, i, new TimeValue(0)));
var delayMs = ConvertTransitionTime(GetWrappingTransitionData(delays, i, new TimeValue(0)));
float combinedDuration = Mathf.Max(0, durationMs) + delayMs;
if (combinedDuration <= 0)
continue;
var easingFunction = GetWrappingTransitionData(timingFunctions, i, EasingMode.Ease);
outData.Add(new ComputedTransitionProperty
{
id = id,
durationMs = durationMs,
delayMs = delayMs,
easingCurve = ConvertTransitionFunction(easingFunction.mode)
});
}
}
static T GetWrappingTransitionData<T>(List<T> list, int i, T defaultValue)
{
return list.Count == 0 ? defaultValue : list[i % list.Count];
}
static int ConvertTransitionTime(TimeValue time)
{
return Mathf.RoundToInt(time.unit == TimeUnit.Millisecond ? time.value : time.value * 1000);
}
static Func<float, float> ConvertTransitionFunction(EasingMode mode)
{
// See https://www.w3schools.com/cssref/css3_pr_transition-timing-function.asp#:~:text=The%20transition%2Dtiming%2Dfunction%20property,change%20speed%20over%20its%20duration.
// Each of the easing function is equivalent to a cubic-bézier curve with some given P0..P3:
// (1-t)^3*P0 + 3*(1-t)^2*t*P1 + 3*(1-t)*t^2*P2 + t^3*P3
// Assuming P0=(0,0) and P3=(1,1), the 4 arguments are x1,y1,x2,y2, specifying P1 and P2.
// However, we won't implement these exact curves at the moment because they aren't simple t => f(t)
// methods (see https://github.com/gre/bezier-easing/blob/master/src/index.js for example).
// Instead, we will use slightly different curves that have a similar feel.
switch (mode)
{
default:
case EasingMode.Ease:
// "Best-fit" cubic curve trying to match start/end points and derivatives (stays within 0.079 of the exact curve).
// y = a t^3 + b t^2 + c t + d, where a = -0.2, b = -0.6, c = 1.8, d = 0
// Should be equivalent to cubic-bezier(0.25,0.1,0.25,1)
return t => t * (1.8f + t * (-0.6f + t * -0.2f));
case EasingMode.EaseIn:
// Should be equivalent to cubic-bezier(0.42,0,1,1)
return t => Easing.InQuad(t);
case EasingMode.EaseOut:
// Should be equivalent to cubic-bezier(0,0,0.58,1)
return t => Easing.OutQuad(t);
case EasingMode.EaseInOut:
// Should be equivalent to cubic-bezier(0.42,0,0.58,1)
return t => Easing.InOutQuad(t);
case EasingMode.Linear:
// Should be equivalent to cubic-bezier(0,0,1,1)
return t => Easing.Linear(t);
case EasingMode.EaseInSine:
return t => Easing.InSine(t);
case EasingMode.EaseOutSine:
return t => Easing.OutSine(t);
case EasingMode.EaseInOutSine:
return t => Easing.InOutSine(t);
case EasingMode.EaseInCubic:
return t => Easing.InCubic(t);
case EasingMode.EaseOutCubic:
return t => Easing.OutCubic(t);
case EasingMode.EaseInOutCubic:
return t => Easing.InOutCubic(t);
case EasingMode.EaseInCirc:
return t => Easing.InCirc(t);
case EasingMode.EaseOutCirc:
return t => Easing.OutCirc(t);
case EasingMode.EaseInOutCirc:
return t => Easing.InOutCirc(t);
case EasingMode.EaseInElastic:
return t => Easing.InElastic(t);
case EasingMode.EaseOutElastic:
return t => Easing.OutElastic(t);
case EasingMode.EaseInOutElastic:
return t => Easing.InOutElastic(t);
case EasingMode.EaseInBack:
return t => Easing.InBack(t);
case EasingMode.EaseOutBack:
return t => Easing.OutBack(t);
case EasingMode.EaseInOutBack:
return t => Easing.InOutBack(t);
case EasingMode.EaseInBounce:
return t => Easing.InBounce(t);
case EasingMode.EaseOutBounce:
return t => Easing.OutBounce(t);
case EasingMode.EaseInOutBounce:
return t => Easing.InOutBounce(t);
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/ComputedTransitions.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/ComputedTransitions.cs",
"repo_id": "UnityCsReference",
"token_count": 5556
} | 502 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
/******************************************************************************/
//
// DO NOT MODIFY
// This file has been generated by the UIElementsGenerator tool
// See StyleGroupStructsCsGenerator class for details
//
/******************************************************************************/
using System;
using System.Collections.Generic;
namespace UnityEngine.UIElements
{
internal interface IStyleDataGroup<T>
{
T Copy();
void CopyFrom(ref T other);
}
internal struct InheritedData : IStyleDataGroup<InheritedData>, IEquatable<InheritedData>
{
public Color color;
public Length fontSize;
public Length letterSpacing;
public TextShadow textShadow;
public Font unityFont;
public FontDefinition unityFontDefinition;
public FontStyle unityFontStyleAndWeight;
public Length unityParagraphSpacing;
public TextAnchor unityTextAlign;
public TextGeneratorType unityTextGenerator;
public Color unityTextOutlineColor;
public float unityTextOutlineWidth;
public Visibility visibility;
public WhiteSpace whiteSpace;
public Length wordSpacing;
public InheritedData Copy()
{
return this;
}
public void CopyFrom(ref InheritedData other)
{
this = other;
}
public static bool operator ==(InheritedData lhs, InheritedData rhs)
{
return lhs.color == rhs.color &&
lhs.fontSize == rhs.fontSize &&
lhs.letterSpacing == rhs.letterSpacing &&
lhs.textShadow == rhs.textShadow &&
lhs.unityFont == rhs.unityFont &&
lhs.unityFontDefinition == rhs.unityFontDefinition &&
lhs.unityFontStyleAndWeight == rhs.unityFontStyleAndWeight &&
lhs.unityParagraphSpacing == rhs.unityParagraphSpacing &&
lhs.unityTextAlign == rhs.unityTextAlign &&
lhs.unityTextGenerator == rhs.unityTextGenerator &&
lhs.unityTextOutlineColor == rhs.unityTextOutlineColor &&
lhs.unityTextOutlineWidth == rhs.unityTextOutlineWidth &&
lhs.visibility == rhs.visibility &&
lhs.whiteSpace == rhs.whiteSpace &&
lhs.wordSpacing == rhs.wordSpacing;
}
public static bool operator !=(InheritedData lhs, InheritedData rhs)
{
return !(lhs == rhs);
}
public bool Equals(InheritedData other)
{
return other == this;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is InheritedData &&
Equals((InheritedData)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = color.GetHashCode();
hashCode = (hashCode * 397) ^ fontSize.GetHashCode();
hashCode = (hashCode * 397) ^ letterSpacing.GetHashCode();
hashCode = (hashCode * 397) ^ textShadow.GetHashCode();
hashCode = (hashCode * 397) ^ (unityFont == null ? 0 : unityFont.GetHashCode());
hashCode = (hashCode * 397) ^ unityFontDefinition.GetHashCode();
hashCode = (hashCode * 397) ^ (int)unityFontStyleAndWeight;
hashCode = (hashCode * 397) ^ unityParagraphSpacing.GetHashCode();
hashCode = (hashCode * 397) ^ (int)unityTextAlign;
hashCode = (hashCode * 397) ^ (int)unityTextGenerator;
hashCode = (hashCode * 397) ^ unityTextOutlineColor.GetHashCode();
hashCode = (hashCode * 397) ^ unityTextOutlineWidth.GetHashCode();
hashCode = (hashCode * 397) ^ (int)visibility;
hashCode = (hashCode * 397) ^ (int)whiteSpace;
hashCode = (hashCode * 397) ^ wordSpacing.GetHashCode();
return hashCode;
}
}
}
internal struct LayoutData : IStyleDataGroup<LayoutData>, IEquatable<LayoutData>
{
public Align alignContent;
public Align alignItems;
public Align alignSelf;
public float borderBottomWidth;
public float borderLeftWidth;
public float borderRightWidth;
public float borderTopWidth;
public Length bottom;
public DisplayStyle display;
public Length flexBasis;
public FlexDirection flexDirection;
public float flexGrow;
public float flexShrink;
public Wrap flexWrap;
public Length height;
public Justify justifyContent;
public Length left;
public Length marginBottom;
public Length marginLeft;
public Length marginRight;
public Length marginTop;
public Length maxHeight;
public Length maxWidth;
public Length minHeight;
public Length minWidth;
public Length paddingBottom;
public Length paddingLeft;
public Length paddingRight;
public Length paddingTop;
public Position position;
public Length right;
public Length top;
public Length width;
public LayoutData Copy()
{
return this;
}
public void CopyFrom(ref LayoutData other)
{
this = other;
}
public static bool operator ==(LayoutData lhs, LayoutData rhs)
{
return lhs.alignContent == rhs.alignContent &&
lhs.alignItems == rhs.alignItems &&
lhs.alignSelf == rhs.alignSelf &&
lhs.borderBottomWidth == rhs.borderBottomWidth &&
lhs.borderLeftWidth == rhs.borderLeftWidth &&
lhs.borderRightWidth == rhs.borderRightWidth &&
lhs.borderTopWidth == rhs.borderTopWidth &&
lhs.bottom == rhs.bottom &&
lhs.display == rhs.display &&
lhs.flexBasis == rhs.flexBasis &&
lhs.flexDirection == rhs.flexDirection &&
lhs.flexGrow == rhs.flexGrow &&
lhs.flexShrink == rhs.flexShrink &&
lhs.flexWrap == rhs.flexWrap &&
lhs.height == rhs.height &&
lhs.justifyContent == rhs.justifyContent &&
lhs.left == rhs.left &&
lhs.marginBottom == rhs.marginBottom &&
lhs.marginLeft == rhs.marginLeft &&
lhs.marginRight == rhs.marginRight &&
lhs.marginTop == rhs.marginTop &&
lhs.maxHeight == rhs.maxHeight &&
lhs.maxWidth == rhs.maxWidth &&
lhs.minHeight == rhs.minHeight &&
lhs.minWidth == rhs.minWidth &&
lhs.paddingBottom == rhs.paddingBottom &&
lhs.paddingLeft == rhs.paddingLeft &&
lhs.paddingRight == rhs.paddingRight &&
lhs.paddingTop == rhs.paddingTop &&
lhs.position == rhs.position &&
lhs.right == rhs.right &&
lhs.top == rhs.top &&
lhs.width == rhs.width;
}
public static bool operator !=(LayoutData lhs, LayoutData rhs)
{
return !(lhs == rhs);
}
public bool Equals(LayoutData other)
{
return other == this;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is LayoutData &&
Equals((LayoutData)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (int)alignContent;
hashCode = (hashCode * 397) ^ (int)alignItems;
hashCode = (hashCode * 397) ^ (int)alignSelf;
hashCode = (hashCode * 397) ^ borderBottomWidth.GetHashCode();
hashCode = (hashCode * 397) ^ borderLeftWidth.GetHashCode();
hashCode = (hashCode * 397) ^ borderRightWidth.GetHashCode();
hashCode = (hashCode * 397) ^ borderTopWidth.GetHashCode();
hashCode = (hashCode * 397) ^ bottom.GetHashCode();
hashCode = (hashCode * 397) ^ (int)display;
hashCode = (hashCode * 397) ^ flexBasis.GetHashCode();
hashCode = (hashCode * 397) ^ (int)flexDirection;
hashCode = (hashCode * 397) ^ flexGrow.GetHashCode();
hashCode = (hashCode * 397) ^ flexShrink.GetHashCode();
hashCode = (hashCode * 397) ^ (int)flexWrap;
hashCode = (hashCode * 397) ^ height.GetHashCode();
hashCode = (hashCode * 397) ^ (int)justifyContent;
hashCode = (hashCode * 397) ^ left.GetHashCode();
hashCode = (hashCode * 397) ^ marginBottom.GetHashCode();
hashCode = (hashCode * 397) ^ marginLeft.GetHashCode();
hashCode = (hashCode * 397) ^ marginRight.GetHashCode();
hashCode = (hashCode * 397) ^ marginTop.GetHashCode();
hashCode = (hashCode * 397) ^ maxHeight.GetHashCode();
hashCode = (hashCode * 397) ^ maxWidth.GetHashCode();
hashCode = (hashCode * 397) ^ minHeight.GetHashCode();
hashCode = (hashCode * 397) ^ minWidth.GetHashCode();
hashCode = (hashCode * 397) ^ paddingBottom.GetHashCode();
hashCode = (hashCode * 397) ^ paddingLeft.GetHashCode();
hashCode = (hashCode * 397) ^ paddingRight.GetHashCode();
hashCode = (hashCode * 397) ^ paddingTop.GetHashCode();
hashCode = (hashCode * 397) ^ (int)position;
hashCode = (hashCode * 397) ^ right.GetHashCode();
hashCode = (hashCode * 397) ^ top.GetHashCode();
hashCode = (hashCode * 397) ^ width.GetHashCode();
return hashCode;
}
}
}
internal struct RareData : IStyleDataGroup<RareData>, IEquatable<RareData>
{
public Cursor cursor;
public TextOverflow textOverflow;
public Color unityBackgroundImageTintColor;
public OverflowClipBox unityOverflowClipBox;
public int unitySliceBottom;
public int unitySliceLeft;
public int unitySliceRight;
public float unitySliceScale;
public int unitySliceTop;
public TextOverflowPosition unityTextOverflowPosition;
public RareData Copy()
{
return this;
}
public void CopyFrom(ref RareData other)
{
this = other;
}
public static bool operator ==(RareData lhs, RareData rhs)
{
return lhs.cursor == rhs.cursor &&
lhs.textOverflow == rhs.textOverflow &&
lhs.unityBackgroundImageTintColor == rhs.unityBackgroundImageTintColor &&
lhs.unityOverflowClipBox == rhs.unityOverflowClipBox &&
lhs.unitySliceBottom == rhs.unitySliceBottom &&
lhs.unitySliceLeft == rhs.unitySliceLeft &&
lhs.unitySliceRight == rhs.unitySliceRight &&
lhs.unitySliceScale == rhs.unitySliceScale &&
lhs.unitySliceTop == rhs.unitySliceTop &&
lhs.unityTextOverflowPosition == rhs.unityTextOverflowPosition;
}
public static bool operator !=(RareData lhs, RareData rhs)
{
return !(lhs == rhs);
}
public bool Equals(RareData other)
{
return other == this;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is RareData &&
Equals((RareData)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = cursor.GetHashCode();
hashCode = (hashCode * 397) ^ (int)textOverflow;
hashCode = (hashCode * 397) ^ unityBackgroundImageTintColor.GetHashCode();
hashCode = (hashCode * 397) ^ (int)unityOverflowClipBox;
hashCode = (hashCode * 397) ^ unitySliceBottom;
hashCode = (hashCode * 397) ^ unitySliceLeft;
hashCode = (hashCode * 397) ^ unitySliceRight;
hashCode = (hashCode * 397) ^ unitySliceScale.GetHashCode();
hashCode = (hashCode * 397) ^ unitySliceTop;
hashCode = (hashCode * 397) ^ (int)unityTextOverflowPosition;
return hashCode;
}
}
}
internal struct TransformData : IStyleDataGroup<TransformData>, IEquatable<TransformData>
{
public Rotate rotate;
public Scale scale;
public TransformOrigin transformOrigin;
public Translate translate;
public TransformData Copy()
{
return this;
}
public void CopyFrom(ref TransformData other)
{
this = other;
}
public static bool operator ==(TransformData lhs, TransformData rhs)
{
return lhs.rotate == rhs.rotate &&
lhs.scale == rhs.scale &&
lhs.transformOrigin == rhs.transformOrigin &&
lhs.translate == rhs.translate;
}
public static bool operator !=(TransformData lhs, TransformData rhs)
{
return !(lhs == rhs);
}
public bool Equals(TransformData other)
{
return other == this;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is TransformData &&
Equals((TransformData)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = rotate.GetHashCode();
hashCode = (hashCode * 397) ^ scale.GetHashCode();
hashCode = (hashCode * 397) ^ transformOrigin.GetHashCode();
hashCode = (hashCode * 397) ^ translate.GetHashCode();
return hashCode;
}
}
}
[UnityEngine.Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal struct TransitionData : IStyleDataGroup<TransitionData>, IEquatable<TransitionData>
{
public List<TimeValue> transitionDelay;
public List<TimeValue> transitionDuration;
public List<StylePropertyName> transitionProperty;
public List<EasingFunction> transitionTimingFunction;
public TransitionData Copy()
{
var data = new TransitionData();
data.transitionDelay = new List<TimeValue>(transitionDelay);
data.transitionDuration = new List<TimeValue>(transitionDuration);
data.transitionProperty = new List<StylePropertyName>(transitionProperty);
data.transitionTimingFunction = new List<EasingFunction>(transitionTimingFunction);
return data;
}
public void CopyFrom(ref TransitionData other)
{
if (!ReferenceEquals(transitionDelay, other.transitionDelay))
{
transitionDelay.Clear();
transitionDelay.AddRange(other.transitionDelay);
}
if (!ReferenceEquals(transitionDuration, other.transitionDuration))
{
transitionDuration.Clear();
transitionDuration.AddRange(other.transitionDuration);
}
if (!ReferenceEquals(transitionProperty, other.transitionProperty))
{
transitionProperty.Clear();
transitionProperty.AddRange(other.transitionProperty);
}
if (!ReferenceEquals(transitionTimingFunction, other.transitionTimingFunction))
{
transitionTimingFunction.Clear();
transitionTimingFunction.AddRange(other.transitionTimingFunction);
}
}
public static bool operator ==(TransitionData lhs, TransitionData rhs)
{
return lhs.transitionDelay == rhs.transitionDelay &&
lhs.transitionDuration == rhs.transitionDuration &&
lhs.transitionProperty == rhs.transitionProperty &&
lhs.transitionTimingFunction == rhs.transitionTimingFunction;
}
public static bool operator !=(TransitionData lhs, TransitionData rhs)
{
return !(lhs == rhs);
}
public bool Equals(TransitionData other)
{
return other == this;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is TransitionData &&
Equals((TransitionData)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = transitionDelay.GetHashCode();
hashCode = (hashCode * 397) ^ transitionDuration.GetHashCode();
hashCode = (hashCode * 397) ^ transitionProperty.GetHashCode();
hashCode = (hashCode * 397) ^ transitionTimingFunction.GetHashCode();
return hashCode;
}
}
}
internal struct VisualData : IStyleDataGroup<VisualData>, IEquatable<VisualData>
{
public Color backgroundColor;
public Background backgroundImage;
public BackgroundPosition backgroundPositionX;
public BackgroundPosition backgroundPositionY;
public BackgroundRepeat backgroundRepeat;
public BackgroundSize backgroundSize;
public Color borderBottomColor;
public Length borderBottomLeftRadius;
public Length borderBottomRightRadius;
public Color borderLeftColor;
public Color borderRightColor;
public Color borderTopColor;
public Length borderTopLeftRadius;
public Length borderTopRightRadius;
public float opacity;
public OverflowInternal overflow;
public VisualData Copy()
{
return this;
}
public void CopyFrom(ref VisualData other)
{
this = other;
}
public static bool operator ==(VisualData lhs, VisualData rhs)
{
return lhs.backgroundColor == rhs.backgroundColor &&
lhs.backgroundImage == rhs.backgroundImage &&
lhs.backgroundPositionX == rhs.backgroundPositionX &&
lhs.backgroundPositionY == rhs.backgroundPositionY &&
lhs.backgroundRepeat == rhs.backgroundRepeat &&
lhs.backgroundSize == rhs.backgroundSize &&
lhs.borderBottomColor == rhs.borderBottomColor &&
lhs.borderBottomLeftRadius == rhs.borderBottomLeftRadius &&
lhs.borderBottomRightRadius == rhs.borderBottomRightRadius &&
lhs.borderLeftColor == rhs.borderLeftColor &&
lhs.borderRightColor == rhs.borderRightColor &&
lhs.borderTopColor == rhs.borderTopColor &&
lhs.borderTopLeftRadius == rhs.borderTopLeftRadius &&
lhs.borderTopRightRadius == rhs.borderTopRightRadius &&
lhs.opacity == rhs.opacity &&
lhs.overflow == rhs.overflow;
}
public static bool operator !=(VisualData lhs, VisualData rhs)
{
return !(lhs == rhs);
}
public bool Equals(VisualData other)
{
return other == this;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is VisualData &&
Equals((VisualData)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = backgroundColor.GetHashCode();
hashCode = (hashCode * 397) ^ backgroundImage.GetHashCode();
hashCode = (hashCode * 397) ^ backgroundPositionX.GetHashCode();
hashCode = (hashCode * 397) ^ backgroundPositionY.GetHashCode();
hashCode = (hashCode * 397) ^ backgroundRepeat.GetHashCode();
hashCode = (hashCode * 397) ^ backgroundSize.GetHashCode();
hashCode = (hashCode * 397) ^ borderBottomColor.GetHashCode();
hashCode = (hashCode * 397) ^ borderBottomLeftRadius.GetHashCode();
hashCode = (hashCode * 397) ^ borderBottomRightRadius.GetHashCode();
hashCode = (hashCode * 397) ^ borderLeftColor.GetHashCode();
hashCode = (hashCode * 397) ^ borderRightColor.GetHashCode();
hashCode = (hashCode * 397) ^ borderTopColor.GetHashCode();
hashCode = (hashCode * 397) ^ borderTopLeftRadius.GetHashCode();
hashCode = (hashCode * 397) ^ borderTopRightRadius.GetHashCode();
hashCode = (hashCode * 397) ^ opacity.GetHashCode();
hashCode = (hashCode * 397) ^ (int)overflow;
return hashCode;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/Generated/StyleDataStructs.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/Generated/StyleDataStructs.cs",
"repo_id": "UnityCsReference",
"token_count": 10197
} | 503 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Properties;
namespace UnityEngine.UIElements
{
public partial struct Scale
{
internal class PropertyBag : ContainerPropertyBag<Scale>
{
class ValueProperty : Property<Scale, Vector3>
{
public override string Name { get; } = nameof(value);
public override bool IsReadOnly { get; } = false;
public override Vector3 GetValue(ref Scale container) => container.value;
public override void SetValue(ref Scale container, Vector3 value) => container.value = value;
}
public PropertyBag()
{
AddProperty(new ValueProperty());
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/Scale.PropertyBag.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/Scale.PropertyBag.cs",
"repo_id": "UnityCsReference",
"token_count": 366
} | 504 |
// 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 UnityEngine.UIElements
{
/// <summary>
/// Style value that can be either a list or a <see cref="StyleKeyword"/>.
/// </summary>
/// <typeparam name="T">List type.</typeparam>
public struct StyleList<T> : IStyleValue<List<T>>, IEquatable<StyleList<T>>
{
/// <summary>
/// The style value.
/// </summary>
public List<T> value
{
get { return m_Keyword == StyleKeyword.Undefined ? m_Value : default; }
set
{
m_Value = value;
m_Keyword = StyleKeyword.Undefined;
}
}
/// <summary>
/// The style keyword.
/// </summary>
public StyleKeyword keyword
{
get { return m_Keyword; }
set { m_Keyword = value; }
}
/// <summary>
/// Creates from either a list or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleList(List<T> v)
: this(v, StyleKeyword.Undefined)
{}
/// <summary>
/// Creates from either a list or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleList(StyleKeyword keyword)
: this(default, keyword)
{}
internal StyleList(List<T> v, StyleKeyword keyword)
{
m_Keyword = keyword;
m_Value = v;
}
private StyleKeyword m_Keyword;
private List<T> m_Value;
/// <undoc/>
public static bool operator==(StyleList<T> lhs, StyleList<T> rhs)
{
if (lhs.m_Keyword != rhs.m_Keyword)
return false;
var list1 = lhs.m_Value;
var list2 = rhs.m_Value;
if (ReferenceEquals(list1, list2))
return true;
if (list1 == null || list2 == null)
return false;
return list1.Count == list2.Count && list1.SequenceEqual(list2);
}
/// <undoc/>
public static bool operator!=(StyleList<T> lhs, StyleList<T> rhs)
{
return !(lhs == rhs);
}
/// <undoc/>
public static implicit operator StyleList<T>(StyleKeyword keyword)
{
return new StyleList<T>(keyword);
}
/// <undoc/>
public static implicit operator StyleList<T>(List<T> v)
{
return new StyleList<T>(v);
}
/// <undoc/>
public bool Equals(StyleList<T> other)
{
return other == this;
}
/// <undoc/>
public override bool Equals(object obj)
{
return obj is StyleList<T> other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = 0;
if (m_Value != null && m_Value.Count > 0)
{
hashCode = EqualityComparer<T>.Default.GetHashCode(m_Value[0]);
for (int i = 1; i < m_Value.Count; i++)
{
hashCode = (hashCode * 397) ^ EqualityComparer<T>.Default.GetHashCode(m_Value[i]);
}
}
hashCode = (hashCode * 397) ^ (int)m_Keyword;
return hashCode;
}
}
public override string ToString()
{
return this.DebugString();
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/StyleList.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/StyleList.cs",
"repo_id": "UnityCsReference",
"token_count": 1881
} | 505 |
// 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.Assertions;
using UnityEngine.UIElements.Experimental;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEngine.UIElements
{
internal interface IStylePropertyAnimations
{
bool Start(StylePropertyId id, float from, float to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, int from, int to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, Length from, Length to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, Color from, Color to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool StartEnum(StylePropertyId id, int from, int to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, Background from, Background to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, FontDefinition from, FontDefinition to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, Font from, Font to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, TextShadow from, TextShadow to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, Scale from, Scale to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, Translate from, Translate to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, Rotate from, Rotate to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, TransformOrigin from, TransformOrigin to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, BackgroundPosition from, BackgroundPosition to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, BackgroundRepeat from, BackgroundRepeat to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool Start(StylePropertyId id, BackgroundSize from, BackgroundSize to, int durationMs, int delayMs, Func<float, float> easingCurve);
bool HasRunningAnimation(StylePropertyId id);
void UpdateAnimation(StylePropertyId id);
void GetAllAnimations(List<StylePropertyId> outPropertyIds);
void CancelAnimation(StylePropertyId id);
void CancelAllAnimations();
int runningAnimationCount { get; set; }
int completedAnimationCount { get; set; }
}
public partial class VisualElement : IStylePropertyAnimations
{
internal bool hasRunningAnimations => styleAnimation.runningAnimationCount > 0;
internal bool hasCompletedAnimations => styleAnimation.completedAnimationCount > 0;
int IStylePropertyAnimations.runningAnimationCount { get; set; }
int IStylePropertyAnimations.completedAnimationCount { get; set; }
private IStylePropertyAnimationSystem GetStylePropertyAnimationSystem()
{
return elementPanel?.styleAnimationSystem;
}
internal IStylePropertyAnimations styleAnimation => this;
bool IStylePropertyAnimations.Start(StylePropertyId id, float from, float to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, int from, int to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, Length from, Length to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, Color from, Color to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.StartEnum(StylePropertyId id, int from, int to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, Background from, Background to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, FontDefinition from, FontDefinition to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, Font from, Font to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, TextShadow from, TextShadow to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, Scale from, Scale to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, Translate from, Translate to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, Rotate from, Rotate to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, TransformOrigin from, TransformOrigin to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, BackgroundPosition from, BackgroundPosition to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, BackgroundRepeat from, BackgroundRepeat to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
bool IStylePropertyAnimations.Start(StylePropertyId id, BackgroundSize from, BackgroundSize to, int durationMs, int delayMs, Func<float, float> easingCurve)
{
return GetStylePropertyAnimationSystem().StartTransition(this, id, from, to, durationMs, delayMs, easingCurve);
}
void IStylePropertyAnimations.CancelAnimation(StylePropertyId id)
{
GetStylePropertyAnimationSystem()?.CancelAnimation(this, id);
}
void IStylePropertyAnimations.CancelAllAnimations()
{
if (hasRunningAnimations || hasCompletedAnimations)
GetStylePropertyAnimationSystem()?.CancelAllAnimations(this);
}
bool IStylePropertyAnimations.HasRunningAnimation(StylePropertyId id)
{
return hasRunningAnimations && GetStylePropertyAnimationSystem().HasRunningAnimation(this, id);
}
void IStylePropertyAnimations.UpdateAnimation(StylePropertyId id)
{
GetStylePropertyAnimationSystem().UpdateAnimation(this, id);
}
void IStylePropertyAnimations.GetAllAnimations(List<StylePropertyId> outPropertyIds)
{
if (hasRunningAnimations || hasCompletedAnimations)
GetStylePropertyAnimationSystem().GetAllAnimations(this, outPropertyIds);
}
internal bool TryConvertLengthUnits(StylePropertyId id, ref Length from, ref Length to, int subPropertyIndex = 0)
{
if (from.IsAuto() || from.IsNone() || to.IsAuto() || to.IsNone())
return false;
if (float.IsNaN(from.value) || float.IsNaN(to.value))
return false;
if (from.unit == to.unit)
return true;
// At the moment, LengthUnit only accepts Pixel and Percent. A slightly more complicated conversion might
// be needed when we have multiple units to account for, e.g. from -> px -> to.
if (to.unit == LengthUnit.Pixel)
{
if (Mathf.Approximately(from.value, 0))
{
from = new Length(0, LengthUnit.Pixel);
return true;
}
var parentSize = GetParentSizeForLengthConversion(id, subPropertyIndex);
if (parentSize == null || !(parentSize.Value >= 0)) // Reject NaN and negative values
return false;
from = new Length(from.value * parentSize.Value / 100, LengthUnit.Pixel);
}
else
{
// When more units are supported, this Assert will make sure we remember to implement them here.
Assert.AreEqual(LengthUnit.Percent, to.unit);
var parentSize = GetParentSizeForLengthConversion(id, subPropertyIndex);
if (parentSize == null || !(parentSize.Value > 0)) // Reject NaN, zero, and negative values
return false;
from = new Length(from.value * 100 / parentSize.Value, LengthUnit.Percent);
}
return true;
}
// Changes the from TransformOrigin so that it apply the same result as before, but with the unit of the "to" value
// return false if not possible
internal bool TryConvertTransformOriginUnits(ref TransformOrigin from, ref TransformOrigin to)
{
Length fromX = from.x, fromY = from.y, toX = to.x, toY = to.y;
if (!TryConvertLengthUnits(StylePropertyId.TransformOrigin, ref fromX, ref toX, 0))
return false;
if (!TryConvertLengthUnits(StylePropertyId.TransformOrigin, ref fromY, ref toY, 1))
return false;
from.x = fromX;
from.y = fromY;
return true;
}
// Changes the from Translate so that it apply the same result as before, but with the unit of the "to"
// return false if not possible
internal bool TryConvertTranslateUnits(ref Translate from, ref Translate to)
{
Length fromX = from.x, fromY = from.y, toX = to.x, toY = to.y;
if (!TryConvertLengthUnits(StylePropertyId.Translate, ref fromX, ref toX, 0))
return false;
if (!TryConvertLengthUnits(StylePropertyId.Translate, ref fromY, ref toY, 1))
return false;
from.x = fromX;
from.y = fromY;
return true;
}
// Changes the from BackgroundPosition so that it apply the same result as before, but with the unit of the "to"
// return false if not possible
internal bool TryConvertBackgroundPositionUnits(ref BackgroundPosition from, ref BackgroundPosition to)
{
Length fromX = from.offset, toX = to.offset;
if (!TryConvertLengthUnits(StylePropertyId.BackgroundPosition, ref fromX, ref toX, 0))
return false;
from.offset = fromX;
return true;
}
// Changes the from BackgroundSize so that it apply the same result as before, but with the unit of the "to" value
// return false if not possible
internal bool TryConvertBackgroundSizeUnits(ref BackgroundSize from, ref BackgroundSize to)
{
Length fromX = from.x, fromY = from.y, toX = to.x, toY = to.y;
if (!TryConvertLengthUnits(StylePropertyId.BackgroundSize, ref fromX, ref toX, 0))
return false;
if (!TryConvertLengthUnits(StylePropertyId.BackgroundSize, ref fromY, ref toY, 1))
return false;
from.x = fromX;
from.y = fromY;
return true;
}
private float? GetParentSizeForLengthConversion(StylePropertyId id, int subPropertyIndex = 0)
{
switch (id)
{
case StylePropertyId.Bottom:
case StylePropertyId.Top:
case StylePropertyId.Height:
case StylePropertyId.MaxHeight:
case StylePropertyId.MinHeight:
return hierarchy.parent?.resolvedStyle.height;
case StylePropertyId.Left:
case StylePropertyId.Right:
case StylePropertyId.Width:
case StylePropertyId.MaxWidth:
case StylePropertyId.MinWidth:
case StylePropertyId.MarginBottom:
case StylePropertyId.MarginTop:
case StylePropertyId.MarginLeft:
case StylePropertyId.MarginRight:
case StylePropertyId.PaddingBottom: //The size of the padding as a percentage, relative to the width of the containing block. Must be nonnegative.
case StylePropertyId.PaddingTop:
case StylePropertyId.PaddingLeft:
case StylePropertyId.PaddingRight:
return hierarchy.parent?.resolvedStyle.width;
case StylePropertyId.FlexBasis:
if (hierarchy.parent == null) return null;
switch (hierarchy.parent.resolvedStyle.flexDirection)
{
case FlexDirection.Column: case FlexDirection.ColumnReverse:
return hierarchy.parent.resolvedStyle.height;
default:
return hierarchy.parent.resolvedStyle.width;
}
case StylePropertyId.BorderBottomLeftRadius: //Refer to the corresponding dimension of the border box
case StylePropertyId.BorderBottomRightRadius:
case StylePropertyId.BorderTopLeftRadius:
case StylePropertyId.BorderTopRightRadius:
// Technically a border-radius is made of 2 values (Vector2) but currently we only support one value in the style
return resolvedStyle.width;
case StylePropertyId.FontSize: //Specifies extra spacing as a percentage of the affected character’s advance width.
case StylePropertyId.LetterSpacing: //No percentage values
case StylePropertyId.UnityParagraphSpacing: //No CSS equivalent
case StylePropertyId.WordSpacing: //Specifies extra spacing as a percentage of the affected character’s advance width.
return null;
case StylePropertyId.Translate:
case StylePropertyId.TransformOrigin:
return subPropertyIndex == 0 ? resolvedStyle.width : resolvedStyle.height;
}
return null;
}
}
}
| UnityCsReference/Modules/UIElements/Core/StylePropertyAnimation.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/StylePropertyAnimation.cs",
"repo_id": "UnityCsReference",
"token_count": 6583
} | 506 |
// 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.UIElements
{
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal enum StyleSelectorType
{
Unknown,
Wildcard,
Type,
Class,
PseudoClass,
RecursivePseudoClass,
ID,
Predicate
}
}
| UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleSelectorType.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleSelectorType.cs",
"repo_id": "UnityCsReference",
"token_count": 197
} | 507 |
// 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.UIElements
{
/// <summary>
/// Represents a style sheet that's assembled from other style sheets.
/// </summary>
[HelpURL("UIE-tss")]
[Serializable]
public class ThemeStyleSheet : StyleSheet
{
internal override void OnEnable()
{
isDefaultStyleSheet = true;
base.OnEnable();
}
}
}
| UnityCsReference/Modules/UIElements/Core/StyleSheets/ThemeStyleSheet.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/ThemeStyleSheet.cs",
"repo_id": "UnityCsReference",
"token_count": 213
} | 508 |
// 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 UnityEngine.UIElements
{
/// <summary>
/// Script interface for <see cref="VisualElement"/> text-shadow style property <see cref="IStyle.textShadow"/>.
/// </summary>
public partial struct TextShadow : IEquatable<TextShadow>
{
/// <summary>
/// The offset of the shadow.
/// </summary>
public Vector2 offset;
/// <summary>
/// The blur radius of the shadow.
/// </summary>
public float blurRadius;
/// <summary>
/// The color of the shadow.
/// </summary>
public Color color;
public override bool Equals(object obj)
{
return obj is TextShadow && Equals((TextShadow)obj);
}
/// <undoc/>
public bool Equals(TextShadow other)
{
return other.offset == offset && other.blurRadius == blurRadius && other.color == color;
}
public override int GetHashCode()
{
var hashCode = 1500536833;
hashCode = hashCode * -1521134295 + offset.GetHashCode();
hashCode = hashCode * -1521134295 + blurRadius.GetHashCode();
hashCode = hashCode * -1521134295 + color.GetHashCode();
return hashCode;
}
/// <undoc/>
public static bool operator==(TextShadow style1, TextShadow style2)
{
return style1.Equals(style2);
}
/// <undoc/>
public static bool operator!=(TextShadow style1, TextShadow style2)
{
return !(style1 == style2);
}
public override string ToString()
{
return $"offset={offset}, blurRadius={blurRadius}, color={color}";
}
internal static TextShadow LerpUnclamped(TextShadow a, TextShadow b, float t)
{
return new TextShadow
{
offset = Vector2.LerpUnclamped(a.offset, b.offset, t),
blurRadius = Mathf.LerpUnclamped(a.blurRadius, b.blurRadius, t),
color = Color.LerpUnclamped(a.color, b.color, t)
};
}
}
}
| UnityCsReference/Modules/UIElements/Core/TextShadow.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/TextShadow.cs",
"repo_id": "UnityCsReference",
"token_count": 1037
} | 509 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEngine.Pool;
using UnityEngine.Serialization;
namespace UnityEngine.UIElements
{
internal readonly struct UxmlDescription
{
public readonly string uxmlName;
public readonly string cSharpName;
public readonly FieldInfo serializedField;
public readonly FieldInfo serializedFieldAttributeFlags;
public readonly Type fieldType;
public readonly string[] obsoleteNames;
public UxmlDescription(string uxmlName, string cSharpName, FieldInfo serializedField, string[] obsoleteNames = null)
{
this.uxmlName = uxmlName;
this.cSharpName = cSharpName;
this.serializedField = serializedField;
serializedFieldAttributeFlags = serializedField.DeclaringType.GetField(serializedField.Name + UxmlSerializedData.AttributeFlagSuffix, BindingFlags.Instance | BindingFlags.NonPublic);
// Type are not serializable. They are serialized as string with a UxmlTypeReferenceAttribute.
fieldType = serializedField.GetCustomAttribute<UxmlTypeReferenceAttribute>() != null ? typeof(Type) : serializedField.FieldType;
this.obsoleteNames = obsoleteNames;
}
}
internal readonly struct UxmlTypeDescription
{
public readonly Type type;
public readonly List<UxmlDescription> attributeDescriptions;
public readonly Dictionary<string, int> uxmlNameToIndex;
public readonly Dictionary<string, int> cSharpNameToIndex;
public UxmlTypeDescription(Type type)
{
if (!typeof(UxmlSerializedData).IsAssignableFrom(type))
throw new ArgumentException();
this.type = type;
attributeDescriptions = new();
uxmlNameToIndex = new();
cSharpNameToIndex = new();
GenerateAttributeDescription(type);
}
private void GenerateAttributeDescription(Type t)
{
if (t == typeof(UxmlSerializedData))
return;
GenerateAttributeDescription(t.BaseType);
var serializedFields = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
// Some type don't define Uxml attributes and only inherit them
if (serializedFields.Length == 0)
return;
foreach (var fieldInfo in serializedFields)
{
if (!TryCreateSerializedAttributeDescription(fieldInfo, out var description))
{
continue;
}
var attributeName = description.uxmlName;
if (uxmlNameToIndex.TryGetValue(attributeName, out var index))
{
// Override base class attribute
attributeDescriptions[index] = description;
}
else
{
attributeDescriptions.Add(description);
index = attributeDescriptions.Count - 1;
uxmlNameToIndex[attributeName] = index;
}
cSharpNameToIndex[fieldInfo.Name] = index;
}
}
private static bool TryCreateSerializedAttributeDescription(FieldInfo fieldInfo, out UxmlDescription description)
{
if (fieldInfo.GetCustomAttribute<UxmlIgnoreAttribute>() != null)
{
description = default;
return false;
}
var cSharpName = fieldInfo.Name;
var uxmlNames = GetUxmlNames(fieldInfo);
if (!uxmlNames.valid)
{
description = default;
return false;
}
description = new UxmlDescription(uxmlNames.uxmlName, cSharpName, fieldInfo, uxmlNames.obsoleteNames);
return true;
}
internal static (bool valid, string uxmlName, string[] obsoleteNames) GetUxmlNames(FieldInfo fieldInfo)
{
using var pooledListHandle = ListPool<string>.Get(out var obsoleteNamesList);
using var pooledHashSetHandle = HashSetPool<string>.Get(out var obsoleteNamesSet);
string[] GetArray(List<string> list)
{
if (list.Count == 0)
return Array.Empty<string>();
return list.ToArray();
}
var formerlySerializedAttributes = fieldInfo.GetCustomAttributes<FormerlySerializedAsAttribute>();
foreach (var formerlySerializedAs in formerlySerializedAttributes)
{
if (obsoleteNamesSet.Add(formerlySerializedAs.oldName))
obsoleteNamesList.Add(formerlySerializedAs.oldName);
}
var uxmlAttribute = fieldInfo.GetCustomAttribute<UxmlAttributeAttribute>();
if (null != uxmlAttribute)
{
if (null != uxmlAttribute.obsoleteNames)
{
foreach (var obsoleteName in uxmlAttribute?.obsoleteNames)
{
if (obsoleteNamesSet.Add(obsoleteName))
obsoleteNamesList.Add(obsoleteName);
}
}
if (!string.IsNullOrWhiteSpace(uxmlAttribute.name))
{
var nameValidationError = UxmlUtility.ValidateUxmlName(uxmlAttribute.name);
if (nameValidationError != null)
{
Debug.LogError($"Invalid UXML name '{uxmlAttribute.name}' for attribute '{fieldInfo.Name}' in type '{fieldInfo.DeclaringType.DeclaringType}'. {nameValidationError}");
return (false, null, null);
}
return (true, uxmlAttribute.name, GetArray(obsoleteNamesList));
}
}
var uxmlObjectAttribute = fieldInfo.GetCustomAttribute<UxmlObjectReferenceAttribute>();
if (null != uxmlObjectAttribute)
{
if (!string.IsNullOrWhiteSpace(uxmlObjectAttribute.name))
{
var validName = UxmlUtility.ValidateUxmlName(uxmlObjectAttribute.name);
if (validName != null)
{
Debug.LogError($"Invalid UXML Object name '{uxmlObjectAttribute.name}' for attribute '{fieldInfo.Name}' in type '{fieldInfo.DeclaringType.DeclaringType}'. {validName}");
return (false, null, null);
}
return (true, uxmlObjectAttribute.name, GetArray(obsoleteNamesList));
}
}
// Use the name of the field to determine the attribute name
var sb = GenericPool<StringBuilder>.Get();
var fieldName = fieldInfo.Name;
for (var i = 0; i < fieldName.Length; i++)
{
var c = fieldName[i];
if (char.IsUpper(c))
{
c = char.ToLower(c);
if (i > 0)
sb.Append("-");
}
sb.Append(c);
}
var result = sb.ToString();
GenericPool<StringBuilder>.Release(sb.Clear());
return (true, result, GetArray(obsoleteNamesList));
}
}
internal static class UxmlDescriptionRegistry
{
private static readonly Dictionary<Type, UxmlTypeDescription> s_UxmlDescriptions = new();
public static UxmlTypeDescription GetDescription(Type type)
{
if (!s_UxmlDescriptions.TryGetValue(type, out var description))
s_UxmlDescriptions.Add(type, description = new UxmlTypeDescription(type));
return description;
}
}
}
| UnityCsReference/Modules/UIElements/Core/UXML/UxmlDescriptionRegistry.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/UXML/UxmlDescriptionRegistry.cs",
"repo_id": "UnityCsReference",
"token_count": 3762
} | 510 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.UIElements.Experimental;
namespace UnityEngine.UIElements
{
/// <summary>
/// Base class for objects that are part of the UIElements visual tree.
/// </summary>
/// <remarks>
/// VisualElement contains several features that are common to all controls in UIElements, such as layout, styling and event handling.
/// Several other classes derive from it to implement custom rendering and define behaviour for controls.
/// </remarks>
public partial class VisualElement : ITransitionAnimations
{
List<IValueAnimationUpdate> m_RunningAnimations;
private VisualElementAnimationSystem GetAnimationSystem()
{
if (elementPanel != null)
{
return elementPanel.GetUpdater(VisualTreeUpdatePhase.Animation) as VisualElementAnimationSystem;
}
return null;
}
internal void RegisterAnimation(IValueAnimationUpdate anim)
{
if (m_RunningAnimations == null)
{
m_RunningAnimations = new List<IValueAnimationUpdate>();
}
m_RunningAnimations.Add(anim);
var sys = GetAnimationSystem();
if (sys != null)
{
sys.RegisterAnimation(anim);
}
}
internal void UnregisterAnimation(IValueAnimationUpdate anim)
{
if (m_RunningAnimations != null)
{
m_RunningAnimations.Remove(anim);
}
var sys = GetAnimationSystem();
if (sys != null)
{
sys.UnregisterAnimation(anim);
}
}
private void UnregisterRunningAnimations()
{
if (m_RunningAnimations != null && m_RunningAnimations.Count > 0)
{
var sys = GetAnimationSystem();
if (sys != null)
sys.UnregisterAnimations(m_RunningAnimations);
}
styleAnimation.CancelAllAnimations();
}
private void RegisterRunningAnimations()
{
if (m_RunningAnimations != null && m_RunningAnimations.Count > 0)
{
var sys = GetAnimationSystem();
if (sys != null)
sys.RegisterAnimations(m_RunningAnimations);
}
}
ValueAnimation<float> ITransitionAnimations.Start(float from, float to, int durationMs, Action<VisualElement, float> onValueChanged)
{
return experimental.animation.Start((e) => from, to, durationMs, onValueChanged);
}
ValueAnimation<Rect> ITransitionAnimations.Start(Rect from, Rect to, int durationMs, Action<VisualElement, Rect> onValueChanged)
{
return experimental.animation.Start((e) => from, to, durationMs, onValueChanged);
}
ValueAnimation<Color> ITransitionAnimations.Start(Color from, Color to, int durationMs, Action<VisualElement, Color> onValueChanged)
{
return experimental.animation.Start((e) => from, to, durationMs, onValueChanged);
}
ValueAnimation<Vector3> ITransitionAnimations.Start(Vector3 from, Vector3 to, int durationMs, Action<VisualElement, Vector3> onValueChanged)
{
return experimental.animation.Start((e) => from, to, durationMs, onValueChanged);
}
ValueAnimation<Vector2> ITransitionAnimations.Start(Vector2 from, Vector2 to, int durationMs, Action<VisualElement, Vector2> onValueChanged)
{
return experimental.animation.Start((e) => from, to, durationMs, onValueChanged);
}
ValueAnimation<Quaternion> ITransitionAnimations.Start(Quaternion from, Quaternion to, int durationMs, Action<VisualElement, Quaternion> onValueChanged)
{
return experimental.animation.Start((e) => from, to, durationMs, onValueChanged);
}
ValueAnimation<StyleValues> ITransitionAnimations.Start(StyleValues from, StyleValues to, int durationMs)
{
if (from.m_StyleValues == null)
from.Values();
if (to.m_StyleValues == null)
to.Values();
return Start((e) => from, to, durationMs);
}
ValueAnimation<float> ITransitionAnimations.Start(Func<VisualElement, float> fromValueGetter, float to, int durationMs, Action<VisualElement, float> onValueChanged)
{
return StartAnimation(ValueAnimation<float>.Create(this, Lerp.Interpolate), fromValueGetter, to, durationMs, onValueChanged);
}
ValueAnimation<Rect> ITransitionAnimations.Start(Func<VisualElement, Rect> fromValueGetter, Rect to, int durationMs, Action<VisualElement, Rect> onValueChanged)
{
return StartAnimation(ValueAnimation<Rect>.Create(this, Lerp.Interpolate), fromValueGetter, to, durationMs, onValueChanged);
}
ValueAnimation<Color> ITransitionAnimations.Start(Func<VisualElement, Color> fromValueGetter, Color to, int durationMs, Action<VisualElement, Color> onValueChanged)
{
return StartAnimation(ValueAnimation<Color>.Create(this, Lerp.Interpolate), fromValueGetter, to, durationMs, onValueChanged);
}
ValueAnimation<Vector3> ITransitionAnimations.Start(Func<VisualElement, Vector3> fromValueGetter, Vector3 to, int durationMs, Action<VisualElement, Vector3> onValueChanged)
{
return StartAnimation(ValueAnimation<Vector3>.Create(this, Lerp.Interpolate), fromValueGetter, to, durationMs, onValueChanged);
}
ValueAnimation<Vector2> ITransitionAnimations.Start(Func<VisualElement, Vector2> fromValueGetter, Vector2 to, int durationMs, Action<VisualElement, Vector2> onValueChanged)
{
return StartAnimation(ValueAnimation<Vector2>.Create(this, Lerp.Interpolate), fromValueGetter, to, durationMs, onValueChanged);
}
ValueAnimation<Quaternion> ITransitionAnimations.Start(Func<VisualElement, Quaternion> fromValueGetter, Quaternion to, int durationMs, Action<VisualElement, Quaternion> onValueChanged)
{
return StartAnimation(ValueAnimation<Quaternion>.Create(this, Lerp.Interpolate), fromValueGetter, to, durationMs, onValueChanged);
}
private static ValueAnimation<T> StartAnimation<T>(ValueAnimation<T> anim, Func<VisualElement, T> fromValueGetter, T to, int durationMs, Action<VisualElement, T> onValueChanged)
{
anim.initialValue = fromValueGetter;
anim.to = to;
anim.durationMs = durationMs;
anim.valueUpdated = onValueChanged;
anim.Start();
return anim;
}
private static void AssignStyleValues(VisualElement ve, StyleValues src)
{
var s = ve.style;
if (src.m_StyleValues != null)
{
foreach (var styleValue in src.m_StyleValues.m_Values)
{
switch (styleValue.id)
{
case StyleSheets.StylePropertyId.Unknown:
break;
case StyleSheets.StylePropertyId.MarginLeft:
s.marginLeft = styleValue.number;
break;
case StyleSheets.StylePropertyId.MarginTop:
s.marginTop = styleValue.number;
break;
case StyleSheets.StylePropertyId.MarginRight:
s.marginRight = styleValue.number;
break;
case StyleSheets.StylePropertyId.MarginBottom:
s.marginBottom = styleValue.number;
break;
case StyleSheets.StylePropertyId.PaddingLeft:
s.paddingLeft = styleValue.number;
break;
case StyleSheets.StylePropertyId.PaddingTop:
s.paddingTop = styleValue.number;
break;
case StyleSheets.StylePropertyId.PaddingRight:
s.paddingRight = styleValue.number;
break;
case StyleSheets.StylePropertyId.PaddingBottom:
s.paddingBottom = styleValue.number;
break;
case StyleSheets.StylePropertyId.Left:
s.left = styleValue.number;
break;
case StyleSheets.StylePropertyId.Top:
s.top = styleValue.number;
break;
case StyleSheets.StylePropertyId.Right:
s.right = styleValue.number;
break;
case StyleSheets.StylePropertyId.Bottom:
s.bottom = styleValue.number;
break;
case StyleSheets.StylePropertyId.Width:
s.width = styleValue.number;
break;
case StyleSheets.StylePropertyId.Height:
s.height = styleValue.number;
break;
case StyleSheets.StylePropertyId.FlexGrow:
s.flexGrow = styleValue.number;
break;
case StyleSheets.StylePropertyId.FlexShrink:
s.flexShrink = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderLeftWidth:
s.borderLeftWidth = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderTopWidth:
s.borderTopWidth = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderRightWidth:
s.borderRightWidth = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderBottomWidth:
s.borderBottomWidth = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderTopLeftRadius:
s.borderTopLeftRadius = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderTopRightRadius:
s.borderTopRightRadius = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderBottomRightRadius:
s.borderBottomRightRadius = styleValue.number;
break;
case StyleSheets.StylePropertyId.BorderBottomLeftRadius:
s.borderBottomLeftRadius = styleValue.number;
break;
case StyleSheets.StylePropertyId.FontSize:
s.fontSize = styleValue.number;
break;
case StyleSheets.StylePropertyId.Color:
s.color = styleValue.color;
break;
case StyleSheets.StylePropertyId.BackgroundColor:
s.backgroundColor = styleValue.color;
break;
case StyleSheets.StylePropertyId.BorderColor:
s.borderLeftColor = styleValue.color;
s.borderTopColor = styleValue.color;
s.borderRightColor = styleValue.color;
s.borderBottomColor = styleValue.color;
break;
case StyleSheets.StylePropertyId.UnityBackgroundImageTintColor:
s.unityBackgroundImageTintColor = styleValue.color;
break;
case StyleSheets.StylePropertyId.Opacity:
s.opacity = styleValue.number;
break;
default:
break;
}
}
}
}
StyleValues ReadCurrentValues(VisualElement ve, StyleValues targetValuesToRead)
{
StyleValues s = new StyleValues();
var src = ve.resolvedStyle;
if (targetValuesToRead.m_StyleValues != null)
{
foreach (var styleValue in targetValuesToRead.m_StyleValues.m_Values)
{
switch (styleValue.id)
{
case StyleSheets.StylePropertyId.Unknown:
break;
case StyleSheets.StylePropertyId.MarginLeft:
s.marginLeft = src.marginLeft;
break;
case StyleSheets.StylePropertyId.MarginTop:
s.marginTop = src.marginTop;
break;
case StyleSheets.StylePropertyId.MarginRight:
s.marginRight = src.marginRight;
break;
case StyleSheets.StylePropertyId.MarginBottom:
s.marginBottom = src.marginBottom;
break;
case StyleSheets.StylePropertyId.PaddingLeft:
s.paddingLeft = src.paddingLeft;
break;
case StyleSheets.StylePropertyId.PaddingTop:
s.paddingTop = src.paddingTop;
break;
case StyleSheets.StylePropertyId.PaddingRight:
s.paddingRight = src.paddingRight;
break;
case StyleSheets.StylePropertyId.PaddingBottom:
s.paddingBottom = src.paddingBottom;
break;
case StyleSheets.StylePropertyId.Left:
s.left = src.left;
break;
case StyleSheets.StylePropertyId.Top:
s.top = src.top;
break;
case StyleSheets.StylePropertyId.Right:
s.right = src.right;
break;
case StyleSheets.StylePropertyId.Bottom:
s.bottom = src.bottom;
break;
case StyleSheets.StylePropertyId.Width:
s.width = src.width;
break;
case StyleSheets.StylePropertyId.Height:
s.height = src.height;
break;
case StyleSheets.StylePropertyId.FlexGrow:
s.flexGrow = src.flexGrow;
break;
case StyleSheets.StylePropertyId.FlexShrink:
s.flexShrink = src.flexShrink;
break;
case StyleSheets.StylePropertyId.BorderLeftWidth:
s.borderLeftWidth = src.borderLeftWidth;
break;
case StyleSheets.StylePropertyId.BorderTopWidth:
s.borderTopWidth = src.borderTopWidth;
break;
case StyleSheets.StylePropertyId.BorderRightWidth:
s.borderRightWidth = src.borderRightWidth;
break;
case StyleSheets.StylePropertyId.BorderBottomWidth:
s.borderBottomWidth = src.borderBottomWidth;
break;
case StyleSheets.StylePropertyId.BorderTopLeftRadius:
s.borderTopLeftRadius = src.borderTopLeftRadius;
break;
case StyleSheets.StylePropertyId.BorderTopRightRadius:
s.borderTopRightRadius = src.borderTopRightRadius;
break;
case StyleSheets.StylePropertyId.BorderBottomRightRadius:
s.borderBottomRightRadius = src.borderBottomRightRadius;
break;
case StyleSheets.StylePropertyId.BorderBottomLeftRadius:
s.borderBottomLeftRadius = src.borderBottomLeftRadius;
break;
case StyleSheets.StylePropertyId.Color:
s.color = src.color;
break;
case StyleSheets.StylePropertyId.BackgroundColor:
s.backgroundColor = src.backgroundColor;
break;
case StyleSheets.StylePropertyId.BorderColor:
s.borderColor = src.borderLeftColor;
break;
case StyleSheets.StylePropertyId.UnityBackgroundImageTintColor:
s.unityBackgroundImageTintColor = src.unityBackgroundImageTintColor;
break;
case StyleSheets.StylePropertyId.Opacity:
s.opacity = src.opacity;
break;
default:
break;
}
}
}
return s;
}
ValueAnimation<StyleValues> ITransitionAnimations.Start(StyleValues to, int durationMs)
{
if (to.m_StyleValues == null)
to.Values();
return Start((e) => ReadCurrentValues(e, to), to, durationMs);
}
private ValueAnimation<StyleValues> Start(Func<VisualElement, StyleValues> fromValueGetter, StyleValues to, int durationMs)
{
return StartAnimation(ValueAnimation<StyleValues>.Create(this, Lerp.Interpolate), fromValueGetter, to, durationMs, AssignStyleValues);
}
ValueAnimation<Rect> ITransitionAnimations.Layout(Rect to, int durationMs)
{
return experimental.animation.Start((e) =>
new Rect(
e.resolvedStyle.left,
e.resolvedStyle.top,
e.resolvedStyle.width,
e.resolvedStyle.height
)
, to, durationMs,
(e, c) =>
{
e.style.left = c.x;
e.style.top = c.y;
e.style.width = c.width;
e.style.height = c.height;
});
}
ValueAnimation<Vector2> ITransitionAnimations.TopLeft(Vector2 to, int durationMs)
{
return experimental.animation.Start((e) => new Vector2(e.resolvedStyle.left, e.resolvedStyle.top),
to, durationMs,
(e, c) =>
{
e.style.left = c.x;
e.style.top = c.y;
});
}
ValueAnimation<Vector2> ITransitionAnimations.Size(Vector2 to, int durationMs)
{
return experimental.animation.Start((e) => e.layout.size,
to, durationMs,
(e, c) =>
{
e.style.width = c.x;
e.style.height = c.y;
});
}
ValueAnimation<float> ITransitionAnimations.Scale(float to, int durationMs)
{
return experimental.animation.Start((e) => e.transform.scale.x, to, durationMs, (e, c) => { e.transform.scale = new Vector3(c, c, c); });
}
ValueAnimation<Vector3> ITransitionAnimations.Position(Vector3 to, int durationMs)
{
return experimental.animation.Start((e) => e.transform.position, to, durationMs, (e, c) => { e.transform.position = c; });
}
ValueAnimation<Quaternion> ITransitionAnimations.Rotation(Quaternion to, int durationMs)
{
return experimental.animation.Start((e) => e.transform.rotation, to, durationMs, (e, c) => { e.transform.rotation = c; });
}
}
}
| UnityCsReference/Modules/UIElements/Core/VisualElementAnimation.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/VisualElementAnimation.cs",
"repo_id": "UnityCsReference",
"token_count": 11330
} | 511 |
// 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.UIElements
{
//Keep in sync with HierarchyChangeType in HierarchyChangeType.h
internal enum HierarchyChangeType
{
Add, // TODO: Rename to AddedToParent
Remove, // TODO: Rename to RemovedFromParent
Move // TODO: Rename to ChildrenReordered
}
internal abstract class BaseVisualTreeHierarchyTrackerUpdater : BaseVisualTreeUpdater
{
enum State
{
Waiting,
TrackingAddOrMove,
TrackingRemove,
}
private State m_State = State.Waiting;
private VisualElement m_CurrentChangeElement;
private VisualElement m_CurrentChangeParent;
protected abstract void OnHierarchyChange(VisualElement ve, HierarchyChangeType type);
internal abstract void PollElementsWithBindings(Action<VisualElement, IBinding> callback);
public override void OnVersionChanged(VisualElement ve, VersionChangeType versionChangeType)
{
if ((versionChangeType & VersionChangeType.Hierarchy) == VersionChangeType.Hierarchy)
{
switch (m_State)
{
case State.Waiting:
ProcessNewChange(ve);
break;
case State.TrackingRemove:
ProcessRemove(ve);
break;
case State.TrackingAddOrMove:
ProcessAddOrMove(ve);
break;
}
}
}
public override void Update()
{
Debug.Assert(m_State == State.TrackingAddOrMove || m_State == State.Waiting);
if (m_State == State.TrackingAddOrMove)
{
// Still waiting for a parent add change
// which means that last change was a move
OnHierarchyChange(m_CurrentChangeElement, HierarchyChangeType.Move);
m_State = State.Waiting;
}
m_CurrentChangeElement = null;
m_CurrentChangeParent = null;
}
private void ProcessNewChange(VisualElement ve)
{
// Children are always the first to receive a Hierarchy change
m_CurrentChangeElement = ve;
m_CurrentChangeParent = ve.parent;
if (m_CurrentChangeParent == null && ve.panel != null)
{
// The changed element is the VisualTree root so it has to be a move.
OnHierarchyChange(m_CurrentChangeElement, HierarchyChangeType.Move);
m_State = State.Waiting;
}
else
{
m_State = m_CurrentChangeParent == null ? State.TrackingRemove : State.TrackingAddOrMove;
}
}
private void ProcessAddOrMove(VisualElement ve)
{
Debug.Assert(m_CurrentChangeParent != null);
if (m_CurrentChangeParent == ve)
{
OnHierarchyChange(m_CurrentChangeElement, HierarchyChangeType.Add);
m_State = State.Waiting;
}
else
{
// This is a new change, last change was a move
OnHierarchyChange(m_CurrentChangeElement, HierarchyChangeType.Move);
ProcessNewChange(ve);
}
}
private void ProcessRemove(VisualElement ve)
{
OnHierarchyChange(m_CurrentChangeElement, HierarchyChangeType.Remove);
if (ve.panel != null)
{
// This is the parent (or VisualTree root) of the removed children
m_CurrentChangeParent = null;
m_CurrentChangeElement = null;
m_State = State.Waiting;
}
else
{
m_CurrentChangeElement = ve;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/VisualTreeHierarchyTracker.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/VisualTreeHierarchyTracker.cs",
"repo_id": "UnityCsReference",
"token_count": 1962
} | 512 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
namespace UnityEngine.UIElements;
/// <summary>
/// The <see cref="VisualNodeHandle"/> represents a lightweight handle to native visual node data.
/// </summary>
[NativeType(Header = "Modules/UIElements/VisualNodeHandle.h")]
[StructLayout(LayoutKind.Sequential)]
readonly struct VisualNodeHandle : IEquatable<VisualNodeHandle>
{
/// <summary>
/// Represents a null/invalid handle.
/// </summary>
public static readonly VisualNodeHandle Null;
readonly int m_Id;
readonly int m_Version;
/// <summary>
/// The unique id for this handle.
/// </summary>
public int Id => m_Id;
/// <summary>
/// The version number for this handle.
/// </summary>
public int Version => m_Version;
/// <summary>
/// Initializes a new instance of the <see cref="VisualNodeHandle"/> struct.
/// </summary>
/// <param name="id">The handle id.</param>
/// <param name="version">The handle version.</param>
public VisualNodeHandle(int id, int version)
{
m_Id = id;
m_Version = version;
}
public static bool operator ==(in VisualNodeHandle lhs, in VisualNodeHandle rhs) => lhs.Id == rhs.Id && lhs.Version == rhs.Version;
public static bool operator !=(in VisualNodeHandle lhs, in VisualNodeHandle rhs) => !(lhs == rhs);
public bool Equals(VisualNodeHandle other) => other.Id == Id && other.Version == Version;
public override string ToString() => $"{nameof(VisualNodeHandle)}({(this == Null ? nameof(Null) : $"{Id}:{Version}")})";
public override bool Equals(object obj) => obj is VisualNodeHandle node && Equals(node);
public override int GetHashCode() => HashCode.Combine(Id, Version);
}
| UnityCsReference/Modules/UIElements/ScriptBindings/VisualNodeHandle.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/ScriptBindings/VisualNodeHandle.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 632
} | 513 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.