code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Base class for all tweening operations.
/// </summary>
public abstract class UITweener : MonoBehaviour
{
/// <summary>
/// Current tween that triggered the callback function.
/// </summary>
static public UITweener current;
public enum Method
{
Linear,
EaseIn,
EaseOut,
EaseInOut,
BounceIn,
BounceOut,
}
public enum Style
{
Once,
Loop,
PingPong,
}
/// <summary>
/// Tweening method used.
/// </summary>
[HideInInspector]
public Method method = Method.Linear;
/// <summary>
/// Does it play once? Does it loop?
/// </summary>
[HideInInspector]
public Style style = Style.Once;
/// <summary>
/// Optional curve to apply to the tween's time factor value.
/// </summary>
[HideInInspector]
public AnimationCurve animationCurve = new AnimationCurve(new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f));
/// <summary>
/// Whether the tween will ignore the timescale, making it work while the game is paused.
/// </summary>
[HideInInspector]
public bool ignoreTimeScale = true;
/// <summary>
/// How long will the tweener wait before starting the tween?
/// </summary>
[HideInInspector]
public float delay = 0f;
/// <summary>
/// How long is the duration of the tween?
/// </summary>
[HideInInspector]
public float duration = 1f;
/// <summary>
/// Whether the tweener will use steeper curves for ease in / out style interpolation.
/// </summary>
[HideInInspector]
public bool steeperCurves = false;
/// <summary>
/// Used by buttons and tween sequences. Group of '0' means not in a sequence.
/// </summary>
[HideInInspector]
public int tweenGroup = 0;
/// <summary>
/// Event delegates called when the animation finishes.
/// </summary>
[HideInInspector]
public List<EventDelegate> onFinished = new List<EventDelegate>();
// Deprecated functionality, kept for backwards compatibility
[HideInInspector] public GameObject eventReceiver;
[HideInInspector] public string callWhenFinished;
bool mStarted = false;
float mStartTime = 0f;
float mDuration = 0f;
float mAmountPerDelta = 1000f;
float mFactor = 0f;
/// <summary>
/// Amount advanced per delta time.
/// </summary>
public float amountPerDelta
{
get
{
if (mDuration != duration)
{
mDuration = duration;
mAmountPerDelta = Mathf.Abs((duration > 0f) ? 1f / duration : 1000f);
}
return mAmountPerDelta;
}
}
/// <summary>
/// Tween factor, 0-1 range.
/// </summary>
public float tweenFactor { get { return mFactor; } set { mFactor = Mathf.Clamp01(value); } }
/// <summary>
/// Direction that the tween is currently playing in.
/// </summary>
public AnimationOrTween.Direction direction { get { return mAmountPerDelta < 0f ? AnimationOrTween.Direction.Reverse : AnimationOrTween.Direction.Forward; } }
/// <summary>
/// This function is called by Unity when you add a component. Automatically set the starting values for convenience.
/// </summary>
void Reset ()
{
if (!mStarted)
{
SetStartToCurrentValue();
SetEndToCurrentValue();
}
}
/// <summary>
/// Update as soon as it's started so that there is no delay.
/// </summary>
protected virtual void Start () { Update(); }
/// <summary>
/// Update the tweening factor and call the virtual update function.
/// </summary>
void Update ()
{
float delta = ignoreTimeScale ? RealTime.deltaTime : Time.deltaTime;
float time = ignoreTimeScale ? RealTime.time : Time.time;
if (!mStarted)
{
mStarted = true;
mStartTime = time + delay;
}
if (time < mStartTime) return;
// Advance the sampling factor
mFactor += amountPerDelta * delta;
// Loop style simply resets the play factor after it exceeds 1.
if (style == Style.Loop)
{
if (mFactor > 1f)
{
mFactor -= Mathf.Floor(mFactor);
}
}
else if (style == Style.PingPong)
{
// Ping-pong style reverses the direction
if (mFactor > 1f)
{
mFactor = 1f - (mFactor - Mathf.Floor(mFactor));
mAmountPerDelta = -mAmountPerDelta;
}
else if (mFactor < 0f)
{
mFactor = -mFactor;
mFactor -= Mathf.Floor(mFactor);
mAmountPerDelta = -mAmountPerDelta;
}
}
// If the factor goes out of range and this is a one-time tweening operation, disable the script
if ((style == Style.Once) && (duration == 0f || mFactor > 1f || mFactor < 0f))
{
mFactor = Mathf.Clamp01(mFactor);
Sample(mFactor, true);
// Disable this script unless the function calls above changed something
if (duration == 0f || (mFactor == 1f && mAmountPerDelta > 0f || mFactor == 0f && mAmountPerDelta < 0f))
enabled = false;
if (current == null)
{
current = this;
if (onFinished != null)
{
mTemp = onFinished;
onFinished = new List<EventDelegate>();
// Notify the listener delegates
EventDelegate.Execute(mTemp);
// Re-add the previous persistent delegates
for (int i = 0; i < mTemp.Count; ++i)
{
EventDelegate ed = mTemp[i];
if (ed != null) EventDelegate.Add(onFinished, ed, ed.oneShot);
}
mTemp = null;
}
// Deprecated legacy functionality support
if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
eventReceiver.SendMessage(callWhenFinished, this, SendMessageOptions.DontRequireReceiver);
current = null;
}
}
else Sample(mFactor, false);
}
List<EventDelegate> mTemp = null;
/// <summary>
/// Convenience function -- set a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
/// </summary>
public void SetOnFinished (EventDelegate.Callback del) { EventDelegate.Set(onFinished, del); }
/// <summary>
/// Convenience function -- set a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
/// </summary>
public void SetOnFinished (EventDelegate del) { EventDelegate.Set(onFinished, del); }
/// <summary>
/// Convenience function -- add a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
/// </summary>
public void AddOnFinished (EventDelegate.Callback del) { EventDelegate.Add(onFinished, del); }
/// <summary>
/// Convenience function -- add a new OnFinished event delegate (here for to be consistent with RemoveOnFinished).
/// </summary>
public void AddOnFinished (EventDelegate del) { EventDelegate.Add(onFinished, del); }
/// <summary>
/// Remove an OnFinished delegate. Will work even while iterating through the list when the tweener has finished its operation.
/// </summary>
public void RemoveOnFinished (EventDelegate del)
{
if (onFinished != null) onFinished.Remove(del);
if (mTemp != null) mTemp.Remove(del);
}
/// <summary>
/// Mark as not started when finished to enable delay on next play.
/// </summary>
void OnDisable () { mStarted = false; }
/// <summary>
/// Sample the tween at the specified factor.
/// </summary>
public void Sample (float factor, bool isFinished)
{
// Calculate the sampling value
float val = Mathf.Clamp01(factor);
if (method == Method.EaseIn)
{
val = 1f - Mathf.Sin(0.5f * Mathf.PI * (1f - val));
if (steeperCurves) val *= val;
}
else if (method == Method.EaseOut)
{
val = Mathf.Sin(0.5f * Mathf.PI * val);
if (steeperCurves)
{
val = 1f - val;
val = 1f - val * val;
}
}
else if (method == Method.EaseInOut)
{
const float pi2 = Mathf.PI * 2f;
val = val - Mathf.Sin(val * pi2) / pi2;
if (steeperCurves)
{
val = val * 2f - 1f;
float sign = Mathf.Sign(val);
val = 1f - Mathf.Abs(val);
val = 1f - val * val;
val = sign * val * 0.5f + 0.5f;
}
}
else if (method == Method.BounceIn)
{
val = BounceLogic(val);
}
else if (method == Method.BounceOut)
{
val = 1f - BounceLogic(1f - val);
}
// Call the virtual update
OnUpdate((animationCurve != null) ? animationCurve.Evaluate(val) : val, isFinished);
}
/// <summary>
/// Main Bounce logic to simplify the Sample function
/// </summary>
float BounceLogic (float val)
{
if (val < 0.363636f) // 0.363636 = (1/ 2.75)
{
val = 7.5685f * val * val;
}
else if (val < 0.727272f) // 0.727272 = (2 / 2.75)
{
val = 7.5625f * (val -= 0.545454f) * val + 0.75f; // 0.545454f = (1.5 / 2.75)
}
else if (val < 0.909090f) // 0.909090 = (2.5 / 2.75)
{
val = 7.5625f * (val -= 0.818181f) * val + 0.9375f; // 0.818181 = (2.25 / 2.75)
}
else
{
val = 7.5625f * (val -= 0.9545454f) * val + 0.984375f; // 0.9545454 = (2.625 / 2.75)
}
return val;
}
/// <summary>
/// Play the tween.
/// </summary>
[System.Obsolete("Use PlayForward() instead")]
public void Play () { Play(true); }
/// <summary>
/// Play the tween forward.
/// </summary>
public void PlayForward () { Play(true); }
/// <summary>
/// Play the tween in reverse.
/// </summary>
public void PlayReverse () { Play(false); }
/// <summary>
/// Manually activate the tweening process, reversing it if necessary.
/// </summary>
public void Play (bool forward)
{
mAmountPerDelta = Mathf.Abs(amountPerDelta);
if (!forward) mAmountPerDelta = -mAmountPerDelta;
enabled = true;
Update();
}
/// <summary>
/// Manually reset the tweener's state to the beginning.
/// If the tween is playing forward, this means the tween's start.
/// If the tween is playing in reverse, this means the tween's end.
/// </summary>
public void ResetToBeginning ()
{
mStarted = false;
mFactor = (mAmountPerDelta < 0f) ? 1f : 0f;
Sample(mFactor, false);
}
/// <summary>
/// Manually start the tweening process, reversing its direction.
/// </summary>
public void Toggle ()
{
if (mFactor > 0f)
{
mAmountPerDelta = -amountPerDelta;
}
else
{
mAmountPerDelta = Mathf.Abs(amountPerDelta);
}
enabled = true;
}
/// <summary>
/// Actual tweening logic should go here.
/// </summary>
abstract protected void OnUpdate (float factor, bool isFinished);
/// <summary>
/// Starts the tweening operation.
/// </summary>
static public T Begin<T> (GameObject go, float duration) where T : UITweener
{
T comp = go.GetComponent<T>();
#if UNITY_FLASH
if ((object)comp == null) comp = (T)go.AddComponent<T>();
#else
// Find the tween with an unset group ID (group ID of 0).
if (comp != null && comp.tweenGroup != 0)
{
comp = null;
T[] comps = go.GetComponents<T>();
for (int i = 0, imax = comps.Length; i < imax; ++i)
{
comp = comps[i];
if (comp != null && comp.tweenGroup == 0) break;
comp = null;
}
}
if (comp == null) comp = go.AddComponent<T>();
#endif
comp.mStarted = false;
comp.duration = duration;
comp.mFactor = 0f;
comp.mAmountPerDelta = Mathf.Abs(comp.mAmountPerDelta);
comp.style = Style.Once;
comp.animationCurve = new AnimationCurve(new Keyframe(0f, 0f, 0f, 1f), new Keyframe(1f, 1f, 1f, 0f));
comp.eventReceiver = null;
comp.callWhenFinished = null;
comp.enabled = true;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
/// <summary>
/// Set the 'from' value to the current one.
/// </summary>
public virtual void SetStartToCurrentValue () { }
/// <summary>
/// Set the 'to' value to the current one.
/// </summary>
public virtual void SetEndToCurrentValue () { }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/UITweener.cs
|
C#
|
asf20
| 11,547
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the object's color.
/// </summary>
[AddComponentMenu("NGUI/Tween/Tween Color")]
public class TweenColor : UITweener
{
public Color from = Color.white;
public Color to = Color.white;
bool mCached = false;
UIWidget mWidget;
Material mMat;
Light mLight;
void Cache ()
{
mCached = true;
mWidget = GetComponent<UIWidget>();
Renderer ren = renderer;
if (ren != null) mMat = ren.material;
mLight = light;
if (mWidget == null && mMat == null && mLight == null)
mWidget = GetComponentInChildren<UIWidget>();
}
[System.Obsolete("Use 'value' instead")]
public Color color { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public Color value
{
get
{
if (!mCached) Cache();
if (mWidget != null) return mWidget.color;
if (mLight != null) return mLight.color;
if (mMat != null) return mMat.color;
return Color.black;
}
set
{
if (!mCached) Cache();
if (mWidget != null) mWidget.color = value;
if (mMat != null) mMat.color = value;
if (mLight != null)
{
mLight.color = value;
mLight.enabled = (value.r + value.g + value.b) > 0.01f;
}
}
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = Color.Lerp(from, to, factor); }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenColor Begin (GameObject go, float duration, Color color)
{
#if UNITY_EDITOR
if (!Application.isPlaying) return null;
#endif
TweenColor comp = UITweener.Begin<TweenColor>(go, duration);
comp.from = comp.value;
comp.to = color;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenColor.cs
|
C#
|
asf20
| 2,392
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the camera's orthographic size.
/// </summary>
[RequireComponent(typeof(Camera))]
[AddComponentMenu("NGUI/Tween/Tween Orthographic Size")]
public class TweenOrthoSize : UITweener
{
public float from = 1f;
public float to = 1f;
Camera mCam;
/// <summary>
/// Camera that's being tweened.
/// </summary>
public Camera cachedCamera { get { if (mCam == null) mCam = camera; return mCam; } }
[System.Obsolete("Use 'value' instead")]
public float orthoSize { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public float value
{
get { return cachedCamera.orthographicSize; }
set { cachedCamera.orthographicSize = value; }
}
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished) { value = from * (1f - factor) + to * factor; }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenOrthoSize Begin (GameObject go, float duration, float to)
{
TweenOrthoSize comp = UITweener.Begin<TweenOrthoSize>(go, duration);
comp.from = comp.value;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
public override void SetStartToCurrentValue () { from = value; }
public override void SetEndToCurrentValue () { to = value; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenOrthoSize.cs
|
C#
|
asf20
| 1,598
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Makes it possible to animate a color of the widget.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(UIWidget))]
public class AnimatedColor : MonoBehaviour
{
public Color color = Color.white;
UIWidget mWidget;
void OnEnable () { mWidget = GetComponent<UIWidget>(); LateUpdate(); }
void LateUpdate () { mWidget.color = color; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/AnimatedColor.cs
|
C#
|
asf20
| 570
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the object's rotation.
/// </summary>
[AddComponentMenu("NGUI/Tween/Tween Rotation")]
public class TweenRotation : UITweener
{
public Vector3 from;
public Vector3 to;
Transform mTrans;
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
[System.Obsolete("Use 'value' instead")]
public Quaternion rotation { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween's current value.
/// </summary>
public Quaternion value { get { return cachedTransform.localRotation; } set { cachedTransform.localRotation = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
value = Quaternion.Euler(new Vector3(
Mathf.Lerp(from.x, to.x, factor),
Mathf.Lerp(from.y, to.y, factor),
Mathf.Lerp(from.z, to.z, factor)));
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenRotation Begin (GameObject go, float duration, Quaternion rot)
{
TweenRotation comp = UITweener.Begin<TweenRotation>(go, duration);
comp.from = comp.value.eulerAngles;
comp.to = rot.eulerAngles;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value.eulerAngles; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value.eulerAngles; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = Quaternion.Euler(from); }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = Quaternion.Euler(to); }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenRotation.cs
|
C#
|
asf20
| 1,963
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Makes it possible to animate alpha of the widget or a panel.
/// </summary>
[ExecuteInEditMode]
public class AnimatedAlpha : MonoBehaviour
{
#if !UNITY_3_5
[Range(0f, 1f)]
#endif
public float alpha = 1f;
UIWidget mWidget;
UIPanel mPanel;
void OnEnable ()
{
mWidget = GetComponent<UIWidget>();
mPanel = GetComponent<UIPanel>();
LateUpdate();
}
void LateUpdate ()
{
if (mWidget != null) mWidget.alpha = alpha;
if (mPanel != null) mPanel.alpha = alpha;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/AnimatedAlpha.cs
|
C#
|
asf20
| 700
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the object's local scale.
/// </summary>
[AddComponentMenu("NGUI/Tween/Tween Scale")]
public class TweenScale : UITweener
{
public Vector3 from = Vector3.one;
public Vector3 to = Vector3.one;
public bool updateTable = false;
Transform mTrans;
UITable mTable;
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
public Vector3 value { get { return cachedTransform.localScale; } set { cachedTransform.localScale = value; } }
[System.Obsolete("Use 'value' instead")]
public Vector3 scale { get { return this.value; } set { this.value = value; } }
/// <summary>
/// Tween the value.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
value = from * (1f - factor) + to * factor;
if (updateTable)
{
if (mTable == null)
{
mTable = NGUITools.FindInParents<UITable>(gameObject);
if (mTable == null) { updateTable = false; return; }
}
mTable.repositionNow = true;
}
}
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenScale Begin (GameObject go, float duration, Vector3 scale)
{
TweenScale comp = UITweener.Begin<TweenScale>(go, duration);
comp.from = comp.value;
comp.to = scale;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
[ContextMenu("Set 'From' to current value")]
public override void SetStartToCurrentValue () { from = value; }
[ContextMenu("Set 'To' to current value")]
public override void SetEndToCurrentValue () { to = value; }
[ContextMenu("Assume value of 'From'")]
void SetCurrentValueToStart () { value = from; }
[ContextMenu("Assume value of 'To'")]
void SetCurrentValueToEnd () { value = to; }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenScale.cs
|
C#
|
asf20
| 1,974
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Tween the object's position, rotation and scale.
/// </summary>
[AddComponentMenu("NGUI/Tween/Tween Transform")]
public class TweenTransform : UITweener
{
public Transform from;
public Transform to;
public bool parentWhenFinished = false;
Transform mTrans;
Vector3 mPos;
Quaternion mRot;
Vector3 mScale;
/// <summary>
/// Interpolate the position, scale, and rotation.
/// </summary>
protected override void OnUpdate (float factor, bool isFinished)
{
if (to != null)
{
if (mTrans == null)
{
mTrans = transform;
mPos = mTrans.position;
mRot = mTrans.rotation;
mScale = mTrans.localScale;
}
if (from != null)
{
mTrans.position = from.position * (1f - factor) + to.position * factor;
mTrans.localScale = from.localScale * (1f - factor) + to.localScale * factor;
mTrans.rotation = Quaternion.Slerp(from.rotation, to.rotation, factor);
}
else
{
mTrans.position = mPos * (1f - factor) + to.position * factor;
mTrans.localScale = mScale * (1f - factor) + to.localScale * factor;
mTrans.rotation = Quaternion.Slerp(mRot, to.rotation, factor);
}
// Change the parent when finished, if requested
if (parentWhenFinished && isFinished) mTrans.parent = to;
}
}
/// <summary>
/// Start the tweening operation from the current position/rotation/scale to the target transform.
/// </summary>
static public TweenTransform Begin (GameObject go, float duration, Transform to) { return Begin(go, duration, null, to); }
/// <summary>
/// Start the tweening operation.
/// </summary>
static public TweenTransform Begin (GameObject go, float duration, Transform from, Transform to)
{
TweenTransform comp = UITweener.Begin<TweenTransform>(go, duration);
comp.from = from;
comp.to = to;
if (duration <= 0f)
{
comp.Sample(1f, true);
comp.enabled = false;
}
return comp;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Tweening/TweenTransform.cs
|
C#
|
asf20
| 2,103
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Base class for all UI components that should be derived from when creating new widget types.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/UI/NGUI Widget")]
public class UIWidget : UIRect
{
public enum Pivot
{
TopLeft,
Top,
TopRight,
Left,
Center,
Right,
BottomLeft,
Bottom,
BottomRight,
}
// Cached and saved values
[HideInInspector][SerializeField] protected Color mColor = Color.white;
[HideInInspector][SerializeField] protected Pivot mPivot = Pivot.Center;
[HideInInspector][SerializeField] protected int mWidth = 100;
[HideInInspector][SerializeField] protected int mHeight = 100;
[HideInInspector][SerializeField] protected int mDepth = 0;
public delegate void OnDimensionsChanged ();
/// <summary>
/// Notification triggered when the widget's dimensions or position changes.
/// </summary>
public OnDimensionsChanged onChange;
/// <summary>
/// If set to 'true', the box collider's dimensions will be adjusted to always match the widget whenever it resizes.
/// </summary>
public bool autoResizeBoxCollider = false;
/// <summary>
/// Hide the widget if it happens to be off-screen.
/// </summary>
public bool hideIfOffScreen = false;
public enum AspectRatioSource
{
Free,
BasedOnWidth,
BasedOnHeight,
}
/// <summary>
/// Whether the rectangle will attempt to maintain a specific aspect ratio.
/// </summary>
public AspectRatioSource keepAspectRatio = AspectRatioSource.Free;
/// <summary>
/// If you want the anchored rectangle to keep a specific aspect ratio, set this value.
/// </summary>
public float aspectRatio = 1f;
public delegate bool HitCheck (Vector3 worldPos);
/// <summary>
/// Custom hit check function. If set, all hit checks (including events) will call this function,
/// passing the world position. Return 'true' if it's within the bounds of your choice, 'false' otherwise.
/// </summary>
public HitCheck hitCheck;
/// <summary>
/// Panel that's managing this widget.
/// </summary>
[System.NonSerialized]
public UIPanel panel;
/// <summary>
/// Widget's generated geometry.
/// </summary>
[System.NonSerialized]
public UIGeometry geometry = new UIGeometry();
/// <summary>
/// If set to 'false', the widget's OnFill function will not be called, letting you define custom geometry at will.
/// </summary>
[System.NonSerialized]
public bool fillGeometry = true;
protected bool mPlayMode = true;
protected Vector4 mDrawRegion = new Vector4(0f, 0f, 1f, 1f);
Matrix4x4 mLocalToPanel;
bool mIsVisibleByAlpha = true;
bool mIsVisibleByPanel = true;
bool mIsInFront = true;
float mLastAlpha = 0f;
bool mMoved = false;
/// <summary>
/// Internal usage -- draw call that's drawing the widget.
/// </summary>
[HideInInspector][System.NonSerialized] public UIDrawCall drawCall;
protected Vector3[] mCorners = new Vector3[4];
/// <summary>
/// Draw region alters how the widget looks without modifying the widget's rectangle.
/// A region is made up of 4 relative values (0-1 range). The order is Left (X), Bottom (Y), Right (Z) and Top (W).
/// To have a widget's left edge be 30% from the left side, set X to 0.3. To have the widget's right edge be 30%
/// from the right hand side, set Z to 0.7.
/// </summary>
public Vector4 drawRegion
{
get
{
return mDrawRegion;
}
set
{
if (mDrawRegion != value)
{
mDrawRegion = value;
if (autoResizeBoxCollider) ResizeCollider();
MarkAsChanged();
}
}
}
/// <summary>
/// Pivot offset in relative coordinates. Bottom-left is (0, 0). Top-right is (1, 1).
/// </summary>
public Vector2 pivotOffset { get { return NGUIMath.GetPivotOffset(pivot); } }
/// <summary>
/// Widget's width in pixels.
/// </summary>
public int width
{
get
{
return mWidth;
}
set
{
int min = minWidth;
if (value < min) value = min;
if (mWidth != value && keepAspectRatio != AspectRatioSource.BasedOnHeight)
{
if (isAnchoredHorizontally)
{
if (leftAnchor.target != null && rightAnchor.target != null)
{
if (mPivot == Pivot.BottomLeft || mPivot == Pivot.Left || mPivot == Pivot.TopLeft)
{
NGUIMath.AdjustWidget(this, 0f, 0f, value - mWidth, 0f);
}
else if (mPivot == Pivot.BottomRight || mPivot == Pivot.Right || mPivot == Pivot.TopRight)
{
NGUIMath.AdjustWidget(this, mWidth - value, 0f, 0f, 0f);
}
else
{
int diff = value - mWidth;
diff = diff - (diff & 1);
if (diff != 0) NGUIMath.AdjustWidget(this, -diff * 0.5f, 0f, diff * 0.5f, 0f);
}
}
else if (leftAnchor.target != null)
{
NGUIMath.AdjustWidget(this, 0f, 0f, value - mWidth, 0f);
}
else NGUIMath.AdjustWidget(this, mWidth - value, 0f, 0f, 0f);
}
else SetDimensions(value, mHeight);
}
}
}
/// <summary>
/// Widget's height in pixels.
/// </summary>
public int height
{
get
{
return mHeight;
}
set
{
int min = minHeight;
if (value < min) value = min;
if (mHeight != value && keepAspectRatio != AspectRatioSource.BasedOnWidth)
{
if (isAnchoredVertically)
{
if (bottomAnchor.target != null && topAnchor.target != null)
{
if (mPivot == Pivot.BottomLeft || mPivot == Pivot.Bottom || mPivot == Pivot.BottomRight)
{
NGUIMath.AdjustWidget(this, 0f, 0f, 0f, value - mHeight);
}
else if (mPivot == Pivot.TopLeft || mPivot == Pivot.Top || mPivot == Pivot.TopRight)
{
NGUIMath.AdjustWidget(this, 0f, mHeight - value, 0f, 0f);
}
else
{
int diff = value - mHeight;
diff = diff - (diff & 1);
if (diff != 0) NGUIMath.AdjustWidget(this, 0f, -diff * 0.5f, 0f, diff * 0.5f);
}
}
else if (bottomAnchor.target != null)
{
NGUIMath.AdjustWidget(this, 0f, 0f, 0f, value - mHeight);
}
else NGUIMath.AdjustWidget(this, 0f, mHeight - value, 0f, 0f);
}
else SetDimensions(mWidth, value);
}
}
}
/// <summary>
/// Color used by the widget.
/// </summary>
public Color color
{
get
{
return mColor;
}
set
{
if (mColor != value)
{
bool alphaChange = (mColor.a != value.a);
mColor = value;
Invalidate(alphaChange);
}
}
}
/// <summary>
/// Widget's alpha -- a convenience method.
/// </summary>
public override float alpha
{
get
{
return mColor.a;
}
set
{
if (mColor.a != value)
{
mColor.a = value;
Invalidate(true);
}
}
}
/// <summary>
/// Whether the widget is currently visible.
/// </summary>
public bool isVisible { get { return mIsVisibleByPanel && mIsVisibleByAlpha && mIsInFront && finalAlpha > 0.001f && NGUITools.GetActive(this); } }
/// <summary>
/// Whether the widget has vertices to draw.
/// </summary>
public bool hasVertices { get { return geometry != null && geometry.hasVertices; } }
/// <summary>
/// Change the pivot point and do not attempt to keep the widget in the same place by adjusting its transform.
/// </summary>
public Pivot rawPivot
{
get
{
return mPivot;
}
set
{
if (mPivot != value)
{
mPivot = value;
if (autoResizeBoxCollider) ResizeCollider();
MarkAsChanged();
}
}
}
/// <summary>
/// Set or get the value that specifies where the widget's pivot point should be.
/// </summary>
public Pivot pivot
{
get
{
return mPivot;
}
set
{
if (mPivot != value)
{
Vector3 before = worldCorners[0];
mPivot = value;
mChanged = true;
Vector3 after = worldCorners[0];
Transform t = cachedTransform;
Vector3 pos = t.position;
float z = t.localPosition.z;
pos.x += (before.x - after.x);
pos.y += (before.y - after.y);
cachedTransform.position = pos;
pos = cachedTransform.localPosition;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = z;
cachedTransform.localPosition = pos;
}
}
}
/// <summary>
/// Depth controls the rendering order -- lowest to highest.
/// </summary>
public int depth
{
get
{
return mDepth;
}
set
{
if (mDepth != value)
{
if (panel != null) panel.RemoveWidget(this);
mDepth = value;
if (panel != null)
{
panel.AddWidget(this);
if (!Application.isPlaying)
{
panel.SortWidgets();
panel.RebuildAllDrawCalls();
}
}
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
}
/// <summary>
/// Raycast depth order on widgets takes the depth of their panel into consideration.
/// This functionality is used to determine the "final" depth of the widget for drawing and raycasts.
/// </summary>
public int raycastDepth
{
get
{
if (panel == null) CreatePanel();
return (panel != null) ? mDepth + panel.depth * 1000 : mDepth;
}
}
/// <summary>
/// Local space corners of the widget. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
public override Vector3[] localCorners
{
get
{
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
mCorners[0] = new Vector3(x0, y0);
mCorners[1] = new Vector3(x0, y1);
mCorners[2] = new Vector3(x1, y1);
mCorners[3] = new Vector3(x1, y0);
return mCorners;
}
}
/// <summary>
/// Local width and height of the widget in pixels.
/// </summary>
public virtual Vector2 localSize
{
get
{
Vector3[] cr = localCorners;
return cr[2] - cr[0];
}
}
/// <summary>
/// World-space corners of the widget. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
public override Vector3[] worldCorners
{
get
{
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
Transform wt = cachedTransform;
mCorners[0] = wt.TransformPoint(x0, y0, 0f);
mCorners[1] = wt.TransformPoint(x0, y1, 0f);
mCorners[2] = wt.TransformPoint(x1, y1, 0f);
mCorners[3] = wt.TransformPoint(x1, y0, 0f);
return mCorners;
}
}
/// <summary>
/// Local space region where the actual drawing will take place.
/// X = left, Y = bottom, Z = right, W = top.
/// </summary>
public virtual Vector4 drawingDimensions
{
get
{
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
return new Vector4(
mDrawRegion.x == 0f ? x0 : Mathf.Lerp(x0, x1, mDrawRegion.x),
mDrawRegion.y == 0f ? y0 : Mathf.Lerp(y0, y1, mDrawRegion.y),
mDrawRegion.z == 1f ? x1 : Mathf.Lerp(x0, x1, mDrawRegion.z),
mDrawRegion.w == 1f ? y1 : Mathf.Lerp(y0, y1, mDrawRegion.w));
}
}
/// <summary>
/// Material used by the widget.
/// </summary>
public virtual Material material
{
get
{
return null;
}
set
{
throw new System.NotImplementedException(GetType() + " has no material setter");
}
}
/// <summary>
/// Texture used by the widget.
/// </summary>
public virtual Texture mainTexture
{
get
{
Material mat = material;
return (mat != null) ? mat.mainTexture : null;
}
set
{
throw new System.NotImplementedException(GetType() + " has no mainTexture setter");
}
}
/// <summary>
/// Shader is used to create a dynamic material if the widget has no material to work with.
/// </summary>
public virtual Shader shader
{
get
{
Material mat = material;
return (mat != null) ? mat.shader : null;
}
set
{
throw new System.NotImplementedException(GetType() + " has no shader setter");
}
}
/// <summary>
/// Do not use this, it's obsolete.
/// </summary>
[System.Obsolete("There is no relative scale anymore. Widgets now have width and height instead")]
public Vector2 relativeSize { get { return Vector2.one; } }
/// <summary>
/// Convenience function that returns 'true' if the widget has a box collider.
/// </summary>
public bool hasBoxCollider
{
get
{
BoxCollider box = collider as BoxCollider;
return (box != null);
}
}
/// <summary>
/// Adjust the widget's dimensions without going through the anchor validation logic.
/// </summary>
public void SetDimensions (int w, int h)
{
if (mWidth != w || mHeight != h)
{
mWidth = w;
mHeight = h;
if (keepAspectRatio == AspectRatioSource.BasedOnWidth)
mHeight = Mathf.RoundToInt(mWidth / aspectRatio);
else if (keepAspectRatio == AspectRatioSource.BasedOnHeight)
mWidth = Mathf.RoundToInt(mHeight * aspectRatio);
else if (keepAspectRatio == AspectRatioSource.Free)
aspectRatio = mWidth / (float)mHeight;
mMoved = true;
if (autoResizeBoxCollider) ResizeCollider();
MarkAsChanged();
}
}
/// <summary>
/// Get the sides of the rectangle relative to the specified transform.
/// The order is left, top, right, bottom.
/// </summary>
public override Vector3[] GetSides (Transform relativeTo)
{
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
float cx = (x0 + x1) * 0.5f;
float cy = (y0 + y1) * 0.5f;
Transform trans = cachedTransform;
mCorners[0] = trans.TransformPoint(x0, cy, 0f);
mCorners[1] = trans.TransformPoint(cx, y1, 0f);
mCorners[2] = trans.TransformPoint(x1, cy, 0f);
mCorners[3] = trans.TransformPoint(cx, y0, 0f);
if (relativeTo != null)
{
for (int i = 0; i < 4; ++i)
mCorners[i] = relativeTo.InverseTransformPoint(mCorners[i]);
}
return mCorners;
}
int mAlphaFrameID = -1;
/// <summary>
/// Widget's final alpha, after taking the panel's alpha into account.
/// </summary>
public override float CalculateFinalAlpha (int frameID)
{
if (mAlphaFrameID != frameID)
{
mAlphaFrameID = frameID;
UpdateFinalAlpha(frameID);
}
return finalAlpha;
}
/// <summary>
/// Force-calculate the final alpha value.
/// </summary>
protected void UpdateFinalAlpha (int frameID)
{
if (!mIsVisibleByAlpha || !mIsInFront)
{
finalAlpha = 0f;
}
else
{
UIRect pt = parent;
finalAlpha = (parent != null) ? pt.CalculateFinalAlpha(frameID) * mColor.a : mColor.a;
}
}
/// <summary>
/// Update the widget's visibility and final alpha.
/// </summary>
public override void Invalidate (bool includeChildren)
{
mChanged = true;
mAlphaFrameID = -1;
if (panel != null)
{
bool vis = (hideIfOffScreen || panel.hasCumulativeClipping) ? panel.IsVisible(this) : true;
UpdateVisibility(CalculateCumulativeAlpha(Time.frameCount) > 0.001f, vis);
UpdateFinalAlpha(Time.frameCount);
if (includeChildren) base.Invalidate(true);
}
}
/// <summary>
/// Same as final alpha, except it doesn't take own visibility into consideration. Used by panels.
/// </summary>
public float CalculateCumulativeAlpha (int frameID)
{
UIRect pt = parent;
return (pt != null) ? pt.CalculateFinalAlpha(frameID) * mColor.a : mColor.a;
}
/// <summary>
/// Set the widget's rectangle.
/// </summary>
public override void SetRect (float x, float y, float width, float height)
{
Vector2 po = pivotOffset;
float fx = Mathf.Lerp(x, x + width, po.x);
float fy = Mathf.Lerp(y, y + height, po.y);
int finalWidth = Mathf.FloorToInt(width + 0.5f);
int finalHeight = Mathf.FloorToInt(height + 0.5f);
if (po.x == 0.5f) finalWidth = ((finalWidth >> 1) << 1);
if (po.y == 0.5f) finalHeight = ((finalHeight >> 1) << 1);
Transform t = cachedTransform;
Vector3 pos = t.localPosition;
pos.x = Mathf.Floor(fx + 0.5f);
pos.y = Mathf.Floor(fy + 0.5f);
if (finalWidth < minWidth) finalWidth = minWidth;
if (finalHeight < minHeight) finalHeight = minHeight;
t.localPosition = pos;
this.width = finalWidth;
this.height = finalHeight;
if (isAnchored)
{
t = t.parent;
if (leftAnchor.target) leftAnchor.SetHorizontal(t, x);
if (rightAnchor.target) rightAnchor.SetHorizontal(t, x + width);
if (bottomAnchor.target) bottomAnchor.SetVertical(t, y);
if (topAnchor.target) topAnchor.SetVertical(t, y + height);
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
}
/// <summary>
/// Adjust the widget's collider size to match the widget's dimensions.
/// </summary>
public void ResizeCollider ()
{
if (NGUITools.GetActive(this))
{
BoxCollider box = collider as BoxCollider;
if (box != null) NGUITools.UpdateWidgetCollider(box, true);
}
}
/// <summary>
/// Static widget comparison function used for depth sorting.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public int FullCompareFunc (UIWidget left, UIWidget right)
{
int val = UIPanel.CompareFunc(left.panel, right.panel);
return (val == 0) ? PanelCompareFunc(left, right) : val;
}
/// <summary>
/// Static widget comparison function used for inter-panel depth sorting.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public int PanelCompareFunc (UIWidget left, UIWidget right)
{
if (left.mDepth < right.mDepth) return -1;
if (left.mDepth > right.mDepth) return 1;
Material leftMat = left.material;
Material rightMat = right.material;
if (leftMat == rightMat) return 0;
if (leftMat != null) return -1;
if (rightMat != null) return 1;
return (leftMat.GetInstanceID() < rightMat.GetInstanceID()) ? -1 : 1;
}
/// <summary>
/// Calculate the widget's bounds, optionally making them relative to the specified transform.
/// </summary>
public Bounds CalculateBounds () { return CalculateBounds(null); }
/// <summary>
/// Calculate the widget's bounds, optionally making them relative to the specified transform.
/// </summary>
public Bounds CalculateBounds (Transform relativeParent)
{
if (relativeParent == null)
{
Vector3[] corners = localCorners;
Bounds b = new Bounds(corners[0], Vector3.zero);
for (int j = 1; j < 4; ++j) b.Encapsulate(corners[j]);
return b;
}
else
{
Matrix4x4 toLocal = relativeParent.worldToLocalMatrix;
Vector3[] corners = worldCorners;
Bounds b = new Bounds(toLocal.MultiplyPoint3x4(corners[0]), Vector3.zero);
for (int j = 1; j < 4; ++j) b.Encapsulate(toLocal.MultiplyPoint3x4(corners[j]));
return b;
}
}
/// <summary>
/// Mark the widget as changed so that the geometry can be rebuilt.
/// </summary>
public void SetDirty ()
{
if (drawCall != null)
{
drawCall.isDirty = true;
}
else if (isVisible && hasVertices)
{
CreatePanel();
}
}
/// <summary>
/// Remove this widget from the panel.
/// </summary>
protected void RemoveFromPanel ()
{
if (panel != null)
{
panel.RemoveWidget(this);
panel = null;
}
#if UNITY_EDITOR
mOldTex = null;
mOldShader = null;
#endif
}
#if UNITY_EDITOR
Texture mOldTex;
Shader mOldShader;
/// <summary>
/// This callback is sent inside the editor notifying us that some property has changed.
/// </summary>
protected override void OnValidate()
{
if (NGUITools.GetActive(this))
{
base.OnValidate();
// Prior to NGUI 2.7.0 width and height was specified as transform's local scale
if ((mWidth == 100 || mWidth == minWidth) &&
(mHeight == 100 || mHeight == minHeight) && cachedTransform.localScale.magnitude > 8f)
{
UpgradeFrom265();
cachedTransform.localScale = Vector3.one;
}
if (mWidth < minWidth) mWidth = minWidth;
if (mHeight < minHeight) mHeight = minHeight;
if (autoResizeBoxCollider) ResizeCollider();
// If the texture is changing, we need to make sure to rebuild the draw calls
if (mOldTex != mainTexture || mOldShader != shader)
{
mOldTex = mainTexture;
mOldShader = shader;
}
if (panel != null)
{
panel.RemoveWidget(this);
panel = null;
}
aspectRatio = (keepAspectRatio == AspectRatioSource.Free) ?
(float)mWidth / mHeight : Mathf.Max(0.01f, aspectRatio);
if (keepAspectRatio == AspectRatioSource.BasedOnHeight)
{
mWidth = Mathf.RoundToInt(mHeight * aspectRatio);
}
else if (keepAspectRatio == AspectRatioSource.BasedOnWidth)
{
mHeight = Mathf.RoundToInt(mWidth / aspectRatio);
}
CreatePanel();
}
else
{
if (mWidth < minWidth) mWidth = minWidth;
if (mHeight < minHeight) mHeight = minHeight;
}
}
#endif
/// <summary>
/// Tell the panel responsible for the widget that something has changed and the buffers need to be rebuilt.
/// </summary>
public virtual void MarkAsChanged ()
{
if (NGUITools.GetActive(this))
{
mChanged = true;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
// If we're in the editor, update the panel right away so its geometry gets updated.
if (panel != null && enabled && NGUITools.GetActive(gameObject) && !mPlayMode)
{
SetDirty();
CheckLayer();
#if UNITY_EDITOR
// Mark the panel as dirty so it gets updated
if (material != null) NGUITools.SetDirty(panel.gameObject);
#endif
}
}
}
/// <summary>
/// Ensure we have a panel referencing this widget.
/// </summary>
public UIPanel CreatePanel ()
{
if (mStarted && panel == null && enabled && NGUITools.GetActive(gameObject))
{
panel = UIPanel.Find(cachedTransform, true, cachedGameObject.layer);
if (panel != null)
{
mParentFound = false;
panel.AddWidget(this);
CheckLayer();
Invalidate(true);
}
}
return panel;
}
/// <summary>
/// Check to ensure that the widget resides on the same layer as its panel.
/// </summary>
public void CheckLayer ()
{
if (panel != null && panel.gameObject.layer != gameObject.layer)
{
Debug.LogWarning("You can't place widgets on a layer different than the UIPanel that manages them.\n" +
"If you want to move widgets to a different layer, parent them to a new panel instead.", this);
gameObject.layer = panel.gameObject.layer;
}
}
/// <summary>
/// Checks to ensure that the widget is still parented to the right panel.
/// </summary>
public override void ParentHasChanged ()
{
base.ParentHasChanged();
if (panel != null)
{
UIPanel p = UIPanel.Find(cachedTransform, true, cachedGameObject.layer);
if (panel != p)
{
RemoveFromPanel();
CreatePanel();
}
}
}
/// <summary>
/// Remember whether we're in play mode.
/// </summary>
protected virtual void Awake ()
{
mGo = gameObject;
mPlayMode = Application.isPlaying;
}
/// <summary>
/// Mark the widget and the panel as having been changed.
/// </summary>
protected override void OnInit ()
{
base.OnInit();
RemoveFromPanel();
mMoved = true;
// Prior to NGUI 2.7.0 width and height was specified as transform's local scale
if (mWidth == 100 && mHeight == 100 && cachedTransform.localScale.magnitude > 8f)
{
UpgradeFrom265();
cachedTransform.localScale = Vector3.one;
#if UNITY_EDITOR
NGUITools.SetDirty(this);
#endif
}
Update();
}
/// <summary>
/// Facilitates upgrading from NGUI 2.6.5 or earlier versions.
/// </summary>
protected virtual void UpgradeFrom265 ()
{
Vector3 scale = cachedTransform.localScale;
mWidth = Mathf.Abs(Mathf.RoundToInt(scale.x));
mHeight = Mathf.Abs(Mathf.RoundToInt(scale.y));
if (GetComponent<BoxCollider>() != null)
NGUITools.AddWidgetCollider(gameObject, true);
}
/// <summary>
/// Virtual Start() functionality for widgets.
/// </summary>
protected override void OnStart () { CreatePanel(); }
/// <summary>
/// Update the anchored edges and ensure the widget is registered with a panel.
/// </summary>
protected override void OnAnchor ()
{
float lt, bt, rt, tt;
Transform trans = cachedTransform;
Transform parent = trans.parent;
Vector3 pos = trans.localPosition;
Vector2 pvt = pivotOffset;
// Attempt to fast-path if all anchors match
if (leftAnchor.target == bottomAnchor.target &&
leftAnchor.target == rightAnchor.target &&
leftAnchor.target == topAnchor.target)
{
Vector3[] sides = leftAnchor.GetSides(parent);
if (sides != null)
{
lt = NGUIMath.Lerp(sides[0].x, sides[2].x, leftAnchor.relative) + leftAnchor.absolute;
rt = NGUIMath.Lerp(sides[0].x, sides[2].x, rightAnchor.relative) + rightAnchor.absolute;
bt = NGUIMath.Lerp(sides[3].y, sides[1].y, bottomAnchor.relative) + bottomAnchor.absolute;
tt = NGUIMath.Lerp(sides[3].y, sides[1].y, topAnchor.relative) + topAnchor.absolute;
mIsInFront = true;
}
else
{
// Anchored to a single transform
Vector3 lp = GetLocalPos(leftAnchor, parent);
lt = lp.x + leftAnchor.absolute;
bt = lp.y + bottomAnchor.absolute;
rt = lp.x + rightAnchor.absolute;
tt = lp.y + topAnchor.absolute;
mIsInFront = (!hideIfOffScreen || lp.z >= 0f);
}
}
else
{
mIsInFront = true;
// Left anchor point
if (leftAnchor.target)
{
Vector3[] sides = leftAnchor.GetSides(parent);
if (sides != null)
{
lt = NGUIMath.Lerp(sides[0].x, sides[2].x, leftAnchor.relative) + leftAnchor.absolute;
}
else
{
lt = GetLocalPos(leftAnchor, parent).x + leftAnchor.absolute;
}
}
else lt = pos.x - pvt.x * mWidth;
// Right anchor point
if (rightAnchor.target)
{
Vector3[] sides = rightAnchor.GetSides(parent);
if (sides != null)
{
rt = NGUIMath.Lerp(sides[0].x, sides[2].x, rightAnchor.relative) + rightAnchor.absolute;
}
else
{
rt = GetLocalPos(rightAnchor, parent).x + rightAnchor.absolute;
}
}
else rt = pos.x - pvt.x * mWidth + mWidth;
// Bottom anchor point
if (bottomAnchor.target)
{
Vector3[] sides = bottomAnchor.GetSides(parent);
if (sides != null)
{
bt = NGUIMath.Lerp(sides[3].y, sides[1].y, bottomAnchor.relative) + bottomAnchor.absolute;
}
else
{
bt = GetLocalPos(bottomAnchor, parent).y + bottomAnchor.absolute;
}
}
else bt = pos.y - pvt.y * mHeight;
// Top anchor point
if (topAnchor.target)
{
Vector3[] sides = topAnchor.GetSides(parent);
if (sides != null)
{
tt = NGUIMath.Lerp(sides[3].y, sides[1].y, topAnchor.relative) + topAnchor.absolute;
}
else
{
tt = GetLocalPos(topAnchor, parent).y + topAnchor.absolute;
}
}
else tt = pos.y - pvt.y * mHeight + mHeight;
}
// Calculate the new position, width and height
Vector3 newPos = new Vector3(Mathf.Lerp(lt, rt, pvt.x), Mathf.Lerp(bt, tt, pvt.y), pos.z);
int w = Mathf.FloorToInt(rt - lt + 0.5f);
int h = Mathf.FloorToInt(tt - bt + 0.5f);
// Maintain the aspect ratio if requested and possible
if (keepAspectRatio != AspectRatioSource.Free && aspectRatio != 0f)
{
if (keepAspectRatio == AspectRatioSource.BasedOnHeight)
{
w = Mathf.RoundToInt(h * aspectRatio);
}
else h = Mathf.RoundToInt(w / aspectRatio);
}
// Don't let the width and height get too small
if (w < minWidth) w = minWidth;
if (h < minHeight) h = minHeight;
// Update the position if it has changed
if (Vector3.SqrMagnitude(pos - newPos) > 0.001f)
{
cachedTransform.localPosition = newPos;
if (mIsInFront) mChanged = true;
}
// Update the width and height if it has changed
if (mWidth != w || mHeight != h)
{
mWidth = w;
mHeight = h;
if (mIsInFront) mChanged = true;
if (autoResizeBoxCollider) ResizeCollider();
}
}
/// <summary>
/// Ensure we have a panel to work with.
/// </summary>
protected override void OnUpdate ()
{
if (panel == null) CreatePanel();
#if UNITY_EDITOR
else if (!mPlayMode) ParentHasChanged();
#endif
}
#if !UNITY_EDITOR
/// <summary>
/// Mark the UI as changed when returning from paused state.
/// </summary>
void OnApplicationPause (bool paused) { if (!paused) MarkAsChanged(); }
#endif
/// <summary>
/// Clear references.
/// </summary>
protected override void OnDisable ()
{
RemoveFromPanel();
base.OnDisable();
}
/// <summary>
/// Unregister this widget.
/// </summary>
void OnDestroy () { RemoveFromPanel(); }
#if UNITY_EDITOR
static int mHandles = -1;
/// <summary>
/// Whether widgets will show handles with the Move Tool, or just the View Tool.
/// </summary>
static public bool showHandlesWithMoveTool
{
get
{
if (mHandles == -1)
{
mHandles = UnityEditor.EditorPrefs.GetInt("NGUI Handles", 1);
}
return (mHandles == 1);
}
set
{
int val = value ? 1 : 0;
if (mHandles != val)
{
mHandles = val;
UnityEditor.EditorPrefs.SetInt("NGUI Handles", mHandles);
}
}
}
/// <summary>
/// Whether the widget should have some form of handles shown.
/// </summary>
static public bool showHandles
{
get
{
if (showHandlesWithMoveTool)
{
return UnityEditor.Tools.current == UnityEditor.Tool.Move;
}
return UnityEditor.Tools.current == UnityEditor.Tool.View;
}
}
/// <summary>
/// Draw some selectable gizmos.
/// </summary>
void OnDrawGizmos ()
{
if (isVisible && NGUITools.GetActive(this))
{
if (UnityEditor.Selection.activeGameObject == gameObject && showHandles) return;
Color outline = new Color(1f, 1f, 1f, 0.2f);
float adjustment = (root != null) ? 0.05f : 0.001f;
Vector2 offset = pivotOffset;
Vector3 center = new Vector3(mWidth * (0.5f - offset.x), mHeight * (0.5f - offset.y), -mDepth * adjustment);
Vector3 size = new Vector3(mWidth, mHeight, 1f);
// Draw the gizmo
Gizmos.matrix = cachedTransform.localToWorldMatrix;
Gizmos.color = (UnityEditor.Selection.activeGameObject == cachedTransform) ? Color.white : outline;
Gizmos.DrawWireCube(center, size);
// Make the widget selectable
size.z = 0.01f;
Gizmos.color = Color.clear;
Gizmos.DrawCube(center, size);
}
}
#endif // UNITY_EDITOR
/// <summary>
/// Update the widget's visibility state.
/// </summary>
public bool UpdateVisibility (bool visibleByAlpha, bool visibleByPanel)
{
if (mIsVisibleByAlpha != visibleByAlpha || mIsVisibleByPanel != visibleByPanel)
{
mChanged = true;
mIsVisibleByAlpha = visibleByAlpha;
mIsVisibleByPanel = visibleByPanel;
return true;
}
return false;
}
int mMatrixFrame = -1;
Vector3 mOldV0;
Vector3 mOldV1;
/// <summary>
/// Check to see if the widget has moved relative to the panel that manages it
/// </summary>
public bool UpdateTransform (int frame)
{
#if UNITY_EDITOR
if (!mMoved && !panel.widgetsAreStatic || !mPlayMode)
#else
if (!mMoved && !panel.widgetsAreStatic)
#endif
{
#if UNITY_3_5 || UNITY_4_0
if (HasTransformChanged())
{
#else
if (cachedTransform.hasChanged)
{
mTrans.hasChanged = false;
#endif
mLocalToPanel = panel.worldToLocal * cachedTransform.localToWorldMatrix;
mMatrixFrame = frame;
Vector2 offset = pivotOffset;
float x0 = -offset.x * mWidth;
float y0 = -offset.y * mHeight;
float x1 = x0 + mWidth;
float y1 = y0 + mHeight;
Transform wt = cachedTransform;
Vector3 v0 = wt.TransformPoint(x0, y0, 0f);
Vector3 v1 = wt.TransformPoint(x1, y1, 0f);
v0 = panel.worldToLocal.MultiplyPoint3x4(v0);
v1 = panel.worldToLocal.MultiplyPoint3x4(v1);
if (Vector3.SqrMagnitude(mOldV0 - v0) > 0.000001f ||
Vector3.SqrMagnitude(mOldV1 - v1) > 0.000001f)
{
mMoved = true;
mOldV0 = v0;
mOldV1 = v1;
}
}
}
// Notify the listeners
if (mMoved && onChange != null) onChange();
return mMoved || mChanged;
}
#if UNITY_3_5 || UNITY_4_0
Vector3 mOldPos;
Quaternion mOldRot;
Vector3 mOldScale;
/// <summary>
/// Whether the transform has changed since the last time it was checked.
/// </summary>
bool HasTransformChanged ()
{
Transform t = cachedTransform;
if (t.position != mOldPos || t.rotation != mOldRot || t.lossyScale != mOldScale)
{
mOldPos = t.position;
mOldRot = t.rotation;
mOldScale = t.lossyScale;
return true;
}
return false;
}
#endif
/// <summary>
/// Update the widget and fill its geometry if necessary. Returns whether something was changed.
/// </summary>
public bool UpdateGeometry (int frame)
{
// Has the alpha changed?
float finalAlpha = CalculateFinalAlpha(frame);
if (mIsVisibleByAlpha && mLastAlpha != finalAlpha) mChanged = true;
mLastAlpha = finalAlpha;
if (mChanged)
{
mChanged = false;
if (mIsVisibleByAlpha && finalAlpha > 0.001f && shader != null)
{
bool hadVertices = geometry.hasVertices;
if (fillGeometry)
{
geometry.Clear();
OnFill(geometry.verts, geometry.uvs, geometry.cols);
}
if (geometry.hasVertices)
{
// Want to see what's being filled? Uncomment this line.
//Debug.Log("Fill " + name + " (" + Time.time + ")");
if (mMatrixFrame != frame)
{
mLocalToPanel = panel.worldToLocal * cachedTransform.localToWorldMatrix;
mMatrixFrame = frame;
}
geometry.ApplyTransform(mLocalToPanel);
mMoved = false;
return true;
}
return hadVertices;
}
else if (geometry.hasVertices)
{
if (fillGeometry) geometry.Clear();
mMoved = false;
return true;
}
}
else if (mMoved && geometry.hasVertices)
{
if (mMatrixFrame != frame)
{
mLocalToPanel = panel.worldToLocal * cachedTransform.localToWorldMatrix;
mMatrixFrame = frame;
}
geometry.ApplyTransform(mLocalToPanel);
mMoved = false;
return true;
}
mMoved = false;
return false;
}
/// <summary>
/// Append the local geometry buffers to the specified ones.
/// </summary>
public void WriteToBuffers (BetterList<Vector3> v, BetterList<Vector2> u, BetterList<Color32> c, BetterList<Vector3> n, BetterList<Vector4> t)
{
geometry.WriteToBuffers(v, u, c, n, t);
}
/// <summary>
/// Make the widget pixel-perfect.
/// </summary>
virtual public void MakePixelPerfect ()
{
Vector3 pos = cachedTransform.localPosition;
pos.z = Mathf.Round(pos.z);
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
cachedTransform.localPosition = pos;
Vector3 ls = cachedTransform.localScale;
cachedTransform.localScale = new Vector3(Mathf.Sign(ls.x), Mathf.Sign(ls.y), 1f);
}
/// <summary>
/// Minimum allowed width for this widget.
/// </summary>
virtual public int minWidth { get { return 2; } }
/// <summary>
/// Minimum allowed height for this widget.
/// </summary>
virtual public int minHeight { get { return 2; } }
/// <summary>
/// Dimensions of the sprite's border, if any.
/// </summary>
virtual public Vector4 border { get { return Vector4.zero; } }
/// <summary>
/// Virtual function called by the UIPanel that fills the buffers.
/// </summary>
virtual public void OnFill(BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols) { }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/UIWidget.cs
|
C#
|
asf20
| 34,907
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
using System.Diagnostics;
/// <summary>
/// This improved version of the System.Collections.Generic.List that doesn't release the buffer on Clear(), resulting in better performance and less garbage collection.
/// </summary>
public class BetterList<T>
{
#if UNITY_FLASH
List<T> mList = new List<T>();
/// <summary>
/// Direct access to the buffer. Note that you should not use its 'Length' parameter, but instead use BetterList.size.
/// </summary>
public T this[int i]
{
get { return mList[i]; }
set { mList[i] = value; }
}
/// <summary>
/// Compatibility with the non-flash syntax.
/// </summary>
public List<T> buffer { get { return mList; } }
/// <summary>
/// Direct access to the buffer's size. Note that it's only public for speed and efficiency. You shouldn't modify it.
/// </summary>
public int size { get { return mList.Count; } }
/// <summary>
/// For 'foreach' functionality.
/// </summary>
public IEnumerator<T> GetEnumerator () { return mList.GetEnumerator(); }
/// <summary>
/// Clear the array by resetting its size to zero. Note that the memory is not actually released.
/// </summary>
public void Clear () { mList.Clear(); }
/// <summary>
/// Clear the array and release the used memory.
/// </summary>
public void Release () { mList.Clear(); }
/// <summary>
/// Add the specified item to the end of the list.
/// </summary>
public void Add (T item) { mList.Add(item); }
/// <summary>
/// Insert an item at the specified index, pushing the entries back.
/// </summary>
public void Insert (int index, T item) { mList.Insert(index, item); }
/// <summary>
/// Returns 'true' if the specified item is within the list.
/// </summary>
public bool Contains (T item) { return mList.Contains(item); }
/// <summary>
/// Remove the specified item from the list. Note that RemoveAt() is faster and is advisable if you already know the index.
/// </summary>
public bool Remove (T item) { return mList.Remove(item); }
/// <summary>
/// Remove an item at the specified index.
/// </summary>
public void RemoveAt (int index) { mList.RemoveAt(index); }
/// <summary>
/// Remove an item from the end.
/// </summary>
public T Pop ()
{
if (buffer != null && size != 0)
{
T val = buffer[mList.Count - 1];
mList.RemoveAt(mList.Count - 1);
return val;
}
return default(T);
}
/// <summary>
/// Mimic List's ToArray() functionality, except that in this case the list is resized to match the current size.
/// </summary>
public T[] ToArray () { return mList.ToArray(); }
/// <summary>
/// List.Sort equivalent.
/// </summary>
public void Sort (System.Comparison<T> comparer) { mList.Sort(comparer); }
#else
/// <summary>
/// Direct access to the buffer. Note that you should not use its 'Length' parameter, but instead use BetterList.size.
/// </summary>
public T[] buffer;
/// <summary>
/// Direct access to the buffer's size. Note that it's only public for speed and efficiency. You shouldn't modify it.
/// </summary>
public int size = 0;
/// <summary>
/// For 'foreach' functionality.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public IEnumerator<T> GetEnumerator ()
{
if (buffer != null)
{
for (int i = 0; i < size; ++i)
{
yield return buffer[i];
}
}
}
/// <summary>
/// Convenience function. I recommend using .buffer instead.
/// </summary>
[DebuggerHidden]
public T this[int i]
{
get { return buffer[i]; }
set { buffer[i] = value; }
}
/// <summary>
/// Helper function that expands the size of the array, maintaining the content.
/// </summary>
void AllocateMore ()
{
T[] newList = (buffer != null) ? new T[Mathf.Max(buffer.Length << 1, 32)] : new T[32];
if (buffer != null && size > 0) buffer.CopyTo(newList, 0);
buffer = newList;
}
/// <summary>
/// Trim the unnecessary memory, resizing the buffer to be of 'Length' size.
/// Call this function only if you are sure that the buffer won't need to resize anytime soon.
/// </summary>
void Trim ()
{
if (size > 0)
{
if (size < buffer.Length)
{
T[] newList = new T[size];
for (int i = 0; i < size; ++i) newList[i] = buffer[i];
buffer = newList;
}
}
else buffer = null;
}
/// <summary>
/// Clear the array by resetting its size to zero. Note that the memory is not actually released.
/// </summary>
public void Clear () { size = 0; }
/// <summary>
/// Clear the array and release the used memory.
/// </summary>
public void Release () { size = 0; buffer = null; }
/// <summary>
/// Add the specified item to the end of the list.
/// </summary>
public void Add (T item)
{
if (buffer == null || size == buffer.Length) AllocateMore();
buffer[size++] = item;
}
/// <summary>
/// Insert an item at the specified index, pushing the entries back.
/// </summary>
public void Insert (int index, T item)
{
if (buffer == null || size == buffer.Length) AllocateMore();
if (index < size)
{
for (int i = size; i > index; --i) buffer[i] = buffer[i - 1];
buffer[index] = item;
++size;
}
else Add(item);
}
/// <summary>
/// Returns 'true' if the specified item is within the list.
/// </summary>
public bool Contains (T item)
{
if (buffer == null) return false;
for (int i = 0; i < size; ++i) if (buffer[i].Equals(item)) return true;
return false;
}
/// <summary>
/// Remove the specified item from the list. Note that RemoveAt() is faster and is advisable if you already know the index.
/// </summary>
public bool Remove (T item)
{
if (buffer != null)
{
EqualityComparer<T> comp = EqualityComparer<T>.Default;
for (int i = 0; i < size; ++i)
{
if (comp.Equals(buffer[i], item))
{
--size;
buffer[i] = default(T);
for (int b = i; b < size; ++b) buffer[b] = buffer[b + 1];
buffer[size] = default(T);
return true;
}
}
}
return false;
}
/// <summary>
/// Remove an item at the specified index.
/// </summary>
public void RemoveAt (int index)
{
if (buffer != null && index < size)
{
--size;
buffer[index] = default(T);
for (int b = index; b < size; ++b) buffer[b] = buffer[b + 1];
buffer[size] = default(T);
}
}
/// <summary>
/// Remove an item from the end.
/// </summary>
public T Pop ()
{
if (buffer != null && size != 0)
{
T val = buffer[--size];
buffer[size] = default(T);
return val;
}
return default(T);
}
/// <summary>
/// Mimic List's ToArray() functionality, except that in this case the list is resized to match the current size.
/// </summary>
public T[] ToArray () { Trim(); return buffer; }
//class Comparer : System.Collections.IComparer
//{
// public System.Comparison<T> func;
// public int Compare (object x, object y) { return func((T)x, (T)y); }
//}
//Comparer mComp = new Comparer();
/// <summary>
/// List.Sort equivalent. Doing Array.Sort causes GC allocations.
/// </summary>
//public void Sort (System.Comparison<T> comparer)
//{
// if (size > 0)
// {
// mComp.func = comparer;
// System.Array.Sort(buffer, 0, size, mComp);
// }
//}
/// <summary>
/// List.Sort equivalent. Manual sorting causes no GC allocations.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public void Sort (CompareFunc comparer)
{
int start = 0;
int max = size - 1;
bool changed = true;
while (changed)
{
changed = false;
for (int i = start; i < max; ++i)
{
// Compare the two values
if (comparer(buffer[i], buffer[i + 1]) > 0)
{
// Swap the values
T temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
changed = true;
}
else if (!changed)
{
// Nothing has changed -- we can start here next time
start = (i == 0) ? 0 : i - 1;
}
}
}
}
/// <summary>
/// Comparison function should return -1 if left is less than right, 1 if left is greater than right, and 0 if they match.
/// </summary>
public delegate int CompareFunc (T left, T right);
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/BetterList.cs
|
C#
|
asf20
| 8,308
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Text;
using System.Collections.Generic;
/// <summary>
/// MemoryStream.ReadLine has an interesting oddity: it doesn't always advance the stream's position by the correct amount:
/// http://social.msdn.microsoft.com/Forums/en-AU/Vsexpressvcs/thread/b8f7837b-e396-494e-88e1-30547fcf385f
/// Solution? Custom line reader with the added benefit of not having to use streams at all.
/// </summary>
public class ByteReader
{
byte[] mBuffer;
int mOffset = 0;
public ByteReader (byte[] bytes) { mBuffer = bytes; }
public ByteReader (TextAsset asset) { mBuffer = asset.bytes; }
/// <summary>
/// Whether the buffer is readable.
/// </summary>
public bool canRead { get { return (mBuffer != null && mOffset < mBuffer.Length); } }
/// <summary>
/// Read a single line from the buffer.
/// </summary>
static string ReadLine (byte[] buffer, int start, int count)
{
#if UNITY_FLASH
// Encoding.UTF8 is not supported in Flash :(
StringBuilder sb = new StringBuilder();
int max = start + count;
for (int i = start; i < max; ++i)
{
byte byte0 = buffer[i];
if ((byte0 & 128) == 0)
{
// If an UCS fits 7 bits, its coded as 0xxxxxxx. This makes ASCII character represented by themselves
sb.Append((char)byte0);
}
else if ((byte0 & 224) == 192)
{
// If an UCS fits 11 bits, it is coded as 110xxxxx 10xxxxxx
if (++i == count) break;
byte byte1 = buffer[i];
int ch = (byte0 & 31) << 6;
ch |= (byte1 & 63);
sb.Append((char)ch);
}
else if ((byte0 & 240) == 224)
{
// If an UCS fits 16 bits, it is coded as 1110xxxx 10xxxxxx 10xxxxxx
if (++i == count) break;
byte byte1 = buffer[i];
if (++i == count) break;
byte byte2 = buffer[i];
if (byte0 == 0xEF && byte1 == 0xBB && byte2 == 0xBF)
{
// Byte Order Mark -- generally the first 3 bytes in a Windows-saved UTF-8 file. Skip it.
}
else
{
int ch = (byte0 & 15) << 12;
ch |= (byte1 & 63) << 6;
ch |= (byte2 & 63);
sb.Append((char)ch);
}
}
else if ((byte0 & 248) == 240)
{
// If an UCS fits 21 bits, it is coded as 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
if (++i == count) break;
byte byte1 = buffer[i];
if (++i == count) break;
byte byte2 = buffer[i];
if (++i == count) break;
byte byte3 = buffer[i];
int ch = (byte0 & 7) << 18;
ch |= (byte1 & 63) << 12;
ch |= (byte2 & 63) << 6;
ch |= (byte3 & 63);
sb.Append((char)ch);
}
}
return sb.ToString();
#else
return Encoding.UTF8.GetString(buffer, start, count);
#endif
}
/// <summary>
/// Read a single line from the buffer.
/// </summary>
public string ReadLine () { return ReadLine(true); }
/// <summary>
/// Read a single line from the buffer.
/// </summary>
public string ReadLine (bool skipEmptyLines)
{
int max = mBuffer.Length;
// Skip empty characters
if (skipEmptyLines)
{
while (mOffset < max && mBuffer[mOffset] < 32) ++mOffset;
}
int end = mOffset;
if (end < max)
{
for (; ; )
{
if (end < max)
{
int ch = mBuffer[end++];
if (ch != '\n' && ch != '\r') continue;
}
else ++end;
string line = ReadLine(mBuffer, mOffset, end - mOffset - 1);
mOffset = end;
return line;
}
}
mOffset = max;
return null;
}
/// <summary>
/// Assume that the entire file is a collection of key/value pairs.
/// </summary>
public Dictionary<string, string> ReadDictionary ()
{
Dictionary<string, string> dict = new Dictionary<string, string>();
char[] separator = new char[] { '=' };
while (canRead)
{
string line = ReadLine();
if (line == null) break;
if (line.StartsWith("//")) continue;
#if UNITY_FLASH
string[] split = line.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
#else
string[] split = line.Split(separator, 2, System.StringSplitOptions.RemoveEmptyEntries);
#endif
if (split.Length == 2)
{
string key = split[0].Trim();
string val = split[1].Trim().Replace("\\n", "\n");
dict[key] = val;
}
}
return dict;
}
static BetterList<string> mTemp = new BetterList<string>();
/// <summary>
/// Read a single line of Comma-Separated Values from the file.
/// </summary>
public BetterList<string> ReadCSV ()
{
mTemp.Clear();
string line = "";
bool insideQuotes = false;
int wordStart = 0;
while (canRead)
{
if (insideQuotes)
{
string s = ReadLine(false);
if (s == null) return null;
s = s.Replace("\\n", "\n");
line += "\n" + s;
++wordStart;
}
else
{
line = ReadLine(true);
if (line == null) return null;
line = line.Replace("\\n", "\n");
wordStart = 0;
}
for (int i = wordStart, imax = line.Length; i < imax; ++i)
{
char ch = line[i];
if (ch == ',')
{
if (!insideQuotes)
{
mTemp.Add(line.Substring(wordStart, i - wordStart));
wordStart = i + 1;
}
}
else if (ch == '"')
{
if (insideQuotes)
{
if (i + 1 >= imax)
{
mTemp.Add(line.Substring(wordStart, i - wordStart).Replace("\"\"", "\""));
return mTemp;
}
if (line[i + 1] != '"')
{
mTemp.Add(line.Substring(wordStart, i - wordStart));
insideQuotes = false;
if (line[i + 1] == ',')
{
++i;
wordStart = i + 1;
}
}
else ++i;
}
else
{
wordStart = i + 1;
insideQuotes = true;
}
}
}
if (wordStart < line.Length)
{
if (insideQuotes) continue;
mTemp.Add(line.Substring(wordStart, line.Length - wordStart));
}
return mTemp;
}
return null;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/ByteReader.cs
|
C#
|
asf20
| 5,859
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Generated geometry class. All widgets have one.
/// This class separates the geometry creation into several steps, making it possible to perform
/// actions selectively depending on what has changed. For example, the widget doesn't need to be
/// rebuilt unless something actually changes, so its geometry can be cached. Likewise, the widget's
/// transformed coordinates only change if the widget's transform moves relative to the panel,
/// so that can be cached as well. In the end, using this class means using more memory, but at
/// the same time it allows for significant performance gains, especially when using widgets that
/// spit out a lot of vertices, such as UILabels.
/// </summary>
public class UIGeometry
{
/// <summary>
/// Widget's vertices (before they get transformed).
/// </summary>
public BetterList<Vector3> verts = new BetterList<Vector3>();
/// <summary>
/// Widget's texture coordinates for the geometry's vertices.
/// </summary>
public BetterList<Vector2> uvs = new BetterList<Vector2>();
/// <summary>
/// Array of colors for the geometry's vertices.
/// </summary>
public BetterList<Color32> cols = new BetterList<Color32>();
// Relative-to-panel vertices, normal, and tangent
BetterList<Vector3> mRtpVerts = new BetterList<Vector3>();
Vector3 mRtpNormal;
Vector4 mRtpTan;
/// <summary>
/// Whether the geometry contains usable vertices.
/// </summary>
public bool hasVertices { get { return (verts.size > 0); } }
/// <summary>
/// Whether the geometry has usable transformed vertex data.
/// </summary>
public bool hasTransformed { get { return (mRtpVerts != null) && (mRtpVerts.size > 0) && (mRtpVerts.size == verts.size); } }
/// <summary>
/// Step 1: Prepare to fill the buffers -- make them clean and valid.
/// </summary>
public void Clear ()
{
verts.Clear();
uvs.Clear();
cols.Clear();
mRtpVerts.Clear();
}
/// <summary>
/// Step 2: Transform the vertices by the provided matrix.
/// </summary>
public void ApplyTransform (Matrix4x4 widgetToPanel)
{
if (verts.size > 0)
{
mRtpVerts.Clear();
for (int i = 0, imax = verts.size; i < imax; ++i) mRtpVerts.Add(widgetToPanel.MultiplyPoint3x4(verts[i]));
// Calculate the widget's normal and tangent
mRtpNormal = widgetToPanel.MultiplyVector(Vector3.back).normalized;
Vector3 tangent = widgetToPanel.MultiplyVector(Vector3.right).normalized;
mRtpTan = new Vector4(tangent.x, tangent.y, tangent.z, -1f);
}
else mRtpVerts.Clear();
}
/// <summary>
/// Step 3: Fill the specified buffer using the transformed values.
/// </summary>
public void WriteToBuffers (BetterList<Vector3> v, BetterList<Vector2> u, BetterList<Color32> c, BetterList<Vector3> n, BetterList<Vector4> t)
{
if (mRtpVerts != null && mRtpVerts.size > 0)
{
if (n == null)
{
for (int i = 0; i < mRtpVerts.size; ++i)
{
v.Add(mRtpVerts.buffer[i]);
u.Add(uvs.buffer[i]);
c.Add(cols.buffer[i]);
}
}
else
{
for (int i = 0; i < mRtpVerts.size; ++i)
{
v.Add(mRtpVerts.buffer[i]);
u.Add(uvs.buffer[i]);
c.Add(cols.buffer[i]);
n.Add(mRtpNormal);
t.Add(mRtpTan);
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/UIGeometry.cs
|
C#
|
asf20
| 3,445
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Event Hook class lets you easily add remote event listener functions to an object.
/// Example usage: UIEventListener.Get(gameObject).onClick += MyClickFunction;
/// </summary>
[AddComponentMenu("NGUI/Internal/Event Listener")]
public class UIEventListener : MonoBehaviour
{
public delegate void VoidDelegate (GameObject go);
public delegate void BoolDelegate (GameObject go, bool state);
public delegate void FloatDelegate (GameObject go, float delta);
public delegate void VectorDelegate (GameObject go, Vector2 delta);
public delegate void ObjectDelegate (GameObject go, GameObject draggedObject);
public delegate void KeyCodeDelegate (GameObject go, KeyCode key);
public object parameter;
public VoidDelegate onSubmit;
public VoidDelegate onClick;
public VoidDelegate onDoubleClick;
public BoolDelegate onHover;
public BoolDelegate onPress;
public BoolDelegate onSelect;
public FloatDelegate onScroll;
public VectorDelegate onDrag;
public ObjectDelegate onDrop;
public KeyCodeDelegate onKey;
void OnSubmit () { if (onSubmit != null) onSubmit(gameObject); }
void OnClick () { if (onClick != null) onClick(gameObject); }
void OnDoubleClick () { if (onDoubleClick != null) onDoubleClick(gameObject); }
void OnHover (bool isOver) { if (onHover != null) onHover(gameObject, isOver); }
void OnPress (bool isPressed) { if (onPress != null) onPress(gameObject, isPressed); }
void OnSelect (bool selected) { if (onSelect != null) onSelect(gameObject, selected); }
void OnScroll (float delta) { if (onScroll != null) onScroll(gameObject, delta); }
void OnDrag (Vector2 delta) { if (onDrag != null) onDrag(gameObject, delta); }
void OnDrop (GameObject go) { if (onDrop != null) onDrop(gameObject, go); }
void OnKey (KeyCode key) { if (onKey != null) onKey(gameObject, key); }
/// <summary>
/// Get or add an event listener to the specified game object.
/// </summary>
static public UIEventListener Get (GameObject go)
{
UIEventListener listener = go.GetComponent<UIEventListener>();
if (listener == null) listener = go.AddComponent<UIEventListener>();
return listener;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/UIEventListener.cs
|
C#
|
asf20
| 2,350
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif
using UnityEngine;
using System.Text;
/// <summary>
/// Helper class containing functionality related to using dynamic fonts.
/// </summary>
static public class NGUIText
{
public enum Alignment
{
Automatic,
Left,
Center,
Right,
Justified,
}
public enum SymbolStyle
{
None,
Normal,
Colored,
}
public class GlyphInfo
{
public Vector2 v0;
public Vector2 v1;
public Vector2 u0;
public Vector2 u1;
public float advance = 0f;
public int channel = 0;
public bool rotatedUVs = false;
}
/// <summary>
/// When printing text, a lot of additional data must be passed in. In order to save allocations,
/// this data is not passed at all, but is rather set in a single place before calling the functions that use it.
/// </summary>
static public UIFont bitmapFont;
#if DYNAMIC_FONT
static public Font dynamicFont;
#endif
static public GlyphInfo glyph = new GlyphInfo();
static public int fontSize = 16;
static public float fontScale = 1f;
static public float pixelDensity = 1f;
static public FontStyle fontStyle = FontStyle.Normal;
static public Alignment alignment = Alignment.Left;
static public Color tint = Color.white;
static public int rectWidth = 1000000;
static public int rectHeight = 1000000;
static public int maxLines = 0;
static public bool gradient = false;
static public Color gradientBottom = Color.white;
static public Color gradientTop = Color.white;
static public bool encoding = false;
static public float spacingX = 0f;
static public float spacingY = 0f;
static public bool premultiply = false;
static public SymbolStyle symbolStyle;
static public int finalSize = 0;
static public float finalSpacingX = 0f;
static public float finalLineHeight = 0f;
static public float baseline = 0f;
static public bool useSymbols = false;
/// <summary>
/// Recalculate the 'final' values.
/// </summary>
static public void Update () { Update(true); }
/// <summary>
/// Recalculate the 'final' values.
/// </summary>
static public void Update (bool request)
{
finalSize = Mathf.RoundToInt(fontSize / pixelDensity);
finalSpacingX = spacingX * fontScale;
finalLineHeight = (fontSize + spacingY) * fontScale;
useSymbols = (bitmapFont != null && bitmapFont.hasSymbols) && encoding && symbolStyle != SymbolStyle.None;
#if DYNAMIC_FONT
if (dynamicFont != null && request)
{
dynamicFont.RequestCharactersInTexture(")_-", finalSize, fontStyle);
if (!dynamicFont.GetCharacterInfo(')', out mTempChar, finalSize, fontStyle))
{
dynamicFont.RequestCharactersInTexture("A", finalSize, fontStyle);
{
if (!dynamicFont.GetCharacterInfo('A', out mTempChar, finalSize, fontStyle))
{
baseline = 0f;
return;
}
}
}
float y0 = mTempChar.vert.yMax;
float y1 = mTempChar.vert.yMin;
baseline = Mathf.Round(y0 + (finalSize - y0 + y1) * 0.5f);
}
#endif
}
/// <summary>
/// Prepare to use the specified text.
/// </summary>
static public void Prepare (string text)
{
#if DYNAMIC_FONT
if (dynamicFont != null)
dynamicFont.RequestCharactersInTexture(text, finalSize, fontStyle);
#endif
}
/// <summary>
/// Get the specified symbol.
/// </summary>
static public BMSymbol GetSymbol (string text, int index, int textLength)
{
return (bitmapFont != null) ? bitmapFont.MatchSymbol(text, index, textLength) : null;
}
/// <summary>
/// Get the width of the specified glyph. Returns zero if the glyph could not be retrieved.
/// </summary>
static public float GetGlyphWidth (int ch, int prev)
{
if (bitmapFont != null)
{
BMGlyph bmg = bitmapFont.bmFont.GetGlyph(ch);
if (bmg != null)
{
return fontScale * ((prev != 0) ? bmg.advance + bmg.GetKerning(prev) : bmg.advance);
}
}
#if DYNAMIC_FONT
else if (dynamicFont != null)
{
if (dynamicFont.GetCharacterInfo((char)ch, out mTempChar, finalSize, fontStyle))
return Mathf.Round(mTempChar.width * fontScale * pixelDensity);
}
#endif
return 0f;
}
/// <summary>
/// Get the specified glyph.
/// </summary>
static public GlyphInfo GetGlyph (int ch, int prev)
{
if (bitmapFont != null)
{
BMGlyph bmg = bitmapFont.bmFont.GetGlyph(ch);
if (bmg != null)
{
int kern = (prev != 0) ? bmg.GetKerning(prev) : 0;
glyph.v0.x = (prev != 0) ? bmg.offsetX + kern : bmg.offsetX;
glyph.v1.y = -bmg.offsetY;
glyph.v1.x = glyph.v0.x + bmg.width;
glyph.v0.y = glyph.v1.y - bmg.height;
glyph.u0.x = bmg.x;
glyph.u0.y = bmg.y + bmg.height;
glyph.u1.x = bmg.x + bmg.width;
glyph.u1.y = bmg.y;
glyph.advance = bmg.advance + kern;
glyph.channel = bmg.channel;
glyph.rotatedUVs = false;
if (fontScale != 1f)
{
glyph.v0 *= fontScale;
glyph.v1 *= fontScale;
glyph.advance *= fontScale;
}
return glyph;
}
}
#if DYNAMIC_FONT
else if (dynamicFont != null)
{
if (dynamicFont.GetCharacterInfo((char)ch, out mTempChar, finalSize, fontStyle))
{
glyph.v0.x = mTempChar.vert.xMin;
glyph.v1.x = glyph.v0.x + mTempChar.vert.width;
glyph.v0.y = mTempChar.vert.yMax - baseline;
glyph.v1.y = glyph.v0.y - mTempChar.vert.height;
glyph.u0.x = mTempChar.uv.xMin;
glyph.u0.y = mTempChar.uv.yMin;
glyph.u1.x = mTempChar.uv.xMax;
glyph.u1.y = mTempChar.uv.yMax;
glyph.advance = mTempChar.width;
glyph.channel = 0;
glyph.rotatedUVs = mTempChar.flipped;
float pd = fontScale * pixelDensity;
if (pd != 1f)
{
glyph.v0 *= pd;
glyph.v1 *= pd;
glyph.advance *= pd;
}
glyph.advance = Mathf.Round(glyph.advance);
return glyph;
}
}
#endif
return null;
}
static Color mInvisible = new Color(0f, 0f, 0f, 0f);
static BetterList<Color> mColors = new BetterList<Color>();
#if DYNAMIC_FONT
static CharacterInfo mTempChar;
#endif
/// <summary>
/// Parse a RrGgBb color encoded in the string.
/// </summary>
static public Color ParseColor (string text, int offset)
{
int r = (NGUIMath.HexToDecimal(text[offset]) << 4) | NGUIMath.HexToDecimal(text[offset + 1]);
int g = (NGUIMath.HexToDecimal(text[offset + 2]) << 4) | NGUIMath.HexToDecimal(text[offset + 3]);
int b = (NGUIMath.HexToDecimal(text[offset + 4]) << 4) | NGUIMath.HexToDecimal(text[offset + 5]);
float f = 1f / 255f;
return new Color(f * r, f * g, f * b);
}
/// <summary>
/// The reverse of ParseColor -- encodes a color in RrGgBb format.
/// </summary>
static public string EncodeColor (Color c)
{
int i = 0xFFFFFF & (NGUIMath.ColorToInt(c) >> 8);
return NGUIMath.DecimalToHex(i);
}
/// <summary>
/// Parse an embedded symbol, such as [FFAA00] (set color) or [-] (undo color change). Returns whether the index was adjusted.
/// </summary>
static public bool ParseSymbol (string text, ref int index)
{
int n = 1;
bool bold = false;
bool italic = false;
bool underline = false;
bool strikethrough = false;
return ParseSymbol(text, ref index, null, false, ref n, ref bold, ref italic, ref underline, ref strikethrough);
}
/// <summary>
/// Parse the symbol, if possible. Returns 'true' if the 'index' was adjusted. Advanced symbol support contributed by Rudy Pangestu.
/// </summary>
static public bool ParseSymbol (string text, ref int index, BetterList<Color> colors, bool premultiply,
ref int sub, ref bool bold, ref bool italic, ref bool underline, ref bool strike)
{
int length = text.Length;
if (index + 3 > length || text[index] != '[') return false;
if (text[index + 2] == ']')
{
if (text[index + 1] == '-')
{
if (colors != null && colors.size > 1)
colors.RemoveAt(colors.size - 1);
index += 3;
return true;
}
string sub3 = text.Substring(index, 3);
switch (sub3)
{
case "[b]":
bold = true;
index += 3;
return true;
case "[i]":
italic = true;
index += 3;
return true;
case "[u]":
underline = true;
index += 3;
return true;
case "[s]":
strike = true;
index += 3;
return true;
}
}
if (index + 4 > length) return false;
if (text[index + 3] == ']')
{
string sub4 = text.Substring(index, 4);
switch (sub4)
{
case "[/b]":
bold = false;
index += 4;
return true;
case "[/i]":
italic = false;
index += 4;
return true;
case "[/u]":
underline = false;
index += 4;
return true;
case "[/s]":
strike = false;
index += 4;
return true;
}
}
if (index + 5 > length) return false;
if (text[index + 4] == ']')
{
string sub5 = text.Substring(index, 5);
switch (sub5)
{
case "[sub]":
sub = 1;
index += 5;
return true;
case "[sup]":
sub = 2;
index += 5;
return true;
}
}
if (index + 6 > length) return false;
if (text[index + 5] == ']')
{
string sub6 = text.Substring(index, 6);
switch (sub6)
{
case "[/sub]":
sub = 0;
index += 6;
return true;
case "[/sup]":
sub = 0;
index += 6;
return true;
case "[/url]":
index += 6;
return true;
}
}
if (text[index + 1] == 'u' && text[index + 2] == 'r' && text[index + 3] == 'l' && text[index + 4] == '=')
{
int closingBracket = text.IndexOf(']', index + 4);
if (closingBracket != -1)
{
index = closingBracket + 1;
return true;
}
}
if (index + 8 > length) return false;
if (text[index + 7] == ']')
{
Color c = ParseColor(text, index + 1);
if (EncodeColor(c) != text.Substring(index + 1, 6).ToUpper())
return false;
if (colors != null)
{
c.a = colors[colors.size - 1].a;
if (premultiply && c.a != 1f)
c = Color.Lerp(mInvisible, c, c.a);
colors.Add(c);
}
index += 8;
return true;
}
return false;
}
/// <summary>
/// Runs through the specified string and removes all color-encoding symbols.
/// </summary>
static public string StripSymbols (string text)
{
if (text != null)
{
for (int i = 0, imax = text.Length; i < imax; )
{
char c = text[i];
if (c == '[')
{
int sub = 0;
bool bold = false;
bool italic = false;
bool underline = false;
bool strikethrough = false;
int retVal = i;
if (ParseSymbol(text, ref retVal, null, false, ref sub, ref bold, ref italic, ref underline, ref strikethrough))
{
text = text.Remove(i, retVal - i);
imax = text.Length;
continue;
}
}
++i;
}
}
return text;
}
/// <summary>
/// Align the vertices to be right or center-aligned given the line width specified by NGUIText.lineWidth.
/// </summary>
static public void Align (BetterList<Vector3> verts, int indexOffset, float printedWidth)
{
switch (alignment)
{
case Alignment.Right:
{
float padding = rectWidth - printedWidth;
if (padding < 0f) return;
#if UNITY_FLASH
for (int i = indexOffset; i < verts.size; ++i)
verts.buffer[i] = verts.buffer[i] + new Vector3(padding, 0f);
#else
for (int i = indexOffset; i < verts.size; ++i)
verts.buffer[i].x += padding;
#endif
break;
}
case Alignment.Center:
{
float padding = (rectWidth - printedWidth) * 0.5f;
if (padding < 0f) return;
// Keep it pixel-perfect
int diff = Mathf.RoundToInt(rectWidth - printedWidth);
int intWidth = Mathf.RoundToInt(rectWidth);
bool oddDiff = (diff & 1) == 1;
bool oddWidth = (intWidth & 1) == 1;
if ((oddDiff && !oddWidth) || (!oddDiff && oddWidth))
padding += 0.5f * fontScale;
#if UNITY_FLASH
for (int i = indexOffset; i < verts.size; ++i)
verts.buffer[i] = verts.buffer[i] + new Vector3(padding, 0f);
#else
for (int i = indexOffset; i < verts.size; ++i)
verts.buffer[i].x += padding;
#endif
break;
}
case Alignment.Justified:
{
// Printed text needs to reach at least 65% of the width in order to be justified
if (printedWidth < rectWidth * 0.65f) return;
// There must be some padding involved
float padding = (rectWidth - printedWidth) * 0.5f;
if (padding < 1f) return;
// There must be at least two characters
int chars = (verts.size - indexOffset) / 4;
if (chars < 1) return;
float progressPerChar = 1f / (chars - 1);
float scale = rectWidth / printedWidth;
for (int i = indexOffset + 4, charIndex = 1; i < verts.size; ++charIndex)
{
float x0 = verts.buffer[i].x;
float x1 = verts.buffer[i+2].x;
float w = x1 - x0;
float x0a = x0 * scale;
float x1a = x0a + w;
float x1b = x1 * scale;
float x0b = x1b - w;
float progress = charIndex * progressPerChar;
x0 = Mathf.Lerp(x0a, x0b, progress);
x1 = Mathf.Lerp(x1a, x1b, progress);
x0 = Mathf.Round(x0);
x1 = Mathf.Round(x1);
#if UNITY_FLASH
verts.buffer[i] = verts.buffer[i] + new Vector3(x0, 0f);
verts.buffer[i+1] = verts.buffer[i+1] + new Vector3(x0, 0f);
verts.buffer[i+2] = verts.buffer[i+2] + new Vector3(x1, 0f);
verts.buffer[i+3] = verts.buffer[i+3] + new Vector3(x1, 0f);
i += 4;
#else
verts.buffer[i++].x = x0;
verts.buffer[i++].x = x0;
verts.buffer[i++].x = x1;
verts.buffer[i++].x = x1;
#endif
}
break;
}
}
}
/// <summary>
/// Get the index of the closest character within the provided list of values.
/// This function first sorts by Y, and only then by X.
/// </summary>
static public int GetClosestCharacter (BetterList<Vector3> verts, Vector2 pos)
{
// First sort by Y, and only then by X
float bestX = float.MaxValue;
float bestY = float.MaxValue;
int bestIndex = 0;
for (int i = 0; i < verts.size; ++i)
{
float diffY = Mathf.Abs(pos.y - verts[i].y);
if (diffY > bestY) continue;
float diffX = Mathf.Abs(pos.x - verts[i].x);
if (diffY < bestY)
{
bestY = diffY;
bestX = diffX;
bestIndex = i;
}
else if (diffX < bestX)
{
bestX = diffX;
bestIndex = i;
}
}
return bestIndex;
}
/// <summary>
/// Convenience function that ends the line by either appending a new line character or replacing a space with one.
/// </summary>
static public void EndLine (ref StringBuilder s)
{
int i = s.Length - 1;
if (i > 0 && s[i] == ' ') s[i] = '\n';
else s.Append('\n');
}
/// <summary>
/// Convenience function that ends the line by replacing a space with a newline character.
/// </summary>
static void ReplaceSpaceWithNewline (ref StringBuilder s)
{
int i = s.Length - 1;
if (i > 0 && s[i] == ' ') s[i] = '\n';
}
/// <summary>
/// Get the printed size of the specified string. The returned value is in pixels.
/// </summary>
static public Vector2 CalculatePrintedSize (string text)
{
Vector2 v = Vector2.zero;
if (!string.IsNullOrEmpty(text))
{
// When calculating printed size, get rid of all symbols first since they are invisible anyway
if (encoding) text = StripSymbols(text);
// Ensure we have characters to work with
Prepare(text);
float x = 0f, y = 0f, maxX = 0f;
int textLength = text.Length, ch = 0, prev = 0;
for (int i = 0; i < textLength; ++i)
{
ch = text[i];
// Start a new line
if (ch == '\n')
{
if (x > maxX) maxX = x;
x = 0f;
y += finalLineHeight;
continue;
}
// Skip invalid characters
if (ch < ' ') continue;
// See if there is a symbol matching this text
BMSymbol symbol = useSymbols ? GetSymbol(text, i, textLength) : null;
if (symbol == null)
{
float w = GetGlyphWidth(ch, prev);
if (w != 0f)
{
w += finalSpacingX;
if (Mathf.RoundToInt(x + w) > rectWidth)
{
if (x > maxX) maxX = x - finalSpacingX;
x = w;
y += finalLineHeight;
}
else x += w;
prev = ch;
}
}
else
{
float w = finalSpacingX + symbol.advance * fontScale;
if (Mathf.RoundToInt(x + w) > rectWidth)
{
if (x > maxX) maxX = x - finalSpacingX;
x = w;
y += finalLineHeight;
}
else x += w;
i += symbol.sequence.Length - 1;
prev = 0;
}
}
v.x = ((x > maxX) ? x - finalSpacingX : maxX);
v.y = (y + finalLineHeight);
}
return v;
}
static BetterList<float> mSizes = new BetterList<float>();
/// <summary>
/// Calculate the character index offset required to print the end of the specified text.
/// </summary>
static public int CalculateOffsetToFit (string text)
{
if (string.IsNullOrEmpty(text) || rectWidth < 1) return 0;
Prepare(text);
int textLength = text.Length, ch = 0, prev = 0;
for (int i = 0, imax = text.Length; i < imax; ++i)
{
// See if there is a symbol matching this text
BMSymbol symbol = useSymbols ? GetSymbol(text, i, textLength) : null;
if (symbol == null)
{
ch = text[i];
float w = GetGlyphWidth(ch, prev);
if (w != 0f) mSizes.Add(finalSpacingX + w);
prev = ch;
}
else
{
mSizes.Add(finalSpacingX + symbol.advance * fontScale);
for (int b = 0, bmax = symbol.sequence.Length - 1; b < bmax; ++b) mSizes.Add(0);
i += symbol.sequence.Length - 1;
prev = 0;
}
}
float remainingWidth = rectWidth;
int currentCharacterIndex = mSizes.size;
while (currentCharacterIndex > 0 && remainingWidth > 0)
remainingWidth -= mSizes[--currentCharacterIndex];
mSizes.Clear();
if (remainingWidth < 0) ++currentCharacterIndex;
return currentCharacterIndex;
}
/// <summary>
/// Get the end of line that would fit into a field of given width.
/// </summary>
static public string GetEndOfLineThatFits (string text)
{
int textLength = text.Length;
int offset = CalculateOffsetToFit(text);
return text.Substring(offset, textLength - offset);
}
/// <summary>
/// Text wrapping functionality. The 'width' and 'height' should be in pixels.
/// </summary>
static public bool WrapText (string text, out string finalText)
{
return WrapText(text, out finalText, false);
}
/// <summary>
/// Text wrapping functionality. The 'width' and 'height' should be in pixels.
/// </summary>
static public bool WrapText (string text, out string finalText, bool keepCharCount)
{
if (rectWidth < 1 || rectHeight < 1 || finalLineHeight < 1f)
{
finalText = "";
return false;
}
float height = (maxLines > 0) ? Mathf.Min(rectHeight, finalLineHeight * maxLines) : rectHeight;
int maxLineCount = (maxLines > 0) ? maxLines : 1000000;
maxLineCount = Mathf.FloorToInt(Mathf.Min(maxLineCount, height / finalLineHeight) + 0.01f);
if (maxLineCount == 0)
{
finalText = "";
return false;
}
if (string.IsNullOrEmpty(text)) text = " ";
Prepare(text);
StringBuilder sb = new StringBuilder();
int textLength = text.Length;
float remainingWidth = rectWidth;
int start = 0, offset = 0, lineCount = 1, prev = 0;
bool lineIsEmpty = true;
bool fits = true;
bool eastern = false;
// Run through all characters
for (; offset < textLength; ++offset)
{
char ch = text[offset];
if (ch > 12287) eastern = true;
// New line character -- start a new line
if (ch == '\n')
{
if (lineCount == maxLineCount) break;
remainingWidth = rectWidth;
// Add the previous word to the final string
if (start < offset) sb.Append(text.Substring(start, offset - start + 1));
else sb.Append(ch);
lineIsEmpty = true;
++lineCount;
start = offset + 1;
prev = 0;
continue;
}
// When encoded symbols such as [RrGgBb] or [-] are encountered, skip past them
if (encoding && ParseSymbol(text, ref offset)) { --offset; continue; }
// See if there is a symbol matching this text
BMSymbol symbol = useSymbols ? GetSymbol(text, offset, textLength) : null;
// Calculate how wide this symbol or character is going to be
float glyphWidth;
if (symbol == null)
{
// Find the glyph for this character
float w = GetGlyphWidth(ch, prev);
if (w == 0f) continue;
glyphWidth = finalSpacingX + w;
}
else glyphWidth = finalSpacingX + symbol.advance * fontScale;
// Reduce the width
remainingWidth -= glyphWidth;
// If this marks the end of a word, add it to the final string.
if (ch == ' ' && !eastern)
{
if (prev == ' ')
{
sb.Append(' ');
start = offset + 1;
}
else if (prev != ' ' && start < offset)
{
int end = offset - start + 1;
// Last word on the last line should not include an invisible character
if (lineCount == maxLineCount && remainingWidth <= 0f && offset < textLength && text[offset] <= ' ') --end;
sb.Append(text.Substring(start, end));
lineIsEmpty = false;
start = offset + 1;
prev = ch;
}
}
// Doesn't fit?
if (Mathf.RoundToInt(remainingWidth) < 0)
{
// Can't start a new line
if (lineIsEmpty || lineCount == maxLineCount)
{
// This is the first word on the line -- add it up to the character that fits
sb.Append(text.Substring(start, Mathf.Max(0, offset - start)));
if (ch != ' ' && !eastern) fits = false;
if (lineCount++ == maxLineCount)
{
start = offset;
break;
}
if (keepCharCount) ReplaceSpaceWithNewline(ref sb);
else EndLine(ref sb);
// Start a brand-new line
lineIsEmpty = true;
if (ch == ' ')
{
start = offset + 1;
remainingWidth = rectWidth;
}
else
{
start = offset;
remainingWidth = rectWidth - glyphWidth;
}
prev = 0;
}
else
{
// Revert the position to the beginning of the word and reset the line
lineIsEmpty = true;
remainingWidth = rectWidth;
offset = start - 1;
prev = 0;
if (lineCount++ == maxLineCount) break;
if (keepCharCount) ReplaceSpaceWithNewline(ref sb);
else EndLine(ref sb);
continue;
}
}
else prev = ch;
// Advance the offset past the symbol
if (symbol != null)
{
offset += symbol.length - 1;
prev = 0;
}
}
if (start < offset) sb.Append(text.Substring(start, offset - start));
finalText = sb.ToString();
return fits && ((offset == textLength) || (lineCount <= Mathf.Min(maxLines, maxLineCount)));
}
static Color32 s_c0, s_c1;
/// <summary>
/// Print the specified text into the buffers.
/// </summary>
static public void Print (string text, BetterList<Vector3> verts, BetterList<Vector2> uvs, BetterList<Color32> cols)
{
if (string.IsNullOrEmpty(text)) return;
int indexOffset = verts.size;
Prepare(text);
// Start with the white tint
mColors.Add(Color.white);
int ch = 0, prev = 0;
float x = 0f, y = 0f, maxX = 0f;
float sizeF = finalSize;
Color gb = tint * gradientBottom;
Color gt = tint * gradientTop;
Color32 uc = tint;
int textLength = text.Length;
Rect uvRect = new Rect();
float invX = 0f, invY = 0f;
float sizePD = sizeF * pixelDensity;
// Advanced symbol support contributed by Rudy Pangestu.
bool subscript = false;
int subscriptMode = 0; // 0 = normal, 1 = subscript, 2 = superscript
bool bold = false;
bool italic = false;
bool underline = false;
bool strikethrough = false;
const float sizeShrinkage = 0.75f;
float v0x;
float v1x;
float v1y;
float v0y;
float prevX = 0;
if (bitmapFont != null)
{
uvRect = bitmapFont.uvRect;
invX = uvRect.width / bitmapFont.texWidth;
invY = uvRect.height / bitmapFont.texHeight;
}
for (int i = 0; i < textLength; ++i)
{
ch = text[i];
prevX = x;
// New line character -- skip to the next line
if (ch == '\n')
{
if (x > maxX) maxX = x;
if (alignment != Alignment.Left)
{
Align(verts, indexOffset, x - finalSpacingX);
indexOffset = verts.size;
}
x = 0;
y += finalLineHeight;
prev = 0;
continue;
}
// Invalid character -- skip it
if (ch < ' ')
{
prev = ch;
continue;
}
// Color changing symbol
if (encoding && ParseSymbol(text, ref i, mColors, premultiply, ref subscriptMode, ref bold, ref italic, ref underline, ref strikethrough))
{
Color fc = tint * mColors[mColors.size - 1];
uc = fc;
if (gradient)
{
gb = gradientBottom * fc;
gt = gradientTop * fc;
}
--i;
continue;
}
// See if there is a symbol matching this text
BMSymbol symbol = useSymbols ? GetSymbol(text, i, textLength) : null;
if (symbol != null)
{
v0x = x + symbol.offsetX * fontScale;
v1x = v0x + symbol.width * fontScale;
v1y = -(y + symbol.offsetY * fontScale);
v0y = v1y - symbol.height * fontScale;
// Doesn't fit? Move down to the next line
if (Mathf.RoundToInt(x + symbol.advance * fontScale) > rectWidth)
{
if (x == 0f) return;
if (alignment != Alignment.Left && indexOffset < verts.size)
{
Align(verts, indexOffset, x - finalSpacingX);
indexOffset = verts.size;
}
v0x -= x;
v1x -= x;
v0y -= finalLineHeight;
v1y -= finalLineHeight;
x = 0;
y += finalLineHeight;
prevX = 0;
}
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
x += finalSpacingX + symbol.advance * fontScale;
i += symbol.length - 1;
prev = 0;
if (uvs != null)
{
Rect uv = symbol.uvRect;
float u0x = uv.xMin;
float u0y = uv.yMin;
float u1x = uv.xMax;
float u1y = uv.yMax;
uvs.Add(new Vector2(u0x, u0y));
uvs.Add(new Vector2(u0x, u1y));
uvs.Add(new Vector2(u1x, u1y));
uvs.Add(new Vector2(u1x, u0y));
}
if (cols != null)
{
if (symbolStyle == SymbolStyle.Colored)
{
for (int b = 0; b < 4; ++b) cols.Add(uc);
}
else
{
Color32 col = Color.white;
col.a = uc.a;
for (int b = 0; b < 4; ++b) cols.Add(col);
}
}
}
else // No symbol present
{
GlyphInfo glyph = GetGlyph(ch, prev);
if (glyph == null) continue;
prev = ch;
if (subscriptMode != 0)
{
glyph.v0.x *= sizeShrinkage;
glyph.v0.y *= sizeShrinkage;
glyph.v1.x *= sizeShrinkage;
glyph.v1.y *= sizeShrinkage;
if (subscriptMode == 1)
{
glyph.v0.y -= fontScale * fontSize * 0.4f;
glyph.v1.y -= fontScale * fontSize * 0.4f;
}
else
{
glyph.v0.y += fontScale * fontSize * 0.05f;
glyph.v1.y += fontScale * fontSize * 0.05f;
}
}
float y0 = glyph.v0.y;
float y1 = glyph.v1.y;
v0x = glyph.v0.x + x;
v0y = glyph.v0.y - y;
v1x = glyph.v1.x + x;
v1y = glyph.v1.y - y;
float w = glyph.advance;
if (finalSpacingX < 0f) w += finalSpacingX;
// Doesn't fit? Move down to the next line
if (Mathf.RoundToInt(x + w) > rectWidth)
{
if (x == 0f) return;
if (alignment != Alignment.Left && indexOffset < verts.size)
{
Align(verts, indexOffset, x - finalSpacingX);
indexOffset = verts.size;
}
v0x -= x;
v1x -= x;
v0y -= finalLineHeight;
v1y -= finalLineHeight;
x = 0;
y += finalLineHeight;
prevX = 0;
}
if (ch == ' ')
{
if (underline)
{
ch = '_';
}
else if (strikethrough)
{
ch = '-';
}
}
// Advance the position
x += (subscriptMode == 0) ? finalSpacingX + glyph.advance :
(finalSpacingX + glyph.advance) * sizeShrinkage;
// No need to continue if this is a space character
if (ch == ' ') continue;
// Texture coordinates
if (uvs != null)
{
if (bitmapFont != null)
{
glyph.u0.x = uvRect.xMin + invX * glyph.u0.x;
glyph.u1.x = uvRect.xMin + invX * glyph.u1.x;
glyph.u0.y = uvRect.yMax - invY * glyph.u0.y;
glyph.u1.y = uvRect.yMax - invY * glyph.u1.y;
}
for (int j = 0, jmax = (bold ? 4 : 1); j < jmax; ++j)
{
if (glyph.rotatedUVs)
{
uvs.Add(glyph.u0);
uvs.Add(new Vector2(glyph.u1.x, glyph.u0.y));
uvs.Add(glyph.u1);
uvs.Add(new Vector2(glyph.u0.x, glyph.u1.y));
}
else
{
uvs.Add(glyph.u0);
uvs.Add(new Vector2(glyph.u0.x, glyph.u1.y));
uvs.Add(glyph.u1);
uvs.Add(new Vector2(glyph.u1.x, glyph.u0.y));
}
}
}
// Vertex colors
if (cols != null)
{
if (glyph.channel == 0 || glyph.channel == 15)
{
if (gradient)
{
float min = sizePD + y0 / fontScale;
float max = sizePD + y1 / fontScale;
min /= sizePD;
max /= sizePD;
s_c0 = Color.Lerp(gb, gt, min);
s_c1 = Color.Lerp(gb, gt, max);
for (int j = 0, jmax = (bold ? 4 : 1); j < jmax; ++j)
{
cols.Add(s_c0);
cols.Add(s_c1);
cols.Add(s_c1);
cols.Add(s_c0);
}
}
else
{
for (int j = 0, jmax = (bold ? 16 : 4); j < jmax; ++j)
cols.Add(uc);
}
}
else
{
// Packed fonts come as alpha masks in each of the RGBA channels.
// In order to use it we need to use a special shader.
//
// Limitations:
// - Effects (drop shadow, outline) will not work.
// - Should not be a part of the atlas (eastern fonts rarely are anyway).
// - Lower color precision
Color col = uc;
col *= 0.49f;
switch (glyph.channel)
{
case 1: col.b += 0.51f; break;
case 2: col.g += 0.51f; break;
case 4: col.r += 0.51f; break;
case 8: col.a += 0.51f; break;
}
Color32 c = col;
for (int j = 0, jmax = (bold ? 16 : 4); j < jmax; ++j)
cols.Add(c);
}
}
// Bold and italic contributed by Rudy Pangestu.
if (!bold)
{
if (!italic)
{
verts.Add(new Vector3(v0x, v0y));
verts.Add(new Vector3(v0x, v1y));
verts.Add(new Vector3(v1x, v1y));
verts.Add(new Vector3(v1x, v0y));
}
else // Italic
{
float slant = fontSize * 0.1f * ((v1y - v0y) / fontSize);
verts.Add(new Vector3(v0x - slant, v0y));
verts.Add(new Vector3(v0x + slant, v1y));
verts.Add(new Vector3(v1x + slant, v1y));
verts.Add(new Vector3(v1x - slant, v0y));
}
}
else // Bold
{
for (int j = 0; j < 4; ++j)
{
float a = mBoldOffset[j * 2];
float b = mBoldOffset[j * 2 + 1];
float slant = a + (italic ? fontSize * 0.1f * ((v1y - v0y) / fontSize) : 0f);
verts.Add(new Vector3(v0x - slant, v0y + b));
verts.Add(new Vector3(v0x + slant, v1y + b));
verts.Add(new Vector3(v1x + slant, v1y + b));
verts.Add(new Vector3(v1x - slant, v0y + b));
}
}
// Underline and strike-through contributed by Rudy Pangestu.
if (underline || strikethrough)
{
GlyphInfo dash = GetGlyph(strikethrough ? '-' : '_', prev);
if (dash == null) continue;
if (uvs != null)
{
if (bitmapFont != null)
{
dash.u0.x = uvRect.xMin + invX * dash.u0.x;
dash.u1.x = uvRect.xMin + invX * dash.u1.x;
dash.u0.y = uvRect.yMax - invY * dash.u0.y;
dash.u1.y = uvRect.yMax - invY * dash.u1.y;
}
float cx = (dash.u0.x + dash.u1.x) * 0.5f;
float cy = (dash.u0.y + dash.u1.y) * 0.5f;
uvs.Add(new Vector2(cx, cy));
uvs.Add(new Vector2(cx, cy));
uvs.Add(new Vector2(cx, cy));
uvs.Add(new Vector2(cx, cy));
}
if (subscript && strikethrough)
{
v0y = (-y + dash.v0.y) * sizeShrinkage;
v1y = (-y + dash.v1.y) * sizeShrinkage;
}
else
{
v0y = (-y + dash.v0.y);
v1y = (-y + dash.v1.y);
}
verts.Add(new Vector3(prevX, v0y));
verts.Add(new Vector3(prevX, v1y));
verts.Add(new Vector3(x, v1y));
verts.Add(new Vector3(x, v0y));
Color tint2 = uc;
if (strikethrough)
{
tint2.r *= 0.5f;
tint2.g *= 0.5f;
tint2.b *= 0.5f;
}
tint2.a *= 0.75f;
Color32 uc2 = tint2;
cols.Add(uc2);
cols.Add(uc);
cols.Add(uc);
cols.Add(uc2);
}
}
}
if (alignment != Alignment.Left && indexOffset < verts.size)
{
Align(verts, indexOffset, x - finalSpacingX);
indexOffset = verts.size;
}
mColors.Clear();
}
static float[] mBoldOffset = new float[]
{
-0.5f, 0f, 0.5f, 0f,
0f, -0.5f, 0f, 0.5f
};
/// <summary>
/// Print character positions and indices into the specified buffer. Meant to be used with the "find closest vertex" calculations.
/// </summary>
static public void PrintCharacterPositions (string text, BetterList<Vector3> verts, BetterList<int> indices)
{
if (string.IsNullOrEmpty(text)) text = " ";
Prepare(text);
float x = 0f, y = 0f, maxX = 0f, halfSize = fontSize * fontScale * 0.5f;
int textLength = text.Length, indexOffset = verts.size, ch = 0, prev = 0;
for (int i = 0; i < textLength; ++i)
{
ch = text[i];
verts.Add(new Vector3(x, -y - halfSize));
indices.Add(i);
if (ch == '\n')
{
if (x > maxX) maxX = x;
if (alignment != Alignment.Left)
{
Align(verts, indexOffset, x - finalSpacingX);
indexOffset = verts.size;
}
x = 0;
y += finalLineHeight;
prev = 0;
continue;
}
else if (ch < ' ')
{
prev = 0;
continue;
}
if (encoding && ParseSymbol(text, ref i))
{
--i;
continue;
}
// See if there is a symbol matching this text
BMSymbol symbol = useSymbols ? GetSymbol(text, i, textLength) : null;
if (symbol == null)
{
float w = GetGlyphWidth(ch, prev);
if (w != 0f)
{
w += finalSpacingX;
if (Mathf.RoundToInt(x + w) > rectWidth)
{
if (x == 0f) return;
if (alignment != Alignment.Left && indexOffset < verts.size)
{
Align(verts, indexOffset, x - finalSpacingX);
indexOffset = verts.size;
}
x = w;
y += finalLineHeight;
}
else x += w;
verts.Add(new Vector3(x, -y - halfSize));
indices.Add(i + 1);
prev = ch;
}
}
else
{
float w = symbol.advance * fontScale + finalSpacingX;
if (Mathf.RoundToInt(x + w) > rectWidth)
{
if (x == 0f) return;
if (alignment != Alignment.Left && indexOffset < verts.size)
{
Align(verts, indexOffset, x - finalSpacingX);
indexOffset = verts.size;
}
x = w;
y += finalLineHeight;
}
else x += w;
verts.Add(new Vector3(x, -y - halfSize));
indices.Add(i + 1);
i += symbol.sequence.Length - 1;
prev = 0;
}
}
if (alignment != Alignment.Left && indexOffset < verts.size)
Align(verts, indexOffset, x - finalSpacingX);
}
/// <summary>
/// Print the caret and selection vertices. Note that it's expected that 'text' has been stripped clean of symbols.
/// </summary>
static public void PrintCaretAndSelection (string text, int start, int end, BetterList<Vector3> caret, BetterList<Vector3> highlight)
{
if (string.IsNullOrEmpty(text)) text = " ";
Prepare(text);
int caretPos = end;
if (start > end)
{
end = start;
start = caretPos;
}
float x = 0f, y = 0f, maxX = 0f, fs = fontSize * fontScale;
int caretOffset = (caret != null) ? caret.size : 0;
int highlightOffset = (highlight != null) ? highlight.size : 0;
int textLength = text.Length, index = 0, ch = 0, prev = 0;
bool highlighting = false, caretSet = false;
Vector2 last0 = Vector2.zero;
Vector2 last1 = Vector2.zero;
for (; index < textLength; ++index)
{
// Print the caret
if (caret != null && !caretSet && caretPos <= index)
{
caretSet = true;
caret.Add(new Vector3(x - 1f, -y - fs));
caret.Add(new Vector3(x - 1f, -y));
caret.Add(new Vector3(x + 1f, -y));
caret.Add(new Vector3(x + 1f, -y - fs));
}
ch = text[index];
if (ch == '\n')
{
// Used for alignment purposes
if (x > maxX) maxX = x;
// Align the caret
if (caret != null && caretSet)
{
if (alignment != Alignment.Left) Align(caret, caretOffset, x - finalSpacingX);
caret = null;
}
if (highlight != null)
{
if (highlighting)
{
// Close the selection on this line
highlighting = false;
highlight.Add(last1);
highlight.Add(last0);
}
else if (start <= index && end > index)
{
// This must be an empty line. Add a narrow vertical highlight.
highlight.Add(new Vector3(x, -y - fs));
highlight.Add(new Vector3(x, -y));
highlight.Add(new Vector3(x + 2f, -y));
highlight.Add(new Vector3(x + 2f, -y - fs));
}
// Align the highlight
if (alignment != Alignment.Left && highlightOffset < highlight.size)
{
Align(highlight, highlightOffset, x - finalSpacingX);
highlightOffset = highlight.size;
}
}
x = 0;
y += finalLineHeight;
prev = 0;
continue;
}
else if (ch < ' ')
{
prev = 0;
continue;
}
if (encoding && ParseSymbol(text, ref index))
{
--index;
continue;
}
// See if there is a symbol matching this text
BMSymbol symbol = useSymbols ? GetSymbol(text, index, textLength) : null;
float w = (symbol != null) ? symbol.advance * fontScale : GetGlyphWidth(ch, prev);
if (w != 0f)
{
float v0x = x;
float v1x = x + w;
float v0y = -y - fs;
float v1y = -y;
if (Mathf.RoundToInt(v1x + finalSpacingX) > rectWidth)
{
if (x == 0f) return;
// Used for alignment purposes
if (x > maxX) maxX = x;
// Align the caret
if (caret != null && caretSet)
{
if (alignment != Alignment.Left) Align(caret, caretOffset, x - finalSpacingX);
caret = null;
}
if (highlight != null)
{
if (highlighting)
{
// Close the selection on this line
highlighting = false;
highlight.Add(last1);
highlight.Add(last0);
}
else if (start <= index && end > index)
{
// This must be an empty line. Add a narrow vertical highlight.
highlight.Add(new Vector3(x, -y - fs));
highlight.Add(new Vector3(x, -y));
highlight.Add(new Vector3(x + 2f, -y));
highlight.Add(new Vector3(x + 2f, -y - fs));
}
// Align the highlight
if (alignment != Alignment.Left && highlightOffset < highlight.size)
{
Debug.Log("Aligning");
Align(highlight, highlightOffset, x - finalSpacingX);
highlightOffset = highlight.size;
}
}
v0x -= x;
v1x -= x;
v0y -= finalLineHeight;
v1y -= finalLineHeight;
x = 0;
y += finalLineHeight;
}
x += w + finalSpacingX;
// Print the highlight
if (highlight != null)
{
if (start > index || end <= index)
{
if (highlighting)
{
// Finish the highlight
highlighting = false;
highlight.Add(last1);
highlight.Add(last0);
}
}
else if (!highlighting)
{
// Start the highlight
highlighting = true;
highlight.Add(new Vector3(v0x, v0y));
highlight.Add(new Vector3(v0x, v1y));
}
}
// Save what the character ended with
last0 = new Vector2(v1x, v0y);
last1 = new Vector2(v1x, v1y);
prev = ch;
}
}
// Ensure we always have a caret
if (caret != null)
{
if (!caretSet)
{
caret.Add(new Vector3(x - 1f, -y - fs));
caret.Add(new Vector3(x - 1f, -y));
caret.Add(new Vector3(x + 1f, -y));
caret.Add(new Vector3(x + 1f, -y - fs));
}
if (alignment != Alignment.Left)
Align(caret, caretOffset, x - finalSpacingX);
}
// Close the selection
if (highlight != null)
{
if (highlighting)
{
// Finish the highlight
highlight.Add(last1);
highlight.Add(last0);
}
else if (start < index && end == index)
{
// Happens when highlight ends on an empty line. Highlight it with a thin line.
highlight.Add(new Vector3(x, -y - fs));
highlight.Add(new Vector3(x, -y));
highlight.Add(new Vector3(x + 2f, -y));
highlight.Add(new Vector3(x + 2f, -y - fs));
}
// Align the highlight
if (alignment != Alignment.Left && highlightOffset < highlight.size)
Align(highlight, highlightOffset, x - finalSpacingX);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/NGUIText.cs
|
C#
|
asf20
| 40,312
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
#define USE_MECANIM
#endif
using UnityEngine;
using AnimationOrTween;
using System.Collections.Generic;
/// <summary>
/// Mainly an internal script used by UIButtonPlayAnimation, but can also be used to call
/// the specified function on the game object after it finishes animating.
/// </summary>
[AddComponentMenu("NGUI/Internal/Active Animation")]
public class ActiveAnimation : MonoBehaviour
{
/// <summary>
/// Active animation that resulted in the event notification.
/// </summary>
static public ActiveAnimation current;
/// <summary>
/// Event delegates called when the animation finishes.
/// </summary>
public List<EventDelegate> onFinished = new List<EventDelegate>();
// Deprecated functionality, kept for backwards compatibility
[HideInInspector] public GameObject eventReceiver;
[HideInInspector] public string callWhenFinished;
Animation mAnim;
Direction mLastDirection = Direction.Toggle;
Direction mDisableDirection = Direction.Toggle;
bool mNotify = false;
#if USE_MECANIM
Animator mAnimator;
string mClip = "";
float playbackTime
{
get
{
AnimatorStateInfo state = mAnimator.GetCurrentAnimatorStateInfo(0);
return Mathf.Clamp01(state.normalizedTime);
}
}
#endif
/// <summary>
/// Whether the animation is currently playing.
/// </summary>
public bool isPlaying
{
get
{
if (mAnim == null)
{
#if USE_MECANIM
if (mAnimator != null)
{
if (mLastDirection == Direction.Reverse)
{
if (playbackTime == 0f) return false;
}
else if (playbackTime == 1f) return false;
return true;
}
#endif
return false;
}
foreach (AnimationState state in mAnim)
{
if (!mAnim.IsPlaying(state.name)) continue;
if (mLastDirection == Direction.Forward)
{
if (state.time < state.length) return true;
}
else if (mLastDirection == Direction.Reverse)
{
if (state.time > 0f) return true;
}
else return true;
}
return false;
}
}
/// <summary>
/// Immediately finish playing the animation.
/// </summary>
public void Finish ()
{
if (mAnim != null)
{
foreach (AnimationState state in mAnim)
{
if (mLastDirection == Direction.Forward) state.time = state.length;
else if (mLastDirection == Direction.Reverse) state.time = 0f;
}
}
#if USE_MECANIM
else if (mAnimator != null)
{
mAnimator.Play(mClip, 0, (mLastDirection == Direction.Forward) ? 1f : 0f);
}
#endif
}
/// <summary>
/// Manually reset the active animation to the beginning.
/// </summary>
public void Reset ()
{
if (mAnim != null)
{
foreach (AnimationState state in mAnim)
{
if (mLastDirection == Direction.Reverse) state.time = state.length;
else if (mLastDirection == Direction.Forward) state.time = 0f;
}
}
#if USE_MECANIM
else if (mAnimator != null)
{
mAnimator.Play(mClip, 0, (mLastDirection == Direction.Reverse) ? 1f : 0f);
}
#endif
}
/// <summary>
/// Event receiver is only kept for backwards compatibility purposes. It's removed on start if new functionality is used.
/// </summary>
void Start ()
{
if (eventReceiver != null && EventDelegate.IsValid(onFinished))
{
eventReceiver = null;
callWhenFinished = null;
}
}
/// <summary>
/// Notify the target when the animation finishes playing.
/// </summary>
void Update ()
{
float delta = RealTime.deltaTime;
if (delta == 0f) return;
#if USE_MECANIM
if (mAnimator != null)
{
mAnimator.Update((mLastDirection == Direction.Reverse) ? -delta : delta);
if (isPlaying) return;
mAnimator.enabled = false;
enabled = false;
}
else if (mAnim != null)
#else
if (mAnim != null)
#endif
{
bool playing = false;
foreach (AnimationState state in mAnim)
{
if (!mAnim.IsPlaying(state.name)) continue;
float movement = state.speed * delta;
state.time += movement;
if (movement < 0f)
{
if (state.time > 0f) playing = true;
else state.time = 0f;
}
else
{
if (state.time < state.length) playing = true;
else state.time = state.length;
}
}
mAnim.Sample();
if (playing) return;
enabled = false;
}
else
{
enabled = false;
return;
}
if (mNotify)
{
mNotify = false;
if (current == null)
{
current = this;
EventDelegate.Execute(onFinished);
// Deprecated functionality, kept for backwards compatibility
if (eventReceiver != null && !string.IsNullOrEmpty(callWhenFinished))
eventReceiver.SendMessage(callWhenFinished, SendMessageOptions.DontRequireReceiver);
current = null;
}
if (mDisableDirection != Direction.Toggle && mLastDirection == mDisableDirection)
NGUITools.SetActive(gameObject, false);
}
}
/// <summary>
/// Play the specified animation.
/// </summary>
void Play (string clipName, Direction playDirection)
{
// Determine the play direction
if (playDirection == Direction.Toggle)
playDirection = (mLastDirection != Direction.Forward) ? Direction.Forward : Direction.Reverse;
if (mAnim != null)
{
// We will sample the animation manually so that it works when the time is paused
enabled = true;
mAnim.enabled = false;
bool noName = string.IsNullOrEmpty(clipName);
// Play the animation if it's not playing already
if (noName)
{
if (!mAnim.isPlaying) mAnim.Play();
}
else if (!mAnim.IsPlaying(clipName))
{
mAnim.Play(clipName);
}
// Update the animation speed based on direction -- forward or back
foreach (AnimationState state in mAnim)
{
if (string.IsNullOrEmpty(clipName) || state.name == clipName)
{
float speed = Mathf.Abs(state.speed);
state.speed = speed * (int)playDirection;
// Automatically start the animation from the end if it's playing in reverse
if (playDirection == Direction.Reverse && state.time == 0f) state.time = state.length;
else if (playDirection == Direction.Forward && state.time == state.length) state.time = 0f;
}
}
// Remember the direction for disable checks in Update()
mLastDirection = playDirection;
mNotify = true;
mAnim.Sample();
}
#if USE_MECANIM
else if (mAnimator != null)
{
if (enabled && isPlaying)
{
if (mClip == clipName)
{
mLastDirection = playDirection;
return;
}
}
enabled = true;
mNotify = true;
mLastDirection = playDirection;
mClip = clipName;
mAnimator.Play(mClip, 0, (playDirection == Direction.Forward) ? 0f : 1f);
// NOTE: If you are getting a message "Animator.GotoState: State could not be found"
// it means that you chose a state name that doesn't exist in the Animator window.
}
#endif
}
/// <summary>
/// Play the specified animation on the specified object.
/// </summary>
static public ActiveAnimation Play (Animation anim, string clipName, Direction playDirection,
EnableCondition enableBeforePlay, DisableCondition disableCondition)
{
if (!NGUITools.GetActive(anim.gameObject))
{
// If the object is disabled, don't do anything
if (enableBeforePlay != EnableCondition.EnableThenPlay) return null;
// Enable the game object before animating it
NGUITools.SetActive(anim.gameObject, true);
// Refresh all panels right away so that there is no one frame delay
UIPanel[] panels = anim.gameObject.GetComponentsInChildren<UIPanel>();
for (int i = 0, imax = panels.Length; i < imax; ++i) panels[i].Refresh();
}
ActiveAnimation aa = anim.GetComponent<ActiveAnimation>();
if (aa == null) aa = anim.gameObject.AddComponent<ActiveAnimation>();
aa.mAnim = anim;
aa.mDisableDirection = (Direction)(int)disableCondition;
aa.onFinished.Clear();
aa.Play(clipName, playDirection);
if (aa.mAnim != null) aa.mAnim.Sample();
#if USE_MECANIM
else if (aa.mAnimator != null) aa.mAnimator.Update(0f);
#endif
return aa;
}
/// <summary>
/// Play the specified animation.
/// </summary>
static public ActiveAnimation Play (Animation anim, string clipName, Direction playDirection)
{
return Play(anim, clipName, playDirection, EnableCondition.DoNothing, DisableCondition.DoNotDisable);
}
/// <summary>
/// Play the specified animation.
/// </summary>
static public ActiveAnimation Play (Animation anim, Direction playDirection)
{
return Play(anim, null, playDirection, EnableCondition.DoNothing, DisableCondition.DoNotDisable);
}
#if USE_MECANIM
/// <summary>
/// Play the specified animation on the specified object.
/// </summary>
static public ActiveAnimation Play (Animator anim, string clipName, Direction playDirection,
EnableCondition enableBeforePlay, DisableCondition disableCondition)
{
if (!NGUITools.GetActive(anim.gameObject))
{
// If the object is disabled, don't do anything
if (enableBeforePlay != EnableCondition.EnableThenPlay) return null;
// Enable the game object before animating it
NGUITools.SetActive(anim.gameObject, true);
// Refresh all panels right away so that there is no one frame delay
UIPanel[] panels = anim.gameObject.GetComponentsInChildren<UIPanel>();
for (int i = 0, imax = panels.Length; i < imax; ++i) panels[i].Refresh();
}
ActiveAnimation aa = anim.GetComponent<ActiveAnimation>();
if (aa == null) aa = anim.gameObject.AddComponent<ActiveAnimation>();
aa.mAnimator = anim;
aa.mDisableDirection = (Direction)(int)disableCondition;
aa.onFinished.Clear();
aa.Play(clipName, playDirection);
if (aa.mAnim != null) aa.mAnim.Sample();
#if USE_MECANIM
else if (aa.mAnimator != null) aa.mAnimator.Update(0f);
#endif
return aa;
}
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/ActiveAnimation.cs
|
C#
|
asf20
| 9,803
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_EDITOR || (!UNITY_FLASH && !NETFX_CORE && !UNITY_WP8)
#define REFLECTION_SUPPORT
#endif
using System;
using System.IO;
using System.Globalization;
using System.Collections.Generic;
using UnityEngine;
#if REFLECTION_SUPPORT
using System.Reflection;
#endif
namespace Tasharen
{
/// <summary>
/// Data Node is a hierarchical data type containing a name and a value, as well as a variable number of children.
/// Data Nodes can be serialized to and from IO data streams.
/// Think of it as an alternative to having to include a huge 1 MB+ XML parsing library in your project.
///
/// Basic Usage:
/// To create a new node: new DataNode (name, value).
/// To add a new child node: dataNode.AddChild("Scale", Vector3.one).
/// To retrieve a Vector3 value: dataNode.GetChild<Vector3>("Scale").
///
/// To make it possible to serialize custom classes, make sure to override your class's ToString() function,
/// and add a "static object FromString (string data);" function to actually perform parsing of the same string,
/// returning an instance of your class created from the text data. For example:
///
/// public class MyClass
/// {
/// public int someID = 0;
///
/// public override string ToString () { return someID.ToString(); }
///
/// static object FromString (string data)
/// {
/// MyClass inst = new MyClass();
/// int.TryParse(data, out inst.someID);
/// return inst;
/// }
/// }
/// </summary>
public class DataNode
{
/// <summary>
/// Data node's name.
/// </summary>
public string name;
/// <summary>
/// Data node's value.
/// </summary>
public object value;
/// <summary>
/// Type the value is currently in.
/// </summary>
public Type type { get { return (value != null) ? value.GetType() : typeof(void); } }
/// <summary>
/// List of child nodes.
/// </summary>
public List<DataNode> children = new List<DataNode>();
/// <summary>
/// Get the node's value cast into the specified type.
/// </summary>
public object Get (Type type) { return ConvertValue(value, type); }
/// <summary>
/// Retrieve the value cast into the appropriate type.
/// </summary>
public T Get<T> ()
{
if (value is T) return (T)value;
object retVal = Get(typeof(T));
return (value != null) ? (T)retVal : default(T);
}
/// <summary>
/// Convenience function to add a new child node.
/// </summary>
public DataNode AddChild ()
{
DataNode tn = new DataNode();
children.Add(tn);
return tn;
}
/// <summary>
/// Add a new child node without checking to see if another child with the same name already exists.
/// </summary>
public DataNode AddChild (string name)
{
DataNode node = AddChild();
node.name = name;
return node;
}
/// <summary>
/// Add a new child node without checking to see if another child with the same name already exists.
/// </summary>
public DataNode AddChild (string name, object value)
{
DataNode node = AddChild();
node.name = name;
node.value = (value is Enum) ? value.ToString() : value;
return node;
}
/// <summary>
/// Set a child value. Will add a new child if a child with the same name is not already present.
/// </summary>
public DataNode SetChild (string name, object value)
{
DataNode node = GetChild(name);
if (node == null) node = AddChild();
node.name = name;
node.value = (value is Enum) ? value.ToString() : value;
return node;
}
/// <summary>
/// Retrieve a child by name.
/// </summary>
public DataNode GetChild (string name)
{
for (int i = 0; i < children.Count; ++i)
if (children[i].name == name)
return children[i];
return null;
}
/// <summary>
/// Get the value of the existing child.
/// </summary>
public T GetChild<T> (string name)
{
DataNode node = GetChild(name);
if (node == null) return default(T);
return node.Get<T>();
}
/// <summary>
/// Get the value of the existing child or the default value if the child is not present.
/// </summary>
public T GetChild<T> (string name, T defaultValue)
{
DataNode node = GetChild(name);
if (node == null) return defaultValue;
return node.Get<T>();
}
/// <summary>
/// Write the node hierarchy to the stream reader.
/// </summary>
public void Write (StreamWriter writer) { Write(writer, 0); }
/// <summary>
/// Read the node hierarchy from the stream reader.
/// </summary>
public void Read (StreamReader reader)
{
string line = GetNextLine(reader);
int offset = CalculateTabs(line);
Read(reader, line, ref offset);
}
/// <summary>
/// Clear the value and the list of children.
/// </summary>
public void Clear ()
{
value = null;
children.Clear();
}
#region Private Functions
/// <summary>
/// Convert the node's value to a human-readable string.
/// </summary>
string GetValueDataString ()
{
if (value is float)
{
float f = (float)value;
return f.ToString(CultureInfo.InvariantCulture);
}
else if (value is Vector2)
{
Vector2 v = (Vector2)value;
return v.x.ToString(CultureInfo.InvariantCulture) + ", " +
v.y.ToString(CultureInfo.InvariantCulture);
}
else if (value is Vector3)
{
Vector3 v = (Vector3)value;
return v.x.ToString(CultureInfo.InvariantCulture) + ", " +
v.y.ToString(CultureInfo.InvariantCulture) + ", " +
v.z.ToString(CultureInfo.InvariantCulture);
}
else if (value is Vector4)
{
Vector4 v = (Vector4)value;
return v.x.ToString(CultureInfo.InvariantCulture) + ", " +
v.y.ToString(CultureInfo.InvariantCulture) + ", " +
v.z.ToString(CultureInfo.InvariantCulture) + ", " +
v.w.ToString(CultureInfo.InvariantCulture);
}
else if (value is Quaternion)
{
Quaternion q = (Quaternion)value;
Vector3 v = q.eulerAngles;
return v.x.ToString(CultureInfo.InvariantCulture) + ", " +
v.y.ToString(CultureInfo.InvariantCulture) + ", " +
v.z.ToString(CultureInfo.InvariantCulture);
}
else if (value is Color)
{
Color v = (Color)value;
return v.r.ToString(CultureInfo.InvariantCulture) + ", " +
v.g.ToString(CultureInfo.InvariantCulture) + ", " +
v.b.ToString(CultureInfo.InvariantCulture) + ", " +
v.a.ToString(CultureInfo.InvariantCulture);
}
else if (value is Color32)
{
Color v = (Color32)value;
return v.r + ", " + v.g + ", " + v.b + ", " + v.a;
}
else if (value is Rect)
{
Rect r = (Rect)value;
return r.x.ToString(CultureInfo.InvariantCulture) + ", " +
r.y.ToString(CultureInfo.InvariantCulture) + ", " +
r.width.ToString(CultureInfo.InvariantCulture) + ", " +
r.height.ToString(CultureInfo.InvariantCulture);
}
else if (value != null)
{
return value.ToString().Replace("\n", "\\n");
}
return "";
}
/// <summary>
/// Convert the node's value to a human-readable string.
/// </summary>
string GetValueString ()
{
if (type == typeof(string)) return "\"" + value + "\"";
if (type == typeof(Vector2) || type == typeof(Vector3) || type == typeof(Color))
return "(" + GetValueDataString() + ")";
return string.Format("{0}({1})", TypeToName(type), GetValueDataString());
}
/// <summary>
/// Set the node's value using its text representation.
/// </summary>
bool SetValue (string text, Type type, string[] parts)
{
if (type == null || type == typeof(void))
{
value = null;
}
else if (type == typeof(string))
{
value = text;
}
else if (type == typeof(bool))
{
bool b;
if (bool.TryParse(text, out b)) value = b;
}
else if (type == typeof(byte))
{
byte b;
if (byte.TryParse(text, out b)) value = b;
}
else if (type == typeof(Int16))
{
Int16 b;
if (Int16.TryParse(text, out b)) value = b;
}
else if (type == typeof(UInt16))
{
UInt16 b;
if (UInt16.TryParse(text, out b)) value = b;
}
else if (type == typeof(Int32))
{
Int32 b;
if (Int32.TryParse(text, out b)) value = b;
}
else if (type == typeof(UInt32))
{
UInt32 b;
if (UInt32.TryParse(text, out b)) value = b;
}
else if (type == typeof(float))
{
float b;
if (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out b)) value = b;
}
else if (type == typeof(double))
{
double b;
if (double.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out b)) value = b;
}
else if (type == typeof(Vector2))
{
if (parts == null) parts = text.Split(',');
if (parts.Length == 2)
{
Vector2 v;
if (float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out v.x) &&
float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out v.y))
value = v;
}
}
else if (type == typeof(Vector3))
{
if (parts == null) parts = text.Split(',');
if (parts.Length == 3)
{
Vector3 v;
if (float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out v.x) &&
float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out v.y) &&
float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out v.z))
value = v;
}
}
else if (type == typeof(Vector4))
{
if (parts == null) parts = text.Split(',');
if (parts.Length == 4)
{
Vector4 v;
if (float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out v.x) &&
float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out v.y) &&
float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out v.z) &&
float.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out v.w))
value = v;
}
}
else if (type == typeof(Quaternion))
{
if (parts == null) parts = text.Split(',');
if (parts.Length == 4)
{
Quaternion v;
if (float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out v.x) &&
float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out v.y) &&
float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out v.z) &&
float.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out v.w))
value = v;
}
}
else if (type == typeof(Color32))
{
if (parts == null) parts = text.Split(',');
if (parts.Length == 4)
{
Color32 v;
if (byte.TryParse(parts[0], out v.r) &&
byte.TryParse(parts[1], out v.g) &&
byte.TryParse(parts[2], out v.b) &&
byte.TryParse(parts[3], out v.a))
value = v;
}
}
else if (type == typeof(Color))
{
if (parts == null) parts = text.Split(',');
if (parts.Length == 4)
{
Color v;
if (float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out v.r) &&
float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out v.g) &&
float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out v.b) &&
float.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out v.a))
value = v;
}
}
else if (type == typeof(Rect))
{
if (parts == null) parts = text.Split(',');
if (parts.Length == 4)
{
Vector4 v;
if (float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out v.x) &&
float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out v.y) &&
float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out v.z) &&
float.TryParse(parts[3], NumberStyles.Float, CultureInfo.InvariantCulture, out v.w))
value = new Rect(v.x, v.y, v.z, v.w);
}
}
#if REFLECTION_SUPPORT
else if (!type.IsSubclassOf(typeof(Component)))
{
try
{
MethodInfo info = type.GetMethod("FromString",
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static);
if (info != null)
{
mInvokeParams[0] = text.Replace("\\n", "\n");
value = info.Invoke(null, mInvokeParams);
}
else return false;
}
catch (Exception ex)
{
Debug.LogWarning(ex.Message);
return false;
}
}
#endif
else return false;
return true;
}
#if REFLECTION_SUPPORT
static object[] mInvokeParams = new object[1];
#endif
/// <summary>
/// Convenience function for easy debugging -- convert the entire data into the string representation form.
/// </summary>
public override string ToString ()
{
string data = "";
Write(ref data, 0);
return data;
}
/// <summary>
/// Write the node into the string.
/// </summary>
void Write (ref string data, int tab)
{
if (!string.IsNullOrEmpty(name))
{
for (int i = 0; i < tab; ++i) data += "\t";
data += Escape(name);
if (value != null) data += " = " + GetValueString();
data += "\n";
for (int i = 0; i < children.Count; ++i)
children[i].Write(ref data, tab + 1);
}
}
/// <summary>
/// Write the node into the stream writer.
/// </summary>
void Write (StreamWriter writer, int tab)
{
if (!string.IsNullOrEmpty(name))
{
for (int i = 0; i < tab; ++i)
writer.Write("\t");
writer.Write(Escape(name));
if (value != null)
{
writer.Write(" = ");
writer.Write(GetValueString());
}
writer.Write("\n");
for (int i = 0; i < children.Count; ++i)
children[i].Write(writer, tab + 1);
}
}
/// <summary>
/// Read this node and all of its children from the stream reader.
/// </summary>
string Read (StreamReader reader, string line, ref int offset)
{
if (line != null)
{
int expected = offset;
Set(line, expected);
line = GetNextLine(reader);
offset = CalculateTabs(line);
while (line != null)
{
if (offset == expected + 1)
{
line = AddChild().Read(reader, line, ref offset);
}
else break;
}
}
return line;
}
/// <summary>
/// Helper function to set the node's name and value using the line that was read from a stream.
/// </summary>
bool Set (string line, int offset)
{
int divider = line.IndexOf("=", offset);
if (divider == -1)
{
name = Unescape(line.Substring(offset)).Trim();
return true;
}
name = Unescape(line.Substring(offset, divider - offset)).Trim();
// Skip past the divider
line = line.Substring(divider + 1).Trim();
// There must be at least 3 characters present at this point
if (line.Length < 3) return false;
// If the line starts with a quote, it must also end with a quote
if (line[0] == '"' && line[line.Length - 1] == '"')
{
value = line.Substring(1, line.Length - 2);
return true;
}
// If the line starts with an opening bracket, it must always end with a closing bracket
if (line[0] == '(' && line[line.Length - 1] == ')')
{
line = line.Substring(1, line.Length - 2);
string[] parts = line.Split(',');
if (parts.Length == 1) return SetValue(line, typeof(float), null);
if (parts.Length == 2) return SetValue(line, typeof(Vector2), parts);
if (parts.Length == 3) return SetValue(line, typeof(Vector3), parts);
if (parts.Length == 4) return SetValue(line, typeof(Color), parts);
value = line;
return true;
}
Type type = typeof(string);
int dataStart = line.IndexOf('(');
if (dataStart != -1)
{
// For some odd reason LastIndexOf() fails to find the last character of the string
int dataEnd = (line[line.Length - 1] == ')') ? line.Length - 1 : line.LastIndexOf(')', dataStart);
if (dataEnd != -1 && line.Length > 2)
{
string strType = line.Substring(0, dataStart);
type = NameToType(strType);
line = line.Substring(dataStart + 1, dataEnd - dataStart - 1);
}
}
return SetValue(line, type, null);
}
#endregion
#region Static Helper Functions
/// <summary>
/// Get the next line from the stream reader.
/// </summary>
static string GetNextLine (StreamReader reader)
{
string line = reader.ReadLine();
while (line != null && line.Trim().StartsWith("//"))
{
line = reader.ReadLine();
if (line == null) return null;
}
return line;
}
/// <summary>
/// Calculate the number of tabs at the beginning of the line.
/// </summary>
static int CalculateTabs (string line)
{
if (line != null)
{
for (int i = 0; i < line.Length; ++i)
{
if (line[i] == '\t') continue;
return i;
}
}
return 0;
}
/// <summary>
/// Escape the characters in the string.
/// </summary>
static string Escape (string val)
{
if (!string.IsNullOrEmpty(val))
{
val = val.Replace("\n", "\\n");
val = val.Replace("\t", "\\t");
}
return val;
}
/// <summary>
/// Recover escaped characters, converting them back to usable characters.
/// </summary>
static string Unescape (string val)
{
if (!string.IsNullOrEmpty(val))
{
val = val.Replace("\\n", "\n");
val = val.Replace("\\t", "\t");
}
return val;
}
static Dictionary<string, Type> mNameToType = new Dictionary<string, Type>();
static Dictionary<Type, string> mTypeToName = new Dictionary<Type, string>();
/// <summary>
/// Given the type name in the string format, return its System.Type.
/// </summary>
static Type NameToType (string name)
{
Type type;
if (!mNameToType.TryGetValue(name, out type))
{
type = Type.GetType(name);
if (type == null)
{
if (name == "String") type = typeof(string);
else if (name == "Vector2") type = typeof(Vector2);
else if (name == "Vector3") type = typeof(Vector3);
else if (name == "Vector4") type = typeof(Vector4);
else if (name == "Quaternion") type = typeof(Quaternion);
else if (name == "Color") type = typeof(Color);
else if (name == "Rect") type = typeof(Rect);
else if (name == "Color32") type = typeof(Color32);
}
mNameToType[name] = type;
}
return type;
}
/// <summary>
/// Convert the specified type to its serialized string type.
/// </summary>
static string TypeToName (Type type)
{
string name;
if (!mTypeToName.TryGetValue(type, out name))
{
name = type.ToString();
if (name.StartsWith("System.")) name = name.Substring(7);
if (name.StartsWith("UnityEngine.")) name = name.Substring(12);
mTypeToName[type] = name;
}
return name;
}
/// <summary>
/// Helper function to convert the specified value into the provided type.
/// </summary>
static object ConvertValue (object value, Type type)
{
if (type.IsAssignableFrom(value.GetType()))
return value;
if (type.IsEnum)
{
if (value.GetType() == typeof(Int32))
return value;
if (value.GetType() == typeof(string))
{
string strVal = (string)value;
if (!string.IsNullOrEmpty(strVal))
{
string[] enumNames = Enum.GetNames(type);
for (int i = 0; i < enumNames.Length; ++i)
if (enumNames[i] == strVal)
return Enum.GetValues(type).GetValue(i);
}
}
}
return null;
}
#endregion
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/DataNode.cs
|
C#
|
asf20
| 18,870
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Localization manager is able to parse localization information from text assets.
/// Using it is simple: text = Localization.Get(key), or just add a UILocalize script to your labels.
/// You can switch the language by using Localization.language = "French", for example.
/// This will attempt to load the file called "French.txt" in the Resources folder,
/// or a column "French" from the Localization.csv file in the Resources folder.
/// If going down the TXT language file route, it's expected that the file is full of key = value pairs, like so:
///
/// LABEL1 = Hello
/// LABEL2 = Music
/// Info = Localization Example
///
/// In the case of the CSV file, the first column should be the "KEY". Other columns
/// should be your localized text values, such as "French" for the first row:
///
/// KEY,English,French
/// LABEL1,Hello,Bonjour
/// LABEL2,Music,Musique
/// Info,"Localization Example","Par exemple la localisation"
/// </summary>
public static class Localization
{
/// <summary>
/// Whether the localization dictionary has been loaded.
/// </summary>
static public bool localizationHasBeenSet = false;
// Loaded languages, if any
static string[] mLanguages = null;
// Key = Value dictionary (single language)
static Dictionary<string, string> mOldDictionary = new Dictionary<string, string>();
// Key = Values dictionary (multiple languages)
static Dictionary<string, string[]> mDictionary = new Dictionary<string, string[]>();
// Index of the selected language within the multi-language dictionary
static int mLanguageIndex = -1;
// Currently selected language
static string mLanguage;
/// <summary>
/// Localization dictionary. Dictionary key is the localization key. Dictionary value is the list of localized values (columns in the CSV file).
/// Be very careful editing this via code, and be sure to set the "KEY" to the list of languages.
/// </summary>
static public Dictionary<string, string[]> dictionary
{
get
{
if (!localizationHasBeenSet) language = PlayerPrefs.GetString("Language", "English");
return mDictionary;
}
set
{
localizationHasBeenSet = (value != null);
mDictionary = value;
}
}
/// <summary>
/// List of loaded languages. Available if a single Localization.csv file was used.
/// </summary>
static public string[] knownLanguages
{
get
{
if (!localizationHasBeenSet) LoadDictionary(PlayerPrefs.GetString("Language", "English"));
return mLanguages;
}
}
/// <summary>
/// Name of the currently active language.
/// </summary>
static public string language
{
get
{
if (string.IsNullOrEmpty(mLanguage))
{
string[] lan = knownLanguages;
mLanguage = PlayerPrefs.GetString("Language", lan != null ? lan[0] : "English");
LoadAndSelect(mLanguage);
}
return mLanguage;
}
set
{
if (mLanguage != value)
{
mLanguage = value;
LoadAndSelect(value);
}
}
}
/// <summary>
/// Load the specified localization dictionary.
/// </summary>
static bool LoadDictionary (string value)
{
// Try to load the Localization CSV
TextAsset txt = localizationHasBeenSet ? null : Resources.Load("Localization", typeof(TextAsset)) as TextAsset;
localizationHasBeenSet = true;
// Try to load the localization file
if (txt != null && LoadCSV(txt)) return true;
// If this point was reached, the localization file was not present
if (string.IsNullOrEmpty(value)) return false;
// Not a referenced asset -- try to load it dynamically
txt = Resources.Load(value, typeof(TextAsset)) as TextAsset;
if (txt != null)
{
Load(txt);
return true;
}
return false;
}
/// <summary>
/// Load the specified language.
/// </summary>
static bool LoadAndSelect (string value)
{
if (!string.IsNullOrEmpty(value))
{
if (mDictionary.Count == 0 && !LoadDictionary(value)) return false;
if (SelectLanguage(value)) return true;
}
// Either the language is null, or it wasn't found
mOldDictionary.Clear();
if (string.IsNullOrEmpty(value)) PlayerPrefs.DeleteKey("Language");
return false;
}
/// <summary>
/// Load the specified asset and activate the localization.
/// </summary>
static public void Load (TextAsset asset)
{
ByteReader reader = new ByteReader(asset);
Set(asset.name, reader.ReadDictionary());
}
/// <summary>
/// Load the specified CSV file.
/// </summary>
static public bool LoadCSV (TextAsset asset)
{
ByteReader reader = new ByteReader(asset);
// The first line should contain "KEY", followed by languages.
BetterList<string> temp = reader.ReadCSV();
// There must be at least two columns in a valid CSV file
if (temp.size < 2) return false;
// The first entry must be 'KEY', capitalized
temp[0] = "KEY";
#if !UNITY_3_5
// Ensure that the first value is what we expect
if (!string.Equals(temp[0], "KEY"))
{
Debug.LogError("Invalid localization CSV file. The first value is expected to be 'KEY', followed by language columns.\n" +
"Instead found '" + temp[0] + "'", asset);
return false;
}
else
#endif
{
mLanguages = new string[temp.size - 1];
for (int i = 0; i < mLanguages.Length; ++i)
mLanguages[i] = temp[i + 1];
}
mDictionary.Clear();
// Read the entire CSV file into memory
while (temp != null)
{
AddCSV(temp);
temp = reader.ReadCSV();
}
return true;
}
/// <summary>
/// Select the specified language from the previously loaded CSV file.
/// </summary>
static bool SelectLanguage (string language)
{
mLanguageIndex = -1;
if (mDictionary.Count == 0) return false;
string[] keys;
if (mDictionary.TryGetValue("KEY", out keys))
{
for (int i = 0; i < keys.Length; ++i)
{
if (keys[i] == language)
{
mOldDictionary.Clear();
mLanguageIndex = i;
mLanguage = language;
PlayerPrefs.SetString("Language", mLanguage);
UIRoot.Broadcast("OnLocalize");
return true;
}
}
}
return false;
}
/// <summary>
/// Helper function that adds a single line from a CSV file to the localization list.
/// </summary>
static void AddCSV (BetterList<string> values)
{
if (values.size < 2) return;
string[] temp = new string[values.size - 1];
for (int i = 1; i < values.size; ++i) temp[i - 1] = values[i];
mDictionary.Add(values[0], temp);
}
/// <summary>
/// Load the specified asset and activate the localization.
/// </summary>
static public void Set (string languageName, Dictionary<string, string> dictionary)
{
mLanguage = languageName;
PlayerPrefs.SetString("Language", mLanguage);
mOldDictionary = dictionary;
localizationHasBeenSet = false;
mLanguageIndex = -1;
mLanguages = new string[] { languageName };
UIRoot.Broadcast("OnLocalize");
}
/// <summary>
/// Localize the specified value.
/// </summary>
static public string Get (string key)
{
// Ensure we have a language to work with
if (!localizationHasBeenSet) language = PlayerPrefs.GetString("Language", "English");
string val;
string[] vals;
#if UNITY_IPHONE || UNITY_ANDROID
string mobKey = key + " Mobile";
if (mLanguageIndex != -1 && mDictionary.TryGetValue(mobKey, out vals))
{
if (mLanguageIndex < vals.Length)
return vals[mLanguageIndex];
}
else if (mOldDictionary.TryGetValue(mobKey, out val)) return val;
#endif
if (mLanguageIndex != -1 && mDictionary.TryGetValue(key, out vals))
{
if (mLanguageIndex < vals.Length)
return vals[mLanguageIndex];
}
else if (mOldDictionary.TryGetValue(key, out val)) return val;
#if UNITY_EDITOR
Debug.LogWarning("Localization key not found: '" + key + "'");
#endif
return key;
}
/// <summary>
/// Localize the specified value.
/// </summary>
[System.Obsolete("Use Localization.Get instead")]
static public string Localize (string key) { return Get(key); }
/// <summary>
/// Returns whether the specified key is present in the localization dictionary.
/// </summary>
static public bool Exists (string key)
{
if (mLanguageIndex != -1) return mDictionary.ContainsKey(key);
return mOldDictionary.ContainsKey(key);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/Localization.cs
|
C#
|
asf20
| 8,331
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Abstract UI rectangle containing functionality common to both panels and widgets.
/// A UI rectangle contains 4 anchor points (one for each side), and it ensures that they are updated in the proper order.
/// </summary>
public abstract class UIRect : MonoBehaviour
{
[System.Serializable]
public class AnchorPoint
{
public Transform target;
public float relative = 0f;
public int absolute = 0;
[System.NonSerialized]
public UIRect rect;
[System.NonSerialized]
public Camera targetCam;
public AnchorPoint () { }
public AnchorPoint (float relative) { this.relative = relative; }
/// <summary>
/// Convenience function that sets the anchor's values.
/// </summary>
public void Set (float relative, float absolute)
{
this.relative = relative;
this.absolute = Mathf.FloorToInt(absolute + 0.5f);
}
/// <summary>
/// Set the anchor's value to the nearest of the 3 possible choices of (left, center, right) or (bottom, center, top).
/// </summary>
public void SetToNearest (float abs0, float abs1, float abs2) { SetToNearest(0f, 0.5f, 1f, abs0, abs1, abs2); }
/// <summary>
/// Set the anchor's value given the 3 possible anchor combinations. Chooses the one with the smallest absolute offset.
/// </summary>
public void SetToNearest (float rel0, float rel1, float rel2, float abs0, float abs1, float abs2)
{
float a0 = Mathf.Abs(abs0);
float a1 = Mathf.Abs(abs1);
float a2 = Mathf.Abs(abs2);
if (a0 < a1 && a0 < a2) Set(rel0, abs0);
else if (a1 < a0 && a1 < a2) Set(rel1, abs1);
else Set(rel2, abs2);
}
/// <summary>
/// Set the anchor's absolute coordinate relative to the specified parent, keeping the relative setting intact.
/// </summary>
public void SetHorizontal (Transform parent, float localPos)
{
if (rect)
{
Vector3[] sides = rect.GetSides(parent);
float targetPos = Mathf.Lerp(sides[0].x, sides[2].x, relative);
absolute = Mathf.FloorToInt(localPos - targetPos + 0.5f);
}
else
{
Vector3 targetPos = target.position;
if (parent != null) targetPos = parent.InverseTransformPoint(targetPos);
absolute = Mathf.FloorToInt(localPos - targetPos.x + 0.5f);
}
}
/// <summary>
/// Set the anchor's absolute coordinate relative to the specified parent, keeping the relative setting intact.
/// </summary>
public void SetVertical (Transform parent, float localPos)
{
if (rect)
{
Vector3[] sides = rect.GetSides(parent);
float targetPos = Mathf.Lerp(sides[3].y, sides[1].y, relative);
absolute = Mathf.FloorToInt(localPos - targetPos + 0.5f);
}
else
{
Vector3 targetPos = target.position;
if (parent != null) targetPos = parent.InverseTransformPoint(targetPos);
absolute = Mathf.FloorToInt(localPos - targetPos.y + 0.5f);
}
}
/// <summary>
/// Convenience function that returns the sides the anchored point is anchored to.
/// </summary>
public Vector3[] GetSides (Transform relativeTo)
{
if (target != null)
{
if (rect != null) return rect.GetSides(relativeTo);
if (target.camera != null) return target.camera.GetSides(relativeTo);
}
return null;
}
}
/// <summary>
/// Left side anchor.
/// </summary>
public AnchorPoint leftAnchor = new AnchorPoint();
/// <summary>
/// Right side anchor.
/// </summary>
public AnchorPoint rightAnchor = new AnchorPoint(1f);
/// <summary>
/// Bottom side anchor.
/// </summary>
public AnchorPoint bottomAnchor = new AnchorPoint();
/// <summary>
/// Top side anchor.
/// </summary>
public AnchorPoint topAnchor = new AnchorPoint(1f);
public enum AnchorUpdate
{
OnEnable,
OnUpdate,
}
/// <summary>
/// Whether anchors will be recalculated on every update.
/// </summary>
public AnchorUpdate updateAnchors = AnchorUpdate.OnUpdate;
protected GameObject mGo;
protected Transform mTrans;
protected BetterList<UIRect> mChildren = new BetterList<UIRect>();
protected bool mChanged = true;
protected bool mStarted = false;
protected bool mParentFound = false;
protected bool mUpdateAnchors = false;
/// <summary>
/// Final calculated alpha.
/// </summary>
[System.NonSerialized]
public float finalAlpha = 1f;
UIRoot mRoot;
UIRect mParent;
Camera mMyCam;
int mUpdateFrame = -1;
bool mAnchorsCached = false;
bool mRootSet = false;
/// <summary>
/// Game object gets cached for speed. Can't simply return 'mGo' set in Awake because this function may be called on a prefab.
/// </summary>
public GameObject cachedGameObject { get { if (mGo == null) mGo = gameObject; return mGo; } }
/// <summary>
/// Transform gets cached for speed. Can't simply return 'mTrans' set in Awake because this function may be called on a prefab.
/// </summary>
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
/// <summary>
/// Camera used by anchors.
/// </summary>
public Camera anchorCamera { get { if (!mAnchorsCached) ResetAnchors(); return mMyCam; } }
/// <summary>
/// Whether the rectangle is currently anchored fully on all sides.
/// </summary>
public bool isFullyAnchored { get { return leftAnchor.target && rightAnchor.target && topAnchor.target && bottomAnchor.target; } }
/// <summary>
/// Whether the rectangle is anchored horizontally.
/// </summary>
public virtual bool isAnchoredHorizontally { get { return leftAnchor.target || rightAnchor.target; } }
/// <summary>
/// Whether the rectangle is anchored vertically.
/// </summary>
public virtual bool isAnchoredVertically { get { return bottomAnchor.target || topAnchor.target; } }
/// <summary>
/// Whether the rectangle can be anchored.
/// </summary>
public virtual bool canBeAnchored { get { return true; } }
/// <summary>
/// Get the rectangle's parent, if any.
/// </summary>
public UIRect parent
{
get
{
if (!mParentFound)
{
mParentFound = true;
mParent = NGUITools.FindInParents<UIRect>(cachedTransform.parent);
}
return mParent;
}
}
/// <summary>
/// Get the root object, if any.
/// </summary>
public UIRoot root
{
get
{
if (parent != null) return mParent.root;
if (!mRootSet)
{
mRootSet = true;
mRoot = NGUITools.FindInParents<UIRoot>(cachedTransform);
}
return mRoot;
}
}
/// <summary>
/// Returns 'true' if the widget is currently anchored on any side.
/// </summary>
public bool isAnchored
{
get
{
return (leftAnchor.target || rightAnchor.target || topAnchor.target || bottomAnchor.target) && canBeAnchored;
}
}
/// <summary>
/// Local alpha, not relative to anything.
/// </summary>
public abstract float alpha { get; set; }
/// <summary>
/// Get the final cumulative alpha.
/// </summary>
public abstract float CalculateFinalAlpha (int frameID);
/// <summary>
/// Local-space corners of the UI rectangle. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
public abstract Vector3[] localCorners { get; }
/// <summary>
/// World-space corners of the UI rectangle. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
public abstract Vector3[] worldCorners { get; }
/// <summary>
/// Sets the local 'changed' flag, indicating that some parent value(s) are now be different, such as alpha for example.
/// </summary>
public virtual void Invalidate (bool includeChildren)
{
mChanged = true;
if (includeChildren)
for (int i = 0; i < mChildren.size; ++i)
mChildren.buffer[i].Invalidate(true);
}
// Temporary variable to avoid GC allocation
static Vector3[] mSides = new Vector3[4];
/// <summary>
/// Get the sides of the rectangle relative to the specified transform.
/// The order is left, top, right, bottom.
/// </summary>
public virtual Vector3[] GetSides (Transform relativeTo)
{
if (anchorCamera != null)
{
return anchorCamera.GetSides(relativeTo);
}
else
{
Vector3 pos = cachedTransform.position;
for (int i = 0; i < 4; ++i)
mSides[i] = pos;
if (relativeTo != null)
{
for (int i = 0; i < 4; ++i)
mSides[i] = relativeTo.InverseTransformPoint(mSides[i]);
}
return mSides;
}
}
/// <summary>
/// Helper function that gets the specified anchor's position relative to the chosen transform.
/// </summary>
protected Vector3 GetLocalPos (AnchorPoint ac, Transform trans)
{
if (anchorCamera == null || ac.targetCam == null)
return cachedTransform.localPosition;
Vector3 pos = mMyCam.ViewportToWorldPoint(ac.targetCam.WorldToViewportPoint(ac.target.position));
if (trans != null) pos = trans.InverseTransformPoint(pos);
pos.x = Mathf.Floor(pos.x + 0.5f);
pos.y = Mathf.Floor(pos.y + 0.5f);
return pos;
}
/// <summary>
/// Automatically find the parent rectangle.
/// </summary>
protected virtual void OnEnable ()
{
mAnchorsCached = false;
if (updateAnchors == AnchorUpdate.OnEnable)
mUpdateAnchors = true;
if (mStarted) OnInit();
#if UNITY_EDITOR
OnValidate();
#endif
}
/// <summary>
/// Automatically find the parent rectangle.
/// </summary>
protected virtual void OnInit ()
{
mChanged = true;
mRootSet = false;
mParentFound = false;
if (parent != null) mParent.mChildren.Add(this);
}
/// <summary>
/// Clear the parent rectangle reference.
/// </summary>
protected virtual void OnDisable ()
{
if (mParent) mParent.mChildren.Remove(this);
mParent = null;
mRoot = null;
mRootSet = false;
mParentFound = false;
}
/// <summary>
/// Set anchor rect references on start.
/// </summary>
protected void Start ()
{
mStarted = true;
OnInit();
OnStart();
}
/// <summary>
/// Rectangles need to update in a specific order -- parents before children.
/// When deriving from this class, override its OnUpdate() function instead.
/// </summary>
public void Update ()
{
if (!mAnchorsCached) ResetAnchors();
int frame = Time.frameCount;
if (mUpdateFrame != frame)
{
#if !UNITY_EDITOR
if (updateAnchors == AnchorUpdate.OnUpdate || mUpdateAnchors)
#endif
{
mUpdateFrame = frame;
mUpdateAnchors = false;
bool anchored = false;
if (leftAnchor.target)
{
anchored = true;
if (leftAnchor.rect != null && leftAnchor.rect.mUpdateFrame != frame)
leftAnchor.rect.Update();
}
if (bottomAnchor.target)
{
anchored = true;
if (bottomAnchor.rect != null && bottomAnchor.rect.mUpdateFrame != frame)
bottomAnchor.rect.Update();
}
if (rightAnchor.target)
{
anchored = true;
if (rightAnchor.rect != null && rightAnchor.rect.mUpdateFrame != frame)
rightAnchor.rect.Update();
}
if (topAnchor.target)
{
anchored = true;
if (topAnchor.rect != null && topAnchor.rect.mUpdateFrame != frame)
topAnchor.rect.Update();
}
// Update the dimensions using anchors
if (anchored) OnAnchor();
}
// Continue with the update
OnUpdate();
}
}
/// <summary>
/// Manually update anchored sides.
/// </summary>
public void UpdateAnchors () { if (isAnchored) OnAnchor(); }
/// <summary>
/// Update the dimensions of the rectangle using anchor points.
/// </summary>
protected abstract void OnAnchor ();
/// <summary>
/// Anchor this rectangle to the specified transform.
/// Note that this function will not keep the rectangle's current dimensions, but will instead assume the target's dimensions.
/// </summary>
public void SetAnchor (Transform t)
{
leftAnchor.target = t;
rightAnchor.target = t;
topAnchor.target = t;
bottomAnchor.target = t;
ResetAnchors();
UpdateAnchors();
}
/// <summary>
/// Anchor this rectangle to the specified transform.
/// Note that this function will not keep the rectangle's current dimensions, but will instead assume the target's dimensions.
/// </summary>
public void SetAnchor (GameObject go)
{
Transform t = (go != null) ? go.transform : null;
leftAnchor.target = t;
rightAnchor.target = t;
topAnchor.target = t;
bottomAnchor.target = t;
ResetAnchors();
UpdateAnchors();
}
/// <summary>
/// Anchor this rectangle to the specified transform.
/// </summary>
public void SetAnchor (GameObject go, int left, int bottom, int right, int top)
{
Transform t = (go != null) ? go.transform : null;
leftAnchor.target = t;
rightAnchor.target = t;
topAnchor.target = t;
bottomAnchor.target = t;
leftAnchor.relative = 0f;
rightAnchor.relative = 1f;
bottomAnchor.relative = 0f;
topAnchor.relative = 1f;
leftAnchor.absolute = left;
rightAnchor.absolute = right;
bottomAnchor.absolute = bottom;
topAnchor.absolute = top;
ResetAnchors();
UpdateAnchors();
}
/// <summary>
/// Ensure that all rect references are set correctly on the anchors.
/// </summary>
public void ResetAnchors ()
{
mAnchorsCached = true;
leftAnchor.rect = (leftAnchor.target) ? leftAnchor.target.GetComponent<UIRect>() : null;
bottomAnchor.rect = (bottomAnchor.target) ? bottomAnchor.target.GetComponent<UIRect>() : null;
rightAnchor.rect = (rightAnchor.target) ? rightAnchor.target.GetComponent<UIRect>() : null;
topAnchor.rect = (topAnchor.target) ? topAnchor.target.GetComponent<UIRect>() : null;
mMyCam = NGUITools.FindCameraForLayer(cachedGameObject.layer);
FindCameraFor(leftAnchor);
FindCameraFor(bottomAnchor);
FindCameraFor(rightAnchor);
FindCameraFor(topAnchor);
mUpdateAnchors = true;
}
/// <summary>
/// Set the rectangle manually.
/// </summary>
public abstract void SetRect (float x, float y, float width, float height);
/// <summary>
/// Helper function -- attempt to find the camera responsible for the specified anchor.
/// </summary>
void FindCameraFor (AnchorPoint ap)
{
// If we don't have a target or have a rectangle to work with, camera isn't needed
if (ap.target == null || ap.rect != null)
{
ap.targetCam = null;
}
else
{
// Find the camera responsible for the target object
ap.targetCam = NGUITools.FindCameraForLayer(ap.target.gameObject.layer);
}
}
/// <summary>
/// Call this function when the rectangle's parent has changed.
/// </summary>
public virtual void ParentHasChanged ()
{
mParentFound = false;
UIRect pt = NGUITools.FindInParents<UIRect>(cachedTransform.parent);
if (mParent != pt)
{
if (mParent) mParent.mChildren.Remove(this);
mParent = pt;
if (mParent) mParent.mChildren.Add(this);
mRootSet = false;
}
}
/// <summary>
/// Abstract start functionality, ensured to happen after the anchor rect references have been set.
/// </summary>
protected abstract void OnStart ();
/// <summary>
/// Abstract update functionality, ensured to happen after the targeting anchors have been updated.
/// </summary>
protected virtual void OnUpdate () { }
#if UNITY_EDITOR
/// <summary>
/// This callback is sent inside the editor notifying us that some property has changed.
/// </summary>
protected virtual void OnValidate ()
{
if (NGUITools.GetActive(this))
{
ResetAnchors();
Invalidate(true);
}
}
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/UIRect.cs
|
C#
|
asf20
| 15,290
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Time class has no timeScale-independent time. This class fixes that.
/// </summary>
public class RealTime : MonoBehaviour
{
static RealTime mInst;
float mRealTime = 0f;
float mRealDelta = 0f;
/// <summary>
/// Real time since startup.
/// </summary>
static public float time
{
get
{
#if UNITY_EDITOR
if (!Application.isPlaying) return Time.realtimeSinceStartup;
#endif
if (mInst == null) Spawn();
return mInst.mRealTime;
}
}
/// <summary>
/// Real delta time.
/// </summary>
static public float deltaTime
{
get
{
#if UNITY_EDITOR
if (!Application.isPlaying) return 0f;
#endif
if (mInst == null) Spawn();
return mInst.mRealDelta;
}
}
static void Spawn ()
{
GameObject go = new GameObject("_RealTime");
DontDestroyOnLoad(go);
mInst = go.AddComponent<RealTime>();
mInst.mRealTime = Time.realtimeSinceStartup;
}
void Update ()
{
float rt = Time.realtimeSinceStartup;
mRealDelta = Mathf.Clamp01(rt - mRealTime);
mRealTime = rt;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/RealTime.cs
|
C#
|
asf20
| 1,222
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
namespace AnimationOrTween
{
public enum Trigger
{
OnClick,
OnHover,
OnPress,
OnHoverTrue,
OnHoverFalse,
OnPressTrue,
OnPressFalse,
OnActivate,
OnActivateTrue,
OnActivateFalse,
OnDoubleClick,
OnSelect,
OnSelectTrue,
OnSelectFalse,
}
public enum Direction
{
Reverse = -1,
Toggle = 0,
Forward = 1,
}
public enum EnableCondition
{
DoNothing = 0,
EnableThenPlay,
}
public enum DisableCondition
{
DisableAfterReverse = -1,
DoNotDisable = 0,
DisableAfterForward = 1,
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/AnimationOrTween.cs
|
C#
|
asf20
| 731
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Similar to SpringPosition, but also moves the panel's clipping. Works in local coordinates.
/// </summary>
[RequireComponent(typeof(UIPanel))]
[AddComponentMenu("NGUI/Internal/Spring Panel")]
public class SpringPanel : MonoBehaviour
{
static public SpringPanel current;
/// <summary>
/// Target position to spring the panel to.
/// </summary>
public Vector3 target = Vector3.zero;
/// <summary>
/// Strength of the spring. The higher the value, the faster the movement.
/// </summary>
public float strength = 10f;
public delegate void OnFinished ();
/// <summary>
/// Delegate function to call when the operation finishes.
/// </summary>
public OnFinished onFinished;
UIPanel mPanel;
Transform mTrans;
UIScrollView mDrag;
/// <summary>
/// Cache the transform.
/// </summary>
void Start ()
{
mPanel = GetComponent<UIPanel>();
mDrag = GetComponent<UIScrollView>();
mTrans = transform;
}
/// <summary>
/// Advance toward the target position.
/// </summary>
void Update ()
{
AdvanceTowardsPosition();
}
/// <summary>
/// Advance toward the target position.
/// </summary>
protected virtual void AdvanceTowardsPosition ()
{
float delta = RealTime.deltaTime;
bool trigger = false;
Vector3 before = mTrans.localPosition;
Vector3 after = NGUIMath.SpringLerp(mTrans.localPosition, target, strength, delta);
if ((after - target).sqrMagnitude < 0.01f)
{
after = target;
enabled = false;
trigger = true;
}
mTrans.localPosition = after;
Vector3 offset = after - before;
Vector2 cr = mPanel.clipOffset;
cr.x -= offset.x;
cr.y -= offset.y;
mPanel.clipOffset = cr;
if (mDrag != null) mDrag.UpdateScrollbars(false);
if (trigger && onFinished != null)
{
current = this;
onFinished();
current = null;
}
}
/// <summary>
/// Start the tweening process.
/// </summary>
static public SpringPanel Begin (GameObject go, Vector3 pos, float strength)
{
SpringPanel sp = go.GetComponent<SpringPanel>();
if (sp == null) sp = go.AddComponent<SpringPanel>();
sp.target = pos;
sp.strength = strength;
sp.onFinished = null;
sp.enabled = true;
return sp;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/SpringPanel.cs
|
C#
|
asf20
| 2,397
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_EDITOR || (!UNITY_FLASH && !NETFX_CORE && !UNITY_WP8)
#define REFLECTION_SUPPORT
#endif
#if REFLECTION_SUPPORT
using System.Reflection;
using System.Diagnostics;
#endif
using UnityEngine;
using System;
/// <summary>
/// Reference to a specific field or property that can be set via inspector.
/// </summary>
[System.Serializable]
public class PropertyReference
{
[SerializeField] Component mTarget;
[SerializeField] string mName;
#if REFLECTION_SUPPORT
FieldInfo mField = null;
PropertyInfo mProperty = null;
#endif
/// <summary>
/// Event delegate's target object.
/// </summary>
public Component target
{
get
{
return mTarget;
}
set
{
mTarget = value;
#if REFLECTION_SUPPORT
mProperty = null;
mField = null;
#endif
}
}
/// <summary>
/// Event delegate's method name.
/// </summary>
public string name
{
get
{
return mName;
}
set
{
mName = value;
#if REFLECTION_SUPPORT
mProperty = null;
mField = null;
#endif
}
}
/// <summary>
/// Whether this delegate's values have been set.
/// </summary>
public bool isValid { get { return (mTarget != null && !string.IsNullOrEmpty(mName)); } }
/// <summary>
/// Whether the target script is actually enabled.
/// </summary>
public bool isEnabled
{
get
{
if (mTarget == null) return false;
MonoBehaviour mb = (mTarget as MonoBehaviour);
return (mb == null || mb.enabled);
}
}
public PropertyReference () { }
public PropertyReference (Component target, string fieldName)
{
mTarget = target;
mName = fieldName;
}
/// <summary>
/// Helper function that returns the property type.
/// </summary>
public Type GetPropertyType ()
{
#if REFLECTION_SUPPORT
if (mProperty == null && mField == null && isValid) Cache();
if (mProperty != null) return mProperty.PropertyType;
if (mField != null) return mField.FieldType;
#endif
return typeof(void);
}
/// <summary>
/// Equality operator.
/// </summary>
public override bool Equals (object obj)
{
if (obj == null)
{
return !isValid;
}
if (obj is PropertyReference)
{
PropertyReference pb = obj as PropertyReference;
return (mTarget == pb.mTarget && string.Equals(mName, pb.mName));
}
return false;
}
static int s_Hash = "PropertyBinding".GetHashCode();
/// <summary>
/// Used in equality operators.
/// </summary>
public override int GetHashCode () { return s_Hash; }
/// <summary>
/// Set the delegate callback using the target and method names.
/// </summary>
public void Set (Component target, string methodName)
{
mTarget = target;
mName = methodName;
}
/// <summary>
/// Clear the event delegate.
/// </summary>
public void Clear ()
{
mTarget = null;
mName = null;
}
/// <summary>
/// Reset the cached references.
/// </summary>
public void Reset ()
{
mField = null;
mProperty = null;
}
/// <summary>
/// Convert the delegate to its string representation.
/// </summary>
public override string ToString () { return ToString(mTarget, name); }
/// <summary>
/// Convenience function that converts the specified component + property pair into its string representation.
/// </summary>
static public string ToString (Component comp, string property)
{
if (comp != null)
{
string typeName = comp.GetType().ToString();
int period = typeName.LastIndexOf('.');
if (period > 0) typeName = typeName.Substring(period + 1);
if (!string.IsNullOrEmpty(property)) return typeName + "." + property;
else return typeName + ".[property]";
}
return null;
}
#if REFLECTION_SUPPORT
/// <summary>
/// Retrieve the property's value.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public object Get ()
{
if (mProperty == null && mField == null && isValid) Cache();
if (mProperty != null)
{
if (mProperty.CanRead)
return mProperty.GetValue(mTarget, null);
}
else if (mField != null)
{
return mField.GetValue(mTarget);
}
return null;
}
/// <summary>
/// Assign the bound property's value.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public bool Set (object value)
{
if (mProperty == null && mField == null && isValid) Cache();
if (mProperty == null && mField == null) return false;
if (value == null)
{
try
{
if (mProperty != null) mProperty.SetValue(mTarget, null, null);
else mField.SetValue(mTarget, null);
}
catch (Exception) { return false; }
}
// Can we set the value?
if (!Convert(ref value))
{
if (Application.isPlaying)
UnityEngine.Debug.LogError("Unable to convert " + value.GetType() + " to " + GetPropertyType());
}
else if (mField != null)
{
mField.SetValue(mTarget, value);
return true;
}
else if (mProperty.CanWrite)
{
mProperty.SetValue(mTarget, value, null);
return true;
}
return false;
}
/// <summary>
/// Cache the field or property.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
bool Cache ()
{
if (mTarget != null && !string.IsNullOrEmpty(mName))
{
Type type = mTarget.GetType();
mField = type.GetField(mName);
mProperty = type.GetProperty(mName);
}
else
{
mField = null;
mProperty = null;
}
return (mField != null || mProperty != null);
}
/// <summary>
/// Whether we can assign the property using the specified value.
/// </summary>
bool Convert (ref object value)
{
if (mTarget == null) return false;
Type to = GetPropertyType();
Type from;
if (value == null)
{
if (!to.IsClass) return false;
from = to;
}
else from = value.GetType();
return Convert(ref value, from, to);
}
#else // Everything below = no reflection support
public object Get ()
{
Debug.LogError("Reflection is not supported on this platform");
return null;
}
public bool Set (object value)
{
Debug.LogError("Reflection is not supported on this platform");
return false;
}
bool Cache () { return false; }
bool Convert (ref object value) { return false; }
#endif
/// <summary>
/// Whether we can convert one type to another for assignment purposes.
/// </summary>
static public bool Convert (Type from, Type to)
{
object temp = null;
return Convert(ref temp, from, to);
}
/// <summary>
/// Whether we can convert one type to another for assignment purposes.
/// </summary>
static public bool Convert (object value, Type to)
{
if (value == null)
{
value = null;
return Convert(ref value, to, to);
}
return Convert(ref value, value.GetType(), to);
}
/// <summary>
/// Whether we can convert one type to another for assignment purposes.
/// </summary>
static public bool Convert (ref object value, Type from, Type to)
{
#if REFLECTION_SUPPORT
// If the value can be assigned as-is, we're done
if (to.IsAssignableFrom(from)) return true;
#else
if (from == to) return true;
#endif
// If the target type is a string, just convert the value
if (to == typeof(string))
{
value = (value != null) ? value.ToString() : "null";
return true;
}
// If the value is null we should not proceed further
if (value == null) return false;
if (to == typeof(int))
{
if (from == typeof(string))
{
int val;
if (int.TryParse((string)value, out val))
{
value = val;
return true;
}
}
else if (from == typeof(float))
{
value = Mathf.RoundToInt((float)value);
return true;
}
}
else if (to == typeof(float))
{
if (from == typeof(string))
{
float val;
if (float.TryParse((string)value, out val))
{
value = val;
return true;
}
}
}
return false;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/PropertyReference.cs
|
C#
|
asf20
| 7,801
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// BMFont reader. C# implementation of http://www.angelcode.com/products/bmfont/
/// </summary>
[System.Serializable]
public class BMFont
{
[HideInInspector][SerializeField] int mSize = 16; // How much to move the cursor when moving to the next line
[HideInInspector][SerializeField] int mBase = 0; // Offset from the top of the line to the base of each character
[HideInInspector][SerializeField] int mWidth = 0; // Original width of the texture
[HideInInspector][SerializeField] int mHeight = 0; // Original height of the texture
[HideInInspector][SerializeField] string mSpriteName;
// List of serialized glyphs
[HideInInspector][SerializeField] List<BMGlyph> mSaved = new List<BMGlyph>();
// Actual glyphs that we'll be working with are stored in a dictionary, making the lookup faster
Dictionary<int, BMGlyph> mDict = new Dictionary<int, BMGlyph>();
/// <summary>
/// Whether the font can be used.
/// </summary>
public bool isValid { get { return (mSaved.Count > 0); } }
/// <summary>
/// Size of this font (for example 32 means 32 pixels).
/// </summary>
public int charSize { get { return mSize; } set { mSize = value; } }
/// <summary>
/// Base offset applied to characters.
/// </summary>
public int baseOffset { get { return mBase; } set { mBase = value; } }
/// <summary>
/// Original width of the texture.
/// </summary>
public int texWidth { get { return mWidth; } set { mWidth = value; } }
/// <summary>
/// Original height of the texture.
/// </summary>
public int texHeight { get { return mHeight; } set { mHeight = value; } }
/// <summary>
/// Number of valid glyphs.
/// </summary>
public int glyphCount { get { return isValid ? mSaved.Count : 0; } }
/// <summary>
/// Original name of the sprite that the font is expecting to find (usually the name of the texture).
/// </summary>
public string spriteName { get { return mSpriteName; } set { mSpriteName = value; } }
/// <summary>
/// Access to BMFont's entire set of glyphs.
/// </summary>
public List<BMGlyph> glyphs { get { return mSaved; } }
/// <summary>
/// Helper function that retrieves the specified glyph, creating it if necessary.
/// </summary>
public BMGlyph GetGlyph (int index, bool createIfMissing)
{
// Get the requested glyph
BMGlyph glyph = null;
if (mDict.Count == 0)
{
// Populate the dictionary for faster access
for (int i = 0, imax = mSaved.Count; i < imax; ++i)
{
BMGlyph bmg = mSaved[i];
mDict.Add(bmg.index, bmg);
}
}
// Saved check is here so that the function call is not needed if it's true
if (!mDict.TryGetValue(index, out glyph) && createIfMissing)
{
glyph = new BMGlyph();
glyph.index = index;
mSaved.Add(glyph);
mDict.Add(index, glyph);
}
return glyph;
}
/// <summary>
/// Retrieve the specified glyph, if it's present.
/// </summary>
public BMGlyph GetGlyph (int index) { return GetGlyph(index, false); }
/// <summary>
/// Clear the glyphs.
/// </summary>
public void Clear ()
{
mDict.Clear();
mSaved.Clear();
}
/// <summary>
/// Trim the glyphs, ensuring that they will never go past the specified bounds.
/// </summary>
public void Trim (int xMin, int yMin, int xMax, int yMax)
{
if (isValid)
{
for (int i = 0, imax = mSaved.Count; i < imax; ++i)
{
BMGlyph glyph = mSaved[i];
if (glyph != null) glyph.Trim(xMin, yMin, xMax, yMax);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/BMFont.cs
|
C#
|
asf20
| 3,679
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Property binding lets you bind two fields or properties so that changing one will update the other.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Internal/Property Binding")]
public class PropertyBinding : MonoBehaviour
{
public enum UpdateCondition
{
OnStart,
OnUpdate,
OnLateUpdate,
OnFixedUpdate,
}
public enum Direction
{
SourceUpdatesTarget,
TargetUpdatesSource,
BiDirectional,
}
/// <summary>
/// First property reference.
/// </summary>
public PropertyReference source;
/// <summary>
/// Second property reference.
/// </summary>
public PropertyReference target;
/// <summary>
/// Direction of updates.
/// </summary>
public Direction direction = Direction.SourceUpdatesTarget;
/// <summary>
/// When the property update will occur.
/// </summary>
public UpdateCondition update = UpdateCondition.OnUpdate;
/// <summary>
/// Whether the values will update while in edit mode.
/// </summary>
public bool editMode = true;
// Cached value from the last update, used to see which property changes for bi-directional updates.
object mLastValue = null;
void Start ()
{
UpdateTarget();
if (update == UpdateCondition.OnStart) enabled = false;
}
void Update ()
{
if (update == UpdateCondition.OnUpdate) UpdateTarget();
#if UNITY_EDITOR
else if (editMode && !Application.isPlaying) UpdateTarget();
#endif
}
void LateUpdate ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (update == UpdateCondition.OnLateUpdate) UpdateTarget();
}
void FixedUpdate ()
{
#if UNITY_EDITOR
if (!Application.isPlaying) return;
#endif
if (update == UpdateCondition.OnFixedUpdate) UpdateTarget();
}
void OnValidate ()
{
if (source != null) source.Reset();
if (target != null) target.Reset();
}
/// <summary>
/// Immediately update the bound data.
/// </summary>
[ContextMenu("Update Now")]
public void UpdateTarget ()
{
if (source != null && target != null && source.isValid && target.isValid)
{
if (direction == Direction.SourceUpdatesTarget)
{
target.Set(source.Get());
}
else if (direction == Direction.TargetUpdatesSource)
{
source.Set(target.Get());
}
else if (source.GetPropertyType() == target.GetPropertyType())
{
object current = source.Get();
if (mLastValue == null || !mLastValue.Equals(current))
{
mLastValue = current;
target.Set(current);
}
else
{
current = target.Get();
if (!mLastValue.Equals(current))
{
mLastValue = current;
source.Set(current);
}
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/PropertyBinding.cs
|
C#
|
asf20
| 2,820
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
//#define SHOW_HIDDEN_OBJECTS
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// This is an internally-created script used by the UI system. You shouldn't be attaching it manually.
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("NGUI/Internal/Draw Call")]
public class UIDrawCall : MonoBehaviour
{
static BetterList<UIDrawCall> mActiveList = new BetterList<UIDrawCall>();
static BetterList<UIDrawCall> mInactiveList = new BetterList<UIDrawCall>();
[System.Obsolete("Use UIDrawCall.activeList")]
static public BetterList<UIDrawCall> list { get { return mActiveList; } }
/// <summary>
/// List of active draw calls.
/// </summary>
static public BetterList<UIDrawCall> activeList { get { return mActiveList; } }
/// <summary>
/// List of inactive draw calls. Only used at run-time in order to avoid object creation/destruction.
/// </summary>
static public BetterList<UIDrawCall> inactiveList { get { return mInactiveList; } }
public enum Clipping : int
{
None = 0,
SoftClip = 3, // Alpha-based clipping with a softened edge
ConstrainButDontClip = 4, // No actual clipping, but does have an area
}
[HideInInspector][System.NonSerialized] public int depthStart = int.MaxValue;
[HideInInspector][System.NonSerialized] public int depthEnd = int.MinValue;
[HideInInspector][System.NonSerialized] public UIPanel manager;
[HideInInspector][System.NonSerialized] public UIPanel panel;
[HideInInspector][System.NonSerialized] public bool alwaysOnScreen = false;
[HideInInspector][System.NonSerialized] public BetterList<Vector3> verts = new BetterList<Vector3>();
[HideInInspector][System.NonSerialized] public BetterList<Vector3> norms = new BetterList<Vector3>();
[HideInInspector][System.NonSerialized] public BetterList<Vector4> tans = new BetterList<Vector4>();
[HideInInspector][System.NonSerialized] public BetterList<Vector2> uvs = new BetterList<Vector2>();
[HideInInspector][System.NonSerialized] public BetterList<Color32> cols = new BetterList<Color32>();
Material mMaterial; // Material used by this screen
Texture mTexture; // Main texture used by the material
Shader mShader; // Shader used by the dynamically created material
int mClipCount = 0; // Number of times the draw call's content is getting clipped
Transform mTrans; // Cached transform
Mesh mMesh; // First generated mesh
MeshFilter mFilter; // Mesh filter for this draw call
MeshRenderer mRenderer; // Mesh renderer for this screen
Material mDynamicMat; // Instantiated material
int[] mIndices; // Cached indices
bool mRebuildMat = true;
bool mLegacyShader = false;
int mRenderQueue = 3000;
int mTriangles = 0;
/// <summary>
/// Whether the draw call has changed recently.
/// </summary>
[System.NonSerialized]
public bool isDirty = false;
/// <summary>
/// Render queue used by the draw call.
/// </summary>
public int renderQueue
{
get
{
return mRenderQueue;
}
set
{
if (mRenderQueue != value)
{
mRenderQueue = value;
if (mDynamicMat != null)
{
mDynamicMat.renderQueue = value;
#if UNITY_EDITOR
if (mRenderer != null) mRenderer.enabled = isActive;
#endif
}
}
}
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
/// <summary>
/// Renderer's sorting order, to be used with Unity's 2D system.
/// </summary>
public int sortingOrder
{
get { return (mRenderer != null) ? mRenderer.sortingOrder : 0; }
set { if (mRenderer != null && mRenderer.sortingOrder != value) mRenderer.sortingOrder = value; }
}
#endif
/// <summary>
/// Final render queue used to draw the draw call's geometry.
/// </summary>
public int finalRenderQueue
{
get
{
return (mDynamicMat != null) ? mDynamicMat.renderQueue : mRenderQueue;
}
}
#if UNITY_EDITOR
/// <summary>
/// Whether the draw call is currently active.
/// </summary>
public bool isActive
{
get
{
return mActive;
}
set
{
if (mActive != value)
{
mActive = value;
if (mRenderer != null)
{
mRenderer.enabled = value;
NGUITools.SetDirty(gameObject);
}
}
}
}
bool mActive = true;
#endif
/// <summary>
/// Transform is cached for speed and efficiency.
/// </summary>
public Transform cachedTransform { get { if (mTrans == null) mTrans = transform; return mTrans; } }
/// <summary>
/// Material used by this screen.
/// </summary>
public Material baseMaterial
{
get
{
return mMaterial;
}
set
{
if (mMaterial != value)
{
mMaterial = value;
mRebuildMat = true;
}
}
}
/// <summary>
/// Dynamically created material used by the draw call to actually draw the geometry.
/// </summary>
public Material dynamicMaterial { get { return mDynamicMat; } }
/// <summary>
/// Texture used by the material.
/// </summary>
public Texture mainTexture
{
get
{
return mTexture;
}
set
{
mTexture = value;
if (mDynamicMat != null) mDynamicMat.mainTexture = value;
}
}
/// <summary>
/// Shader used by the material.
/// </summary>
public Shader shader
{
get
{
return mShader;
}
set
{
if (mShader != value)
{
mShader = value;
mRebuildMat = true;
}
}
}
/// <summary>
/// The number of triangles in this draw call.
/// </summary>
public int triangles { get { return (mMesh != null) ? mTriangles : 0; } }
/// <summary>
/// Whether the draw call is currently using a clipped shader.
/// </summary>
public bool isClipped { get { return mClipCount != 0; } }
/// <summary>
/// Create an appropriate material for the draw call.
/// </summary>
void CreateMaterial ()
{
string shaderName = (mShader != null) ? mShader.name :
((mMaterial != null) ? mMaterial.shader.name : "Unlit/Transparent Colored");
// Figure out the normal shader's name
shaderName = shaderName.Replace("GUI/Text Shader", "Unlit/Text");
if (shaderName.Length > 2)
{
if (shaderName[shaderName.Length - 2] == ' ')
{
int index = shaderName[shaderName.Length - 1];
if (index > '0' && index <= '9') shaderName = shaderName.Substring(0, shaderName.Length - 2);
}
}
if (shaderName.StartsWith("Hidden/"))
shaderName = shaderName.Substring(7);
// Legacy functionality
const string soft = " (SoftClip)";
shaderName = shaderName.Replace(soft, "");
// Try to find the new shader
Shader shader;
mLegacyShader = false;
mClipCount = panel.clipCount;
if (mClipCount != 0)
{
shader = Shader.Find("Hidden/" + shaderName + " " + mClipCount);
if (shader == null) Shader.Find(shaderName + " " + mClipCount);
// Legacy functionality
if (shader == null && mClipCount == 1)
{
mLegacyShader = true;
shader = Shader.Find(shaderName + soft);
}
}
else shader = Shader.Find(shaderName);
if (mMaterial != null)
{
mDynamicMat = new Material(mMaterial);
mDynamicMat.hideFlags = HideFlags.DontSave | HideFlags.NotEditable;
mDynamicMat.CopyPropertiesFromMaterial(mMaterial);
}
else
{
mDynamicMat = new Material(shader);
mDynamicMat.hideFlags = HideFlags.DontSave | HideFlags.NotEditable;
}
// If there is a valid shader, assign it to the custom material
if (shader != null)
{
mDynamicMat.shader = shader;
}
else Debug.LogError(shaderName + " shader doesn't have a clipped shader version for " + mClipCount + " clip regions");
}
/// <summary>
/// Rebuild the draw call's material.
/// </summary>
Material RebuildMaterial ()
{
// Destroy the old material
NGUITools.DestroyImmediate(mDynamicMat);
// Create a new material
CreateMaterial();
mDynamicMat.renderQueue = mRenderQueue;
// Assign the main texture
if (mTexture != null) mDynamicMat.mainTexture = mTexture;
// Update the renderer
if (mRenderer != null) mRenderer.sharedMaterials = new Material[] { mDynamicMat };
return mDynamicMat;
}
/// <summary>
/// Update the renderer's materials.
/// </summary>
void UpdateMaterials ()
{
// If clipping should be used, we need to find a replacement shader
if (mRebuildMat || mDynamicMat == null || mClipCount != panel.clipCount)
{
RebuildMaterial();
mRebuildMat = false;
}
else if (mRenderer.sharedMaterial != mDynamicMat)
{
#if UNITY_EDITOR
Debug.LogError("Hmm... This point got hit!");
#endif
mRenderer.sharedMaterials = new Material[] { mDynamicMat };
}
}
/// <summary>
/// Set the draw call's geometry.
/// </summary>
public void UpdateGeometry ()
{
int count = verts.size;
// Safety check to ensure we get valid values
if (count > 0 && (count == uvs.size && count == cols.size) && (count % 4) == 0)
{
// Cache all components
if (mFilter == null) mFilter = gameObject.GetComponent<MeshFilter>();
if (mFilter == null) mFilter = gameObject.AddComponent<MeshFilter>();
if (verts.size < 65000)
{
// Populate the index buffer
int indexCount = (count >> 1) * 3;
bool setIndices = (mIndices == null || mIndices.Length != indexCount);
// Create the mesh
if (mMesh == null)
{
mMesh = new Mesh();
mMesh.hideFlags = HideFlags.DontSave;
mMesh.name = (mMaterial != null) ? mMaterial.name : "Mesh";
#if !UNITY_3_5
mMesh.MarkDynamic();
#endif
setIndices = true;
}
#if !UNITY_FLASH
// If the buffer length doesn't match, we need to trim all buffers
bool trim = (uvs.buffer.Length != verts.buffer.Length) ||
(cols.buffer.Length != verts.buffer.Length) ||
(norms.buffer != null && norms.buffer.Length != verts.buffer.Length) ||
(tans.buffer != null && tans.buffer.Length != verts.buffer.Length);
// Non-automatic render queues rely on Z position, so it's a good idea to trim everything
if (!trim && panel.renderQueue != UIPanel.RenderQueue.Automatic)
trim = (mMesh == null || mMesh.vertexCount != verts.buffer.Length);
// NOTE: Apparently there is a bug with Adreno devices:
// http://www.tasharen.com/forum/index.php?topic=8415.0
#if !UNITY_4_3 || !UNITY_ANDROID
// If the number of vertices in the buffer is less than half of the full buffer, trim it
if (!trim && (verts.size << 1) < verts.buffer.Length) trim = true;
#endif
mTriangles = (verts.size >> 1);
if (trim || verts.buffer.Length > 65000)
{
if (trim || mMesh.vertexCount != verts.size)
{
mMesh.Clear();
setIndices = true;
}
mMesh.vertices = verts.ToArray();
mMesh.uv = uvs.ToArray();
mMesh.colors32 = cols.ToArray();
if (norms != null) mMesh.normals = norms.ToArray();
if (tans != null) mMesh.tangents = tans.ToArray();
}
else
{
if (mMesh.vertexCount != verts.buffer.Length)
{
mMesh.Clear();
setIndices = true;
}
mMesh.vertices = verts.buffer;
mMesh.uv = uvs.buffer;
mMesh.colors32 = cols.buffer;
if (norms != null) mMesh.normals = norms.buffer;
if (tans != null) mMesh.tangents = tans.buffer;
}
#else
mTriangles = (verts.size >> 1);
if (mMesh.vertexCount != verts.size)
{
mMesh.Clear();
setIndices = true;
}
mMesh.vertices = verts.ToArray();
mMesh.uv = uvs.ToArray();
mMesh.colors32 = cols.ToArray();
if (norms != null) mMesh.normals = norms.ToArray();
if (tans != null) mMesh.tangents = tans.ToArray();
#endif
if (setIndices)
{
mIndices = GenerateCachedIndexBuffer(count, indexCount);
mMesh.triangles = mIndices;
}
#if !UNITY_FLASH
if (trim || !alwaysOnScreen)
#endif
mMesh.RecalculateBounds();
mFilter.mesh = mMesh;
}
else
{
mTriangles = 0;
if (mFilter.mesh != null) mFilter.mesh.Clear();
Debug.LogError("Too many vertices on one panel: " + verts.size);
}
if (mRenderer == null) mRenderer = gameObject.GetComponent<MeshRenderer>();
if (mRenderer == null)
{
mRenderer = gameObject.AddComponent<MeshRenderer>();
#if UNITY_EDITOR
mRenderer.enabled = isActive;
#endif
}
UpdateMaterials();
}
else
{
if (mFilter.mesh != null) mFilter.mesh.Clear();
Debug.LogError("UIWidgets must fill the buffer with 4 vertices per quad. Found " + count);
}
verts.Clear();
uvs.Clear();
cols.Clear();
norms.Clear();
tans.Clear();
}
const int maxIndexBufferCache = 10;
#if UNITY_FLASH
List<int[]> mCache = new List<int[]>(maxIndexBufferCache);
#else
static List<int[]> mCache = new List<int[]>(maxIndexBufferCache);
#endif
/// <summary>
/// Generates a new index buffer for the specified number of vertices (or reuses an existing one).
/// </summary>
int[] GenerateCachedIndexBuffer (int vertexCount, int indexCount)
{
for (int i = 0, imax = mCache.Count; i < imax; ++i)
{
int[] ids = mCache[i];
if (ids != null && ids.Length == indexCount)
return ids;
}
int[] rv = new int[indexCount];
int index = 0;
for (int i = 0; i < vertexCount; i += 4)
{
rv[index++] = i;
rv[index++] = i + 1;
rv[index++] = i + 2;
rv[index++] = i + 2;
rv[index++] = i + 3;
rv[index++] = i;
}
if (mCache.Count > maxIndexBufferCache) mCache.RemoveAt(0);
mCache.Add(rv);
return rv;
}
/// <summary>
/// This function is called when it's clear that the object will be rendered.
/// We want to set the shader used by the material, creating a copy of the material in the process.
/// We also want to update the material's properties before it's actually used.
/// </summary>
void OnWillRenderObject ()
{
UpdateMaterials();
if (mDynamicMat == null || mClipCount == 0) return;
if (!mLegacyShader)
{
UIPanel currentPanel = panel;
for (int i = 0; currentPanel != null; )
{
if (currentPanel.hasClipping)
{
float angle = 0f;
Vector4 cr = currentPanel.drawCallClipRange;
// Clipping regions past the first one need additional math
if (currentPanel != panel)
{
Vector3 pos = currentPanel.cachedTransform.InverseTransformPoint(panel.cachedTransform.position);
cr.x -= pos.x;
cr.y -= pos.y;
Vector3 v0 = panel.cachedTransform.rotation.eulerAngles;
Vector3 v1 = currentPanel.cachedTransform.rotation.eulerAngles;
Vector3 diff = v1 - v0;
diff.x = NGUIMath.WrapAngle(diff.x);
diff.y = NGUIMath.WrapAngle(diff.y);
diff.z = NGUIMath.WrapAngle(diff.z);
if (Mathf.Abs(diff.x) > 0.001f || Mathf.Abs(diff.y) > 0.001f)
Debug.LogWarning("Panel can only be clipped properly if X and Y rotation is left at 0", panel);
angle = diff.z;
}
// Pass the clipping parameters to the shader
SetClipping(i++, cr, currentPanel.clipSoftness, angle);
}
currentPanel = currentPanel.parentPanel;
}
}
else // Legacy functionality
{
Vector2 soft = panel.clipSoftness;
Vector4 cr = panel.drawCallClipRange;
Vector2 v0 = new Vector2(-cr.x / cr.z, -cr.y / cr.w);
Vector2 v1 = new Vector2(1f / cr.z, 1f / cr.w);
Vector2 sharpness = new Vector2(1000.0f, 1000.0f);
if (soft.x > 0f) sharpness.x = cr.z / soft.x;
if (soft.y > 0f) sharpness.y = cr.w / soft.y;
mDynamicMat.mainTextureOffset = v0;
mDynamicMat.mainTextureScale = v1;
mDynamicMat.SetVector("_ClipSharpness", sharpness);
}
}
static string[] ClipRange =
{
"_ClipRange0",
"_ClipRange1",
"_ClipRange2",
"_ClipRange4",
};
static string[] ClipArgs =
{
"_ClipArgs0",
"_ClipArgs1",
"_ClipArgs2",
"_ClipArgs3",
};
/// <summary>
/// Set the shader clipping parameters.
/// </summary>
void SetClipping (int index, Vector4 cr, Vector2 soft, float angle)
{
angle *= -Mathf.Deg2Rad;
Vector2 sharpness = new Vector2(1000.0f, 1000.0f);
if (soft.x > 0f) sharpness.x = cr.z / soft.x;
if (soft.y > 0f) sharpness.y = cr.w / soft.y;
if (index < ClipRange.Length)
{
mDynamicMat.SetVector(ClipRange[index], new Vector4(-cr.x / cr.z, -cr.y / cr.w, 1f / cr.z, 1f / cr.w));
mDynamicMat.SetVector(ClipArgs[index], new Vector4(sharpness.x, sharpness.y, Mathf.Sin(angle), Mathf.Cos(angle)));
}
}
/// <summary>
/// The material should be rebuilt when the draw call is enabled.
/// </summary>
void OnEnable () { mRebuildMat = true; }
/// <summary>
/// Clear all references.
/// </summary>
void OnDisable ()
{
depthStart = int.MaxValue;
depthEnd = int.MinValue;
panel = null;
manager = null;
mMaterial = null;
mTexture = null;
NGUITools.DestroyImmediate(mDynamicMat);
mDynamicMat = null;
}
/// <summary>
/// Cleanup.
/// </summary>
void OnDestroy ()
{
NGUITools.DestroyImmediate(mMesh);
}
/// <summary>
/// Return an existing draw call.
/// </summary>
static public UIDrawCall Create (UIPanel panel, Material mat, Texture tex, Shader shader)
{
#if UNITY_EDITOR
string name = null;
if (tex != null) name = tex.name;
else if (shader != null) name = shader.name;
else if (mat != null) name = mat.name;
return Create(name, panel, mat, tex, shader);
#else
return Create(null, panel, mat, tex, shader);
#endif
}
/// <summary>
/// Create a new draw call, reusing an old one if possible.
/// </summary>
static UIDrawCall Create (string name, UIPanel pan, Material mat, Texture tex, Shader shader)
{
UIDrawCall dc = Create(name);
dc.gameObject.layer = pan.cachedGameObject.layer;
dc.baseMaterial = mat;
dc.mainTexture = tex;
dc.shader = shader;
dc.renderQueue = pan.startingRenderQueue;
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
dc.sortingOrder = pan.sortingOrder;
#endif
dc.manager = pan;
return dc;
}
/// <summary>
/// Create a new draw call, reusing an old one if possible.
/// </summary>
static UIDrawCall Create (string name)
{
#if SHOW_HIDDEN_OBJECTS && UNITY_EDITOR
name = (name != null) ? "_UIDrawCall [" + name + "]" : "DrawCall";
#endif
if (mInactiveList.size > 0)
{
UIDrawCall dc = mInactiveList.Pop();
mActiveList.Add(dc);
if (name != null) dc.name = name;
NGUITools.SetActive(dc.gameObject, true);
return dc;
}
#if UNITY_EDITOR
// If we're in the editor, create the game object with hide flags set right away
GameObject go = UnityEditor.EditorUtility.CreateGameObjectWithHideFlags(name,
#if SHOW_HIDDEN_OBJECTS
HideFlags.DontSave | HideFlags.NotEditable, typeof(UIDrawCall));
#else
HideFlags.HideAndDontSave, typeof(UIDrawCall));
#endif
UIDrawCall newDC = go.GetComponent<UIDrawCall>();
#else
GameObject go = new GameObject(name);
DontDestroyOnLoad(go);
UIDrawCall newDC = go.AddComponent<UIDrawCall>();
#endif
// Create the draw call
mActiveList.Add(newDC);
return newDC;
}
/// <summary>
/// Clear all draw calls.
/// </summary>
static public void ClearAll ()
{
bool playing = Application.isPlaying;
for (int i = mActiveList.size; i > 0; )
{
UIDrawCall dc = mActiveList[--i];
if (dc)
{
if (playing) NGUITools.SetActive(dc.gameObject, false);
else NGUITools.DestroyImmediate(dc.gameObject);
}
}
mActiveList.Clear();
}
/// <summary>
/// Immediately destroy all draw calls.
/// </summary>
static public void ReleaseAll ()
{
ClearAll();
ReleaseInactive();
}
/// <summary>
/// Immediately destroy all inactive draw calls (draw calls that have been recycled and are waiting to be re-used).
/// </summary>
static public void ReleaseInactive()
{
for (int i = mInactiveList.size; i > 0; )
{
UIDrawCall dc = mInactiveList[--i];
if (dc) NGUITools.DestroyImmediate(dc.gameObject);
}
mInactiveList.Clear();
}
/// <summary>
/// Count all draw calls managed by the specified panel.
/// </summary>
static public int Count (UIPanel panel)
{
int count = 0;
for (int i = 0; i < mActiveList.size; ++i)
if (mActiveList[i].manager == panel) ++count;
return count;
}
/// <summary>
/// Destroy the specified draw call.
/// </summary>
static public void Destroy (UIDrawCall dc)
{
if (dc)
{
if (Application.isPlaying)
{
if (mActiveList.Remove(dc))
{
NGUITools.SetActive(dc.gameObject, false);
mInactiveList.Add(dc);
}
}
else
{
mActiveList.Remove(dc);
NGUITools.DestroyImmediate(dc.gameObject);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/UIDrawCall.cs
|
C#
|
asf20
| 20,223
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// This class is meant to be used only internally. It's like Debug.Log, but prints using OnGUI to screen instead.
/// </summary>
[AddComponentMenu("NGUI/Internal/Debug")]
public class NGUIDebug : MonoBehaviour
{
static bool mRayDebug = false;
static List<string> mLines = new List<string>();
static NGUIDebug mInstance = null;
/// <summary>
/// Set by UICamera. Can be used to show/hide raycast information.
/// </summary>
static public bool debugRaycast
{
get
{
return mRayDebug;
}
set
{
if (Application.isPlaying)
{
mRayDebug = value;
if (value) CreateInstance();
}
}
}
/// <summary>
/// Ensure we have an instance present.
/// </summary>
static public void CreateInstance ()
{
if (mInstance == null)
{
GameObject go = new GameObject("_NGUI Debug");
mInstance = go.AddComponent<NGUIDebug>();
DontDestroyOnLoad(go);
}
}
/// <summary>
/// Add a new on-screen log entry.
/// </summary>
static void LogString (string text)
{
if (Application.isPlaying)
{
if (mLines.Count > 20) mLines.RemoveAt(0);
mLines.Add(text);
CreateInstance();
}
else
{
Debug.Log(text);
}
}
/// <summary>
/// Add a new log entry, printing all of the specified parameters.
/// </summary>
static public void Log (params object[] objs)
{
string text = "";
for (int i = 0; i < objs.Length; ++i)
{
if (i == 0)
{
text += objs[i].ToString();
}
else
{
text += ", " + objs[i].ToString();
}
}
LogString(text);
}
/// <summary>
/// Draw bounds immediately. Won't be remembered for the next frame.
/// </summary>
static public void DrawBounds (Bounds b)
{
Vector3 c = b.center;
Vector3 v0 = b.center - b.extents;
Vector3 v1 = b.center + b.extents;
Debug.DrawLine(new Vector3(v0.x, v0.y, c.z), new Vector3(v1.x, v0.y, c.z), Color.red);
Debug.DrawLine(new Vector3(v0.x, v0.y, c.z), new Vector3(v0.x, v1.y, c.z), Color.red);
Debug.DrawLine(new Vector3(v1.x, v0.y, c.z), new Vector3(v1.x, v1.y, c.z), Color.red);
Debug.DrawLine(new Vector3(v0.x, v1.y, c.z), new Vector3(v1.x, v1.y, c.z), Color.red);
}
void OnGUI()
{
if (mLines.Count == 0)
{
if (mRayDebug && UICamera.hoveredObject != null && Application.isPlaying)
{
GUILayout.Label("Last Hit: " + NGUITools.GetHierarchy(UICamera.hoveredObject).Replace("\"", ""));
}
}
else
{
for (int i = 0, imax = mLines.Count; i < imax; ++i)
{
GUILayout.Label(mLines[i]);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/NGUIDebug.cs
|
C#
|
asf20
| 2,732
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Glyph structure used by BMFont. For more information see http://www.angelcode.com/products/bmfont/
/// </summary>
[System.Serializable]
public class BMGlyph
{
public int index; // Index of this glyph (used by BMFont)
public int x; // Offset from the left side of the texture to the left side of the glyph
public int y; // Offset from the top of the texture to the top of the glyph
public int width; // Glyph's width in pixels
public int height; // Glyph's height in pixels
public int offsetX; // Offset to apply to the cursor's left position before drawing this glyph
public int offsetY; // Offset to apply to the cursor's top position before drawing this glyph
public int advance; // How much to move the cursor after printing this character
public int channel; // Channel mask (in most cases this will be 15 (RGBA, 1+2+4+8)
public List<int> kerning;
/// <summary>
/// Retrieves the special amount by which to adjust the cursor position, given the specified previous character.
/// </summary>
public int GetKerning (int previousChar)
{
if (kerning != null && previousChar != 0)
{
for (int i = 0, imax = kerning.Count; i < imax; i += 2)
if (kerning[i] == previousChar)
return kerning[i+1];
}
return 0;
}
/// <summary>
/// Add a new kerning entry to the character (or adjust an existing one).
/// </summary>
public void SetKerning (int previousChar, int amount)
{
if (kerning == null) kerning = new List<int>();
for (int i = 0; i < kerning.Count; i += 2)
{
if (kerning[i] == previousChar)
{
kerning[i+1] = amount;
return;
}
}
kerning.Add(previousChar);
kerning.Add(amount);
}
/// <summary>
/// Trim the glyph, given the specified minimum and maximum dimensions in pixels.
/// </summary>
public void Trim (int xMin, int yMin, int xMax, int yMax)
{
int x1 = x + width;
int y1 = y + height;
if (x < xMin)
{
int offset = xMin - x;
x += offset;
width -= offset;
offsetX += offset;
}
if (y < yMin)
{
int offset = yMin - y;
y += offset;
height -= offset;
offsetY += offset;
}
if (x1 > xMax) width -= x1 - xMax;
if (y1 > yMax) height -= y1 - yMax;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/BMGlyph.cs
|
C#
|
asf20
| 2,438
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
/// <summary>
/// Helper class containing generic functions used throughout the UI library.
/// </summary>
static public class NGUITools
{
static AudioListener mListener;
static bool mLoaded = false;
static float mGlobalVolume = 1f;
/// <summary>
/// Globally accessible volume affecting all sounds played via NGUITools.PlaySound().
/// </summary>
static public float soundVolume
{
get
{
if (!mLoaded)
{
mLoaded = true;
mGlobalVolume = PlayerPrefs.GetFloat("Sound", 1f);
}
return mGlobalVolume;
}
set
{
if (mGlobalVolume != value)
{
mLoaded = true;
mGlobalVolume = value;
PlayerPrefs.SetFloat("Sound", value);
}
}
}
/// <summary>
/// Helper function -- whether the disk access is allowed.
/// </summary>
static public bool fileAccess
{
get
{
return Application.platform != RuntimePlatform.WindowsWebPlayer &&
Application.platform != RuntimePlatform.OSXWebPlayer;
}
}
/// <summary>
/// Play the specified audio clip.
/// </summary>
static public AudioSource PlaySound (AudioClip clip) { return PlaySound(clip, 1f, 1f); }
/// <summary>
/// Play the specified audio clip with the specified volume.
/// </summary>
static public AudioSource PlaySound (AudioClip clip, float volume) { return PlaySound(clip, volume, 1f); }
/// <summary>
/// Play the specified audio clip with the specified volume and pitch.
/// </summary>
static public AudioSource PlaySound (AudioClip clip, float volume, float pitch)
{
volume *= soundVolume;
if (clip != null && volume > 0.01f)
{
if (mListener == null || !NGUITools.GetActive(mListener))
{
AudioListener[] listeners = GameObject.FindObjectsOfType(typeof(AudioListener)) as AudioListener[];
if (listeners != null)
{
for (int i = 0; i < listeners.Length; ++i)
{
if (NGUITools.GetActive(listeners[i]))
{
mListener = listeners[i];
break;
}
}
}
if (mListener == null)
{
Camera cam = Camera.main;
if (cam == null) cam = GameObject.FindObjectOfType(typeof(Camera)) as Camera;
if (cam != null) mListener = cam.gameObject.AddComponent<AudioListener>();
}
}
if (mListener != null && mListener.enabled && NGUITools.GetActive(mListener.gameObject))
{
AudioSource source = mListener.audio;
if (source == null) source = mListener.gameObject.AddComponent<AudioSource>();
source.pitch = pitch;
source.PlayOneShot(clip, volume);
return source;
}
}
return null;
}
/// <summary>
/// New WWW call can fail if the crossdomain policy doesn't check out. Exceptions suck. It's much more elegant to check for null instead.
/// </summary>
static public WWW OpenURL (string url)
{
#if UNITY_FLASH
Debug.LogError("WWW is not yet implemented in Flash");
return null;
#else
WWW www = null;
try { www = new WWW(url); }
catch (System.Exception ex) { Debug.LogError(ex.Message); }
return www;
#endif
}
/// <summary>
/// New WWW call can fail if the crossdomain policy doesn't check out. Exceptions suck. It's much more elegant to check for null instead.
/// </summary>
static public WWW OpenURL (string url, WWWForm form)
{
if (form == null) return OpenURL(url);
#if UNITY_FLASH
Debug.LogError("WWW is not yet implemented in Flash");
return null;
#else
WWW www = null;
try { www = new WWW(url, form); }
catch (System.Exception ex) { Debug.LogError(ex != null ? ex.Message : "<null>"); }
return www;
#endif
}
/// <summary>
/// Same as Random.Range, but the returned value is between min and max, inclusive.
/// Unity's Random.Range is less than max instead, unless min == max.
/// This means Range(0,1) produces 0 instead of 0 or 1. That's unacceptable.
/// </summary>
static public int RandomRange (int min, int max)
{
if (min == max) return min;
return UnityEngine.Random.Range(min, max + 1);
}
/// <summary>
/// Returns the hierarchy of the object in a human-readable format.
/// </summary>
static public string GetHierarchy (GameObject obj)
{
string path = obj.name;
while (obj.transform.parent != null)
{
obj = obj.transform.parent.gameObject;
path = obj.name + "\\" + path;
}
return path;
}
/// <summary>
/// Find all active objects of specified type.
/// </summary>
static public T[] FindActive<T> () where T : Component
{
#if UNITY_3_5 || UNITY_4_0
return GameObject.FindSceneObjectsOfType(typeof(T)) as T[];
#else
return GameObject.FindObjectsOfType(typeof(T)) as T[];
#endif
}
/// <summary>
/// Find the camera responsible for drawing the objects on the specified layer.
/// </summary>
static public Camera FindCameraForLayer (int layer)
{
int layerMask = 1 << layer;
Camera cam;
for (int i = 0; i < UICamera.list.size; ++i)
{
cam = UICamera.list.buffer[i].cachedCamera;
if ((cam != null) && (cam.cullingMask & layerMask) != 0)
return cam;
}
cam = Camera.main;
if (cam != null && (cam.cullingMask & layerMask) != 0) return cam;
Camera[] cameras = NGUITools.FindActive<Camera>();
for (int i = 0, imax = cameras.Length; i < imax; ++i)
{
cam = cameras[i];
if ((cam.cullingMask & layerMask) != 0)
return cam;
}
return null;
}
/// <summary>
/// Add a collider to the game object containing one or more widgets.
/// </summary>
static public BoxCollider AddWidgetCollider (GameObject go) { return AddWidgetCollider(go, false); }
/// <summary>
/// Add a collider to the game object containing one or more widgets.
/// </summary>
static public BoxCollider AddWidgetCollider (GameObject go, bool considerInactive)
{
if (go != null)
{
Collider col = go.GetComponent<Collider>();
BoxCollider box = col as BoxCollider;
if (box == null)
{
if (col != null)
{
if (Application.isPlaying) GameObject.Destroy(col);
else GameObject.DestroyImmediate(col);
}
box = go.AddComponent<BoxCollider>();
#if !UNITY_3_5 && UNITY_EDITOR
UnityEditor.Undo.RegisterCreatedObjectUndo(box, "Add Collider");
#endif
box.isTrigger = true;
UIWidget widget = go.GetComponent<UIWidget>();
if (widget != null) widget.autoResizeBoxCollider = true;
}
UpdateWidgetCollider(box, considerInactive);
return box;
}
return null;
}
/// <summary>
/// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions.
/// </summary>
static public void UpdateWidgetCollider (GameObject go)
{
UpdateWidgetCollider(go, false);
}
/// <summary>
/// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions.
/// </summary>
static public void UpdateWidgetCollider (GameObject go, bool considerInactive)
{
if (go != null)
{
UpdateWidgetCollider(go.GetComponent<BoxCollider>(), considerInactive);
}
}
/// <summary>
/// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions.
/// </summary>
static public void UpdateWidgetCollider (BoxCollider bc)
{
UpdateWidgetCollider(bc, false);
}
/// <summary>
/// Adjust the widget's collider based on the depth of the widgets, as well as the widget's dimensions.
/// </summary>
static public void UpdateWidgetCollider (BoxCollider box, bool considerInactive)
{
if (box != null)
{
GameObject go = box.gameObject;
UIWidget w = go.GetComponent<UIWidget>();
if (w != null)
{
Vector4 region = w.drawingDimensions;
box.center = new Vector3((region.x + region.z) * 0.5f, (region.y + region.w) * 0.5f);
box.size = new Vector3(region.z - region.x, region.w - region.y);
}
else
{
Bounds b = NGUIMath.CalculateRelativeWidgetBounds(go.transform, considerInactive);
box.center = b.center;
box.size = new Vector3(b.size.x, b.size.y, 0f);
}
#if UNITY_EDITOR
NGUITools.SetDirty(box);
#endif
}
}
/// <summary>
/// Helper function that returns the string name of the type.
/// </summary>
static public string GetTypeName<T> ()
{
string s = typeof(T).ToString();
if (s.StartsWith("UI")) s = s.Substring(2);
else if (s.StartsWith("UnityEngine.")) s = s.Substring(12);
return s;
}
/// <summary>
/// Helper function that returns the string name of the type.
/// </summary>
static public string GetTypeName (UnityEngine.Object obj)
{
if (obj == null) return "Null";
string s = obj.GetType().ToString();
if (s.StartsWith("UI")) s = s.Substring(2);
else if (s.StartsWith("UnityEngine.")) s = s.Substring(12);
return s;
}
/// <summary>
/// Convenience method that works without warnings in both Unity 3 and 4.
/// </summary>
static public void RegisterUndo (UnityEngine.Object obj, string name)
{
#if UNITY_EDITOR
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
UnityEditor.Undo.RegisterUndo(obj, name);
#else
UnityEditor.Undo.RecordObject(obj, name);
#endif
NGUITools.SetDirty(obj);
#endif
}
/// <summary>
/// Convenience function that marks the specified object as dirty in the Unity Editor.
/// </summary>
static public void SetDirty (UnityEngine.Object obj)
{
#if UNITY_EDITOR
if (obj)
{
//if (obj is Component) Debug.Log(NGUITools.GetHierarchy((obj as Component).gameObject), obj);
//else if (obj is GameObject) Debug.Log(NGUITools.GetHierarchy(obj as GameObject), obj);
//else Debug.Log("Hmm... " + obj.GetType(), obj);
UnityEditor.EditorUtility.SetDirty(obj);
}
#endif
}
/// <summary>
/// Add a new child game object.
/// </summary>
static public GameObject AddChild (GameObject parent) { return AddChild(parent, true); }
/// <summary>
/// Add a new child game object.
/// </summary>
static public GameObject AddChild (GameObject parent, bool undo)
{
GameObject go = new GameObject();
#if UNITY_EDITOR
if (undo) UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Create Object");
#endif
if (parent != null)
{
Transform t = go.transform;
t.parent = parent.transform;
t.localPosition = Vector3.zero;
t.localRotation = Quaternion.identity;
t.localScale = Vector3.one;
go.layer = parent.layer;
}
return go;
}
/// <summary>
/// Instantiate an object and add it to the specified parent.
/// </summary>
static public GameObject AddChild (GameObject parent, GameObject prefab)
{
GameObject go = GameObject.Instantiate(prefab) as GameObject;
#if UNITY_EDITOR && !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
UnityEditor.Undo.RegisterCreatedObjectUndo(go, "Create Object");
#endif
if (go != null && parent != null)
{
Transform t = go.transform;
t.parent = parent.transform;
t.localPosition = Vector3.zero;
t.localRotation = Quaternion.identity;
t.localScale = Vector3.one;
go.layer = parent.layer;
}
return go;
}
/// <summary>
/// Calculate the game object's depth based on the widgets within, and also taking panel depth into consideration.
/// </summary>
static public int CalculateRaycastDepth (GameObject go)
{
UIWidget w = go.GetComponent<UIWidget>();
if (w != null) return w.raycastDepth;
UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>();
if (widgets.Length == 0) return 0;
int depth = int.MaxValue;
for (int i = 0, imax = widgets.Length; i < imax; ++i)
{
if (widgets[i].enabled)
depth = Mathf.Min(depth, widgets[i].raycastDepth);
}
return depth;
}
/// <summary>
/// Gathers all widgets and calculates the depth for the next widget.
/// </summary>
static public int CalculateNextDepth (GameObject go)
{
int depth = -1;
UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>();
for (int i = 0, imax = widgets.Length; i < imax; ++i)
depth = Mathf.Max(depth, widgets[i].depth);
return depth + 1;
}
/// <summary>
/// Gathers all widgets and calculates the depth for the next widget.
/// </summary>
static public int CalculateNextDepth (GameObject go, bool ignoreChildrenWithColliders)
{
if (ignoreChildrenWithColliders)
{
int depth = -1;
UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>();
for (int i = 0, imax = widgets.Length; i < imax; ++i)
{
UIWidget w = widgets[i];
if (w.cachedGameObject != go && w.collider != null) continue;
depth = Mathf.Max(depth, w.depth);
}
return depth + 1;
}
return CalculateNextDepth(go);
}
/// <summary>
/// Adjust the widgets' depth by the specified value.
/// Returns '0' if nothing was adjusted, '1' if panels were adjusted, and '2' if widgets were adjusted.
/// </summary>
static public int AdjustDepth (GameObject go, int adjustment)
{
if (go != null)
{
UIPanel panel = go.GetComponent<UIPanel>();
if (panel != null)
{
UIPanel[] panels = go.GetComponentsInChildren<UIPanel>(true);
for (int i = 0; i < panels.Length; ++i)
{
UIPanel p = panels[i];
#if UNITY_EDITOR
RegisterUndo(p, "Depth Change");
#endif
p.depth = p.depth + adjustment;
}
return 1;
}
else
{
UIWidget[] widgets = go.GetComponentsInChildren<UIWidget>(true);
for (int i = 0, imax = widgets.Length; i < imax; ++i)
{
UIWidget w = widgets[i];
#if UNITY_EDITOR
RegisterUndo(w, "Depth Change");
#endif
w.depth = w.depth + adjustment;
}
return 2;
}
}
return 0;
}
/// <summary>
/// Bring all of the widgets on the specified object forward.
/// </summary>
static public void BringForward (GameObject go)
{
int val = AdjustDepth(go, 1000);
if (val == 1) NormalizePanelDepths();
else if (val == 2) NormalizeWidgetDepths();
}
/// <summary>
/// Push all of the widgets on the specified object back, making them appear behind everything else.
/// </summary>
static public void PushBack (GameObject go)
{
int val = AdjustDepth(go, -1000);
if (val == 1) NormalizePanelDepths();
else if (val == 2) NormalizeWidgetDepths();
}
/// <summary>
/// Normalize the depths of all the widgets and panels in the scene, making them start from 0 and remain in order.
/// </summary>
static public void NormalizeDepths ()
{
NormalizeWidgetDepths();
NormalizePanelDepths();
}
/// <summary>
/// Normalize the depths of all the widgets in the scene, making them start from 0 and remain in order.
/// </summary>
static public void NormalizeWidgetDepths ()
{
UIWidget[] list = FindActive<UIWidget>();
int size = list.Length;
if (size > 0)
{
Array.Sort(list, UIWidget.FullCompareFunc);
int start = 0;
int current = list[0].depth;
for (int i = 0; i < size; ++i)
{
UIWidget w = list[i];
if (w.depth == current)
{
w.depth = start;
}
else
{
current = w.depth;
w.depth = ++start;
}
}
}
}
/// <summary>
/// Normalize the depths of all the panels in the scene, making them start from 0 and remain in order.
/// </summary>
static public void NormalizePanelDepths ()
{
UIPanel[] list = FindActive<UIPanel>();
int size = list.Length;
if (size > 0)
{
Array.Sort(list, UIPanel.CompareFunc);
int start = 0;
int current = list[0].depth;
for (int i = 0; i < size; ++i)
{
UIPanel p = list[i];
if (p.depth == current)
{
p.depth = start;
}
else
{
current = p.depth;
p.depth = ++start;
}
}
}
}
/// <summary>
/// Create a new UI.
/// </summary>
static public UIPanel CreateUI (bool advanced3D) { return CreateUI(null, advanced3D, -1); }
/// <summary>
/// Create a new UI.
/// </summary>
static public UIPanel CreateUI (bool advanced3D, int layer) { return CreateUI(null, advanced3D, layer); }
/// <summary>
/// Create a new UI.
/// </summary>
static public UIPanel CreateUI (Transform trans, bool advanced3D, int layer)
{
// Find the existing UI Root
UIRoot root = (trans != null) ? NGUITools.FindInParents<UIRoot>(trans.gameObject) : null;
if (root == null && UIRoot.list.Count > 0)
root = UIRoot.list[0];
// If no root found, create one
if (root == null)
{
GameObject go = NGUITools.AddChild(null, false);
root = go.AddComponent<UIRoot>();
// Automatically find the layers if none were specified
if (layer == -1) layer = LayerMask.NameToLayer("UI");
if (layer == -1) layer = LayerMask.NameToLayer("2D UI");
go.layer = layer;
if (advanced3D)
{
go.name = "UI Root (3D)";
root.scalingStyle = UIRoot.Scaling.FixedSize;
}
else
{
go.name = "UI Root";
root.scalingStyle = UIRoot.Scaling.PixelPerfect;
}
}
// Find the first panel
UIPanel panel = root.GetComponentInChildren<UIPanel>();
if (panel == null)
{
// Find other active cameras in the scene
Camera[] cameras = NGUITools.FindActive<Camera>();
float depth = -1f;
bool colorCleared = false;
int mask = (1 << root.gameObject.layer);
for (int i = 0; i < cameras.Length; ++i)
{
Camera c = cameras[i];
// If the color is being cleared, we won't need to
if (c.clearFlags == CameraClearFlags.Color ||
c.clearFlags == CameraClearFlags.Skybox)
colorCleared = true;
// Choose the maximum depth
depth = Mathf.Max(depth, c.depth);
// Make sure this camera can't see the UI
c.cullingMask = (c.cullingMask & (~mask));
}
// Create a camera that will draw the UI
Camera cam = NGUITools.AddChild<Camera>(root.gameObject, false);
cam.gameObject.AddComponent<UICamera>();
cam.clearFlags = colorCleared ? CameraClearFlags.Depth : CameraClearFlags.Color;
cam.backgroundColor = Color.grey;
cam.cullingMask = mask;
cam.depth = depth + 1f;
if (advanced3D)
{
cam.nearClipPlane = 0.1f;
cam.farClipPlane = 4f;
cam.transform.localPosition = new Vector3(0f, 0f, -700f);
}
else
{
cam.orthographic = true;
cam.orthographicSize = 1;
cam.nearClipPlane = -10;
cam.farClipPlane = 10;
}
// Make sure there is an audio listener present
AudioListener[] listeners = NGUITools.FindActive<AudioListener>();
if (listeners == null || listeners.Length == 0)
cam.gameObject.AddComponent<AudioListener>();
// Add a panel to the root
panel = root.gameObject.AddComponent<UIPanel>();
#if UNITY_EDITOR
UnityEditor.Selection.activeGameObject = panel.gameObject;
#endif
}
if (trans != null)
{
// Find the root object
while (trans.parent != null) trans = trans.parent;
if (NGUITools.IsChild(trans, panel.transform))
{
// Odd hierarchy -- can't reparent
panel = trans.gameObject.AddComponent<UIPanel>();
}
else
{
// Reparent this root object to be a child of the panel
trans.parent = panel.transform;
trans.localScale = Vector3.one;
trans.localPosition = Vector3.zero;
SetChildLayer(panel.cachedTransform, panel.cachedGameObject.layer);
}
}
return panel;
}
/// <summary>
/// Helper function that recursively sets all children with widgets' game objects layers to the specified value.
/// </summary>
static public void SetChildLayer (Transform t, int layer)
{
for (int i = 0; i < t.childCount; ++i)
{
Transform child = t.GetChild(i);
child.gameObject.layer = layer;
SetChildLayer(child, layer);
}
}
/// <summary>
/// Add a child object to the specified parent and attaches the specified script to it.
/// </summary>
static public T AddChild<T> (GameObject parent) where T : Component
{
GameObject go = AddChild(parent);
go.name = GetTypeName<T>();
return go.AddComponent<T>();
}
/// <summary>
/// Add a child object to the specified parent and attaches the specified script to it.
/// </summary>
static public T AddChild<T> (GameObject parent, bool undo) where T : Component
{
GameObject go = AddChild(parent, undo);
go.name = GetTypeName<T>();
return go.AddComponent<T>();
}
/// <summary>
/// Add a new widget of specified type.
/// </summary>
static public T AddWidget<T> (GameObject go) where T : UIWidget
{
int depth = CalculateNextDepth(go);
// Create the widget and place it above other widgets
T widget = AddChild<T>(go);
widget.width = 100;
widget.height = 100;
widget.depth = depth;
widget.gameObject.layer = go.layer;
return widget;
}
/// <summary>
/// Add a sprite appropriate for the specified atlas sprite.
/// It will be sliced if the sprite has an inner rect, and a regular sprite otherwise.
/// </summary>
static public UISprite AddSprite (GameObject go, UIAtlas atlas, string spriteName)
{
UISpriteData sp = (atlas != null) ? atlas.GetSprite(spriteName) : null;
UISprite sprite = AddWidget<UISprite>(go);
sprite.type = (sp == null || !sp.hasBorder) ? UISprite.Type.Simple : UISprite.Type.Sliced;
sprite.atlas = atlas;
sprite.spriteName = spriteName;
return sprite;
}
/// <summary>
/// Get the rootmost object of the specified game object.
/// </summary>
static public GameObject GetRoot (GameObject go)
{
Transform t = go.transform;
for (; ; )
{
Transform parent = t.parent;
if (parent == null) break;
t = parent;
}
return t.gameObject;
}
/// <summary>
/// Finds the specified component on the game object or one of its parents.
/// </summary>
static public T FindInParents<T> (GameObject go) where T : Component
{
if (go == null) return null;
#if UNITY_FLASH
object comp = go.GetComponent<T>();
#else
T comp = go.GetComponent<T>();
#endif
if (comp == null)
{
Transform t = go.transform.parent;
while (t != null && comp == null)
{
comp = t.gameObject.GetComponent<T>();
t = t.parent;
}
}
#if UNITY_FLASH
return (T)comp;
#else
return comp;
#endif
}
/// <summary>
/// Finds the specified component on the game object or one of its parents.
/// </summary>
static public T FindInParents<T> (Transform trans) where T : Component
{
if (trans == null) return null;
#if UNITY_FLASH
object comp = trans.GetComponent<T>();
#else
T comp = trans.GetComponent<T>();
#endif
if (comp == null)
{
Transform t = trans.transform.parent;
while (t != null && comp == null)
{
comp = t.gameObject.GetComponent<T>();
t = t.parent;
}
}
#if UNITY_FLASH
return (T)comp;
#else
return comp;
#endif
}
/// <summary>
/// Destroy the specified object, immediately if in edit mode.
/// </summary>
static public void Destroy (UnityEngine.Object obj)
{
if (obj != null)
{
if (Application.isPlaying)
{
if (obj is GameObject)
{
GameObject go = obj as GameObject;
go.transform.parent = null;
}
UnityEngine.Object.Destroy(obj);
}
else UnityEngine.Object.DestroyImmediate(obj);
}
}
/// <summary>
/// Destroy the specified object immediately, unless not in the editor, in which case the regular Destroy is used instead.
/// </summary>
static public void DestroyImmediate (UnityEngine.Object obj)
{
if (obj != null)
{
if (Application.isEditor) UnityEngine.Object.DestroyImmediate(obj);
else UnityEngine.Object.Destroy(obj);
}
}
/// <summary>
/// Call the specified function on all objects in the scene.
/// </summary>
static public void Broadcast (string funcName)
{
GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
for (int i = 0, imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, SendMessageOptions.DontRequireReceiver);
}
/// <summary>
/// Call the specified function on all objects in the scene.
/// </summary>
static public void Broadcast (string funcName, object param)
{
GameObject[] gos = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
for (int i = 0, imax = gos.Length; i < imax; ++i) gos[i].SendMessage(funcName, param, SendMessageOptions.DontRequireReceiver);
}
/// <summary>
/// Determines whether the 'parent' contains a 'child' in its hierarchy.
/// </summary>
static public bool IsChild (Transform parent, Transform child)
{
if (parent == null || child == null) return false;
while (child != null)
{
if (child == parent) return true;
child = child.parent;
}
return false;
}
/// <summary>
/// Activate the specified object and all of its children.
/// </summary>
static void Activate (Transform t) { Activate(t, true); }
/// <summary>
/// Activate the specified object and all of its children.
/// </summary>
static void Activate (Transform t, bool compatibilityMode)
{
SetActiveSelf(t.gameObject, true);
// Prior to Unity 4, active state was not nested. It was possible to have an enabled child of a disabled object.
// Unity 4 onwards made it so that the state is nested, and a disabled parent results in a disabled child.
#if UNITY_3_5
for (int i = 0, imax = t.GetChildCount(); i < imax; ++i)
{
Transform child = t.GetChild(i);
Activate(child);
}
#else
if (compatibilityMode)
{
// If there is even a single enabled child, then we're using a Unity 4.0-based nested active state scheme.
for (int i = 0, imax = t.childCount; i < imax; ++i)
{
Transform child = t.GetChild(i);
if (child.gameObject.activeSelf) return;
}
// If this point is reached, then all the children are disabled, so we must be using a Unity 3.5-based active state scheme.
for (int i = 0, imax = t.childCount; i < imax; ++i)
{
Transform child = t.GetChild(i);
Activate(child, true);
}
}
#endif
}
/// <summary>
/// Deactivate the specified object and all of its children.
/// </summary>
static void Deactivate (Transform t)
{
#if UNITY_3_5
for (int i = 0, imax = t.GetChildCount(); i < imax; ++i)
{
Transform child = t.GetChild(i);
Deactivate(child);
}
#endif
SetActiveSelf(t.gameObject, false);
}
/// <summary>
/// SetActiveRecursively enables children before parents. This is a problem when a widget gets re-enabled
/// and it tries to find a panel on its parent.
/// </summary>
static public void SetActive (GameObject go, bool state) { SetActive(go, state, true); }
/// <summary>
/// SetActiveRecursively enables children before parents. This is a problem when a widget gets re-enabled
/// and it tries to find a panel on its parent.
/// </summary>
static public void SetActive (GameObject go, bool state, bool compatibilityMode)
{
if (go)
{
if (state)
{
Activate(go.transform, compatibilityMode);
#if UNITY_EDITOR
if (Application.isPlaying)
#endif
CallCreatePanel(go.transform);
}
else Deactivate(go.transform);
}
}
/// <summary>
/// Ensure that all widgets have had their panels created, forcing the update right away rather than on the following frame.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static void CallCreatePanel (Transform t)
{
UIWidget w = t.GetComponent<UIWidget>();
if (w != null) w.CreatePanel();
for (int i = 0, imax = t.childCount; i < imax; ++i)
CallCreatePanel(t.GetChild(i));
}
/// <summary>
/// Activate or deactivate children of the specified game object without changing the active state of the object itself.
/// </summary>
static public void SetActiveChildren (GameObject go, bool state)
{
Transform t = go.transform;
if (state)
{
for (int i = 0, imax = t.childCount; i < imax; ++i)
{
Transform child = t.GetChild(i);
Activate(child);
}
}
else
{
for (int i = 0, imax = t.childCount; i < imax; ++i)
{
Transform child = t.GetChild(i);
Deactivate(child);
}
}
}
/// <summary>
/// Helper function that returns whether the specified MonoBehaviour is active.
/// </summary>
[System.Obsolete("Use NGUITools.GetActive instead")]
static public bool IsActive (Behaviour mb)
{
#if UNITY_3_5
return mb != null && mb.enabled && mb.gameObject.active;
#else
return mb != null && mb.enabled && mb.gameObject.activeInHierarchy;
#endif
}
/// <summary>
/// Helper function that returns whether the specified MonoBehaviour is active.
/// </summary>
static public bool GetActive (Behaviour mb)
{
#if UNITY_3_5
return mb != null && mb.enabled && mb.gameObject.active;
#else
return mb != null && mb.enabled && mb.gameObject.activeInHierarchy;
#endif
}
/// <summary>
/// Unity4 has changed GameObject.active to GameObject.activeself.
/// </summary>
static public bool GetActive (GameObject go)
{
#if UNITY_3_5
return go && go.active;
#else
return go && go.activeInHierarchy;
#endif
}
/// <summary>
/// Unity4 has changed GameObject.active to GameObject.SetActive.
/// </summary>
static public void SetActiveSelf (GameObject go, bool state)
{
#if UNITY_3_5
go.active = state;
#else
go.SetActive(state);
#endif
}
/// <summary>
/// Recursively set the game object's layer.
/// </summary>
static public void SetLayer (GameObject go, int layer)
{
go.layer = layer;
Transform t = go.transform;
for (int i = 0, imax = t.childCount; i < imax; ++i)
{
Transform child = t.GetChild(i);
SetLayer(child.gameObject, layer);
}
}
/// <summary>
/// Helper function used to make the vector use integer numbers.
/// </summary>
static public Vector3 Round (Vector3 v)
{
v.x = Mathf.Round(v.x);
v.y = Mathf.Round(v.y);
v.z = Mathf.Round(v.z);
return v;
}
/// <summary>
/// Make the specified selection pixel-perfect.
/// </summary>
static public void MakePixelPerfect (Transform t)
{
UIWidget w = t.GetComponent<UIWidget>();
if (w != null) w.MakePixelPerfect();
if (t.GetComponent<UIAnchor>() == null && t.GetComponent<UIRoot>() == null)
{
#if UNITY_EDITOR
RegisterUndo(t, "Make Pixel-Perfect");
#endif
t.localPosition = Round(t.localPosition);
t.localScale = Round(t.localScale);
}
// Recurse into children
for (int i = 0, imax = t.childCount; i < imax; ++i)
MakePixelPerfect(t.GetChild(i));
}
/// <summary>
/// Save the specified binary data into the specified file.
/// </summary>
static public bool Save (string fileName, byte[] bytes)
{
#if UNITY_WEBPLAYER || UNITY_FLASH || UNITY_METRO || UNITY_WP8
return false;
#else
if (!NGUITools.fileAccess) return false;
string path = Application.persistentDataPath + "/" + fileName;
if (bytes == null)
{
if (File.Exists(path)) File.Delete(path);
return true;
}
FileStream file = null;
try
{
file = File.Create(path);
}
catch (System.Exception ex)
{
NGUIDebug.Log(ex.Message);
return false;
}
file.Write(bytes, 0, bytes.Length);
file.Close();
return true;
#endif
}
/// <summary>
/// Load all binary data from the specified file.
/// </summary>
static public byte[] Load (string fileName)
{
#if UNITY_WEBPLAYER || UNITY_FLASH || UNITY_METRO || UNITY_WP8
return null;
#else
if (!NGUITools.fileAccess) return null;
string path = Application.persistentDataPath + "/" + fileName;
if (File.Exists(path))
{
return File.ReadAllBytes(path);
}
return null;
#endif
}
/// <summary>
/// Pre-multiply shaders result in a black outline if this operation is done in the shader. It's better to do it outside.
/// </summary>
static public Color ApplyPMA (Color c)
{
if (c.a != 1f)
{
c.r *= c.a;
c.g *= c.a;
c.b *= c.a;
}
return c;
}
/// <summary>
/// Inform all widgets underneath the specified object that the parent has changed.
/// </summary>
static public void MarkParentAsChanged (GameObject go)
{
UIRect[] rects = go.GetComponentsInChildren<UIRect>();
for (int i = 0, imax = rects.Length; i < imax; ++i)
rects[i].ParentHasChanged();
}
/// <summary>
/// Access to the clipboard via undocumented APIs.
/// </summary>
static public string clipboard
{
get
{
TextEditor te = new TextEditor();
te.Paste();
return te.content.text;
}
set
{
TextEditor te = new TextEditor();
te.content = new GUIContent(value);
te.OnFocus();
te.Copy();
}
}
[System.Obsolete("Use NGUIText.EncodeColor instead")]
static public string EncodeColor (Color c) { return NGUIText.EncodeColor(c); }
[System.Obsolete("Use NGUIText.ParseColor instead")]
static public Color ParseColor (string text, int offset) { return NGUIText.ParseColor(text, offset); }
[System.Obsolete("Use NGUIText.StripSymbols instead")]
static public string StripSymbols (string text) { return NGUIText.StripSymbols(text); }
/// <summary>
/// Extension for the game object that checks to see if the component already exists before adding a new one.
/// If the component is already present it will be returned instead.
/// </summary>
static public T AddMissingComponent<T> (this GameObject go) where T : Component
{
T comp = go.GetComponent<T>();
if (comp == null)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
RegisterUndo(go, "Add " + typeof(T));
#endif
comp = go.AddComponent<T>();
}
return comp;
}
// Temporary variable to avoid GC allocation
static Vector3[] mSides = new Vector3[4];
/// <summary>
/// Get sides relative to the specified camera. The order is left, top, right, bottom.
/// </summary>
static public Vector3[] GetSides (this Camera cam)
{
return cam.GetSides(Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f), null);
}
/// <summary>
/// Get sides relative to the specified camera. The order is left, top, right, bottom.
/// </summary>
static public Vector3[] GetSides (this Camera cam, float depth)
{
return cam.GetSides(depth, null);
}
/// <summary>
/// Get sides relative to the specified camera. The order is left, top, right, bottom.
/// </summary>
static public Vector3[] GetSides (this Camera cam, Transform relativeTo)
{
return cam.GetSides(Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f), relativeTo);
}
/// <summary>
/// Get sides relative to the specified camera. The order is left, top, right, bottom.
/// </summary>
static public Vector3[] GetSides (this Camera cam, float depth, Transform relativeTo)
{
mSides[0] = cam.ViewportToWorldPoint(new Vector3(0f, 0.5f, depth));
mSides[1] = cam.ViewportToWorldPoint(new Vector3(0.5f, 1f, depth));
mSides[2] = cam.ViewportToWorldPoint(new Vector3(1f, 0.5f, depth));
mSides[3] = cam.ViewportToWorldPoint(new Vector3(0.5f, 0f, depth));
if (relativeTo != null)
{
for (int i = 0; i < 4; ++i)
mSides[i] = relativeTo.InverseTransformPoint(mSides[i]);
}
return mSides;
}
/// <summary>
/// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
static public Vector3[] GetWorldCorners (this Camera cam)
{
return cam.GetWorldCorners(Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f), null);
}
/// <summary>
/// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
static public Vector3[] GetWorldCorners (this Camera cam, float depth)
{
return cam.GetWorldCorners(depth, null);
}
/// <summary>
/// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
static public Vector3[] GetWorldCorners (this Camera cam, Transform relativeTo)
{
return cam.GetWorldCorners(Mathf.Lerp(cam.nearClipPlane, cam.farClipPlane, 0.5f), relativeTo);
}
/// <summary>
/// Get the camera's world-space corners. The order is bottom-left, top-left, top-right, bottom-right.
/// </summary>
static public Vector3[] GetWorldCorners (this Camera cam, float depth, Transform relativeTo)
{
mSides[0] = cam.ViewportToWorldPoint(new Vector3(0f, 0f, depth));
mSides[1] = cam.ViewportToWorldPoint(new Vector3(0f, 1f, depth));
mSides[2] = cam.ViewportToWorldPoint(new Vector3(1f, 1f, depth));
mSides[3] = cam.ViewportToWorldPoint(new Vector3(1f, 0f, depth));
if (relativeTo != null)
{
for (int i = 0; i < 4; ++i)
mSides[i] = relativeTo.InverseTransformPoint(mSides[i]);
}
return mSides;
}
/// <summary>
/// Convenience function that converts Class + Function combo into Class.Function representation.
/// </summary>
static public string GetFuncName (object obj, string method)
{
if (obj == null) return "<null>";
if (string.IsNullOrEmpty(method)) return "<Choose>";
string type = obj.GetType().ToString();
int period = type.LastIndexOf('.');
if (period > 0) type = type.Substring(period + 1);
return type + "." + method;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/NGUITools.cs
|
C#
|
asf20
| 36,364
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// Helper class containing generic functions used throughout the UI library.
/// </summary>
static public class NGUIMath
{
/// <summary>
/// Lerp function that doesn't clamp the 'factor' in 0-1 range.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public float Lerp (float from, float to, float factor) { return from * (1f - factor) + to * factor; }
/// <summary>
/// Clamp the specified integer to be between 0 and below 'max'.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public int ClampIndex (int val, int max) { return (val < 0) ? 0 : (val < max ? val : max - 1); }
/// <summary>
/// Wrap the index using repeating logic, so that for example +1 past the end means index of '1'.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public int RepeatIndex (int val, int max)
{
if (max < 1) return 0;
while (val < 0) val += max;
while (val >= max) val -= max;
return val;
}
/// <summary>
/// Ensure that the angle is within -180 to 180 range.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public float WrapAngle (float angle)
{
while (angle > 180f) angle -= 360f;
while (angle < -180f) angle += 360f;
return angle;
}
/// <summary>
/// In the shader, equivalent function would be 'fract'
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public float Wrap01 (float val) { return val - Mathf.FloorToInt(val); }
/// <summary>
/// Convert a hexadecimal character to its decimal value.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public int HexToDecimal (char ch)
{
switch (ch)
{
case '0': return 0x0;
case '1': return 0x1;
case '2': return 0x2;
case '3': return 0x3;
case '4': return 0x4;
case '5': return 0x5;
case '6': return 0x6;
case '7': return 0x7;
case '8': return 0x8;
case '9': return 0x9;
case 'a':
case 'A': return 0xA;
case 'b':
case 'B': return 0xB;
case 'c':
case 'C': return 0xC;
case 'd':
case 'D': return 0xD;
case 'e':
case 'E': return 0xE;
case 'f':
case 'F': return 0xF;
}
return 0xF;
}
/// <summary>
/// Convert a single 0-15 value into its hex representation.
/// It's coded because int.ToString(format) syntax doesn't seem to be supported by Unity's Flash. It just silently crashes.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public char DecimalToHexChar (int num)
{
if (num > 15) return 'F';
if (num < 10) return (char)('0' + num);
return (char)('A' + num - 10);
}
/// <summary>
/// Convert a decimal value to its hex representation.
/// It's coded because num.ToString("X6") syntax doesn't seem to be supported by Unity's Flash. It just silently crashes.
/// string.Format("{0,6:X}", num).Replace(' ', '0') doesn't work either. It returns the format string, not the formatted value.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public string DecimalToHex (int num)
{
num &= 0xFFFFFF;
#if UNITY_FLASH
StringBuilder sb = new StringBuilder();
sb.Append(DecimalToHexChar((num >> 20) & 0xF));
sb.Append(DecimalToHexChar((num >> 16) & 0xF));
sb.Append(DecimalToHexChar((num >> 12) & 0xF));
sb.Append(DecimalToHexChar((num >> 8) & 0xF));
sb.Append(DecimalToHexChar((num >> 4) & 0xF));
sb.Append(DecimalToHexChar(num & 0xF));
return sb.ToString();
#else
return num.ToString("X6");
#endif
}
/// <summary>
/// Convert the specified color to RGBA32 integer format.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public int ColorToInt (Color c)
{
int retVal = 0;
retVal |= Mathf.RoundToInt(c.r * 255f) << 24;
retVal |= Mathf.RoundToInt(c.g * 255f) << 16;
retVal |= Mathf.RoundToInt(c.b * 255f) << 8;
retVal |= Mathf.RoundToInt(c.a * 255f);
return retVal;
}
/// <summary>
/// Convert the specified RGBA32 integer to Color.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public Color IntToColor (int val)
{
float inv = 1f / 255f;
Color c = Color.black;
c.r = inv * ((val >> 24) & 0xFF);
c.g = inv * ((val >> 16) & 0xFF);
c.b = inv * ((val >> 8) & 0xFF);
c.a = inv * (val & 0xFF);
return c;
}
/// <summary>
/// Convert the specified integer to a human-readable string representing the binary value. Useful for debugging bytes.
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public string IntToBinary (int val, int bits)
{
string final = "";
for (int i = bits; i > 0; )
{
if (i == 8 || i == 16 || i == 24) final += " ";
final += ((val & (1 << --i)) != 0) ? '1' : '0';
}
return final;
}
/// <summary>
/// Convenience conversion function, allowing hex format (0xRrGgBbAa).
/// </summary>
[System.Diagnostics.DebuggerHidden]
[System.Diagnostics.DebuggerStepThrough]
static public Color HexToColor (uint val)
{
return IntToColor((int)val);
}
/// <summary>
/// Convert from top-left based pixel coordinates to bottom-left based UV coordinates.
/// </summary>
static public Rect ConvertToTexCoords (Rect rect, int width, int height)
{
Rect final = rect;
if (width != 0f && height != 0f)
{
final.xMin = rect.xMin / width;
final.xMax = rect.xMax / width;
final.yMin = 1f - rect.yMax / height;
final.yMax = 1f - rect.yMin / height;
}
return final;
}
/// <summary>
/// Convert from bottom-left based UV coordinates to top-left based pixel coordinates.
/// </summary>
static public Rect ConvertToPixels (Rect rect, int width, int height, bool round)
{
Rect final = rect;
if (round)
{
final.xMin = Mathf.RoundToInt(rect.xMin * width);
final.xMax = Mathf.RoundToInt(rect.xMax * width);
final.yMin = Mathf.RoundToInt((1f - rect.yMax) * height);
final.yMax = Mathf.RoundToInt((1f - rect.yMin) * height);
}
else
{
final.xMin = rect.xMin * width;
final.xMax = rect.xMax * width;
final.yMin = (1f - rect.yMax) * height;
final.yMax = (1f - rect.yMin) * height;
}
return final;
}
/// <summary>
/// Round the pixel rectangle's dimensions.
/// </summary>
static public Rect MakePixelPerfect (Rect rect)
{
rect.xMin = Mathf.RoundToInt(rect.xMin);
rect.yMin = Mathf.RoundToInt(rect.yMin);
rect.xMax = Mathf.RoundToInt(rect.xMax);
rect.yMax = Mathf.RoundToInt(rect.yMax);
return rect;
}
/// <summary>
/// Round the texture coordinate rectangle's dimensions.
/// </summary>
static public Rect MakePixelPerfect (Rect rect, int width, int height)
{
rect = ConvertToPixels(rect, width, height, true);
rect.xMin = Mathf.RoundToInt(rect.xMin);
rect.yMin = Mathf.RoundToInt(rect.yMin);
rect.xMax = Mathf.RoundToInt(rect.xMax);
rect.yMax = Mathf.RoundToInt(rect.yMax);
return ConvertToTexCoords(rect, width, height);
}
/// <summary>
/// Constrain 'rect' to be within 'area' as much as possible, returning the Vector2 offset necessary for this to happen.
/// This function is useful when trying to restrict one area (window) to always be within another (viewport).
/// </summary>
static public Vector2 ConstrainRect (Vector2 minRect, Vector2 maxRect, Vector2 minArea, Vector2 maxArea)
{
Vector2 offset = Vector2.zero;
float contentX = maxRect.x - minRect.x;
float contentY = maxRect.y - minRect.y;
float areaX = maxArea.x - minArea.x;
float areaY = maxArea.y - minArea.y;
if (contentX > areaX)
{
float diff = contentX - areaX;
minArea.x -= diff;
maxArea.x += diff;
}
if (contentY > areaY)
{
float diff = contentY - areaY;
minArea.y -= diff;
maxArea.y += diff;
}
if (minRect.x < minArea.x) offset.x += minArea.x - minRect.x;
if (maxRect.x > maxArea.x) offset.x -= maxRect.x - maxArea.x;
if (minRect.y < minArea.y) offset.y += minArea.y - minRect.y;
if (maxRect.y > maxArea.y) offset.y -= maxRect.y - maxArea.y;
return offset;
}
/// <summary>
/// Calculate the combined bounds of all widgets attached to the specified game object or its children (in world space).
/// </summary>
static public Bounds CalculateAbsoluteWidgetBounds (Transform trans)
{
if (trans != null)
{
UIWidget[] widgets = trans.GetComponentsInChildren<UIWidget>() as UIWidget[];
if (widgets.Length == 0) return new Bounds(trans.position, Vector3.zero);
Vector3 vMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 vMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
for (int i = 0, imax = widgets.Length; i < imax; ++i)
{
UIWidget w = widgets[i];
if (!w.enabled) continue;
Vector3[] corners = w.worldCorners;
for (int j = 0; j < 4; ++j)
{
vMax = Vector3.Max(corners[j], vMax);
vMin = Vector3.Min(corners[j], vMin);
}
}
Bounds b = new Bounds(vMin, Vector3.zero);
b.Encapsulate(vMax);
return b;
}
return new Bounds(Vector3.zero, Vector3.zero);
}
/// <summary>
/// Calculate the combined bounds of all widgets attached to the specified game object or its children (in relative-to-object space).
/// </summary>
static public Bounds CalculateRelativeWidgetBounds (Transform trans)
{
return CalculateRelativeWidgetBounds(trans, trans, false);
}
/// <summary>
/// Calculate the combined bounds of all widgets attached to the specified game object or its children (in relative-to-object space).
/// </summary>
static public Bounds CalculateRelativeWidgetBounds (Transform trans, bool considerInactive)
{
return CalculateRelativeWidgetBounds(trans, trans, considerInactive);
}
/// <summary>
/// Calculate the combined bounds of all widgets attached to the specified game object or its children (in relative-to-object space).
/// </summary>
static public Bounds CalculateRelativeWidgetBounds (Transform relativeTo, Transform content)
{
return CalculateRelativeWidgetBounds(relativeTo, content, false);
}
/// <summary>
/// Calculate the combined bounds of all widgets attached to the specified game object or its children (in relative-to-object space).
/// </summary>
static public Bounds CalculateRelativeWidgetBounds (Transform relativeTo, Transform content, bool considerInactive)
{
if (content != null)
{
UIWidget[] widgets = content.GetComponentsInChildren<UIWidget>(considerInactive);
if (widgets.Length > 0)
{
Vector3 vMin = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3 vMax = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Matrix4x4 toLocal = relativeTo.worldToLocalMatrix;
bool isSet = false;
Vector3 v;
for (int i = 0, imax = widgets.Length; i < imax; ++i)
{
UIWidget w = widgets[i];
if (!considerInactive && !w.enabled) continue;
Vector3[] corners = w.worldCorners;
for (int j = 0; j < 4; ++j)
{
//v = root.InverseTransformPoint(corners[j]);
v = toLocal.MultiplyPoint3x4(corners[j]);
vMax = Vector3.Max(v, vMax);
vMin = Vector3.Min(v, vMin);
}
isSet = true;
}
if (isSet)
{
Bounds b = new Bounds(vMin, Vector3.zero);
b.Encapsulate(vMax);
return b;
}
}
}
return new Bounds(Vector3.zero, Vector3.zero);
}
/// <summary>
/// This code is not framerate-independent:
///
/// target.position += velocity;
/// velocity = Vector3.Lerp(velocity, Vector3.zero, Time.deltaTime * 9f);
///
/// But this code is:
///
/// target.position += NGUIMath.SpringDampen(ref velocity, 9f, Time.deltaTime);
/// </summary>
static public Vector3 SpringDampen (ref Vector3 velocity, float strength, float deltaTime)
{
if (deltaTime > 1f) deltaTime = 1f;
float dampeningFactor = 1f - strength * 0.001f;
int ms = Mathf.RoundToInt(deltaTime * 1000f);
float totalDampening = Mathf.Pow(dampeningFactor, ms);
Vector3 vTotal = velocity * ((totalDampening - 1f) / Mathf.Log(dampeningFactor));
velocity = velocity * totalDampening;
return vTotal * 0.06f;
}
/// <summary>
/// Same as the Vector3 version, it's a framerate-independent Lerp.
/// </summary>
static public Vector2 SpringDampen (ref Vector2 velocity, float strength, float deltaTime)
{
if (deltaTime > 1f) deltaTime = 1f;
float dampeningFactor = 1f - strength * 0.001f;
int ms = Mathf.RoundToInt(deltaTime * 1000f);
float totalDampening = Mathf.Pow(dampeningFactor, ms);
Vector2 vTotal = velocity * ((totalDampening - 1f) / Mathf.Log(dampeningFactor));
velocity = velocity * totalDampening;
return vTotal * 0.06f;
}
/// <summary>
/// Calculate how much to interpolate by.
/// </summary>
static public float SpringLerp (float strength, float deltaTime)
{
if (deltaTime > 1f) deltaTime = 1f;
int ms = Mathf.RoundToInt(deltaTime * 1000f);
deltaTime = 0.001f * strength;
float cumulative = 0f;
for (int i = 0; i < ms; ++i) cumulative = Mathf.Lerp(cumulative, 1f, deltaTime);
return cumulative;
}
/// <summary>
/// Mathf.Lerp(from, to, Time.deltaTime * strength) is not framerate-independent. This function is.
/// </summary>
static public float SpringLerp (float from, float to, float strength, float deltaTime)
{
if (deltaTime > 1f) deltaTime = 1f;
int ms = Mathf.RoundToInt(deltaTime * 1000f);
deltaTime = 0.001f * strength;
for (int i = 0; i < ms; ++i) from = Mathf.Lerp(from, to, deltaTime);
return from;
}
/// <summary>
/// Vector2.Lerp(from, to, Time.deltaTime * strength) is not framerate-independent. This function is.
/// </summary>
static public Vector2 SpringLerp (Vector2 from, Vector2 to, float strength, float deltaTime)
{
return Vector2.Lerp(from, to, SpringLerp(strength, deltaTime));
}
/// <summary>
/// Vector3.Lerp(from, to, Time.deltaTime * strength) is not framerate-independent. This function is.
/// </summary>
static public Vector3 SpringLerp (Vector3 from, Vector3 to, float strength, float deltaTime)
{
return Vector3.Lerp(from, to, SpringLerp(strength, deltaTime));
}
/// <summary>
/// Quaternion.Slerp(from, to, Time.deltaTime * strength) is not framerate-independent. This function is.
/// </summary>
static public Quaternion SpringLerp (Quaternion from, Quaternion to, float strength, float deltaTime)
{
return Quaternion.Slerp(from, to, SpringLerp(strength, deltaTime));
}
/// <summary>
/// Since there is no Mathf.RotateTowards...
/// </summary>
static public float RotateTowards (float from, float to, float maxAngle)
{
float diff = WrapAngle(to - from);
if (Mathf.Abs(diff) > maxAngle) diff = maxAngle * Mathf.Sign(diff);
return from + diff;
}
/// <summary>
/// Determine the distance from the specified point to the line segment.
/// </summary>
static float DistancePointToLineSegment (Vector2 point, Vector2 a, Vector2 b)
{
float l2 = (b - a).sqrMagnitude;
if (l2 == 0f) return (point - a).magnitude;
float t = Vector2.Dot(point - a, b - a) / l2;
if (t < 0f) return (point - a).magnitude;
else if (t > 1f) return (point - b).magnitude;
Vector2 projection = a + t * (b - a);
return (point - projection).magnitude;
}
/// <summary>
/// Determine the distance from the mouse position to the screen space rectangle specified by the 4 points.
/// </summary>
static public float DistanceToRectangle (Vector2[] screenPoints, Vector2 mousePos)
{
bool oddNodes = false;
int j = 4;
for (int i = 0; i < 5; i++)
{
Vector3 v0 = screenPoints[NGUIMath.RepeatIndex(i, 4)];
Vector3 v1 = screenPoints[NGUIMath.RepeatIndex(j, 4)];
if ((v0.y > mousePos.y) != (v1.y > mousePos.y))
{
if (mousePos.x < (v1.x - v0.x) * (mousePos.y - v0.y) / (v1.y - v0.y) + v0.x)
{
oddNodes = !oddNodes;
}
}
j = i;
}
if (!oddNodes)
{
float dist, closestDist = -1f;
for (int i = 0; i < 4; i++)
{
Vector3 v0 = screenPoints[i];
Vector3 v1 = screenPoints[NGUIMath.RepeatIndex(i + 1, 4)];
dist = DistancePointToLineSegment(mousePos, v0, v1);
if (dist < closestDist || closestDist < 0f) closestDist = dist;
}
return closestDist;
}
else return 0f;
}
/// <summary>
/// Determine the distance from the mouse position to the world rectangle specified by the 4 points.
/// </summary>
static public float DistanceToRectangle (Vector3[] worldPoints, Vector2 mousePos, Camera cam)
{
Vector2[] screenPoints = new Vector2[4];
for (int i = 0; i < 4; ++i)
screenPoints[i] = cam.WorldToScreenPoint(worldPoints[i]);
return DistanceToRectangle(screenPoints, mousePos);
}
/// <summary>
/// Helper function that converts the widget's pivot enum into a 0-1 range vector.
/// </summary>
static public Vector2 GetPivotOffset (UIWidget.Pivot pv)
{
Vector2 v = Vector2.zero;
if (pv == UIWidget.Pivot.Top || pv == UIWidget.Pivot.Center || pv == UIWidget.Pivot.Bottom) v.x = 0.5f;
else if (pv == UIWidget.Pivot.TopRight || pv == UIWidget.Pivot.Right || pv == UIWidget.Pivot.BottomRight) v.x = 1f;
else v.x = 0f;
if (pv == UIWidget.Pivot.Left || pv == UIWidget.Pivot.Center || pv == UIWidget.Pivot.Right) v.y = 0.5f;
else if (pv == UIWidget.Pivot.TopLeft || pv == UIWidget.Pivot.Top || pv == UIWidget.Pivot.TopRight) v.y = 1f;
else v.y = 0f;
return v;
}
/// <summary>
/// Helper function that converts the pivot offset to a pivot point.
/// </summary>
static public UIWidget.Pivot GetPivot (Vector2 offset)
{
if (offset.x == 0f)
{
if (offset.y == 0f) return UIWidget.Pivot.BottomLeft;
if (offset.y == 1f) return UIWidget.Pivot.TopLeft;
return UIWidget.Pivot.Left;
}
else if (offset.x == 1f)
{
if (offset.y == 0f) return UIWidget.Pivot.BottomRight;
if (offset.y == 1f) return UIWidget.Pivot.TopRight;
return UIWidget.Pivot.Right;
}
else
{
if (offset.y == 0f) return UIWidget.Pivot.Bottom;
if (offset.y == 1f) return UIWidget.Pivot.Top;
return UIWidget.Pivot.Center;
}
}
/// <summary>
/// Adjust the widget's position using the specified local delta coordinates.
/// </summary>
static public void MoveWidget (UIRect w, float x, float y) { MoveRect(w, x, y); }
/// <summary>
/// Adjust the rectangle's position using the specified local delta coordinates.
/// </summary>
static public void MoveRect (UIRect rect, float x, float y)
{
int ix = Mathf.FloorToInt(x + 0.5f);
int iy = Mathf.FloorToInt(y + 0.5f);
Transform t = rect.cachedTransform;
t.localPosition += new Vector3(ix, iy);
int anchorCount = 0;
if (rect.leftAnchor.target)
{
++anchorCount;
rect.leftAnchor.absolute += ix;
}
if (rect.rightAnchor.target)
{
++anchorCount;
rect.rightAnchor.absolute += ix;
}
if (rect.bottomAnchor.target)
{
++anchorCount;
rect.bottomAnchor.absolute += iy;
}
if (rect.topAnchor.target)
{
++anchorCount;
rect.topAnchor.absolute += iy;
}
#if UNITY_EDITOR
NGUITools.SetDirty(rect);
#endif
// If all sides were anchored, we're done
if (anchorCount != 0) rect.UpdateAnchors();
}
/// <summary>
/// Given the specified dragged pivot point, adjust the widget's dimensions.
/// </summary>
static public void ResizeWidget (UIWidget w, UIWidget.Pivot pivot, float x, float y, int minWidth, int minHeight)
{
ResizeWidget(w, pivot, x, y, 2, 2, 100000, 100000);
}
/// <summary>
/// Given the specified dragged pivot point, adjust the widget's dimensions.
/// </summary>
static public void ResizeWidget (UIWidget w, UIWidget.Pivot pivot, float x, float y, int minWidth, int minHeight, int maxWidth, int maxHeight)
{
if (pivot == UIWidget.Pivot.Center)
{
int diffX = Mathf.RoundToInt(x - w.width);
int diffY = Mathf.RoundToInt(y - w.height);
diffX = diffX - (diffX & 1);
diffY = diffY - (diffY & 1);
if ((diffX | diffY) != 0)
{
diffX >>= 1;
diffY >>= 1;
AdjustWidget(w, -diffX, -diffY, diffX, diffY, minWidth, minHeight);
}
return;
}
Vector3 v = new Vector3(x, y);
v = Quaternion.Inverse(w.cachedTransform.localRotation) * v;
switch (pivot)
{
case UIWidget.Pivot.BottomLeft:
AdjustWidget(w, v.x, v.y, 0, 0, minWidth, minHeight, maxWidth, maxHeight);
break;
case UIWidget.Pivot.Left:
AdjustWidget(w, v.x, 0, 0, 0, minWidth, minHeight, maxWidth, maxHeight);
break;
case UIWidget.Pivot.TopLeft:
AdjustWidget(w, v.x, 0, 0, v.y, minWidth, minHeight, maxWidth, maxHeight);
break;
case UIWidget.Pivot.Top:
AdjustWidget(w, 0, 0, 0, v.y, minWidth, minHeight, maxWidth, maxHeight);
break;
case UIWidget.Pivot.TopRight:
AdjustWidget(w, 0, 0, v.x, v.y, minWidth, minHeight, maxWidth, maxHeight);
break;
case UIWidget.Pivot.Right:
AdjustWidget(w, 0, 0, v.x, 0, minWidth, minHeight, maxWidth, maxHeight);
break;
case UIWidget.Pivot.BottomRight:
AdjustWidget(w, 0, v.y, v.x, 0, minWidth, minHeight, maxWidth, maxHeight);
break;
case UIWidget.Pivot.Bottom:
AdjustWidget(w, 0, v.y, 0, 0, minWidth, minHeight, maxWidth, maxHeight);
break;
}
}
/// <summary>
/// Adjust the widget's rectangle based on the specified modifier values.
/// </summary>
static public void AdjustWidget (UIWidget w, float left, float bottom, float right, float top)
{
AdjustWidget(w, left, bottom, right, top, 2, 2, 100000, 100000);
}
/// <summary>
/// Adjust the widget's rectangle based on the specified modifier values.
/// </summary>
static public void AdjustWidget (UIWidget w, float left, float bottom, float right, float top, int minWidth, int minHeight)
{
AdjustWidget(w, left, bottom, right, top, minWidth, minHeight, 100000, 100000);
}
/// <summary>
/// Adjust the widget's rectangle based on the specified modifier values.
/// </summary>
static public void AdjustWidget (UIWidget w, float left, float bottom, float right, float top,
int minWidth, int minHeight, int maxWidth, int maxHeight)
{
Vector2 piv = w.pivotOffset;
Transform t = w.cachedTransform;
Quaternion rot = t.localRotation;
// We should be working with whole integers
int iLeft = Mathf.FloorToInt(left + 0.5f);
int iBottom = Mathf.FloorToInt(bottom + 0.5f);
int iRight = Mathf.FloorToInt(right + 0.5f);
int iTop = Mathf.FloorToInt(top + 0.5f);
// Centered pivot should mean having to perform even number adjustments
if (piv.x == 0.5f && (iLeft == 0 || iRight == 0))
{
iLeft = ((iLeft >> 1) << 1);
iRight = ((iRight >> 1) << 1);
}
if (piv.y == 0.5f && (iBottom == 0 || iTop == 0))
{
iBottom = ((iBottom >> 1) << 1);
iTop = ((iTop >> 1) << 1);
}
// The widget's position (pivot point) uses a different coordinate system than
// other corners. This is a source of major PITA, and results in a lot of extra math.
Vector3 rotatedTL = rot * new Vector3(iLeft, iTop);
Vector3 rotatedTR = rot * new Vector3(iRight, iTop);
Vector3 rotatedBL = rot * new Vector3(iLeft, iBottom);
Vector3 rotatedBR = rot * new Vector3(iRight, iBottom);
Vector3 rotatedL = rot * new Vector3(iLeft, 0f);
Vector3 rotatedR = rot * new Vector3(iRight, 0f);
Vector3 rotatedT = rot * new Vector3(0f, iTop);
Vector3 rotatedB = rot * new Vector3(0f, iBottom);
Vector3 offset = Vector3.zero;
if (piv.x == 0f && piv.y == 1f)
{
offset.x = rotatedTL.x;
offset.y = rotatedTL.y;
}
else if (piv.x == 1f && piv.y == 0f)
{
offset.x = rotatedBR.x;
offset.y = rotatedBR.y;
}
else if (piv.x == 0f && piv.y == 0f)
{
offset.x = rotatedBL.x;
offset.y = rotatedBL.y;
}
else if (piv.x == 1f && piv.y == 1f)
{
offset.x = rotatedTR.x;
offset.y = rotatedTR.y;
}
else if (piv.x == 0f && piv.y == 0.5f)
{
offset.x = rotatedL.x + (rotatedT.x + rotatedB.x) * 0.5f;
offset.y = rotatedL.y + (rotatedT.y + rotatedB.y) * 0.5f;
}
else if (piv.x == 1f && piv.y == 0.5f)
{
offset.x = rotatedR.x + (rotatedT.x + rotatedB.x) * 0.5f;
offset.y = rotatedR.y + (rotatedT.y + rotatedB.y) * 0.5f;
}
else if (piv.x == 0.5f && piv.y == 1f)
{
offset.x = rotatedT.x + (rotatedL.x + rotatedR.x) * 0.5f;
offset.y = rotatedT.y + (rotatedL.y + rotatedR.y) * 0.5f;
}
else if (piv.x == 0.5f && piv.y == 0f)
{
offset.x = rotatedB.x + (rotatedL.x + rotatedR.x) * 0.5f;
offset.y = rotatedB.y + (rotatedL.y + rotatedR.y) * 0.5f;
}
else if (piv.x == 0.5f && piv.y == 0.5f)
{
offset.x = (rotatedL.x + rotatedR.x + rotatedT.x + rotatedB.x) * 0.5f;
offset.y = (rotatedT.y + rotatedB.y + rotatedL.y + rotatedR.y) * 0.5f;
}
minWidth = Mathf.Max(minWidth, w.minWidth);
minHeight = Mathf.Max(minHeight, w.minHeight);
// Calculate the widget's width and height after the requested adjustments
int finalWidth = w.width + iRight - iLeft;
int finalHeight = w.height + iTop - iBottom;
// Now it's time to constrain the width and height so that they can't go below min values
Vector3 constraint = Vector3.zero;
int limitWidth = finalWidth;
if (finalWidth < minWidth) limitWidth = minWidth;
else if (finalWidth > maxWidth) limitWidth = maxWidth;
if (finalWidth != limitWidth)
{
if (iLeft != 0) constraint.x -= Mathf.Lerp(limitWidth - finalWidth, 0f, piv.x);
else constraint.x += Mathf.Lerp(0f, limitWidth - finalWidth, piv.x);
finalWidth = limitWidth;
}
int limitHeight = finalHeight;
if (finalHeight < minHeight) limitHeight = minHeight;
else if (finalHeight > maxHeight) limitHeight = maxHeight;
if (finalHeight != limitHeight)
{
if (iBottom != 0) constraint.y -= Mathf.Lerp(limitHeight - finalHeight, 0f, piv.y);
else constraint.y += Mathf.Lerp(0f, limitHeight - finalHeight, piv.y);
finalHeight = limitHeight;
}
// Centered pivot requires power-of-two dimensions
if (piv.x == 0.5f) finalWidth = ((finalWidth >> 1) << 1);
if (piv.y == 0.5f) finalHeight = ((finalHeight >> 1) << 1);
// Update the position, width and height
Vector3 pos = t.localPosition + offset + rot * constraint;
t.localPosition = pos;
w.SetDimensions(finalWidth, finalHeight);
// If the widget is anchored, we should update the anchors as well
if (w.isAnchored)
{
t = t.parent;
float x = pos.x - piv.x * finalWidth;
float y = pos.y - piv.y * finalHeight;
if (w.leftAnchor.target) w.leftAnchor.SetHorizontal(t, x);
if (w.rightAnchor.target) w.rightAnchor.SetHorizontal(t, x + finalWidth);
if (w.bottomAnchor.target) w.bottomAnchor.SetVertical(t, y);
if (w.topAnchor.target) w.topAnchor.SetVertical(t, y + finalHeight);
}
#if UNITY_EDITOR
NGUITools.SetDirty(w);
#endif
}
/// <summary>
/// Adjust the specified value by DPI: height * 96 / DPI.
/// This will result in in a smaller value returned for higher pixel density devices.
/// </summary>
static public int AdjustByDPI (float height)
{
float dpi = Screen.dpi;
RuntimePlatform platform = Application.platform;
if (dpi == 0f)
{
dpi = (platform == RuntimePlatform.Android || platform == RuntimePlatform.IPhonePlayer) ? 160f : 96f;
#if UNITY_BLACKBERRY
if (platform == RuntimePlatform.BB10Player) dpi = 160f;
#elif UNITY_WP8
if (platform == RuntimePlatform.WP8Player) dpi = 160f;
#endif
}
int h = Mathf.RoundToInt(height * (96f / dpi));
if ((h & 1) == 1) ++h;
return h;
}
/// <summary>
/// Convert the specified position, making it relative to the specified object.
/// </summary>
static public Vector2 ScreenToPixels (Vector2 pos, Transform relativeTo)
{
int layer = relativeTo.gameObject.layer;
Camera cam = NGUITools.FindCameraForLayer(layer);
if (cam == null)
{
Debug.LogWarning("No camera found for layer " + layer);
return pos;
}
Vector3 wp = cam.ScreenToWorldPoint(pos);
return relativeTo.InverseTransformPoint(wp);
}
/// <summary>
/// Convert the specified position, making it relative to the specified object's parent.
/// Useful if you plan on positioning the widget using the specified value (think mouse cursor).
/// </summary>
static public Vector2 ScreenToParentPixels (Vector2 pos, Transform relativeTo)
{
int layer = relativeTo.gameObject.layer;
if (relativeTo.parent != null)
relativeTo = relativeTo.parent;
Camera cam = NGUITools.FindCameraForLayer(layer);
if (cam == null)
{
Debug.LogWarning("No camera found for layer " + layer);
return pos;
}
Vector3 wp = cam.ScreenToWorldPoint(pos);
return (relativeTo != null) ? relativeTo.InverseTransformPoint(wp) : wp;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/NGUIMath.cs
|
C#
|
asf20
| 28,811
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Symbols are a sequence of characters such as ":)" that get replaced with a sprite, such as the smiley face.
/// </summary>
[System.Serializable]
public class BMSymbol
{
public string sequence;
public string spriteName;
UISpriteData mSprite = null;
bool mIsValid = false;
int mLength = 0;
int mOffsetX = 0; // (outer - inner) in pixels
int mOffsetY = 0; // (outer - inner) in pixels
int mWidth = 0; // Symbol's width in pixels (sprite.outer.width)
int mHeight = 0; // Symbol's height in pixels (sprite.outer.height)
int mAdvance = 0; // Symbol's inner width in pixels (sprite.inner.width)
Rect mUV;
public int length { get { if (mLength == 0) mLength = sequence.Length; return mLength; } }
public int offsetX { get { return mOffsetX; } }
public int offsetY { get { return mOffsetY; } }
public int width { get { return mWidth; } }
public int height { get { return mHeight; } }
public int advance { get { return mAdvance; } }
public Rect uvRect { get { return mUV; } }
/// <summary>
/// Mark this symbol as dirty, clearing the sprite reference.
/// </summary>
public void MarkAsChanged () { mIsValid = false; }
/// <summary>
/// Validate this symbol, given the specified atlas.
/// </summary>
public bool Validate (UIAtlas atlas)
{
if (atlas == null) return false;
#if UNITY_EDITOR
if (!Application.isPlaying || !mIsValid)
#else
if (!mIsValid)
#endif
{
if (string.IsNullOrEmpty(spriteName)) return false;
mSprite = (atlas != null) ? atlas.GetSprite(spriteName) : null;
if (mSprite != null)
{
Texture tex = atlas.texture;
if (tex == null)
{
mSprite = null;
}
else
{
mUV = new Rect(mSprite.x, mSprite.y, mSprite.width, mSprite.height);
mUV = NGUIMath.ConvertToTexCoords(mUV, tex.width, tex.height);
mOffsetX = mSprite.paddingLeft;
mOffsetY = mSprite.paddingTop;
mWidth = mSprite.width;
mHeight = mSprite.height;
mAdvance = mSprite.width + (mSprite.paddingLeft + mSprite.paddingRight);
mIsValid = true;
}
}
}
return (mSprite != null);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/BMSymbol.cs
|
C#
|
asf20
| 2,334
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_EDITOR || (!UNITY_FLASH && !NETFX_CORE && !UNITY_WP8)
#define REFLECTION_SUPPORT
#endif
#if REFLECTION_SUPPORT
using System.Reflection;
#endif
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Delegate callback that Unity can serialize and set via Inspector.
/// </summary>
[System.Serializable]
public class EventDelegate
{
/// <summary>
/// Delegates can have parameters, and this class makes it possible to save references to properties
/// that can then be passed as function arguments, such as transform.position or widget.color.
/// </summary>
[System.Serializable]
public class Parameter
{
public Object obj;
public string field;
[System.NonSerialized]
public System.Type expectedType = typeof(void);
#if REFLECTION_SUPPORT
// Cached values
[System.NonSerialized] public bool cached = false;
[System.NonSerialized] public PropertyInfo propInfo;
[System.NonSerialized] public FieldInfo fieldInfo;
/// <summary>
/// Return the property's current value.
/// </summary>
public object value
{
get
{
if (!cached)
{
cached = true;
fieldInfo = null;
propInfo = null;
if (obj != null && !string.IsNullOrEmpty(field))
{
System.Type type = obj.GetType();
propInfo = type.GetProperty(field);
if (propInfo == null) fieldInfo = type.GetField(field);
}
}
if (propInfo != null) return propInfo.GetValue(obj, null);
if (fieldInfo != null) return fieldInfo.GetValue(obj);
return obj;
}
}
/// <summary>
/// Parameter type -- a convenience function.
/// </summary>
public System.Type type
{
get
{
if (obj == null) return typeof(void);
return obj.GetType();
}
}
#else
public object value { get { return obj; } }
public System.Type type { get { return typeof(void); } }
#endif
}
[SerializeField] MonoBehaviour mTarget;
[SerializeField] string mMethodName;
[SerializeField] Parameter[] mParameters;
/// <summary>
/// Whether the event delegate will be removed after execution.
/// </summary>
public bool oneShot = false;
// Private variables
public delegate void Callback();
Callback mCachedCallback;
bool mRawDelegate = false;
bool mCached = false;
#if REFLECTION_SUPPORT
MethodInfo mMethod;
object[] mArgs;
#endif
/// <summary>
/// Event delegate's target object.
/// </summary>
public MonoBehaviour target
{
get
{
return mTarget;
}
set
{
mTarget = value;
mCachedCallback = null;
mRawDelegate = false;
mCached = false;
#if REFLECTION_SUPPORT
mMethod = null;
#endif
mParameters = null;
}
}
/// <summary>
/// Event delegate's method name.
/// </summary>
public string methodName
{
get
{
return mMethodName;
}
set
{
mMethodName = value;
mCachedCallback = null;
mRawDelegate = false;
mCached = false;
#if REFLECTION_SUPPORT
mMethod = null;
#endif
mParameters = null;
}
}
/// <summary>
/// Optional parameters if the method requires them.
/// </summary>
public Parameter[] parameters
{
get
{
#if UNITY_EDITOR
if (!mCached || !Application.isPlaying) Cache();
#else
if (!mCached) Cache();
#endif
return mParameters;
}
}
/// <summary>
/// Whether this delegate's values have been set.
/// </summary>
public bool isValid
{
get
{
#if UNITY_EDITOR
if (!mCached || !Application.isPlaying) Cache();
#else
if (!mCached) Cache();
#endif
return (mRawDelegate && mCachedCallback != null) || (mTarget != null && !string.IsNullOrEmpty(mMethodName));
}
}
/// <summary>
/// Whether the target script is actually enabled.
/// </summary>
public bool isEnabled
{
get
{
#if UNITY_EDITOR
if (!mCached || !Application.isPlaying) Cache();
#else
if (!mCached) Cache();
#endif
if (mRawDelegate && mCachedCallback != null) return true;
if (mTarget == null) return false;
MonoBehaviour mb = (mTarget as MonoBehaviour);
return (mb == null || mb.enabled);
}
}
public EventDelegate () { }
public EventDelegate (Callback call) { Set(call); }
public EventDelegate (MonoBehaviour target, string methodName) { Set(target, methodName); }
/// <summary>
/// GetMethodName is not supported on some platforms.
/// </summary>
#if REFLECTION_SUPPORT
#if !UNITY_EDITOR && UNITY_WP8
static string GetMethodName (Callback callback)
{
System.Delegate d = callback as System.Delegate;
return d.Method.Name;
}
static bool IsValid (Callback callback)
{
System.Delegate d = callback as System.Delegate;
return d != null && d.Method != null;
}
#elif !UNITY_EDITOR && UNITY_METRO
static string GetMethodName (Callback callback)
{
System.Delegate d = callback as System.Delegate;
return d.GetMethodInfo().Name;
}
static bool IsValid (Callback callback)
{
System.Delegate d = callback as System.Delegate;
return d != null && d.GetMethodInfo() != null;
}
#else
static string GetMethodName (Callback callback) { return callback.Method.Name; }
static bool IsValid (Callback callback) { return callback != null && callback.Method != null; }
#endif
#else
static bool IsValid (Callback callback) { return callback != null; }
#endif
/// <summary>
/// Equality operator.
/// </summary>
public override bool Equals (object obj)
{
if (obj == null) return !isValid;
if (obj is Callback)
{
Callback callback = obj as Callback;
#if REFLECTION_SUPPORT
if (callback.Equals(mCachedCallback)) return true;
MonoBehaviour mb = callback.Target as MonoBehaviour;
return (mTarget == mb && string.Equals(mMethodName, GetMethodName(callback)));
#elif UNITY_FLASH
return (callback == mCachedCallback);
#else
return callback.Equals(mCachedCallback);
#endif
}
if (obj is EventDelegate)
{
EventDelegate del = obj as EventDelegate;
return (mTarget == del.mTarget && string.Equals(mMethodName, del.mMethodName));
}
return false;
}
static int s_Hash = "EventDelegate".GetHashCode();
/// <summary>
/// Used in equality operators.
/// </summary>
public override int GetHashCode () { return s_Hash; }
/// <summary>
/// Set the delegate callback directly.
/// </summary>
void Set (Callback call)
{
Clear();
if (call != null && IsValid(call))
{
#if REFLECTION_SUPPORT
mTarget = call.Target as MonoBehaviour;
if (mTarget == null)
{
mRawDelegate = true;
mCachedCallback = call;
mMethodName = null;
}
else
{
mMethodName = GetMethodName(call);
mRawDelegate = false;
}
#else
mRawDelegate = true;
mCachedCallback = call;
#endif
}
}
/// <summary>
/// Set the delegate callback using the target and method names.
/// </summary>
public void Set (MonoBehaviour target, string methodName)
{
Clear();
mTarget = target;
mMethodName = methodName;
}
/// <summary>
/// Cache the callback and create the list of the necessary parameters.
/// </summary>
void Cache ()
{
mCached = true;
if (mRawDelegate) return;
#if REFLECTION_SUPPORT
if (mCachedCallback == null || (mCachedCallback.Target as MonoBehaviour) != mTarget || GetMethodName(mCachedCallback) != mMethodName)
{
if (mTarget != null && !string.IsNullOrEmpty(mMethodName))
{
#if NETFX_CORE
System.Type type = mTarget.GetTypeInfo();
#else
System.Type type = mTarget.GetType();
#endif
try
{
mMethod = type.GetMethod(mMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
}
catch (System.Exception ex)
{
Debug.LogError("Failed to bind " + type + "." + mMethodName + "\n" + ex.Message);
return;
}
if (mMethod == null)
{
Debug.LogError("Could not find method '" + mMethodName + "' on " + mTarget.GetType(), mTarget);
return;
}
if (mMethod.ReturnType != typeof(void))
{
Debug.LogError(mTarget.GetType() + "." + mMethodName + " must have a 'void' return type.", mTarget);
return;
}
// Get the list of expected parameters
ParameterInfo[] info = mMethod.GetParameters();
if (info.Length == 0)
{
// No parameters means we can create a simple delegate for it, optimizing the call
mCachedCallback = (Callback)System.Delegate.CreateDelegate(typeof(Callback), mTarget, mMethodName);
mArgs = null;
mParameters = null;
return;
}
else mCachedCallback = null;
// Allocate the initial list of parameters
if (mParameters == null || mParameters.Length != info.Length)
{
mParameters = new Parameter[info.Length];
for (int i = 0, imax = mParameters.Length; i < imax; ++i)
mParameters[i] = new Parameter();
}
// Save the parameter type
for (int i = 0, imax = mParameters.Length; i < imax; ++i)
mParameters[i].expectedType = info[i].ParameterType;
}
}
#endif
}
/// <summary>
/// Execute the delegate, if possible.
/// This will only be used when the application is playing in order to prevent unintentional state changes.
/// </summary>
public bool Execute ()
{
#if !REFLECTION_SUPPORT
if (isValid)
{
if (mRawDelegate) mCachedCallback();
else mTarget.SendMessage(mMethodName, SendMessageOptions.DontRequireReceiver);
return true;
}
#else
#if UNITY_EDITOR
if (!mCached || !Application.isPlaying) Cache();
#else
if (!mCached) Cache();
#endif
if (mCachedCallback != null)
{
#if !UNITY_EDITOR
mCachedCallback();
#else
if (Application.isPlaying)
{
mCachedCallback();
}
else if (mCachedCallback.Target != null)
{
// There must be an [ExecuteInEditMode] flag on the script for us to call the function at edit time
System.Type type = mCachedCallback.Target.GetType();
object[] objs = type.GetCustomAttributes(typeof(ExecuteInEditMode), true);
if (objs != null && objs.Length > 0) mCachedCallback();
}
#endif
return true;
}
if (mMethod != null)
{
#if UNITY_EDITOR
// There must be an [ExecuteInEditMode] flag on the script for us to call the function at edit time
if (mTarget != null && !Application.isPlaying)
{
System.Type type = mTarget.GetType();
object[] objs = type.GetCustomAttributes(typeof(ExecuteInEditMode), true);
if (objs == null || objs.Length == 0) return true;
}
#endif
int len = (mParameters != null) ? mParameters.Length : 0;
if (len == 0)
{
mMethod.Invoke(mTarget, null);
}
else
{
// Allocate the parameter array
if (mArgs == null || mArgs.Length != mParameters.Length)
mArgs = new object[mParameters.Length];
// Set all the parameters
for (int i = 0, imax = mParameters.Length; i < imax; ++i)
mArgs[i] = mParameters[i].value;
// Invoke the callback
try
{
mMethod.Invoke(mTarget, mArgs);
}
catch (System.ArgumentException ex)
{
string msg = ex.Message;
msg += "\nExpected: ";
ParameterInfo[] pis = mMethod.GetParameters();
if (pis.Length == 0)
{
msg += "no arguments";
}
else
{
msg += pis[0];
for (int i = 1; i < pis.Length; ++i)
msg += ", " + pis[i].ParameterType;
}
msg += "\nGot: ";
if (mParameters.Length == 0)
{
msg += "no arguments";
}
else
{
msg += mParameters[0].type;
for (int i = 1; i < mParameters.Length; ++i)
msg += ", " + mParameters[i].type;
}
msg += "\n";
Debug.LogError(msg);
}
// Clear the parameters so that references are not kept
for (int i = 0, imax = mArgs.Length; i < imax; ++i) mArgs[i] = null;
}
return true;
}
#endif
return false;
}
/// <summary>
/// Clear the event delegate.
/// </summary>
public void Clear ()
{
mTarget = null;
mMethodName = null;
mRawDelegate = false;
mCachedCallback = null;
mParameters = null;
mCached = false;
#if REFLECTION_SUPPORT
mMethod = null;
mArgs = null;
#endif
}
/// <summary>
/// Convert the delegate to its string representation.
/// </summary>
public override string ToString ()
{
if (mTarget != null)
{
string typeName = mTarget.GetType().ToString();
int period = typeName.LastIndexOf('.');
if (period > 0) typeName = typeName.Substring(period + 1);
if (!string.IsNullOrEmpty(methodName)) return typeName + "." + methodName;
else return typeName + ".[delegate]";
}
return mRawDelegate ? "[delegate]" : null;
}
/// <summary>
/// Execute an entire list of delegates.
/// </summary>
static public void Execute (List<EventDelegate> list)
{
if (list != null)
{
for (int i = 0; i < list.Count; )
{
EventDelegate del = list[i];
if (del != null)
{
del.Execute();
if (i >= list.Count) break;
if (list[i] != del) continue;
if (del.oneShot)
{
list.RemoveAt(i);
continue;
}
}
++i;
}
}
}
/// <summary>
/// Convenience function to check if the specified list of delegates can be executed.
/// </summary>
static public bool IsValid (List<EventDelegate> list)
{
if (list != null)
{
for (int i = 0, imax = list.Count; i < imax; ++i)
{
EventDelegate del = list[i];
if (del != null && del.isValid)
return true;
}
}
return false;
}
/// <summary>
/// Assign a new event delegate.
/// </summary>
static public void Set (List<EventDelegate> list, Callback callback)
{
if (list != null)
{
list.Clear();
list.Add(new EventDelegate(callback));
}
}
/// <summary>
/// Assign a new event delegate.
/// </summary>
static public void Set (List<EventDelegate> list, EventDelegate del)
{
if (list != null)
{
list.Clear();
list.Add(del);
}
}
/// <summary>
/// Append a new event delegate to the list.
/// </summary>
static public void Add (List<EventDelegate> list, Callback callback) { Add(list, callback, false); }
/// <summary>
/// Append a new event delegate to the list.
/// </summary>
static public void Add (List<EventDelegate> list, Callback callback, bool oneShot)
{
if (list != null)
{
for (int i = 0, imax = list.Count; i < imax; ++i)
{
EventDelegate del = list[i];
if (del != null && del.Equals(callback))
return;
}
EventDelegate ed = new EventDelegate(callback);
ed.oneShot = oneShot;
list.Add(ed);
}
else
{
Debug.LogWarning("Attempting to add a callback to a list that's null");
}
}
/// <summary>
/// Append a new event delegate to the list.
/// </summary>
static public void Add (List<EventDelegate> list, EventDelegate ev) { Add(list, ev, ev.oneShot); }
/// <summary>
/// Append a new event delegate to the list.
/// </summary>
static public void Add (List<EventDelegate> list, EventDelegate ev, bool oneShot)
{
if (ev.mRawDelegate || ev.target == null || string.IsNullOrEmpty(ev.methodName))
{
Add(list, ev.mCachedCallback, oneShot);
}
else if (list != null)
{
for (int i = 0, imax = list.Count; i < imax; ++i)
{
EventDelegate del = list[i];
if (del != null && del.Equals(ev))
return;
}
EventDelegate copy = new EventDelegate(ev.target, ev.methodName);
copy.oneShot = oneShot;
if (ev.mParameters != null && ev.mParameters.Length > 0)
{
copy.mParameters = new Parameter[ev.mParameters.Length];
for (int i = 0; i < ev.mParameters.Length; ++i)
copy.mParameters[i] = ev.mParameters[i];
}
list.Add(copy);
}
else Debug.LogWarning("Attempting to add a callback to a list that's null");
}
/// <summary>
/// Remove an existing event delegate from the list.
/// </summary>
static public bool Remove (List<EventDelegate> list, Callback callback)
{
if (list != null)
{
for (int i = 0, imax = list.Count; i < imax; ++i)
{
EventDelegate del = list[i];
if (del != null && del.Equals(callback))
{
list.RemoveAt(i);
return true;
}
}
}
return false;
}
/// <summary>
/// Remove an existing event delegate from the list.
/// </summary>
static public bool Remove (List<EventDelegate> list, EventDelegate ev)
{
if (list != null)
{
for (int i = 0, imax = list.Count; i < imax; ++i)
{
EventDelegate del = list[i];
if (del != null && del.Equals(ev))
{
list.RemoveAt(i);
return true;
}
}
}
return false;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Internal/EventDelegate.cs
|
C#
|
asf20
| 16,397
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
/// <summary>
/// Inspector class used to view UIDrawCalls.
/// </summary>
[CustomEditor(typeof(UIDrawCall))]
public class UIDrawCallInspector : Editor
{
/// <summary>
/// Draw the inspector widget.
/// </summary>
public override void OnInspectorGUI ()
{
if (Event.current.type == EventType.Repaint || Event.current.type == EventType.Layout)
{
UIDrawCall dc = target as UIDrawCall;
if (dc.manager != null)
{
EditorGUILayout.LabelField("Render Queue", dc.renderQueue.ToString());
EditorGUILayout.LabelField("Owner Panel", NGUITools.GetHierarchy(dc.manager.gameObject));
EditorGUILayout.LabelField("Triangles", dc.triangles.ToString());
}
else if (Event.current.type == EventType.Repaint)
{
Debug.LogWarning("Orphaned UIDrawCall detected!\nUse [Selection -> Force Delete] to get rid of it.");
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIDrawCallInspector.cs
|
C#
|
asf20
| 1,074
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Editor class used to view panels.
/// </summary>
[CustomEditor(typeof(UIPanel))]
public class UIPanelInspector : UIRectEditor
{
static int s_Hash = "PanelHash".GetHashCode();
UIPanel mPanel;
UIWidgetInspector.Action mAction = UIWidgetInspector.Action.None;
UIWidgetInspector.Action mActionUnderMouse = UIWidgetInspector.Action.None;
bool mAllowSelection = true;
Vector3 mLocalPos = Vector3.zero;
Vector3 mWorldPos = Vector3.zero;
Vector4 mStartCR = Vector4.zero;
Vector3 mStartDrag = Vector3.zero;
Vector2 mStartMouse = Vector2.zero;
Vector3 mStartRot = Vector3.zero;
Vector3 mStartDir = Vector3.right;
UIWidget.Pivot mDragPivot = UIWidget.Pivot.Center;
GUIStyle mStyle0 = null;
GUIStyle mStyle1 = null;
protected override void OnEnable ()
{
base.OnEnable();
mPanel = target as UIPanel;
}
/// <summary>
/// Helper function that draws draggable knobs.
/// </summary>
void DrawKnob (Vector4 point, int id, bool canResize)
{
if (mStyle0 == null) mStyle0 = "sv_label_0";
if (mStyle1 == null) mStyle1 = "sv_label_7";
Vector2 screenPoint = HandleUtility.WorldToGUIPoint(point);
Rect rect = new Rect(screenPoint.x - 7f, screenPoint.y - 7f, 14f, 14f);
if (canResize)
{
mStyle1.Draw(rect, GUIContent.none, id);
}
else
{
mStyle0.Draw(rect, GUIContent.none, id);
}
}
void OnDisable () { NGUIEditorTools.HideMoveTool(false); }
/// <summary>
/// Handles & interaction.
/// </summary>
public void OnSceneGUI ()
{
NGUIEditorTools.HideMoveTool(true);
if (!UIWidget.showHandles) return;
Event e = Event.current;
int id = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
EventType type = e.GetTypeForControl(id);
Transform t = mPanel.cachedTransform;
Vector3[] handles = UIWidgetInspector.GetHandles(mPanel.worldCorners);
// Time to figure out what kind of action is underneath the mouse
UIWidgetInspector.Action actionUnderMouse = mAction;
Color handlesColor = new Color(0.5f, 0f, 0.5f);
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);
if (mPanel.isAnchored)
{
UIWidgetInspector.DrawAnchorHandle(mPanel.leftAnchor, mPanel.cachedTransform, handles, 0, id);
UIWidgetInspector.DrawAnchorHandle(mPanel.topAnchor, mPanel.cachedTransform, handles, 1, id);
UIWidgetInspector.DrawAnchorHandle(mPanel.rightAnchor, mPanel.cachedTransform, handles, 2, id);
UIWidgetInspector.DrawAnchorHandle(mPanel.bottomAnchor, mPanel.cachedTransform, handles, 3, id);
}
if (type == EventType.Repaint)
{
bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control) showDetails = true;
if (NGUITools.GetActive(mPanel) && mPanel.parent == null) showDetails = true;
if (showDetails) NGUIHandles.DrawSize(handles, Mathf.RoundToInt(mPanel.width), Mathf.RoundToInt(mPanel.height));
}
bool canResize = (mPanel.clipping != UIDrawCall.Clipping.None);
// NOTE: Remove this part when it's possible to neatly resize rotated anchored panels.
if (canResize && mPanel.isAnchored)
{
Quaternion rot = mPanel.cachedTransform.localRotation;
if (Quaternion.Angle(rot, Quaternion.identity) > 0.01f) canResize = false;
}
bool[] resizable = new bool[8];
resizable[4] = canResize; // left
resizable[5] = canResize; // top
resizable[6] = canResize; // right
resizable[7] = canResize; // bottom
resizable[0] = resizable[7] && resizable[4]; // bottom-left
resizable[1] = resizable[5] && resizable[4]; // top-left
resizable[2] = resizable[5] && resizable[6]; // top-right
resizable[3] = resizable[7] && resizable[6]; // bottom-right
UIWidget.Pivot pivotUnderMouse = UIWidgetInspector.GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);
switch (type)
{
case EventType.Repaint:
{
Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);
if ((v2 - v0).magnitude > 60f)
{
Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);
Handles.BeginGUI();
{
for (int i = 0; i < 4; ++i)
DrawKnob(handles[i], id, resizable[i]);
if (Mathf.Abs(v1.y - v0.y) > 80f)
{
if (mPanel.leftAnchor.target == null || mPanel.leftAnchor.absolute != 0)
DrawKnob(handles[4], id, resizable[4]);
if (mPanel.rightAnchor.target == null || mPanel.rightAnchor.absolute != 0)
DrawKnob(handles[6], id, resizable[6]);
}
if (Mathf.Abs(v3.x - v0.x) > 80f)
{
if (mPanel.topAnchor.target == null || mPanel.topAnchor.absolute != 0)
DrawKnob(handles[5], id, resizable[5]);
if (mPanel.bottomAnchor.target == null || mPanel.bottomAnchor.absolute != 0)
DrawKnob(handles[7], id, resizable[7]);
}
}
Handles.EndGUI();
}
}
break;
case EventType.MouseDown:
{
if (actionUnderMouse != UIWidgetInspector.Action.None)
{
mStartMouse = e.mousePosition;
mAllowSelection = true;
if (e.button == 1)
{
if (e.modifiers == 0)
{
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
}
else if (e.button == 0 && actionUnderMouse != UIWidgetInspector.Action.None &&
UIWidgetInspector.Raycast(handles, out mStartDrag))
{
mWorldPos = t.position;
mLocalPos = t.localPosition;
mStartRot = t.localRotation.eulerAngles;
mStartDir = mStartDrag - t.position;
mStartCR = mPanel.baseClipRegion;
mDragPivot = pivotUnderMouse;
mActionUnderMouse = actionUnderMouse;
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
}
}
break;
case EventType.MouseUp:
{
if (GUIUtility.hotControl == id)
{
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
if (e.button < 2)
{
bool handled = false;
if (e.button == 1)
{
// Right-click: Open a context menu listing all widgets underneath
NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
handled = true;
}
else if (mAction == UIWidgetInspector.Action.None)
{
if (mAllowSelection)
{
// Left-click: Select the topmost widget
NGUIEditorTools.SelectWidget(e.mousePosition);
handled = true;
}
}
else
{
// Finished dragging something
Vector3 pos = t.localPosition;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = Mathf.Round(pos.z);
t.localPosition = pos;
handled = true;
}
if (handled) e.Use();
}
// Clear the actions
mActionUnderMouse = UIWidgetInspector.Action.None;
mAction = UIWidgetInspector.Action.None;
}
else if (mAllowSelection)
{
BetterList<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
if (widgets.size > 0) Selection.activeGameObject = widgets[0].gameObject;
}
mAllowSelection = true;
}
break;
case EventType.MouseDrag:
{
// Prevent selection once the drag operation begins
bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
if (dragStarted) mAllowSelection = false;
if (GUIUtility.hotControl == id)
{
e.Use();
if (mAction != UIWidgetInspector.Action.None || mActionUnderMouse != UIWidgetInspector.Action.None)
{
Vector3 pos;
if (UIWidgetInspector.Raycast(handles, out pos))
{
if (mAction == UIWidgetInspector.Action.None && mActionUnderMouse != UIWidgetInspector.Action.None)
{
// Wait until the mouse moves by more than a few pixels
if (dragStarted)
{
if (mActionUnderMouse == UIWidgetInspector.Action.Move)
{
NGUISnap.Recalculate(mPanel);
}
else if (mActionUnderMouse == UIWidgetInspector.Action.Rotate)
{
mStartRot = t.localRotation.eulerAngles;
mStartDir = mStartDrag - t.position;
}
else if (mActionUnderMouse == UIWidgetInspector.Action.Scale)
{
mStartCR = mPanel.baseClipRegion;
mDragPivot = pivotUnderMouse;
}
mAction = actionUnderMouse;
}
}
if (mAction != UIWidgetInspector.Action.None)
{
NGUIEditorTools.RegisterUndo("Change Rect", t);
NGUIEditorTools.RegisterUndo("Change Rect", mPanel);
if (mAction == UIWidgetInspector.Action.Move)
{
Vector3 before = t.position;
Vector3 beforeLocal = t.localPosition;
t.position = mWorldPos + (pos - mStartDrag);
pos = NGUISnap.Snap(t.localPosition, mPanel.localCorners,
e.modifiers != EventModifiers.Control) - beforeLocal;
t.position = before;
NGUIMath.MoveRect(mPanel, pos.x, pos.y);
}
else if (mAction == UIWidgetInspector.Action.Rotate)
{
Vector3 dir = pos - t.position;
float angle = Vector3.Angle(mStartDir, dir);
if (angle > 0f)
{
float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
if (dot < 0f) angle = -angle;
angle = mStartRot.z + angle;
angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
}
}
else if (mAction == UIWidgetInspector.Action.Scale)
{
// World-space delta since the drag started
Vector3 delta = pos - mStartDrag;
// Adjust the widget's position and scale based on the delta, restricted by the pivot
AdjustClipping(mPanel, mLocalPos, mStartCR, delta, mDragPivot);
}
}
}
}
}
}
break;
case EventType.KeyDown:
{
if (e.keyCode == KeyCode.UpArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
NGUIMath.MoveRect(mPanel, 0f, 1f);
e.Use();
}
else if (e.keyCode == KeyCode.DownArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
NGUIMath.MoveRect(mPanel, 0f, -1f);
e.Use();
}
else if (e.keyCode == KeyCode.LeftArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
NGUIMath.MoveRect(mPanel, -1f, 0f);
e.Use();
}
else if (e.keyCode == KeyCode.RightArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mPanel);
NGUIMath.MoveRect(mPanel, 1f, 0f);
e.Use();
}
else if (e.keyCode == KeyCode.Escape)
{
if (GUIUtility.hotControl == id)
{
if (mAction != UIWidgetInspector.Action.None)
Undo.PerformUndo();
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
mActionUnderMouse = UIWidgetInspector.Action.None;
mAction = UIWidgetInspector.Action.None;
e.Use();
}
else Selection.activeGameObject = null;
}
}
break;
}
}
/// <summary>
/// Draw the inspector widget.
/// </summary>
protected override bool ShouldDrawProperties ()
{
float alpha = EditorGUILayout.Slider("Alpha", mPanel.alpha, 0f, 1f);
if (alpha != mPanel.alpha)
{
NGUIEditorTools.RegisterUndo("Panel Alpha", mPanel);
mPanel.alpha = alpha;
}
GUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel("Depth");
int depth = mPanel.depth;
if (GUILayout.Button("Back", GUILayout.Width(60f))) --depth;
depth = EditorGUILayout.IntField(depth, GUILayout.MinWidth(20f));
if (GUILayout.Button("Forward", GUILayout.Width(68f))) ++depth;
if (mPanel.depth != depth)
{
NGUIEditorTools.RegisterUndo("Panel Depth", mPanel);
mPanel.depth = depth;
if (UIPanelTool.instance != null)
UIPanelTool.instance.Repaint();
if (UIDrawCallViewer.instance != null)
UIDrawCallViewer.instance.Repaint();
}
}
GUILayout.EndHorizontal();
int matchingDepths = 0;
for (int i = 0; i < UIPanel.list.size; ++i)
{
UIPanel p = UIPanel.list[i];
if (p != null && mPanel.depth == p.depth)
++matchingDepths;
}
if (matchingDepths > 1)
{
EditorGUILayout.HelpBox(matchingDepths + " panels are sharing the depth value of " + mPanel.depth, MessageType.Warning);
}
UIDrawCall.Clipping clipping = (UIDrawCall.Clipping)EditorGUILayout.EnumPopup("Clipping", mPanel.clipping);
if (mPanel.clipping != clipping)
{
mPanel.clipping = clipping;
EditorUtility.SetDirty(mPanel);
}
if (mPanel.clipping != UIDrawCall.Clipping.None)
{
Vector4 range = mPanel.baseClipRegion;
// Scroll view is anchored, meaning it adjusts the offset itself, so we don't want it to be modifiable
//EditorGUI.BeginDisabledGroup(mPanel.GetComponent<UIScrollView>() != null);
GUI.changed = false;
GUILayout.BeginHorizontal();
GUILayout.Space(80f);
Vector3 off = EditorGUILayout.Vector2Field("Offset", mPanel.clipOffset);
GUILayout.EndHorizontal();
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Clipping Change", mPanel);
mPanel.clipOffset = off;
EditorUtility.SetDirty(mPanel);
}
//EditorGUI.EndDisabledGroup();
GUILayout.BeginHorizontal();
GUILayout.Space(80f);
Vector2 pos = EditorGUILayout.Vector2Field("Center", new Vector2(range.x, range.y));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(80f);
Vector2 size = EditorGUILayout.Vector2Field("Size", new Vector2(range.z, range.w));
GUILayout.EndHorizontal();
if (size.x < 0f) size.x = 0f;
if (size.y < 0f) size.y = 0f;
range.x = pos.x;
range.y = pos.y;
range.z = size.x;
range.w = size.y;
if (mPanel.baseClipRegion != range)
{
NGUIEditorTools.RegisterUndo("Clipping Change", mPanel);
mPanel.baseClipRegion = range;
EditorUtility.SetDirty(mPanel);
}
if (mPanel.clipping == UIDrawCall.Clipping.SoftClip)
{
GUILayout.BeginHorizontal();
GUILayout.Space(80f);
Vector2 soft = EditorGUILayout.Vector2Field("Softness", mPanel.clipSoftness);
GUILayout.EndHorizontal();
if (soft.x < 0f) soft.x = 0f;
if (soft.y < 0f) soft.y = 0f;
if (mPanel.clipSoftness != soft)
{
NGUIEditorTools.RegisterUndo("Clipping Change", mPanel);
mPanel.clipSoftness = soft;
EditorUtility.SetDirty(mPanel);
}
}
}
if (clipping != UIDrawCall.Clipping.None && !NGUIEditorTools.IsUniform(mPanel.transform.lossyScale))
{
EditorGUILayout.HelpBox("Clipped panels must have a uniform scale, or clipping won't work properly!", MessageType.Error);
if (GUILayout.Button("Auto-fix"))
{
NGUIEditorTools.FixUniform(mPanel.gameObject);
}
}
if (NGUIEditorTools.DrawHeader("Advanced Options"))
{
NGUIEditorTools.BeginContents();
GUILayout.BeginHorizontal();
UIPanel.RenderQueue rq = (UIPanel.RenderQueue)EditorGUILayout.EnumPopup("Render Q", mPanel.renderQueue);
if (mPanel.renderQueue != rq)
{
mPanel.renderQueue = rq;
mPanel.RebuildAllDrawCalls();
EditorUtility.SetDirty(mPanel);
if (UIDrawCallViewer.instance != null)
UIDrawCallViewer.instance.Repaint();
}
if (rq != UIPanel.RenderQueue.Automatic)
{
int sq = EditorGUILayout.IntField(mPanel.startingRenderQueue, GUILayout.Width(40f));
if (mPanel.startingRenderQueue != sq)
{
mPanel.startingRenderQueue = sq;
mPanel.RebuildAllDrawCalls();
EditorUtility.SetDirty(mPanel);
if (UIDrawCallViewer.instance != null)
UIDrawCallViewer.instance.Repaint();
}
}
GUILayout.EndHorizontal();
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
if (rq == UIPanel.RenderQueue.Explicit)
{
GUI.changed = false;
int so = EditorGUILayout.IntField("Sort Order", mPanel.sortingOrder, GUILayout.Width(120f));
if (GUI.changed) mPanel.sortingOrder = so;
}
#endif
GUILayout.BeginHorizontal();
bool norms = EditorGUILayout.Toggle("Normals", mPanel.generateNormals, GUILayout.Width(100f));
GUILayout.Label("Needed for lit shaders", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
if (mPanel.generateNormals != norms)
{
mPanel.generateNormals = norms;
mPanel.RebuildAllDrawCalls();
EditorUtility.SetDirty(mPanel);
}
GUILayout.BeginHorizontal();
bool cull = EditorGUILayout.Toggle("Cull", mPanel.cullWhileDragging, GUILayout.Width(100f));
GUILayout.Label("Cull widgets while dragging them", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
if (mPanel.cullWhileDragging != cull)
{
mPanel.cullWhileDragging = cull;
mPanel.RebuildAllDrawCalls();
EditorUtility.SetDirty(mPanel);
}
GUILayout.BeginHorizontal();
bool alw = EditorGUILayout.Toggle("Visible", mPanel.alwaysOnScreen, GUILayout.Width(100f));
GUILayout.Label("Check if widgets never go off-screen", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
if (mPanel.alwaysOnScreen != alw)
{
mPanel.alwaysOnScreen = alw;
mPanel.RebuildAllDrawCalls();
EditorUtility.SetDirty(mPanel);
}
GUILayout.BeginHorizontal();
bool off = EditorGUILayout.Toggle("Offset", mPanel.anchorOffset, GUILayout.Width(100f));
GUILayout.Label("Offset anchors by position", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
if (mPanel.anchorOffset != off)
{
mPanel.anchorOffset = off;
mPanel.RebuildAllDrawCalls();
EditorUtility.SetDirty(mPanel);
}
GUILayout.BeginHorizontal();
bool stat = EditorGUILayout.Toggle("Static", mPanel.widgetsAreStatic, GUILayout.Width(100f));
GUILayout.Label("Check if widgets won't move", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
if (mPanel.widgetsAreStatic != stat)
{
mPanel.widgetsAreStatic = stat;
mPanel.RebuildAllDrawCalls();
EditorUtility.SetDirty(mPanel);
}
if (stat)
{
EditorGUILayout.HelpBox("Only mark the panel as 'static' if you know FOR CERTAIN that the widgets underneath will not move, rotate, or scale. Doing this improves performance, but moving widgets around will have no effect.", MessageType.Warning);
}
GUILayout.BeginHorizontal();
bool tool = EditorGUILayout.Toggle("Panel Tool", mPanel.showInPanelTool, GUILayout.Width(100f));
GUILayout.Label("Show in panel tool");
GUILayout.EndHorizontal();
if (mPanel.showInPanelTool != tool)
{
mPanel.showInPanelTool = !mPanel.showInPanelTool;
EditorUtility.SetDirty(mPanel);
EditorWindow.FocusWindowIfItsOpen<UIPanelTool>();
}
NGUIEditorTools.EndContents();
}
return true;
}
/// <summary>
/// Add the "Show draw calls" button at the very end.
/// </summary>
protected override void DrawFinalProperties ()
{
base.DrawFinalProperties();
if (GUILayout.Button("Show Draw Calls"))
{
NGUISettings.showAllDCs = false;
if (UIDrawCallViewer.instance != null)
{
UIDrawCallViewer.instance.Focus();
UIDrawCallViewer.instance.Repaint();
}
else
{
EditorWindow.GetWindow<UIDrawCallViewer>(false, "Draw Call Tool", true);
}
}
}
/// <summary>
/// Adjust the panel's position and clipping rectangle.
/// </summary>
void AdjustClipping (UIPanel p, Vector3 startLocalPos, Vector4 startCR, Vector3 worldDelta, UIWidget.Pivot pivot)
{
Transform t = p.cachedTransform;
Transform parent = t.parent;
Matrix4x4 parentToLocal = (parent != null) ? t.parent.worldToLocalMatrix : Matrix4x4.identity;
Matrix4x4 worldToLocal = parentToLocal;
Quaternion invRot = Quaternion.Inverse(t.localRotation);
worldToLocal = worldToLocal * Matrix4x4.TRS(Vector3.zero, invRot, Vector3.one);
Vector3 localDelta = worldToLocal.MultiplyVector(worldDelta);
float left = 0f;
float right = 0f;
float top = 0f;
float bottom = 0f;
Vector2 dragPivot = NGUIMath.GetPivotOffset(pivot);
if (dragPivot.x == 0f && dragPivot.y == 1f)
{
left = localDelta.x;
top = localDelta.y;
}
else if (dragPivot.x == 0f && dragPivot.y == 0.5f)
{
left = localDelta.x;
}
else if (dragPivot.x == 0f && dragPivot.y == 0f)
{
left = localDelta.x;
bottom = localDelta.y;
}
else if (dragPivot.x == 0.5f && dragPivot.y == 1f)
{
top = localDelta.y;
}
else if (dragPivot.x == 0.5f && dragPivot.y == 0f)
{
bottom = localDelta.y;
}
else if (dragPivot.x == 1f && dragPivot.y == 1f)
{
right = localDelta.x;
top = localDelta.y;
}
else if (dragPivot.x == 1f && dragPivot.y == 0.5f)
{
right = localDelta.x;
}
else if (dragPivot.x == 1f && dragPivot.y == 0f)
{
right = localDelta.x;
bottom = localDelta.y;
}
AdjustClipping(p, startCR,
Mathf.RoundToInt(left),
Mathf.RoundToInt(top),
Mathf.RoundToInt(right),
Mathf.RoundToInt(bottom));
}
/// <summary>
/// Adjust the panel's clipping rectangle based on the specified modifier values.
/// </summary>
void AdjustClipping (UIPanel p, Vector4 cr, int left, int top, int right, int bottom)
{
// Make adjustment values dividable by two since the clipping is centered
right = ((right >> 1) << 1);
left = ((left >> 1) << 1);
bottom = ((bottom >> 1) << 1);
top = ((top >> 1) << 1);
int x = Mathf.RoundToInt(cr.x + (left + right) * 0.5f);
int y = Mathf.RoundToInt(cr.y + (top + bottom) * 0.5f);
int width = Mathf.RoundToInt(cr.z + right - left);
int height = Mathf.RoundToInt(cr.w + top - bottom);
Vector2 soft = p.clipSoftness;
int minx = Mathf.RoundToInt(Mathf.Max(20f, soft.x));
int miny = Mathf.RoundToInt(Mathf.Max(20f, soft.y));
if (width < minx) width = minx;
if (height < miny) height = miny;
if ((width & 1) == 1) ++width;
if ((height & 1) == 1) ++height;
p.baseClipRegion = new Vector4(x, y, width, height);
UpdateAnchors(false);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIPanelInspector.cs
|
C#
|
asf20
| 22,520
|
using UnityEngine;
using UnityEditor;
/// <summary>
/// This editor helper class makes it easy to create and show a context menu.
/// It ensures that it's possible to add multiple items with the same name.
/// </summary>
public static class NGUIContextMenu
{
[MenuItem("Help/NGUI Documentation")]
static void ShowHelp0 (MenuCommand command) { NGUIHelp.Show(); }
[MenuItem("CONTEXT/UIWidget/Copy Widget")]
static void CopyStyle (MenuCommand command) { NGUISettings.CopyWidget(command.context as UIWidget); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Values")]
static void PasteStyle (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, true); }
[MenuItem("CONTEXT/UIWidget/Paste Widget Style")]
static void PasteStyle2 (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, false); }
[MenuItem("CONTEXT/UIWidget/Help")]
static void ShowHelp1 (MenuCommand command) { NGUIHelp.Show(command.context); }
[MenuItem("CONTEXT/UIButton/Help")]
static void ShowHelp2 (MenuCommand command) { NGUIHelp.Show(typeof(UIButton)); }
[MenuItem("CONTEXT/UIToggle/Help")]
static void ShowHelp3 (MenuCommand command) { NGUIHelp.Show(typeof(UIToggle)); }
[MenuItem("CONTEXT/UIRoot/Help")]
static void ShowHelp4 (MenuCommand command) { NGUIHelp.Show(typeof(UIRoot)); }
[MenuItem("CONTEXT/UICamera/Help")]
static void ShowHelp5 (MenuCommand command) { NGUIHelp.Show(typeof(UICamera)); }
[MenuItem("CONTEXT/UIAnchor/Help")]
static void ShowHelp6 (MenuCommand command) { NGUIHelp.Show(typeof(UIAnchor)); }
[MenuItem("CONTEXT/UIStretch/Help")]
static void ShowHelp7 (MenuCommand command) { NGUIHelp.Show(typeof(UIStretch)); }
[MenuItem("CONTEXT/UISlider/Help")]
static void ShowHelp8 (MenuCommand command) { NGUIHelp.Show(typeof(UISlider)); }
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
[MenuItem("CONTEXT/UI2DSprite/Help")]
static void ShowHelp9 (MenuCommand command) { NGUIHelp.Show(typeof(UI2DSprite)); }
#endif
[MenuItem("CONTEXT/UIScrollBar/Help")]
static void ShowHelp10 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollBar)); }
[MenuItem("CONTEXT/UIProgressBar/Help")]
static void ShowHelp11 (MenuCommand command) { NGUIHelp.Show(typeof(UIProgressBar)); }
[MenuItem("CONTEXT/UIPopupList/Help")]
static void ShowHelp12 (MenuCommand command) { NGUIHelp.Show(typeof(UIPopupList)); }
[MenuItem("CONTEXT/UIInput/Help")]
static void ShowHelp13 (MenuCommand command) { NGUIHelp.Show(typeof(UIInput)); }
[MenuItem("CONTEXT/UIKeyBinding/Help")]
static void ShowHelp14 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyBinding)); }
[MenuItem("CONTEXT/UIGrid/Help")]
static void ShowHelp15 (MenuCommand command) { NGUIHelp.Show(typeof(UIGrid)); }
[MenuItem("CONTEXT/UITable/Help")]
static void ShowHelp16 (MenuCommand command) { NGUIHelp.Show(typeof(UITable)); }
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp17 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayTween)); }
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp18 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIPlaySound/Help")]
static void ShowHelp19 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlaySound)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
static void ShowHelp20 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp21 (MenuCommand command) { NGUIHelp.Show(typeof(UIDragScrollView)); }
[MenuItem("CONTEXT/UICenterOnChild/Help")]
static void ShowHelp22 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnChild)); }
[MenuItem("CONTEXT/UICenterOnClick/Help")]
static void ShowHelp23 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnClick)); }
[MenuItem("CONTEXT/UITweener/Help")]
[MenuItem("CONTEXT/UIPlayTween/Help")]
static void ShowHelp24 (MenuCommand command) { NGUIHelp.Show(typeof(UITweener)); }
[MenuItem("CONTEXT/ActiveAnimation/Help")]
[MenuItem("CONTEXT/UIPlayAnimation/Help")]
static void ShowHelp25 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); }
[MenuItem("CONTEXT/UIScrollView/Help")]
[MenuItem("CONTEXT/UIDragScrollView/Help")]
static void ShowHelp26 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); }
[MenuItem("CONTEXT/UIPanel/Help")]
static void ShowHelp27 (MenuCommand command) { NGUIHelp.Show(typeof(UIPanel)); }
[MenuItem("CONTEXT/UILocalize/Help")]
static void ShowHelp28 (MenuCommand command) { NGUIHelp.Show(typeof(UILocalize)); }
[MenuItem("CONTEXT/Localization/Help")]
static void ShowHelp29 (MenuCommand command) { NGUIHelp.Show(typeof(Localization)); }
[MenuItem("CONTEXT/UIKeyNavigation/Help")]
static void ShowHelp30 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyNavigation)); }
[MenuItem("CONTEXT/PropertyBinding/Help")]
static void ShowHelp31 (MenuCommand command) { NGUIHelp.Show(typeof(PropertyBinding)); }
public delegate UIWidget AddFunc (GameObject go);
static BetterList<string> mEntries = new BetterList<string>();
static GenericMenu mMenu;
/// <summary>
/// Clear the context menu list.
/// </summary>
static public void Clear ()
{
mEntries.Clear();
mMenu = null;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.size; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, callback, param);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddChild (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeGameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddChildWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.size; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddChild, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Wrapper function called by the menu that in turn calls the correct callback.
/// </summary>
static public void AddSibling (object obj)
{
AddFunc func = obj as AddFunc;
UIWidget widget = func(Selection.activeTransform.parent.gameObject);
if (widget != null) Selection.activeGameObject = widget.gameObject;
}
/// <summary>
/// Add a new context menu entry.
/// </summary>
static public void AddSiblingWidget (string item, bool isChecked, AddFunc callback)
{
if (callback != null)
{
if (mMenu == null) mMenu = new GenericMenu();
int count = 0;
for (int i = 0; i < mEntries.size; ++i)
{
string str = mEntries[i];
if (str == item) ++count;
}
mEntries.Add(item);
if (count > 0) item += " [" + count + "]";
mMenu.AddItem(new GUIContent(item), isChecked, AddSibling, callback);
}
else AddDisabledItem(item);
}
/// <summary>
/// Add commonly NGUI context menu options.
/// </summary>
static public void AddCommonItems (GameObject target)
{
if (target != null)
{
UIWidget widget = target.GetComponent<UIWidget>();
string myName = string.Format("Selected {0}", (widget != null) ? NGUITools.GetTypeName(widget) : "Object");
AddItem(myName + "/Bring to Front", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.BringForward(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Push to Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.PushBack(Selection.gameObjects[i]);
},
null);
AddItem(myName + "/Nudge Forward", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], 1);
},
null);
AddItem(myName + "/Nudge Back", false,
delegate(object obj)
{
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AdjustDepth(Selection.gameObjects[i], -1);
},
null);
if (widget != null)
{
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Make Pixel-Perfect", false, OnMakePixelPerfect, Selection.activeTransform);
if (target.GetComponent<BoxCollider>() != null)
{
AddItem(myName + "/Reset Collider Size", false, OnBoxCollider, target);
}
}
NGUIContextMenu.AddSeparator(myName + "/");
AddItem(myName + "/Delete", false, OnDelete, target);
NGUIContextMenu.AddSeparator("");
if (Selection.activeTransform.parent != null && widget != null)
{
AddChildWidget("Create/Sprite/Child", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label/Child", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget/Child", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture/Child", false, NGUISettings.AddTexture);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
AddChildWidget("Create/Unity 2D Sprite/Child", false, NGUISettings.Add2DSprite);
#endif
AddSiblingWidget("Create/Sprite/Sibling", false, NGUISettings.AddSprite);
AddSiblingWidget("Create/Label/Sibling", false, NGUISettings.AddLabel);
AddSiblingWidget("Create/Invisible Widget/Sibling", false, NGUISettings.AddWidget);
AddSiblingWidget("Create/Simple Texture/Sibling", false, NGUISettings.AddTexture);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
AddSiblingWidget("Create/Unity 2D Sprite/Sibling", false, NGUISettings.Add2DSprite);
#endif
}
else
{
AddChildWidget("Create/Sprite", false, NGUISettings.AddSprite);
AddChildWidget("Create/Label", false, NGUISettings.AddLabel);
AddChildWidget("Create/Invisible Widget", false, NGUISettings.AddWidget);
AddChildWidget("Create/Simple Texture", false, NGUISettings.AddTexture);
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
AddChildWidget("Create/Unity 2D Sprite", false, NGUISettings.Add2DSprite);
#endif
}
NGUIContextMenu.AddSeparator("Create/");
AddItem("Create/Panel", false, AddPanel, target);
AddItem("Create/Scroll View", false, AddScrollView, target);
AddItem("Create/Grid", false, AddChild<UIGrid>, target);
AddItem("Create/Table", false, AddChild<UITable>, target);
AddItem("Create/Anchor (Legacy)", false, AddChild<UIAnchor>, target);
if (target.GetComponent<UIPanel>() != null)
{
if (target.GetComponent<UIScrollView>() == null)
{
AddItem("Attach/Scroll View", false, Attach, typeof(UIScrollView));
NGUIContextMenu.AddSeparator("Attach/");
}
}
else if (target.collider == null)
{
AddItem("Attach/Box Collider", false, AttachCollider, null);
NGUIContextMenu.AddSeparator("Attach/");
}
bool header = false;
UIScrollView scrollView = NGUITools.FindInParents<UIScrollView>(target);
if (scrollView != null)
{
if (scrollView.GetComponentInChildren<UICenterOnChild>() == null)
{
AddItem("Attach/Center Scroll View on Child", false, Attach, typeof(UICenterOnChild));
header = true;
}
}
if (target.collider != null)
{
if (scrollView != null)
{
if (target.GetComponent<UIDragScrollView>() == null)
{
AddItem("Attach/Drag Scroll View", false, Attach, typeof(UIDragScrollView));
header = true;
}
if (target.GetComponent<UICenterOnClick>() == null && NGUITools.FindInParents<UICenterOnChild>(target) != null)
{
AddItem("Attach/Center Scroll View on Click", false, Attach, typeof(UICenterOnClick));
header = true;
}
}
if (header) NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Button Script", false, Attach, typeof(UIButton));
AddItem("Attach/Toggle Script", false, Attach, typeof(UIToggle));
AddItem("Attach/Slider Script", false, Attach, typeof(UISlider));
AddItem("Attach/Scroll Bar Script", false, Attach, typeof(UIScrollBar));
AddItem("Attach/Progress Bar Script", false, Attach, typeof(UISlider));
AddItem("Attach/Popup List Script", false, Attach, typeof(UIPopupList));
AddItem("Attach/Input Field Script", false, Attach, typeof(UIInput));
NGUIContextMenu.AddSeparator("Attach/");
if (target.GetComponent<UIDragResize>() == null)
AddItem("Attach/Drag Resize Script", false, Attach, typeof(UIDragResize));
if (target.GetComponent<UIDragScrollView>() == null)
{
for (int i = 0; i < UIPanel.list.size; ++i)
{
UIPanel pan = UIPanel.list[i];
if (pan.clipping == UIDrawCall.Clipping.None) continue;
UIScrollView dr = pan.GetComponent<UIScrollView>();
if (dr == null) continue;
AddItem("Attach/Drag Scroll View", false, delegate(object obj)
{ target.AddComponent<UIDragScrollView>().scrollView = dr; }, null);
header = true;
break;
}
}
AddItem("Attach/Key Binding Script", false, Attach, typeof(UIKeyBinding));
if (target.GetComponent<UIKeyNavigation>() == null)
AddItem("Attach/Key Navigation Script", false, Attach, typeof(UIKeyNavigation));
NGUIContextMenu.AddSeparator("Attach/");
AddItem("Attach/Play Tween Script", false, Attach, typeof(UIPlayTween));
AddItem("Attach/Play Animation Script", false, Attach, typeof(UIPlayAnimation));
AddItem("Attach/Play Sound Script", false, Attach, typeof(UIPlaySound));
}
AddItem("Attach/Property Binding", false, Attach, typeof(PropertyBinding));
if (target.GetComponent<UILocalize>() == null)
AddItem("Attach/Localization Script", false, Attach, typeof(UILocalize));
if (widget != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
AddMissingItem<TweenColor>(target, "Tween/Color");
AddMissingItem<TweenWidth>(target, "Tween/Width");
AddMissingItem<TweenHeight>(target, "Tween/Height");
}
else if (target.GetComponent<UIPanel>() != null)
{
AddMissingItem<TweenAlpha>(target, "Tween/Alpha");
}
NGUIContextMenu.AddSeparator("Tween/");
AddMissingItem<TweenPosition>(target, "Tween/Position");
AddMissingItem<TweenRotation>(target, "Tween/Rotation");
AddMissingItem<TweenScale>(target, "Tween/Scale");
AddMissingItem<TweenTransform>(target, "Tween/Transform");
if (target.GetComponent<AudioSource>() != null)
AddMissingItem<TweenVolume>(target, "Tween/Volume");
if (target.GetComponent<Camera>() != null)
{
AddMissingItem<TweenFOV>(target, "Tween/Field of View");
AddMissingItem<TweenOrthoSize>(target, "Tween/Orthographic Size");
}
}
}
/// <summary>
/// Helper function that adds a widget collider to the specified object.
/// </summary>
static void AttachCollider (object obj)
{
if (Selection.activeGameObject != null)
for (int i = 0; i < Selection.gameObjects.Length; ++i)
NGUITools.AddWidgetCollider(Selection.gameObjects[i]);
}
/// <summary>
/// Helper function that adds the specified type to all selected game objects. Used with the menu options above.
/// </summary>
static void Attach (object obj)
{
if (Selection.activeGameObject == null) return;
System.Type type = (System.Type)obj;
for (int i = 0; i < Selection.gameObjects.Length; ++i)
{
GameObject go = Selection.gameObjects[i];
if (go.GetComponent(type) != null) continue;
#if !UNITY_3_5
Component cmp = go.AddComponent(type);
Undo.RegisterCreatedObjectUndo(cmp, "Attach " + type);
#endif
}
}
/// <summary>
/// Helper function.
/// </summary>
static void AddMissingItem<T> (GameObject target, string name) where T : MonoBehaviour
{
if (target.GetComponent<T>() == null)
AddItem(name, false, Attach, typeof(T));
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddChild<T> (object obj) where T : MonoBehaviour
{
GameObject go = obj as GameObject;
T t = NGUITools.AddChild<T>(go);
Selection.activeGameObject = t.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddPanel (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Helper function for menu creation.
/// </summary>
static void AddScrollView (object obj)
{
GameObject go = obj as GameObject;
if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject;
UIPanel panel = NGUISettings.AddPanel(go);
panel.clipping = UIDrawCall.Clipping.SoftClip;
panel.gameObject.AddComponent<UIScrollView>();
panel.name = "Scroll View";
Selection.activeGameObject = panel.gameObject;
}
/// <summary>
/// Add help options based on the components present on the specified game object.
/// </summary>
static public void AddHelp (GameObject go, bool addSeparator)
{
MonoBehaviour[] comps = Selection.activeGameObject.GetComponents<MonoBehaviour>();
bool addedSomething = false;
for (int i = 0; i < comps.Length; ++i)
{
System.Type type = comps[i].GetType();
string url = NGUIHelp.GetHelpURL(type);
if (url != null)
{
if (addSeparator)
{
addSeparator = false;
AddSeparator("");
}
AddItem("Help/" + type, false, delegate(object obj) { Application.OpenURL(url); }, null);
addedSomething = true;
}
}
if (addedSomething) AddSeparator("Help/");
AddItem("Help/All Topics", false, delegate(object obj) { NGUIHelp.Show(); }, null);
}
static void OnHelp (object obj) { NGUIHelp.Show(obj); }
static void OnMakePixelPerfect (object obj) { NGUITools.MakePixelPerfect(obj as Transform); }
static void OnBoxCollider (object obj) { NGUITools.AddWidgetCollider(obj as GameObject); }
static void OnDelete (object obj)
{
GameObject go = obj as GameObject;
Selection.activeGameObject = go.transform.parent.gameObject;
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
NGUITools.Destroy(go);
#else
Undo.DestroyObjectImmediate(go);
#endif
}
/// <summary>
/// Add a new disabled context menu entry.
/// </summary>
static public void AddDisabledItem (string item)
{
if (mMenu == null) mMenu = new GenericMenu();
mMenu.AddDisabledItem(new GUIContent(item));
}
/// <summary>
/// Add a separator to the menu.
/// </summary>
static public void AddSeparator (string path)
{
if (mMenu == null) mMenu = new GenericMenu();
// For some weird reason adding separators on OSX causes the entire menu to be disabled. Wtf?
if (Application.platform != RuntimePlatform.OSXEditor)
mMenu.AddSeparator(path);
}
/// <summary>
/// Show the context menu with all the added items.
/// </summary>
static public void Show ()
{
if (mMenu != null)
{
mMenu.ShowAsContext();
mMenu = null;
mEntries.Clear();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUIContextMenu.cs
|
C#
|
asf20
| 19,430
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit UISprites.
/// </summary>
[CustomEditor(typeof(UIImageButton))]
public class UIImageButtonInspector : Editor
{
public override void OnInspectorGUI ()
{
EditorGUILayout.HelpBox("Image Button component's functionality is now a part of UIButton. You no longer need UIImageButton.", MessageType.Warning, true);
if (GUILayout.Button("Auto-Upgrade"))
{
UIImageButton img = target as UIImageButton;
UIButton btn = img.GetComponent<UIButton>();
if (btn == null)
{
btn = img.gameObject.AddComponent<UIButton>();
if (img.target != null) btn.tweenTarget = img.target.gameObject;
else btn.tweenTarget = img.gameObject;
UISprite sp = btn.tweenTarget.GetComponent<UISprite>();
if (sp != null) sp.spriteName = img.normalSprite;
}
btn.hoverSprite = img.hoverSprite;
btn.pressedSprite = img.pressedSprite;
btn.disabledSprite = img.disabledSprite;
btn.pixelSnap = img.pixelSnap;
NGUITools.DestroyImmediate(img);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIImageButtonInspector.cs
|
C#
|
asf20
| 1,272
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIButtonKeys))]
#else
[CustomEditor(typeof(UIButtonKeys), true)]
#endif
public class UIButtonKeysEditor : UIKeyNavigationEditor
{
public override void OnInspectorGUI ()
{
base.OnInspectorGUI();
EditorGUILayout.HelpBox("This component has been replaced by UIKeyNavigation.", MessageType.Warning);
if (GUILayout.Button("Auto-Upgrade"))
{
NGUIEditorTools.ReplaceClass(serializedObject, typeof(UIKeyNavigation));
Selection.activeGameObject = null;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIButtonKeysEditor.cs
|
C#
|
asf20
| 753
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CustomEditor(typeof(UIEventTrigger))]
public class UIEventTriggerEditor : Editor
{
UIEventTrigger mTrigger;
void OnEnable ()
{
mTrigger = target as UIEventTrigger;
EditorPrefs.SetBool("ET0", EventDelegate.IsValid(mTrigger.onHoverOver));
EditorPrefs.SetBool("ET1", EventDelegate.IsValid(mTrigger.onHoverOut));
EditorPrefs.SetBool("ET2", EventDelegate.IsValid(mTrigger.onPress));
EditorPrefs.SetBool("ET3", EventDelegate.IsValid(mTrigger.onRelease));
EditorPrefs.SetBool("ET4", EventDelegate.IsValid(mTrigger.onSelect));
EditorPrefs.SetBool("ET5", EventDelegate.IsValid(mTrigger.onDeselect));
EditorPrefs.SetBool("ET6", EventDelegate.IsValid(mTrigger.onClick));
EditorPrefs.SetBool("ET7", EventDelegate.IsValid(mTrigger.onDoubleClick));
EditorPrefs.SetBool("ET8", EventDelegate.IsValid(mTrigger.onDragOver));
EditorPrefs.SetBool("ET9", EventDelegate.IsValid(mTrigger.onDragOut));
}
public override void OnInspectorGUI ()
{
GUILayout.Space(3f);
NGUIEditorTools.SetLabelWidth(80f);
DrawEvents("ET0", "On Hover Over", mTrigger.onHoverOver);
DrawEvents("ET1", "On Hover Out", mTrigger.onHoverOut);
DrawEvents("ET2", "On Press", mTrigger.onPress);
DrawEvents("ET3", "On Release", mTrigger.onRelease);
DrawEvents("ET4", "On Select", mTrigger.onSelect);
DrawEvents("ET5", "On Deselect", mTrigger.onDeselect);
DrawEvents("ET6", "On Click/Tap", mTrigger.onClick);
DrawEvents("ET7", "On Double-Click/Tap", mTrigger.onDoubleClick);
DrawEvents("ET8", "On Drag Over", mTrigger.onDragOver);
DrawEvents("ET9", "On Drag Out", mTrigger.onDragOut);
}
void DrawEvents (string key, string text, List<EventDelegate> list)
{
if (!NGUIEditorTools.DrawHeader(text, key, false)) return;
NGUIEditorTools.BeginContents();
EventDelegateEditor.Field(mTrigger, list, null, null);
NGUIEditorTools.EndContents();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIEventTriggerEditor.cs
|
C#
|
asf20
| 2,108
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit UISprites.
/// </summary>
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UISprite))]
#else
[CustomEditor(typeof(UISprite), true)]
#endif
public class UISpriteInspector : UIWidgetInspector
{
/// <summary>
/// Atlas selection callback.
/// </summary>
void OnSelectAtlas (Object obj)
{
serializedObject.Update();
SerializedProperty sp = serializedObject.FindProperty("mAtlas");
sp.objectReferenceValue = obj;
serializedObject.ApplyModifiedProperties();
NGUISettings.atlas = obj as UIAtlas;
}
/// <summary>
/// Sprite selection callback function.
/// </summary>
void SelectSprite (string spriteName)
{
serializedObject.Update();
SerializedProperty sp = serializedObject.FindProperty("mSpriteName");
sp.stringValue = spriteName;
serializedObject.ApplyModifiedProperties();
NGUISettings.selectedSprite = spriteName;
}
/// <summary>
/// Draw the atlas and sprite selection fields.
/// </summary>
protected override bool ShouldDrawProperties ()
{
GUILayout.BeginHorizontal();
if (NGUIEditorTools.DrawPrefixButton("Atlas"))
ComponentSelector.Show<UIAtlas>(OnSelectAtlas);
SerializedProperty atlas = NGUIEditorTools.DrawProperty("", serializedObject, "mAtlas", GUILayout.MinWidth(20f));
if (GUILayout.Button("Edit", GUILayout.Width(40f)))
{
if (atlas != null)
{
UIAtlas atl = atlas.objectReferenceValue as UIAtlas;
NGUISettings.atlas = atl;
NGUIEditorTools.Select(atl.gameObject);
}
}
GUILayout.EndHorizontal();
SerializedProperty sp = serializedObject.FindProperty("mSpriteName");
NGUIEditorTools.DrawAdvancedSpriteField(atlas.objectReferenceValue as UIAtlas, sp.stringValue, SelectSprite, false);
return true;
}
/// <summary>
/// Sprites's custom properties based on the type.
/// </summary>
protected override void DrawCustomProperties ()
{
GUILayout.Space(6f);
SerializedProperty sp = NGUIEditorTools.DrawProperty("Sprite Type", serializedObject, "mType", GUILayout.MinWidth(20f));
EditorGUI.BeginDisabledGroup(sp.hasMultipleDifferentValues);
{
UISprite.Type type = (UISprite.Type)sp.intValue;
if (type == UISprite.Type.Simple || type == UISprite.Type.Tiled)
{
NGUIEditorTools.DrawProperty("Flip", serializedObject, "mFlip");
}
else if (type == UISprite.Type.Sliced)
{
NGUIEditorTools.DrawProperty("Flip", serializedObject, "mFlip");
sp = serializedObject.FindProperty("centerType");
bool val = (sp.intValue != (int)UISprite.AdvancedType.Invisible);
if (val != EditorGUILayout.Toggle("Fill Center", val))
{
sp.intValue = val ? (int)UISprite.AdvancedType.Invisible : (int)UISprite.AdvancedType.Sliced;
}
}
else if (type == UISprite.Type.Filled)
{
NGUIEditorTools.DrawProperty("Flip", serializedObject, "mFlip");
NGUIEditorTools.DrawProperty("Fill Dir", serializedObject, "mFillDirection", GUILayout.MinWidth(20f));
GUILayout.BeginHorizontal();
GUILayout.Space(4f);
NGUIEditorTools.DrawProperty("Fill Amount", serializedObject, "mFillAmount", GUILayout.MinWidth(20f));
GUILayout.Space(4f);
GUILayout.EndHorizontal();
NGUIEditorTools.DrawProperty("Invert Fill", serializedObject, "mInvert", GUILayout.MinWidth(20f));
}
else if (type == UISprite.Type.Advanced)
{
NGUIEditorTools.DrawProperty(" - Left", serializedObject, "leftType");
NGUIEditorTools.DrawProperty(" - Right", serializedObject, "rightType");
NGUIEditorTools.DrawProperty(" - Top", serializedObject, "topType");
NGUIEditorTools.DrawProperty(" - Bottom", serializedObject, "bottomType");
NGUIEditorTools.DrawProperty(" - Center", serializedObject, "centerType");
NGUIEditorTools.DrawProperty("Flip", serializedObject, "mFlip");
}
}
EditorGUI.EndDisabledGroup();
//GUI.changed = false;
//Vector4 draw = EditorGUILayout.Vector4Field("Draw Region", mWidget.drawRegion);
//if (GUI.changed)
//{
// NGUIEditorTools.RegisterUndo("Draw Region", mWidget);
// mWidget.drawRegion = draw;
//}
GUILayout.Space(4f);
base.DrawCustomProperties();
}
/// <summary>
/// All widgets have a preview.
/// </summary>
public override bool HasPreviewGUI () { return !serializedObject.isEditingMultipleObjects; }
/// <summary>
/// Draw the sprite preview.
/// </summary>
public override void OnPreviewGUI (Rect rect, GUIStyle background)
{
UISprite sprite = target as UISprite;
if (sprite == null || !sprite.isValid) return;
Texture2D tex = sprite.mainTexture as Texture2D;
if (tex == null) return;
UISpriteData sd = sprite.atlas.GetSprite(sprite.spriteName);
NGUIEditorTools.DrawSprite(tex, rect, sd, sprite.color);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UISpriteInspector.cs
|
C#
|
asf20
| 4,969
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
/// <summary>
/// Editor helper class containing functions related to drawing things in the Scene View using UnityEditor.Handles.
/// </summary>
public static class NGUIHandles
{
/// <summary>
/// Given a plane the rectangle lies upon, convert the given screen coordinates to world coordinates.
/// </summary>
static public bool ScreenToWorldPoint (Plane p, Vector2 screenPos, out Vector3 worldPos)
{
float dist;
Ray ray = HandleUtility.GUIPointToWorldRay(screenPos);
if (p.Raycast(ray, out dist))
{
worldPos = ray.GetPoint(dist);
return true;
}
worldPos = Vector3.zero;
return false;
}
/// <summary>
/// Given the widget's corners, convert the given screen coordinates to world coordinates.
/// </summary>
static public bool ScreenToWorldPoint (Vector3[] corners, Vector2 screenPos, out Vector3 worldPos)
{
Plane p = new Plane(corners[0], corners[1], corners[3]);
return ScreenToWorldPoint(p, screenPos, out worldPos);
}
/// <summary>
/// Draw width and height around the rectangle specified by the four world-space corners.
/// </summary>
static public void DrawSize (Vector3[] worldPos, int width, int height)
{
Vector2[] screenPos = new Vector2[4];
for (int i = 0; i < 4; ++i)
screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);
Vector2 up = (screenPos[1] - screenPos[0]).normalized;
Vector2 right = (screenPos[3] - screenPos[0]).normalized;
Vector2 v0 = screenPos[0] - right * 20f;
Vector2 v1 = screenPos[1] - right * 20f;
Vector2 v2 = screenPos[0] - up * 20f;
Vector2 v3 = screenPos[3] - up * 20f;
Plane p = new Plane(worldPos[0], worldPos[1], worldPos[3]);
Color color = new Color(1f, 1f, 1f, 1f);
DrawShadowedLine(p, v0, v1, color);
DrawShadowedLine(p, v2, v3, color);
DrawShadowedLine(p, v0 - right * 10f, v0 + right * 10f, color);
DrawShadowedLine(p, v1 - right * 10f, v1 + right * 10f, color);
DrawShadowedLine(p, v2 - up * 10f, v2 + up * 10f, color);
DrawShadowedLine(p, v3 - up * 10f, v3 + up * 10f, color);
if (Event.current.type == EventType.Repaint)
{
Handles.BeginGUI();
DrawCenteredLabel((v2 + v3) * 0.5f, width.ToString());
DrawCenteredLabel((v0 + v1) * 0.5f, height.ToString());
Handles.EndGUI();
}
}
/// <summary>
/// Draw a shadowed line in the scene view.
/// </summary>
static public void DrawShadowedLine (Plane p, Vector2 screenPos0, Vector2 screenPos1, Color c)
{
Handles.color = new Color(0f, 0f, 0f, 0.5f);
DrawLine(p, screenPos0 + Vector2.one, screenPos1 + Vector2.one);
Handles.color = c;
DrawLine(p, screenPos0, screenPos1);
}
/// <summary>
/// Draw a shadowed line in the scene view.
/// </summary>
static public void DrawShadowedLine (Plane p, Vector3 worldPos0, Vector3 worldPos1, Color c)
{
Vector2 s0 = HandleUtility.WorldToGUIPoint(worldPos0);
Vector2 s1 = HandleUtility.WorldToGUIPoint(worldPos1);
DrawShadowedLine(p, s0, s1, c);
}
/// <summary>
/// Draw a shadowed line in the scene view.
/// </summary>
static public void DrawShadowedLine (Vector3[] corners, Vector3 worldPos0, Vector3 worldPos1, Color c)
{
Plane p = new Plane(corners[0], corners[1], corners[3]);
Vector2 s0 = HandleUtility.WorldToGUIPoint(worldPos0);
Vector2 s1 = HandleUtility.WorldToGUIPoint(worldPos1);
DrawShadowedLine(p, s0, s1, c);
}
/// <summary>
/// Draw a line in the scene view.
/// </summary>
static public void DrawLine (Plane p, Vector2 v0, Vector2 v1)
{
#if UNITY_3_5
// Unity 3.5 exhibits a strange offset...
v0.x += 1f;
v1.x += 1f;
v0.y -= 1f;
v1.y -= 1f;
#endif
Vector3 w0, w1;
if (ScreenToWorldPoint(p, v0, out w0) && ScreenToWorldPoint(p, v1, out w1))
Handles.DrawLine(w0, w1);
}
/// <summary>
/// Draw a centered label at the specified world coordinates.
/// </summary>
static public void DrawCenteredLabel (Vector3 worldPos, string text) { DrawCenteredLabel(worldPos, text, 60f); }
/// <summary>
/// Draw a centered label at the specified world coordinates.
/// </summary>
static public void DrawCenteredLabel (Vector3 worldPos, string text, float width)
{
Vector2 screenPoint = HandleUtility.WorldToGUIPoint(worldPos);
DrawCenteredLabel(screenPoint, text, width);
}
/// <summary>
/// Draw a centered label at the specified screen coordinates.
/// </summary>
static public void DrawCenteredLabel (Vector2 screenPos, string text) { DrawCenteredLabel(screenPos, text, 60f); }
/// <summary>
/// Draw a centered label at the specified screen coordinates.
/// It's expected that this call happens inside Handles.BeginGUI() / Handles.EndGUI().
/// </summary>
static public void DrawCenteredLabel (Vector2 screenPos, string text, float width)
{
if (Event.current.type == EventType.Repaint)
{
Color c = GUI.color;
float tw = Mathf.Max(2, text.Length) * 15f;
GUI.color = new Color(0f, 0f, 0f, 0.75f);
GUI.Box(new Rect(screenPos.x - tw * 0.5f, screenPos.y - 10f, tw, 20f), "", "WinBtnInactiveMac");
GUI.color = c;
#if UNITY_3_5
GUI.Label(new Rect(screenPos.x - 30f, screenPos.y - 14f, 60f, 20f), text, "PreLabel");
#else
GUI.Label(new Rect(screenPos.x - 30f, screenPos.y - 10f, 60f, 20f), text, "PreLabel");
#endif
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUIHandles.cs
|
C#
|
asf20
| 5,416
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Utility class that makes it easy to perform snapping while dragging widgets.
/// </summary>
public static class NGUISnap
{
const float SNAP_THRESHOLD = 10f;
static BetterList<Vector3> mSnapCenter = new BetterList<Vector3>();
static BetterList<Vector3> mSnapCorners = new BetterList<Vector3>();
static int mSnapping = -1;
/// <summary>
/// Whether widgets will snap to edges of other widgets when dragged around.
/// </summary>
static public bool allow
{
get
{
if (mSnapping == -1)
{
mSnapping = UnityEditor.EditorPrefs.GetInt("NGUI Snap", 1);
}
return (mSnapping == 1);
}
set
{
int val = value ? 1 : 0;
if (mSnapping != val)
{
mSnapping = val;
UnityEditor.EditorPrefs.SetInt("NGUI Handles", mSnapping);
}
}
}
/// <summary>
/// Recalculate all snapping edges.
/// </summary>
static public void Recalculate (Object obj)
{
mSnapCenter.Clear();
mSnapCorners.Clear();
if (obj is UIWidget)
{
UIWidget w = obj as UIWidget;
Recalculate(w.cachedTransform);
}
else if (obj is UIPanel)
{
UIPanel p = obj as UIPanel;
Recalculate(p.cachedTransform);
}
}
/// <summary>
/// Recalculate all snapping edges.
/// </summary>
static void Recalculate (Transform t)
{
// If the transform is rotated, ignore it
if (Vector3.Dot(t.localRotation * Vector3.up, Vector3.up) < 0.999f) return;
Transform parent = t.parent;
if (parent != null)
{
Add(t, parent);
for (int i = 0; i < parent.childCount; ++i)
{
Transform child = parent.GetChild(i);
if (child != t) Add(t, child);
}
}
}
/// <summary>
/// Add the specified transform's edges to the lists.
/// </summary>
static void Add (Transform root, Transform child)
{
UIWidget w = child.GetComponent<UIWidget>();
if (w != null) Add(root, child, w.localCorners);
UIPanel p = child.GetComponent<UIPanel>();
if (p != null) Add(root, child, p.localCorners);
}
/// <summary>
/// Add the specified transform's edges to the list.
/// </summary>
static void Add (Transform root, Transform child, Vector3[] local)
{
// If the transform is rotated, ignore it
if (Vector3.Dot(child.localRotation * Vector3.forward, Vector3.forward) < 0.999f) return;
// Make the coordinates relative to 'mine' transform
if (root != child)
{
for (int i = 0; i < 4; ++i)
{
local[i] = root.InverseTransformPoint(child.TransformPoint(local[i]));
}
}
Vector3 pos = root.localPosition;
mSnapCenter.Add(pos + (local[0] + local[2]) * 0.5f);
mSnapCorners.Add(pos + local[0]);
mSnapCorners.Add(pos + local[2]);
}
/// <summary>
/// Snap the X coordinate using the previously calculated snapping edges.
/// </summary>
static public Vector3 Snap (Vector3 pos, Vector3[] local, bool snapToEdges)
{
if (snapToEdges && allow)
{
Vector3 center = pos + (local[0] + local[2]) * 0.5f;
Vector3 bl = pos + local[0];
Vector3 tr = pos + local[2];
Vector2 best = new Vector2(float.MaxValue, float.MaxValue);
for (int i = 0; i < mSnapCenter.size; ++i)
ChooseBest(ref best, mSnapCenter[i] - center);
for (int i = 0; i < mSnapCorners.size; ++i)
{
ChooseBest(ref best, mSnapCorners[i] - bl);
ChooseBest(ref best, mSnapCorners[i] - tr);
}
if (Mathf.Abs(best.x) < SNAP_THRESHOLD) pos.x += best.x;
if (Mathf.Abs(best.y) < SNAP_THRESHOLD) pos.y += best.y;
}
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = Mathf.Round(pos.z);
return pos;
}
/// <summary>
/// Choose the closest edge.
/// </summary>
static void ChooseBest (ref Vector2 best, Vector3 diff)
{
if (Mathf.Abs(best.x) > Mathf.Abs(diff.x)) best.x = diff.x;
if (Mathf.Abs(best.y) > Mathf.Abs(diff.y)) best.y = diff.y;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUISnap.cs
|
C#
|
asf20
| 3,965
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit UITextures.
/// </summary>
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UI2DSprite))]
#else
[CustomEditor(typeof(UI2DSprite), true)]
#endif
public class UI2DSpriteEditor : UIWidgetInspector
{
UI2DSprite mSprite;
protected override void OnEnable ()
{
base.OnEnable();
mSprite = target as UI2DSprite;
}
protected override bool ShouldDrawProperties ()
{
SerializedProperty sp = NGUIEditorTools.DrawProperty("2D Sprite", serializedObject, "mSprite");
NGUISettings.sprite2D = sp.objectReferenceValue as Sprite;
NGUIEditorTools.DrawProperty("Material", serializedObject, "mMat");
if (mSprite.material == null || serializedObject.isEditingMultipleObjects)
{
NGUIEditorTools.DrawProperty("Shader", serializedObject, "mShader");
}
return (sp.objectReferenceValue != null);
}
/// <summary>
/// Allow the texture to be previewed.
/// </summary>
public override bool HasPreviewGUI ()
{
return (mSprite != null) && (mSprite.mainTexture as Texture2D != null);
}
/// <summary>
/// Draw the sprite preview.
/// </summary>
public override void OnPreviewGUI (Rect rect, GUIStyle background)
{
if (mSprite != null && mSprite.sprite2D != null)
{
Texture2D tex = mSprite.mainTexture as Texture2D;
if (tex != null) NGUIEditorTools.DrawTexture(tex, rect, mSprite.uvRect, mSprite.color);
}
}
}
#endif
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UI2DSpriteEditor.cs
|
C#
|
asf20
| 1,718
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(UIPlayTween))]
public class UIPlayTweenEditor : Editor
{
enum ResetOnPlay
{
Continue,
Restart,
RestartIfNotPlaying,
}
enum SelectedObject
{
KeepCurrent,
SetToNothing,
}
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(120f);
UIPlayTween tw = target as UIPlayTween;
GUILayout.Space(6f);
GUI.changed = false;
GameObject tt = (GameObject)EditorGUILayout.ObjectField("Tween Target", tw.tweenTarget, typeof(GameObject), true);
bool inc = EditorGUILayout.Toggle("Include Children", tw.includeChildren);
int group = EditorGUILayout.IntField("Tween Group", tw.tweenGroup, GUILayout.Width(160f));
AnimationOrTween.Trigger trigger = (AnimationOrTween.Trigger)EditorGUILayout.EnumPopup("Trigger condition", tw.trigger);
AnimationOrTween.Direction dir = (AnimationOrTween.Direction)EditorGUILayout.EnumPopup("Play direction", tw.playDirection);
AnimationOrTween.EnableCondition enab = (AnimationOrTween.EnableCondition)EditorGUILayout.EnumPopup("If target is disabled", tw.ifDisabledOnPlay);
ResetOnPlay rs = tw.resetOnPlay ? ResetOnPlay.Restart : (tw.resetIfDisabled ? ResetOnPlay.RestartIfNotPlaying : ResetOnPlay.Continue);
ResetOnPlay reset = (ResetOnPlay)EditorGUILayout.EnumPopup("If already playing", rs);
AnimationOrTween.DisableCondition dis = (AnimationOrTween.DisableCondition)EditorGUILayout.EnumPopup("When finished", tw.disableWhenFinished);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.tweenTarget = tt;
tw.tweenGroup = group;
tw.includeChildren = inc;
tw.trigger = trigger;
tw.playDirection = dir;
tw.ifDisabledOnPlay = enab;
tw.resetOnPlay = (reset == ResetOnPlay.Restart);
tw.resetIfDisabled = (reset == ResetOnPlay.RestartIfNotPlaying);
tw.disableWhenFinished = dis;
NGUITools.SetDirty(tw);
}
NGUIEditorTools.SetLabelWidth(80f);
NGUIEditorTools.DrawEvents("On Finished", tw, tw.onFinished);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIPlayTweenEditor.cs
|
C#
|
asf20
| 2,190
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// UI Widget Creation Wizard
/// </summary>
public class UICreateWidgetWizard : EditorWindow
{
public enum WidgetType
{
Label,
Sprite,
Texture,
Button,
ImageButton,
Toggle,
ProgressBar,
Slider,
Input,
PopupList,
PopupMenu,
ScrollBar,
}
static WidgetType mWidgetType = WidgetType.Button;
static string mButton = "";
static string mImage0 = "";
static string mImage1 = "";
static string mImage2 = "";
static string mImage3 = "";
static string mSliderBG = "";
static string mSliderFG = "";
static string mSliderTB = "";
static string mCheckBG = "";
static string mCheck = "";
static string mInputBG = "";
static string mListFG = "";
static string mListBG = "";
static string mListHL = "";
static string mScrollBG = "";
static string mScrollFG = "";
static Color mColor = Color.white;
static bool mLoaded = false;
static bool mScrollCL = true;
static UIScrollBar.FillDirection mFillDir = UIScrollBar.FillDirection.LeftToRight;
/// <summary>
/// Save the specified string into player prefs.
/// </summary>
static void SaveString (string field, string val)
{
if (string.IsNullOrEmpty(val))
{
EditorPrefs.DeleteKey(field);
}
else
{
EditorPrefs.SetString(field, val);
}
}
/// <summary>
/// Load the specified string from player prefs.
/// </summary>
static string LoadString (string field) { string s = EditorPrefs.GetString(field); return (string.IsNullOrEmpty(s)) ? "" : s; }
/// <summary>
/// Save all serialized values in editor prefs.
/// This is necessary because static values get wiped out as soon as scripts get recompiled.
/// </summary>
static void Save ()
{
EditorPrefs.SetInt("NGUI Widget Type", (int)mWidgetType);
EditorPrefs.SetInt("NGUI Color", NGUIMath.ColorToInt(mColor));
EditorPrefs.SetBool("NGUI ScrollCL", mScrollCL);
EditorPrefs.SetInt("NGUI Fill Dir", (int)mFillDir);
SaveString("NGUI Button", mButton);
SaveString("NGUI Image 0", mImage0);
SaveString("NGUI Image 1", mImage1);
SaveString("NGUI Image 2", mImage2);
SaveString("NGUI Image 3", mImage3);
SaveString("NGUI CheckBG", mCheckBG);
SaveString("NGUI Check", mCheck);
SaveString("NGUI SliderBG", mSliderBG);
SaveString("NGUI SliderFG", mSliderFG);
SaveString("NGUI SliderTB", mSliderTB);
SaveString("NGUI InputBG", mInputBG);
SaveString("NGUI ListFG", mListFG);
SaveString("NGUI ListBG", mListBG);
SaveString("NGUI ListHL", mListHL);
SaveString("NGUI ScrollBG", mScrollBG);
SaveString("NGUI ScrollFG", mScrollFG);
}
/// <summary>
/// Load all serialized values from editor prefs.
/// This is necessary because static values get wiped out as soon as scripts get recompiled.
/// </summary>
static void Load ()
{
mWidgetType = (WidgetType)EditorPrefs.GetInt("NGUI Widget Type", 0);
mFillDir = (UIScrollBar.FillDirection)EditorPrefs.GetInt("NGUI Fill Dir", 0);
int color = EditorPrefs.GetInt("NGUI Color", -1);
if (color != -1) mColor = NGUIMath.IntToColor(color);
mButton = LoadString("NGUI Button");
mImage0 = LoadString("NGUI Image 0");
mImage1 = LoadString("NGUI Image 1");
mImage2 = LoadString("NGUI Image 2");
mImage3 = LoadString("NGUI Image 3");
mCheckBG = LoadString("NGUI CheckBG");
mCheck = LoadString("NGUI Check");
mSliderBG = LoadString("NGUI SliderBG");
mSliderFG = LoadString("NGUI SliderFG");
mSliderTB = LoadString("NGUI SliderTB");
mInputBG = LoadString("NGUI InputBG");
mListFG = LoadString("NGUI ListFG");
mListBG = LoadString("NGUI ListBG");
mListHL = LoadString("NGUI ListHL");
mScrollBG = LoadString("NGUI ScrollBG");
mScrollFG = LoadString("NGUI ScrollFG");
mScrollCL = EditorPrefs.GetBool("NGUI ScrollCL", true);
}
/// <summary>
/// Atlas selection function.
/// </summary>
void OnSelectAtlas (Object obj)
{
if (NGUISettings.atlas != obj)
{
NGUISettings.atlas = obj as UIAtlas;
Repaint();
}
}
/// <summary>
/// Font selection function.
/// </summary>
void OnSelectFont (Object obj)
{
Object fnt = obj as UIFont;
if (NGUISettings.ambigiousFont != fnt)
{
NGUISettings.ambigiousFont = fnt;
Repaint();
}
}
/// <summary>
/// Convenience function -- creates the "Add To" button and the parent object field to the right of it.
/// </summary>
static public bool ShouldCreate (GameObject go, bool isValid)
{
GUI.color = isValid ? Color.green : Color.grey;
GUILayout.BeginHorizontal();
bool retVal = GUILayout.Button("Add To", GUILayout.Width(76f));
GUI.color = Color.white;
GameObject sel = EditorGUILayout.ObjectField(go, typeof(GameObject), true, GUILayout.Width(140f)) as GameObject;
GUILayout.Label("Select the parent in the Hierarchy View", GUILayout.MinWidth(10000f));
GUILayout.EndHorizontal();
if (sel != go) Selection.activeGameObject = sel;
if (retVal && isValid)
{
NGUIEditorTools.RegisterUndo("Add a Widget");
return true;
}
return false;
}
/// <summary>
/// Label creation function.
/// </summary>
void CreateLabel (GameObject go)
{
GUILayout.BeginHorizontal();
Color c = EditorGUILayout.ColorField("Color", mColor, GUILayout.Width(220f));
GUILayout.Label("Color tint the label will start with");
GUILayout.EndHorizontal();
if (mColor != c)
{
mColor = c;
Save();
}
if (ShouldCreate(go, NGUISettings.ambigiousFont != null))
{
Selection.activeGameObject = NGUISettings.AddLabel(go).gameObject;
}
}
/// <summary>
/// Sprite creation function.
/// </summary>
void CreateSprite (GameObject go)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Sprite", "Sprite that will be created", NGUISettings.atlas, NGUISettings.selectedSprite, OnSprite, GUILayout.Width(120f));
if (!string.IsNullOrEmpty(NGUISettings.selectedSprite))
{
GUILayout.BeginHorizontal();
NGUISettings.pivot = (UIWidget.Pivot)EditorGUILayout.EnumPopup("Pivot", NGUISettings.pivot, GUILayout.Width(200f));
GUILayout.Space(20f);
GUILayout.Label("Initial pivot point used by the sprite");
GUILayout.EndHorizontal();
}
}
if (ShouldCreate(go, NGUISettings.atlas != null))
{
Selection.activeGameObject = NGUISettings.AddSprite(go).gameObject;
}
}
void OnSprite (string val)
{
if (NGUISettings.selectedSprite != val)
{
NGUISettings.selectedSprite = val;
Repaint();
}
}
/// <summary>
/// UI Texture doesn't do anything other than creating the widget.
/// </summary>
void CreateSimpleTexture (GameObject go)
{
if (ShouldCreate(go, true))
{
Selection.activeGameObject = NGUISettings.AddTexture(go).gameObject;
}
}
/// <summary>
/// Button creation function.
/// </summary>
void CreateButton (GameObject go)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Background", "Sliced Sprite for the background", NGUISettings.atlas, mButton, OnButton, GUILayout.Width(120f));
}
if (ShouldCreate(go, NGUISettings.atlas != null))
{
int depth = NGUITools.CalculateNextDepth(go);
go = NGUITools.AddChild(go);
go.name = "Button";
UISprite bg = NGUITools.AddWidget<UISprite>(go);
bg.type = UISprite.Type.Sliced;
bg.name = "Background";
bg.depth = depth;
bg.atlas = NGUISettings.atlas;
bg.spriteName = mButton;
bg.width = 200;
bg.height = 50;
bg.MakePixelPerfect();
if (NGUISettings.ambigiousFont != null)
{
UILabel lbl = NGUITools.AddWidget<UILabel>(go);
lbl.ambigiousFont = NGUISettings.ambigiousFont;
lbl.text = go.name;
lbl.AssumeNaturalSize();
}
// Add a collider
NGUITools.AddWidgetCollider(go);
// Add the scripts
go.AddComponent<UIButton>().tweenTarget = bg.gameObject;
go.AddComponent<UIPlaySound>();
Selection.activeGameObject = go;
}
}
void OnButton (string val) { mButton = val; Save(); Repaint(); }
/// <summary>
/// Button creation function.
/// </summary>
void CreateImageButton (GameObject go)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Normal", "Normal state sprite", NGUISettings.atlas, mImage0, OnImage0, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Hover", "Hover state sprite", NGUISettings.atlas, mImage1, OnImage1, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Pressed", "Pressed state sprite", NGUISettings.atlas, mImage2, OnImage2, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Disabled", "Disabled state sprite", NGUISettings.atlas, mImage3, OnImage3, GUILayout.Width(120f));
}
if (ShouldCreate(go, NGUISettings.atlas != null))
{
int depth = NGUITools.CalculateNextDepth(go);
go = NGUITools.AddChild(go);
go.name = "Image Button";
UISpriteData sp = NGUISettings.atlas.GetSprite(mImage0);
UISprite sprite = NGUITools.AddWidget<UISprite>(go);
sprite.type = sp.hasBorder ? UISprite.Type.Sliced : UISprite.Type.Simple;
sprite.name = "Background";
sprite.depth = depth;
sprite.atlas = NGUISettings.atlas;
sprite.spriteName = mImage0;
sprite.width = 150;
sprite.height = 40;
sprite.MakePixelPerfect();
if (NGUISettings.ambigiousFont != null)
{
UILabel lbl = NGUITools.AddWidget<UILabel>(go);
lbl.ambigiousFont = NGUISettings.ambigiousFont;
lbl.text = go.name;
lbl.AssumeNaturalSize();
}
// Add a collider
NGUITools.AddWidgetCollider(go);
// Add the scripts
UIImageButton ib = go.AddComponent<UIImageButton>();
ib.target = sprite;
ib.normalSprite = mImage0;
ib.hoverSprite = mImage1;
ib.pressedSprite = mImage2;
ib.disabledSprite = mImage3;
go.AddComponent<UIPlaySound>();
Selection.activeGameObject = go;
}
}
void OnImage0 (string val) { mImage0 = val; Save(); Repaint(); }
void OnImage1 (string val) { mImage1 = val; Save(); Repaint(); }
void OnImage2 (string val) { mImage2 = val; Save(); Repaint(); }
void OnImage3 (string val) { mImage3 = val; Save(); Repaint(); }
/// <summary>
/// Toggle creation function.
/// </summary>
void CreateToggle (GameObject go)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Background", "Sprite used for the background", NGUISettings.atlas, mCheckBG, OnCheckBG, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Checkmark", "Sprite used for the checkmark", NGUISettings.atlas, mCheck, OnCheck, GUILayout.Width(120f));
}
if (ShouldCreate(go, NGUISettings.atlas != null))
{
int depth = NGUITools.CalculateNextDepth(go);
go = NGUITools.AddChild(go);
go.name = "Toggle";
UISprite bg = NGUITools.AddWidget<UISprite>(go);
bg.type = UISprite.Type.Sliced;
bg.name = "Background";
bg.depth = depth;
bg.atlas = NGUISettings.atlas;
bg.spriteName = mCheckBG;
bg.width = 26;
bg.height = 26;
bg.MakePixelPerfect();
UISprite fg = NGUITools.AddWidget<UISprite>(go);
fg.name = "Checkmark";
fg.atlas = NGUISettings.atlas;
fg.spriteName = mCheck;
fg.MakePixelPerfect();
if (NGUISettings.ambigiousFont != null)
{
UILabel lbl = NGUITools.AddWidget<UILabel>(go);
lbl.ambigiousFont = NGUISettings.ambigiousFont;
lbl.text = go.name;
lbl.pivot = UIWidget.Pivot.Left;
lbl.transform.localPosition = new Vector3(16f, 0f, 0f);
lbl.AssumeNaturalSize();
}
// Add a collider
NGUITools.AddWidgetCollider(go);
// Add the scripts
go.AddComponent<UIToggle>().activeSprite = fg;
go.AddComponent<UIButton>().tweenTarget = bg.gameObject;
go.AddComponent<UIButtonScale>().tweenTarget = bg.transform;
go.AddComponent<UIPlaySound>();
Selection.activeGameObject = go;
}
}
void OnCheckBG (string val) { mCheckBG = val; Save(); Repaint(); }
void OnCheck (string val) { mCheck = val; Save(); Repaint(); }
/// <summary>
/// Scroll bar template.
/// </summary>
void CreateScrollBar (GameObject go)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Background", "Sprite used for the background", NGUISettings.atlas, mScrollBG, OnScrollBG, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Foreground", "Sprite used for the foreground (thumb)", NGUISettings.atlas, mScrollFG, OnScrollFG, GUILayout.Width(120f));
GUILayout.BeginHorizontal();
UIScrollBar.FillDirection dir = (UIScrollBar.FillDirection)EditorGUILayout.EnumPopup("Direction", mFillDir, GUILayout.Width(200f));
GUILayout.Space(20f);
GUILayout.Label("Add colliders?", GUILayout.Width(90f));
bool draggable = EditorGUILayout.Toggle(mScrollCL);
GUILayout.EndHorizontal();
if (mScrollCL != draggable || mFillDir != dir)
{
mScrollCL = draggable;
mFillDir = dir;
Save();
}
}
if (ShouldCreate(go, NGUISettings.atlas != null))
{
int depth = NGUITools.CalculateNextDepth(go);
go = NGUITools.AddChild(go);
go.name = "Scroll Bar";
UISprite bg = NGUITools.AddWidget<UISprite>(go);
bg.type = UISprite.Type.Sliced;
bg.name = "Background";
bg.depth = depth;
bg.atlas = NGUISettings.atlas;
bg.spriteName = mScrollBG;
Vector4 border = bg.border;
bg.width = Mathf.RoundToInt(400f + border.x + border.z);
bg.height = Mathf.RoundToInt(14f + border.y + border.w);
bg.MakePixelPerfect();
UISprite fg = NGUITools.AddWidget<UISprite>(go);
fg.type = UISprite.Type.Sliced;
fg.name = "Foreground";
fg.atlas = NGUISettings.atlas;
fg.spriteName = mScrollFG;
UIScrollBar sb = go.AddComponent<UIScrollBar>();
sb.foregroundWidget = fg;
sb.backgroundWidget = bg;
sb.fillDirection = mFillDir;
sb.barSize = 0.3f;
sb.value = 0.3f;
sb.ForceUpdate();
if (mScrollCL)
{
NGUITools.AddWidgetCollider(bg.gameObject);
NGUITools.AddWidgetCollider(fg.gameObject);
}
Selection.activeGameObject = go;
}
}
void OnScrollBG (string val) { mScrollBG = val; Save(); Repaint(); }
void OnScrollFG (string val) { mScrollFG = val; Save(); Repaint(); }
/// <summary>
/// Progress bar creation function.
/// </summary>
void CreateSlider (GameObject go, bool slider)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Empty", "Sprite for the background (empty bar)", NGUISettings.atlas, mSliderBG, OnSliderBG, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Full", "Sprite for the foreground (full bar)", NGUISettings.atlas, mSliderFG, OnSliderFG, GUILayout.Width(120f));
if (slider)
{
NGUIEditorTools.DrawSpriteField("Thumb", "Sprite for the thumb indicator", NGUISettings.atlas, mSliderTB, OnSliderTB, GUILayout.Width(120f));
}
}
if (ShouldCreate(go, NGUISettings.atlas != null))
{
int depth = NGUITools.CalculateNextDepth(go);
go = NGUITools.AddChild(go);
go.name = slider ? "Slider" : "Progress Bar";
// Background sprite
UISpriteData bgs = NGUISettings.atlas.GetSprite(mSliderBG);
UISprite back = (UISprite)NGUITools.AddWidget<UISprite>(go);
back.type = bgs.hasBorder ? UISprite.Type.Sliced : UISprite.Type.Simple;
back.name = "Background";
back.depth = depth;
back.pivot = UIWidget.Pivot.Left;
back.atlas = NGUISettings.atlas;
back.spriteName = mSliderBG;
back.width = 200;
back.height = 30;
back.transform.localPosition = Vector3.zero;
back.MakePixelPerfect();
// Foreground sprite
UISpriteData fgs = NGUISettings.atlas.GetSprite(mSliderFG);
UISprite front = NGUITools.AddWidget<UISprite>(go);
front.type = fgs.hasBorder ? UISprite.Type.Sliced : UISprite.Type.Simple;
front.name = "Foreground";
front.pivot = UIWidget.Pivot.Left;
front.atlas = NGUISettings.atlas;
front.spriteName = mSliderFG;
front.width = 200;
front.height = 30;
front.transform.localPosition = Vector3.zero;
front.MakePixelPerfect();
// Add a collider
if (slider) NGUITools.AddWidgetCollider(go);
// Add the slider script
UISlider uiSlider = go.AddComponent<UISlider>();
uiSlider.foregroundWidget = front;
// Thumb sprite
if (slider)
{
UISpriteData tbs = NGUISettings.atlas.GetSprite(mSliderTB);
UISprite thb = NGUITools.AddWidget<UISprite>(go);
thb.type = tbs.hasBorder ? UISprite.Type.Sliced : UISprite.Type.Simple;
thb.name = "Thumb";
thb.atlas = NGUISettings.atlas;
thb.spriteName = mSliderTB;
thb.width = 20;
thb.height = 40;
thb.transform.localPosition = new Vector3(200f, 0f, 0f);
thb.MakePixelPerfect();
NGUITools.AddWidgetCollider(thb.gameObject);
thb.gameObject.AddComponent<UIButtonColor>();
thb.gameObject.AddComponent<UIButtonScale>();
uiSlider.thumb = thb.transform;
}
uiSlider.value = 1f;
// Select the slider
Selection.activeGameObject = go;
}
}
void OnSliderBG (string val) { mSliderBG = val; Save(); Repaint(); }
void OnSliderFG (string val) { mSliderFG = val; Save(); Repaint(); }
void OnSliderTB (string val) { mSliderTB = val; Save(); Repaint(); }
/// <summary>
/// Input field creation function.
/// </summary>
void CreateInput (GameObject go)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Background", "Sliced Sprite for the background", NGUISettings.atlas, mInputBG, OnInputBG, GUILayout.Width(120f));
}
if (ShouldCreate(go, NGUISettings.atlas != null && NGUISettings.ambigiousFont != null))
{
int depth = NGUITools.CalculateNextDepth(go);
go = NGUITools.AddChild(go);
go.name = "Input";
int padding = 3;
UISprite bg = NGUITools.AddWidget<UISprite>(go);
bg.type = UISprite.Type.Sliced;
bg.name = "Background";
bg.depth = depth;
bg.atlas = NGUISettings.atlas;
bg.spriteName = mInputBG;
bg.pivot = UIWidget.Pivot.Left;
bg.width = 400;
bg.height = NGUISettings.fontSize + padding * 2;
bg.transform.localPosition = Vector3.zero;
bg.MakePixelPerfect();
UILabel lbl = NGUITools.AddWidget<UILabel>(go);
lbl.ambigiousFont = NGUISettings.ambigiousFont;
lbl.pivot = UIWidget.Pivot.Left;
lbl.transform.localPosition = new Vector3(padding, 0f, 0f);
lbl.multiLine = false;
lbl.supportEncoding = false;
lbl.width = Mathf.RoundToInt(400f - padding * 2f);
lbl.text = "You can type here";
lbl.AssumeNaturalSize();
// Add a collider to the background
NGUITools.AddWidgetCollider(go);
// Add an input script to the background and have it point to the label
UIInput input = go.AddComponent<UIInput>();
input.label = lbl;
// Update the selection
Selection.activeGameObject = go;
}
}
void OnInputBG (string val) { mInputBG = val; Save(); Repaint(); }
/// <summary>
/// Create a popup list or a menu.
/// </summary>
void CreatePopup (GameObject go, bool isDropDown)
{
if (NGUISettings.atlas != null)
{
NGUIEditorTools.DrawSpriteField("Foreground", "Foreground sprite (shown on the button)", NGUISettings.atlas, mListFG, OnListFG, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Background", "Background sprite (envelops the options)", NGUISettings.atlas, mListBG, OnListBG, GUILayout.Width(120f));
NGUIEditorTools.DrawSpriteField("Highlight", "Sprite used to highlight the selected option", NGUISettings.atlas, mListHL, OnListHL, GUILayout.Width(120f));
}
if (ShouldCreate(go, NGUISettings.atlas != null && NGUISettings.ambigiousFont != null))
{
int depth = NGUITools.CalculateNextDepth(go);
go = NGUITools.AddChild(go);
go.name = isDropDown ? "Popup List" : "Popup Menu";
UISpriteData sphl = NGUISettings.atlas.GetSprite(mListHL);
UISpriteData spfg = NGUISettings.atlas.GetSprite(mListFG);
Vector2 hlPadding = new Vector2(Mathf.Max(4f, sphl.paddingLeft), Mathf.Max(4f, sphl.paddingTop));
Vector2 fgPadding = new Vector2(Mathf.Max(4f, spfg.paddingLeft), Mathf.Max(4f, spfg.paddingTop));
// Background sprite
UISprite sprite = NGUITools.AddSprite(go, NGUISettings.atlas, mListFG);
sprite.depth = depth;
sprite.atlas = NGUISettings.atlas;
sprite.pivot = UIWidget.Pivot.Left;
sprite.width = Mathf.RoundToInt(150f + fgPadding.x * 2f);
sprite.height = Mathf.RoundToInt(NGUISettings.fontSize + fgPadding.y * 2f);
sprite.transform.localPosition = Vector3.zero;
sprite.MakePixelPerfect();
// Text label
UILabel lbl = NGUITools.AddWidget<UILabel>(go);
lbl.ambigiousFont = NGUISettings.ambigiousFont;
lbl.fontSize = NGUISettings.fontSize;
lbl.fontStyle = NGUISettings.fontStyle;
lbl.text = go.name;
lbl.pivot = UIWidget.Pivot.Left;
lbl.cachedTransform.localPosition = new Vector3(fgPadding.x, 0f, 0f);
lbl.AssumeNaturalSize();
// Add a collider
NGUITools.AddWidgetCollider(go);
// Add the popup list
UIPopupList list = go.AddComponent<UIPopupList>();
list.atlas = NGUISettings.atlas;
list.ambigiousFont = NGUISettings.ambigiousFont;
list.fontSize = NGUISettings.fontSize;
list.fontStyle = NGUISettings.fontStyle;
list.backgroundSprite = mListBG;
list.highlightSprite = mListHL;
list.padding = hlPadding;
if (isDropDown) EventDelegate.Add(list.onChange, lbl.SetCurrentSelection);
for (int i = 0; i < 5; ++i) list.items.Add(isDropDown ? ("List Option " + i) : ("Menu Option " + i));
// Add the scripts
go.AddComponent<UIButton>().tweenTarget = sprite.gameObject;
go.AddComponent<UIPlaySound>();
Selection.activeGameObject = go;
}
}
void OnListFG (string val) { mListFG = val; Save(); Repaint(); }
void OnListBG (string val) { mListBG = val; Save(); Repaint(); }
void OnListHL (string val) { mListHL = val; Save(); Repaint(); }
/// <summary>
/// Repaint the window on selection.
/// </summary>
void OnSelectionChange () { Repaint(); }
#if DYNAMIC_FONT
UILabelInspector.FontType mType = UILabelInspector.FontType.Unity;
#else
UILabelInspector.FontType mType = UILabelInspector.FontType.Unity;
#endif
void OnFont (Object obj) { NGUISettings.ambigiousFont = obj; }
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
// Load the saved preferences
if (!mLoaded)
{
mLoaded = true;
Load();
#if DYNAMIC_FONT
Object font = NGUISettings.ambigiousFont;
mType = ((font != null) && (font is UIFont)) ? UILabelInspector.FontType.NGUI : UILabelInspector.FontType.Unity;
#else
mType = UILabelInspector.FontType.NGUI;
#endif
}
NGUIEditorTools.SetLabelWidth(80f);
GameObject go = NGUIEditorTools.SelectedRoot();
if (go == null)
{
GUILayout.Label("You must create a UI first.");
if (GUILayout.Button("Open the New UI Wizard"))
{
EditorWindow.GetWindow<UICreateNewUIWizard>(false, "New UI", true);
}
}
else
{
GUILayout.Space(4f);
GUILayout.BeginHorizontal();
ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false, GUILayout.Width(140f));
GUILayout.Label("Texture atlas used by widgets", GUILayout.Width(10000f));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (NGUIEditorTools.DrawPrefixButton("Font"))
{
if (mType == UILabelInspector.FontType.NGUI)
{
ComponentSelector.Show<UIFont>(OnFont);
}
else
{
ComponentSelector.Show<Font>(OnFont, new string[] { ".ttf", ".otf" });
}
}
#if DYNAMIC_FONT
GUI.changed = false;
if (mType == UILabelInspector.FontType.Unity)
{
NGUISettings.ambigiousFont = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont, typeof(Font), false, GUILayout.Width(140f));
}
else
{
NGUISettings.ambigiousFont = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont, typeof(UIFont), false, GUILayout.Width(140f));
}
mType = (UILabelInspector.FontType)EditorGUILayout.EnumPopup(mType, GUILayout.Width(62f));
#else
NGUISettings.ambigiousFont = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont, typeof(UIFont), false, GUILayout.Width(140f));
#endif
GUILayout.Label("size", GUILayout.Width(30f));
EditorGUI.BeginDisabledGroup(mType == UILabelInspector.FontType.NGUI);
NGUISettings.fontSize = EditorGUILayout.IntField(NGUISettings.fontSize, GUILayout.Width(30f));
EditorGUI.EndDisabledGroup();
GUILayout.Label("font used by the labels");
GUILayout.EndHorizontal();
NGUIEditorTools.DrawSeparator();
GUILayout.BeginHorizontal();
WidgetType wt = (WidgetType)EditorGUILayout.EnumPopup("Template", mWidgetType, GUILayout.Width(200f));
GUILayout.Space(20f);
GUILayout.Label("Select a widget template to use");
GUILayout.EndHorizontal();
if (mWidgetType != wt) { mWidgetType = wt; Save(); }
switch (mWidgetType)
{
case WidgetType.Label: CreateLabel(go); break;
case WidgetType.Sprite: CreateSprite(go); break;
case WidgetType.Texture: CreateSimpleTexture(go); break;
case WidgetType.Button: CreateButton(go); break;
case WidgetType.ImageButton: CreateImageButton(go); break;
case WidgetType.Toggle: CreateToggle(go); break;
case WidgetType.ProgressBar: CreateSlider(go, false); break;
case WidgetType.Slider: CreateSlider(go, true); break;
case WidgetType.Input: CreateInput(go); break;
case WidgetType.PopupList: CreatePopup(go, true); break;
case WidgetType.PopupMenu: CreatePopup(go, false); break;
case WidgetType.ScrollBar: CreateScrollBar(go); break;
}
EditorGUILayout.HelpBox("Widget Tool has become far less useful with NGUI 3.0.6. Search the Project view for 'Control', then simply drag & drop one of them into your Scene View.", MessageType.Warning);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UICreateWidgetWizard.cs
|
C#
|
asf20
| 25,562
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Panel wizard that allows a bird's eye view of all cameras in your scene.
/// </summary>
public class UICameraTool : EditorWindow
{
Vector2 mScroll = Vector2.zero;
/// <summary>
/// Layer mask field, originally from:
/// http://answers.unity3d.com/questions/60959/mask-field-in-the-editor.html
/// </summary>
public static int LayerMaskField (string label, int mask, params GUILayoutOption[] options)
{
List<string> layers = new List<string>();
List<int> layerNumbers = new List<int>();
string selectedLayers = "";
for (int i = 0; i < 32; ++i)
{
string layerName = LayerMask.LayerToName(i);
if (!string.IsNullOrEmpty(layerName))
{
if (mask == (mask | (1 << i)))
{
if (string.IsNullOrEmpty(selectedLayers))
{
selectedLayers = layerName;
}
else
{
selectedLayers = "Mixed";
}
}
}
}
if (Event.current.type != EventType.MouseDown && Event.current.type != EventType.ExecuteCommand)
{
if (mask == 0)
{
layers.Add("Nothing");
}
else if (mask == -1)
{
layers.Add("Everything");
}
else
{
layers.Add(selectedLayers);
}
layerNumbers.Add(-1);
}
layers.Add((mask == 0 ? "[+] " : " ") + "Nothing");
layerNumbers.Add(-2);
layers.Add((mask == -1 ? "[+] " : " ") + "Everything");
layerNumbers.Add(-3);
for (int i = 0; i < 32; ++i)
{
string layerName = LayerMask.LayerToName(i);
if (layerName != "")
{
if (mask == (mask | (1 << i)))
{
layers.Add("[+] " + layerName);
}
else
{
layers.Add(" " + layerName);
}
layerNumbers.Add(i);
}
}
bool preChange = GUI.changed;
GUI.changed = false;
int newSelected = 0;
if (Event.current.type == EventType.MouseDown)
{
newSelected = -1;
}
if (string.IsNullOrEmpty(label))
{
newSelected = EditorGUILayout.Popup(newSelected, layers.ToArray(), EditorStyles.layerMaskField, options);
}
else
{
newSelected = EditorGUILayout.Popup(label, newSelected, layers.ToArray(), EditorStyles.layerMaskField, options);
}
if (GUI.changed && newSelected >= 0)
{
if (newSelected == 0)
{
mask = 0;
}
else if (newSelected == 1)
{
mask = -1;
}
else
{
if (mask == (mask | (1 << layerNumbers[newSelected])))
{
mask &= ~(1 << layerNumbers[newSelected]);
}
else
{
mask = mask | (1 << layerNumbers[newSelected]);
}
}
}
else
{
GUI.changed = preChange;
}
return mask;
}
public static int LayerMaskField (int mask, params GUILayoutOption[] options)
{
return LayerMaskField(null, mask, options);
}
/// <summary>
/// Refresh the window on selection.
/// </summary>
void OnSelectionChange () { Repaint(); }
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
List<Camera> list = NGUIEditorTools.FindAll<Camera>();
if (list.Count > 0)
{
DrawRow(null);
NGUIEditorTools.DrawSeparator();
mScroll = GUILayout.BeginScrollView(mScroll);
foreach (Camera cam in list) DrawRow(cam);
GUILayout.EndScrollView();
}
else
{
GUILayout.Label("No cameras found in the scene");
}
}
/// <summary>
/// Helper function used to print things in columns.
/// </summary>
void DrawRow (Camera cam)
{
bool highlight = (cam == null || Selection.activeGameObject == null) ? false :
(0 != (cam.cullingMask & (1 << Selection.activeGameObject.layer)));
if (cam != null)
{
GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
GUI.backgroundColor = Color.white;
}
else
{
GUILayout.BeginHorizontal();
}
bool enabled = (cam == null || (NGUITools.GetActive(cam.gameObject) && cam.enabled));
GUI.color = Color.white;
if (cam != null)
{
if (enabled != EditorGUILayout.Toggle(enabled, GUILayout.Width(20f)))
{
cam.enabled = !enabled;
EditorUtility.SetDirty(cam.gameObject);
}
}
else
{
GUILayout.Space(30f);
}
if (enabled)
{
GUI.color = highlight ? new Color(0f, 0.8f, 1f) : Color.white;
}
else
{
GUI.color = highlight ? new Color(0f, 0.5f, 0.8f) : Color.grey;
}
string camName, camLayer;
if (cam == null)
{
camName = "Camera's Name";
camLayer = "Layer";
}
else
{
camName = cam.name + (cam.orthographic ? " (2D)" : " (3D)");
camLayer = LayerMask.LayerToName(cam.gameObject.layer);
}
if (GUILayout.Button(camName, EditorStyles.label, GUILayout.MinWidth(100f)) && cam != null)
{
Selection.activeGameObject = cam.gameObject;
EditorUtility.SetDirty(cam.gameObject);
}
GUILayout.Label(camLayer, GUILayout.Width(70f));
GUI.color = enabled ? Color.white : new Color(0.7f, 0.7f, 0.7f);
if (cam == null)
{
GUILayout.Label("EV", GUILayout.Width(26f));
}
else
{
UICamera uic = cam.GetComponent<UICamera>();
bool ev = (uic != null && uic.enabled);
if (ev != EditorGUILayout.Toggle(ev, GUILayout.Width(20f)))
{
if (uic == null) uic = cam.gameObject.AddComponent<UICamera>();
uic.enabled = !ev;
}
}
if (cam == null)
{
GUILayout.Label("Mask", GUILayout.Width(100f));
}
else
{
int mask = LayerMaskField(cam.cullingMask, GUILayout.Width(105f));
if (cam.cullingMask != mask)
{
NGUIEditorTools.RegisterUndo("Camera Mask Change", cam);
cam.cullingMask = mask;
}
}
GUILayout.EndHorizontal();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UICameraTool.cs
|
C#
|
asf20
| 5,767
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UISlider))]
public class UISliderEditor : UIProgressBarEditor
{
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UISliderEditor.cs
|
C#
|
asf20
| 335
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_FLASH
#define DYNAMIC_FONT
#endif
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit UIPopupLists.
/// </summary>
[CustomEditor(typeof(UIPopupList))]
public class UIPopupListInspector : UIWidgetContainerEditor
{
enum FontType
{
Bitmap,
Dynamic,
}
UIPopupList mList;
FontType mType;
void OnEnable ()
{
SerializedProperty bit = serializedObject.FindProperty("bitmapFont");
mType = (bit.objectReferenceValue != null) ? FontType.Bitmap : FontType.Dynamic;
mList = target as UIPopupList;
if (mList.ambigiousFont == null)
{
mList.ambigiousFont = NGUISettings.ambigiousFont;
mList.fontSize = NGUISettings.fontSize;
mList.fontStyle = NGUISettings.fontStyle;
EditorUtility.SetDirty(mList);
}
if (mList.atlas == null)
{
mList.atlas = NGUISettings.atlas;
mList.backgroundSprite = NGUISettings.selectedSprite;
mList.highlightSprite = NGUISettings.selectedSprite;
EditorUtility.SetDirty(mList);
}
}
void RegisterUndo ()
{
NGUIEditorTools.RegisterUndo("Popup List Change", mList);
}
void OnSelectAtlas (Object obj)
{
RegisterUndo();
mList.atlas = obj as UIAtlas;
NGUISettings.atlas = mList.atlas;
}
void OnBackground (string spriteName)
{
RegisterUndo();
mList.backgroundSprite = spriteName;
Repaint();
}
void OnHighlight (string spriteName)
{
RegisterUndo();
mList.highlightSprite = spriteName;
Repaint();
}
void OnBitmapFont (Object obj)
{
serializedObject.Update();
SerializedProperty sp = serializedObject.FindProperty("bitmapFont");
sp.objectReferenceValue = obj;
serializedObject.ApplyModifiedProperties();
NGUISettings.ambigiousFont = obj;
}
void OnDynamicFont (Object obj)
{
serializedObject.Update();
SerializedProperty sp = serializedObject.FindProperty("trueTypeFont");
sp.objectReferenceValue = obj;
serializedObject.ApplyModifiedProperties();
NGUISettings.ambigiousFont = obj;
}
public override void OnInspectorGUI ()
{
serializedObject.Update();
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.BeginHorizontal();
GUILayout.Space(6f);
GUILayout.Label("Options");
GUILayout.EndHorizontal();
string text = "";
foreach (string s in mList.items) text += s + "\n";
GUILayout.Space(-14f);
GUILayout.BeginHorizontal();
GUILayout.Space(84f);
string modified = EditorGUILayout.TextArea(text, GUILayout.Height(100f));
GUILayout.EndHorizontal();
if (modified != text)
{
RegisterUndo();
string[] split = modified.Split(new char[] { '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
mList.items.Clear();
foreach (string s in split) mList.items.Add(s);
if (string.IsNullOrEmpty(mList.value) || !mList.items.Contains(mList.value))
{
mList.value = mList.items.Count > 0 ? mList.items[0] : "";
}
}
GUI.changed = false;
string sel = NGUIEditorTools.DrawList("Default", mList.items.ToArray(), mList.value);
if (GUI.changed) serializedObject.FindProperty("mSelectedItem").stringValue = sel;
NGUIEditorTools.DrawProperty("Position", serializedObject, "position");
NGUIEditorTools.DrawProperty("Localized", serializedObject, "isLocalized");
DrawAtlas();
DrawFont();
NGUIEditorTools.DrawEvents("On Value Change", mList, mList.onChange);
serializedObject.ApplyModifiedProperties();
}
void DrawAtlas()
{
if (NGUIEditorTools.DrawHeader("Atlas"))
{
NGUIEditorTools.BeginContents();
GUILayout.BeginHorizontal();
{
if (NGUIEditorTools.DrawPrefixButton("Atlas"))
ComponentSelector.Show<UIAtlas>(OnSelectAtlas);
NGUIEditorTools.DrawProperty("", serializedObject, "atlas");
}
GUILayout.EndHorizontal();
NGUIEditorTools.DrawPaddedSpriteField("Background", mList.atlas, mList.backgroundSprite, OnBackground);
NGUIEditorTools.DrawPaddedSpriteField("Highlight", mList.atlas, mList.highlightSprite, OnHighlight);
EditorGUILayout.Space();
NGUIEditorTools.DrawProperty("Background", serializedObject, "backgroundColor");
NGUIEditorTools.DrawProperty("Highlight", serializedObject, "highlightColor");
NGUIEditorTools.DrawProperty("Animated", serializedObject, "isAnimated");
NGUIEditorTools.EndContents();
}
}
void DrawFont ()
{
if (NGUIEditorTools.DrawHeader("Font"))
{
NGUIEditorTools.BeginContents();
SerializedProperty ttf = null;
GUILayout.BeginHorizontal();
{
if (NGUIEditorTools.DrawPrefixButton("Font"))
{
if (mType == FontType.Bitmap)
{
ComponentSelector.Show<UIFont>(OnBitmapFont);
}
else
{
ComponentSelector.Show<Font>(OnDynamicFont, new string[] { ".ttf", ".otf"});
}
}
#if DYNAMIC_FONT
GUI.changed = false;
mType = (FontType)EditorGUILayout.EnumPopup(mType, GUILayout.Width(62f));
if (GUI.changed)
{
GUI.changed = false;
if (mType == FontType.Bitmap)
{
serializedObject.FindProperty("trueTypeFont").objectReferenceValue = null;
}
else
{
serializedObject.FindProperty("bitmapFont").objectReferenceValue = null;
}
}
#else
mType = FontType.Bitmap;
#endif
if (mType == FontType.Bitmap)
{
NGUIEditorTools.DrawProperty("", serializedObject, "bitmapFont", GUILayout.MinWidth(40f));
}
else
{
ttf = NGUIEditorTools.DrawProperty("", serializedObject, "trueTypeFont", GUILayout.MinWidth(40f));
}
}
GUILayout.EndHorizontal();
if (ttf != null && ttf.objectReferenceValue != null)
{
GUILayout.BeginHorizontal();
{
EditorGUI.BeginDisabledGroup(ttf.hasMultipleDifferentValues);
NGUIEditorTools.DrawProperty("Font Size", serializedObject, "fontSize", GUILayout.Width(142f));
NGUIEditorTools.DrawProperty("", serializedObject, "fontStyle", GUILayout.MinWidth(40f));
GUILayout.Space(18f);
EditorGUI.EndDisabledGroup();
}
GUILayout.EndHorizontal();
}
else NGUIEditorTools.DrawProperty("Font Size", serializedObject, "fontSize", GUILayout.Width(142f));
NGUIEditorTools.DrawProperty("Text Color", serializedObject, "textColor");
GUILayout.BeginHorizontal();
NGUIEditorTools.SetLabelWidth(66f);
EditorGUILayout.PrefixLabel("Padding");
NGUIEditorTools.SetLabelWidth(14f);
NGUIEditorTools.DrawProperty("X", serializedObject, "padding.x", GUILayout.MinWidth(30f));
NGUIEditorTools.DrawProperty("Y", serializedObject, "padding.y", GUILayout.MinWidth(30f));
GUILayout.Space(18f);
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.EndHorizontal();
NGUIEditorTools.EndContents();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIPopupListInspector.cs
|
C#
|
asf20
| 6,764
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UILocalize))]
#else
[CustomEditor(typeof(UILocalize), true)]
#endif
public class UILocalizeEditor : Editor
{
BetterList<string> mKeys;
void OnEnable ()
{
Dictionary<string, string[]> dict = Localization.dictionary;
if (dict.Count > 0)
{
mKeys = new BetterList<string>();
foreach (KeyValuePair<string, string[]> pair in dict)
{
if (pair.Key == "KEY") continue;
mKeys.Add(pair.Key);
}
mKeys.Sort(delegate (string left, string right) { return left.CompareTo(right); });
}
}
public override void OnInspectorGUI ()
{
serializedObject.Update();
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.BeginHorizontal();
// Key not found in the localization file -- draw it as a text field
SerializedProperty sp = NGUIEditorTools.DrawProperty("Key", serializedObject, "key");
string myKey = sp.stringValue;
bool isPresent = (mKeys != null) && mKeys.Contains(myKey);
GUI.color = isPresent ? Color.green : Color.red;
GUILayout.BeginVertical(GUILayout.Width(22f));
GUILayout.Space(2f);
#if UNITY_3_5
GUILayout.Label(isPresent? "ok" : "!!", GUILayout.Height(20f));
#else
GUILayout.Label(isPresent? "\u2714" : "\u2718", "TL SelectionButtonNew", GUILayout.Height(20f));
#endif
GUILayout.EndVertical();
GUI.color = Color.white;
GUILayout.EndHorizontal();
if (isPresent)
{
if (NGUIEditorTools.DrawHeader("Preview"))
{
NGUIEditorTools.BeginContents();
string[] keys;
string[] values;
if (Localization.dictionary.TryGetValue("KEY", out keys) && Localization.dictionary.TryGetValue(myKey, out values))
{
for (int i = 0; i < keys.Length; ++i)
{
GUILayout.BeginHorizontal();
GUILayout.Label(keys[i], GUILayout.Width(70f));
if (GUILayout.Button(values[i], "AS TextArea", GUILayout.MinWidth(80f), GUILayout.MaxWidth(Screen.width - 110f)))
{
(target as UILocalize).value = values[i];
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
}
GUILayout.EndHorizontal();
}
}
else
{
GUILayout.Label("No preview available");
}
NGUIEditorTools.EndContents();
}
}
else if (mKeys != null && !string.IsNullOrEmpty(myKey))
{
GUILayout.BeginHorizontal();
GUILayout.Space(80f);
GUILayout.BeginVertical();
GUI.backgroundColor = new Color(1f, 1f, 1f, 0.35f);
int matches = 0;
for (int i = 0; i < mKeys.size; ++i)
{
if (mKeys[i].StartsWith(myKey, System.StringComparison.OrdinalIgnoreCase) || mKeys[i].Contains(myKey))
{
#if UNITY_3_5
if (GUILayout.Button(mKeys[i] + " \u25B2"))
#else
if (GUILayout.Button(mKeys[i] + " \u25B2", "CN CountBadge"))
#endif
{
sp.stringValue = mKeys[i];
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
}
if (++matches == 8)
{
GUILayout.Label("...and more");
break;
}
}
}
GUI.backgroundColor = Color.white;
GUILayout.EndVertical();
GUILayout.Space(22f);
GUILayout.EndHorizontal();
}
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UILocalizeEditor.cs
|
C#
|
asf20
| 3,411
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(PropertyBinding))]
public class PropertyBindingEditor : Editor
{
public override void OnInspectorGUI ()
{
PropertyBinding pb = target as PropertyBinding;
NGUIEditorTools.SetLabelWidth(80f);
serializedObject.Update();
if (pb.direction == PropertyBinding.Direction.TargetUpdatesSource && pb.target != null)
PropertyReferenceDrawer.filter = pb.target.GetPropertyType();
GUILayout.Space(3f);
NGUIEditorTools.DrawProperty(serializedObject, "source");
if (pb.direction == PropertyBinding.Direction.SourceUpdatesTarget && pb.source != null)
PropertyReferenceDrawer.filter = pb.source.GetPropertyType();
if (pb.source.target != null)
{
GUILayout.Space(-18f);
if (pb.direction == PropertyBinding.Direction.TargetUpdatesSource)
{
GUILayout.Label(" \u25B2"); // Up
}
else if (pb.direction == PropertyBinding.Direction.SourceUpdatesTarget)
{
GUILayout.Label(" \u25BC"); // Down
}
else GUILayout.Label(" \u25B2\u25BC");
}
GUILayout.Space(1f);
NGUIEditorTools.DrawProperty(serializedObject, "target");
PropertyReferenceDrawer.filter = typeof(void);
GUILayout.Space(1f);
NGUIEditorTools.DrawPaddedProperty(serializedObject, "direction");
NGUIEditorTools.DrawPaddedProperty(serializedObject, "update");
GUILayout.BeginHorizontal();
NGUIEditorTools.DrawProperty(" ", serializedObject, "editMode", GUILayout.Width(100f));
GUILayout.Label("Update in Edit Mode");
GUILayout.EndHorizontal();
if (!serializedObject.isEditingMultipleObjects)
{
if (pb.source != null && pb.target != null && pb.source.GetPropertyType() != pb.target.GetPropertyType())
{
if (pb.direction == PropertyBinding.Direction.BiDirectional)
{
EditorGUILayout.HelpBox("Bi-Directional updates require both Source and Target to reference values of the same type.", MessageType.Error);
}
else if (pb.direction == PropertyBinding.Direction.SourceUpdatesTarget)
{
if (!PropertyReference.Convert(pb.source.Get(), pb.target.GetPropertyType()))
{
EditorGUILayout.HelpBox("Unable to convert " + pb.source.GetPropertyType() + " to " + pb.target.GetPropertyType(), MessageType.Error);
}
}
else if (!PropertyReference.Convert(pb.target.Get(), pb.source.GetPropertyType()))
{
EditorGUILayout.HelpBox("Unable to convert " + pb.target.GetPropertyType() + " to " + pb.source.GetPropertyType(), MessageType.Error);
}
}
}
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/PropertyBindingEditor.cs
|
C#
|
asf20
| 2,750
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenHeight))]
public class TweenHeightEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenHeight tw = target as TweenHeight;
GUI.changed = false;
int from = EditorGUILayout.IntField("From", tw.from);
int to = EditorGUILayout.IntField("To", tw.to);
bool table = EditorGUILayout.Toggle("Update Table", tw.updateTable);
if (from < 0) from = 0;
if (to < 0) to = 0;
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
tw.updateTable = table;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenHeightEditor.cs
|
C#
|
asf20
| 909
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System;
using System.Collections.Generic;
/// <summary>
/// This script adds the NGUI menu options to the Unity Editor.
/// </summary>
static public class NGUIHelp
{
/// <summary>
/// Get the URL pointing to the documentation for the specified component.
/// </summary>
static public string GetHelpURL (Type type)
{
if (type == typeof(UITexture)) return "http://www.tasharen.com/forum/index.php?topic=6703";
if (type == typeof(UISprite)) return "http://www.tasharen.com/forum/index.php?topic=6704";
if (type == typeof(UIPanel)) return "http://www.tasharen.com/forum/index.php?topic=6705";
if (type == typeof(UILabel)) return "http://www.tasharen.com/forum/index.php?topic=6706";
if (type == typeof(UIButton)) return "http://www.tasharen.com/forum/index.php?topic=6708";
if (type == typeof(UIToggle)) return "http://www.tasharen.com/forum/index.php?topic=6709";
if (type == typeof(UIRoot)) return "http://www.tasharen.com/forum/index.php?topic=6710";
if (type == typeof(UICamera)) return "http://www.tasharen.com/forum/index.php?topic=6711";
if (type == typeof(UIAnchor)) return "http://www.tasharen.com/forum/index.php?topic=6712";
if (type == typeof(UIStretch)) return "http://www.tasharen.com/forum/index.php?topic=6713";
if (type == typeof(UISlider)) return "http://www.tasharen.com/forum/index.php?topic=6715";
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
if (type == typeof(UI2DSprite)) return "http://www.tasharen.com/forum/index.php?topic=6729";
#endif
if (type == typeof(UIScrollBar)) return "http://www.tasharen.com/forum/index.php?topic=6733";
if (type == typeof(UIProgressBar)) return "http://www.tasharen.com/forum/index.php?topic=6738";
if (type == typeof(UIPopupList)) return "http://www.tasharen.com/forum/index.php?topic=6751";
if (type == typeof(UIInput)) return "http://www.tasharen.com/forum/index.php?topic=6752";
if (type == typeof(UIKeyBinding)) return "http://www.tasharen.com/forum/index.php?topic=6753";
if (type == typeof(UIGrid)) return "http://www.tasharen.com/forum/index.php?topic=6756";
if (type == typeof(UITable)) return "http://www.tasharen.com/forum/index.php?topic=6758";
if (type == typeof(UIKeyNavigation)) return "http://www.tasharen.com/forum/index.php?topic=8747";
if (type == typeof(PropertyBinding) || type == typeof(PropertyReference))
return "http://www.tasharen.com/forum/index.php?topic=8808";
if (type == typeof(ActiveAnimation) || type == typeof(UIPlayAnimation))
return "http://www.tasharen.com/forum/index.php?topic=6762";
if (type == typeof(UIScrollView) || type == typeof(UIDragScrollView))
return "http://www.tasharen.com/forum/index.php?topic=6763";
if (type == typeof(UIWidget) || type.IsSubclassOf(typeof(UIWidget)))
return "http://www.tasharen.com/forum/index.php?topic=6702";
if (type == typeof(UIPlayTween) || type.IsSubclassOf(typeof(UITweener)))
return "http://www.tasharen.com/forum/index.php?topic=6760";
if (type == typeof(UILocalize) || type == typeof(Localization))
return "http://www.tasharen.com/forum/index.php?topic=8092.0";
return null;
}
/// <summary>
/// Show generic help.
/// </summary>
static public void Show ()
{
Application.OpenURL("http://www.tasharen.com/forum/index.php?topic=6754");
}
/// <summary>
/// Show help for the specific topic.
/// </summary>
static public void Show (Type type)
{
string url = GetHelpURL(type);
if (url == null) url = "http://www.tasharen.com/ngui/doc.php?topic=" + type;
Application.OpenURL(url);
}
/// <summary>
/// Show help for the specific topic.
/// </summary>
static public void Show (object obj)
{
if (obj is GameObject)
{
GameObject go = obj as GameObject;
UIWidget widget = go.GetComponent<UIWidget>();
if (widget != null)
{
Show(widget.GetType());
return;
}
}
Show(obj.GetType());
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUIHelp.cs
|
C#
|
asf20
| 4,117
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
using System.Reflection;
/// <summary>
/// Generic property binding drawer.
/// </summary>
#if !UNITY_3_5
[CustomPropertyDrawer(typeof(PropertyReference))]
public class PropertyReferenceDrawer : PropertyDrawer
#else
public class PropertyReferenceDrawer
#endif
{
public class Entry
{
public Component target;
public string name;
}
/// <summary>
/// If you want the property drawer to limit its selection list to values of specified type, set this to something other than 'void'.
/// </summary>
static public Type filter = typeof(void);
/// <summary>
/// Whether it's possible to convert between basic types, such as int to string.
/// </summary>
static public bool canConvert = true;
/// <summary>
/// Collect a list of usable properties and fields.
/// </summary>
static public List<Entry> GetProperties (GameObject target, bool read, bool write)
{
Component[] comps = target.GetComponents<Component>();
List<Entry> list = new List<Entry>();
for (int i = 0, imax = comps.Length; i < imax; ++i)
{
Component comp = comps[i];
if (comp == null) continue;
Type type = comp.GetType();
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public;
FieldInfo[] fields = type.GetFields(flags);
PropertyInfo[] props = type.GetProperties(flags);
for (int b = 0; b < fields.Length; ++b)
{
FieldInfo field = fields[b];
if (filter != typeof(void))
{
if (canConvert)
{
if (!PropertyReference.Convert(field.FieldType, filter)) continue;
}
else if (!filter.IsAssignableFrom(field.FieldType)) continue;
}
Entry ent = new Entry();
ent.target = comp;
ent.name = field.Name;
list.Add(ent);
}
for (int b = 0; b < props.Length; ++b)
{
PropertyInfo prop = props[b];
if (read && !prop.CanRead) continue;
if (write && !prop.CanWrite) continue;
if (filter != typeof(void))
{
if (canConvert)
{
if (!PropertyReference.Convert(prop.PropertyType, filter)) continue;
}
else if (!filter.IsAssignableFrom(prop.PropertyType)) continue;
}
Entry ent = new Entry();
ent.target = comp;
ent.name = prop.Name;
list.Add(ent);
}
}
return list;
}
/// <summary>
/// Convert the specified list of delegate entries into a string array.
/// </summary>
static public string[] GetNames (List<Entry> list, string choice, out int index)
{
index = 0;
string[] names = new string[list.Count + 1];
names[0] = string.IsNullOrEmpty(choice) ? "<Choose>" : choice;
for (int i = 0; i < list.Count; )
{
Entry ent = list[i];
string del = NGUITools.GetFuncName(ent.target, ent.name);
names[++i] = del;
if (index == 0 && string.Equals(del, choice))
index = i;
}
return names;
}
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
/// <summary>
/// The property is either going to be 16 or 34 pixels tall, depending on whether the target has been set or not.
/// </summary>
public override float GetPropertyHeight (SerializedProperty prop, GUIContent label)
{
SerializedProperty target = prop.FindPropertyRelative("mTarget");
Component comp = target.objectReferenceValue as Component;
return (comp != null) ? 36f : 16f;
}
/// <summary>
/// Draw the actual property.
/// </summary>
public override void OnGUI (Rect rect, SerializedProperty prop, GUIContent label)
{
SerializedProperty target = prop.FindPropertyRelative("mTarget");
SerializedProperty field = prop.FindPropertyRelative("mName");
rect.height = 16f;
EditorGUI.PropertyField(rect, target, label);
Component comp = target.objectReferenceValue as Component;
if (comp != null)
{
rect.y += 18f;
GUI.changed = false;
EditorGUI.BeginDisabledGroup(target.hasMultipleDifferentValues);
int index = 0;
// Get all the properties on the target game object
List<Entry> list = GetProperties(comp.gameObject, true, true);
// We want the field to look like "Component.property" rather than just "property"
string current = PropertyReference.ToString(target.objectReferenceValue as Component, field.stringValue);
// Convert all the properties to names
string[] names = PropertyReferenceDrawer.GetNames(list, current, out index);
// Draw a selection list
GUI.changed = false;
rect.xMin += EditorGUIUtility.labelWidth;
rect.width -= 18f;
int choice = EditorGUI.Popup(rect, "", index, names);
// Update the target object and property name
if (GUI.changed && choice > 0)
{
Entry ent = list[choice - 1];
target.objectReferenceValue = ent.target;
field.stringValue = ent.name;
}
EditorGUI.EndDisabledGroup();
}
}
#endif
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/PropertyReferenceDrawer.cs
|
C#
|
asf20
| 4,942
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// Inspector class used to edit the UIAtlas.
/// </summary>
[CustomEditor(typeof(UIAtlas))]
public class UIAtlasInspector : Editor
{
static public UIAtlasInspector instance;
enum AtlasType
{
Normal,
Reference,
}
UIAtlas mAtlas;
AtlasType mType = AtlasType.Normal;
UIAtlas mReplacement = null;
void OnEnable () { instance = this; }
void OnDisable () { instance = null; }
/// <summary>
/// Convenience function -- mark all widgets using the sprite as changed.
/// </summary>
void MarkSpriteAsDirty ()
{
UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;
if (sprite == null) return;
UISprite[] sprites = NGUITools.FindActive<UISprite>();
foreach (UISprite sp in sprites)
{
if (UIAtlas.CheckIfRelated(sp.atlas, mAtlas) && sp.spriteName == sprite.name)
{
UIAtlas atl = sp.atlas;
sp.atlas = null;
sp.atlas = atl;
EditorUtility.SetDirty(sp);
}
}
UILabel[] labels = NGUITools.FindActive<UILabel>();
foreach (UILabel lbl in labels)
{
if (lbl.bitmapFont != null && UIAtlas.CheckIfRelated(lbl.bitmapFont.atlas, mAtlas) && lbl.bitmapFont.UsesSprite(sprite.name))
{
UIFont font = lbl.bitmapFont;
lbl.bitmapFont = null;
lbl.bitmapFont = font;
EditorUtility.SetDirty(lbl);
}
}
}
/// <summary>
/// Replacement atlas selection callback.
/// </summary>
void OnSelectAtlas (Object obj)
{
if (mReplacement != obj)
{
// Undo doesn't work correctly in this case... so I won't bother.
//NGUIEditorTools.RegisterUndo("Atlas Change");
//NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
mAtlas.replacement = obj as UIAtlas;
mReplacement = mAtlas.replacement;
NGUITools.SetDirty(mAtlas);
if (mReplacement == null) mType = AtlasType.Normal;
}
}
/// <summary>
/// Draw the inspector widget.
/// </summary>
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
mAtlas = target as UIAtlas;
UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;
GUILayout.Space(6f);
if (mAtlas.replacement != null)
{
mType = AtlasType.Reference;
mReplacement = mAtlas.replacement;
}
GUILayout.BeginHorizontal();
AtlasType after = (AtlasType)EditorGUILayout.EnumPopup("Atlas Type", mType);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (mType != after)
{
if (after == AtlasType.Normal)
{
mType = AtlasType.Normal;
OnSelectAtlas(null);
}
else
{
mType = AtlasType.Reference;
}
}
if (mType == AtlasType.Reference)
{
ComponentSelector.Draw<UIAtlas>(mAtlas.replacement, OnSelectAtlas, true);
GUILayout.Space(6f);
EditorGUILayout.HelpBox("You can have one atlas simply point to " +
"another one. This is useful if you want to be " +
"able to quickly replace the contents of one " +
"atlas with another one, for example for " +
"swapping an SD atlas with an HD one, or " +
"replacing an English atlas with a Chinese " +
"one. All the sprites referencing this atlas " +
"will update their references to the new one.", MessageType.Info);
if (mReplacement != mAtlas && mAtlas.replacement != mReplacement)
{
NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
mAtlas.replacement = mReplacement;
NGUITools.SetDirty(mAtlas);
}
return;
}
//GUILayout.Space(6f);
Material mat = EditorGUILayout.ObjectField("Material", mAtlas.spriteMaterial, typeof(Material), false) as Material;
if (mAtlas.spriteMaterial != mat)
{
NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
mAtlas.spriteMaterial = mat;
// Ensure that this atlas has valid import settings
if (mAtlas.texture != null) NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
mAtlas.MarkAsChanged();
}
if (mat != null)
{
TextAsset ta = EditorGUILayout.ObjectField("TP Import", null, typeof(TextAsset), false) as TextAsset;
if (ta != null)
{
// Ensure that this atlas has valid import settings
if (mAtlas.texture != null) NGUIEditorTools.ImportTexture(mAtlas.texture, false, false, !mAtlas.premultipliedAlpha);
NGUIEditorTools.RegisterUndo("Import Sprites", mAtlas);
NGUIJson.LoadSpriteData(mAtlas, ta);
if (sprite != null) sprite = mAtlas.GetSprite(sprite.name);
mAtlas.MarkAsChanged();
}
float pixelSize = EditorGUILayout.FloatField("Pixel Size", mAtlas.pixelSize, GUILayout.Width(120f));
if (pixelSize != mAtlas.pixelSize)
{
NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
mAtlas.pixelSize = pixelSize;
}
}
if (mAtlas.spriteMaterial != null)
{
Color blueColor = new Color(0f, 0.7f, 1f, 1f);
Color greenColor = new Color(0.4f, 1f, 0f, 1f);
if (sprite == null && mAtlas.spriteList.Count > 0)
{
string spriteName = NGUISettings.selectedSprite;
if (!string.IsNullOrEmpty(spriteName)) sprite = mAtlas.GetSprite(spriteName);
if (sprite == null) sprite = mAtlas.spriteList[0];
}
if (sprite != null)
{
if (sprite == null) return;
Texture2D tex = mAtlas.spriteMaterial.mainTexture as Texture2D;
if (tex != null)
{
if (!NGUIEditorTools.DrawHeader("Sprite Details")) return;
NGUIEditorTools.BeginContents();
GUILayout.Space(3f);
NGUIEditorTools.DrawAdvancedSpriteField(mAtlas, sprite.name, SelectSprite, true);
GUILayout.Space(6f);
GUI.changed = false;
GUI.backgroundColor = greenColor;
NGUIEditorTools.IntVector sizeA = NGUIEditorTools.IntPair("Dimensions", "X", "Y", sprite.x, sprite.y);
NGUIEditorTools.IntVector sizeB = NGUIEditorTools.IntPair(null, "Width", "Height", sprite.width, sprite.height);
EditorGUILayout.Separator();
GUI.backgroundColor = blueColor;
NGUIEditorTools.IntVector borderA = NGUIEditorTools.IntPair("Border", "Left", "Right", sprite.borderLeft, sprite.borderRight);
NGUIEditorTools.IntVector borderB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.borderBottom, sprite.borderTop);
EditorGUILayout.Separator();
GUI.backgroundColor = Color.white;
NGUIEditorTools.IntVector padA = NGUIEditorTools.IntPair("Padding", "Left", "Right", sprite.paddingLeft, sprite.paddingRight);
NGUIEditorTools.IntVector padB = NGUIEditorTools.IntPair(null, "Bottom", "Top", sprite.paddingBottom, sprite.paddingTop);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Atlas Change", mAtlas);
sprite.x = sizeA.x;
sprite.y = sizeA.y;
sprite.width = sizeB.x;
sprite.height = sizeB.y;
sprite.paddingLeft = padA.x;
sprite.paddingRight = padA.y;
sprite.paddingBottom = padB.x;
sprite.paddingTop = padB.y;
sprite.borderLeft = borderA.x;
sprite.borderRight = borderA.y;
sprite.borderBottom = borderB.x;
sprite.borderTop = borderB.y;
MarkSpriteAsDirty();
}
GUILayout.Space(3f);
GUILayout.BeginHorizontal();
if (GUILayout.Button("Duplicate"))
{
UIAtlasMaker.SpriteEntry se = UIAtlasMaker.DuplicateSprite(mAtlas, sprite.name);
if (se != null) NGUISettings.selectedSprite = se.name;
}
if (GUILayout.Button("Save As..."))
{
string path = EditorUtility.SaveFilePanelInProject("Save As", sprite.name + ".png", "png", "Extract sprite into which file?");
if (!string.IsNullOrEmpty(path))
{
UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(mAtlas, sprite.name);
if (se != null)
{
byte[] bytes = se.tex.EncodeToPNG();
File.WriteAllBytes(path, bytes);
AssetDatabase.ImportAsset(path);
if (se.temporaryTexture) DestroyImmediate(se.tex);
}
}
}
GUILayout.EndHorizontal();
NGUIEditorTools.EndContents();
}
if (NGUIEditorTools.DrawHeader("Modify"))
{
NGUIEditorTools.BeginContents();
EditorGUILayout.BeginHorizontal();
GUILayout.Space(20f);
EditorGUILayout.BeginVertical();
NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);
if (GUILayout.Button("Add a Shadow")) AddShadow(sprite);
if (GUILayout.Button("Add a Soft Outline")) AddOutline(sprite);
if (GUILayout.Button("Add a Transparent Border")) AddTransparentBorder(sprite);
if (GUILayout.Button("Add a Clamped Border")) AddClampedBorder(sprite);
if (GUILayout.Button("Add a Tiled Border")) AddTiledBorder(sprite);
EditorGUI.BeginDisabledGroup(!sprite.hasBorder);
if (GUILayout.Button("Crop Border")) CropBorder(sprite);
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndVertical();
GUILayout.Space(20f);
EditorGUILayout.EndHorizontal();
NGUIEditorTools.EndContents();
}
if (NGUIEditorTools.previousSelection != null)
{
GUILayout.Space(3f);
GUI.backgroundColor = Color.green;
if (GUILayout.Button("<< Return to " + NGUIEditorTools.previousSelection.name))
{
NGUIEditorTools.SelectPrevious();
}
GUI.backgroundColor = Color.white;
}
}
}
}
/// <summary>
/// Sprite selection callback.
/// </summary>
void SelectSprite (string spriteName)
{
if (NGUISettings.selectedSprite != spriteName)
{
NGUISettings.selectedSprite = spriteName;
Repaint();
}
}
/// <summary>
/// All widgets have a preview.
/// </summary>
public override bool HasPreviewGUI () { return true; }
/// <summary>
/// Draw the sprite preview.
/// </summary>
public override void OnPreviewGUI (Rect rect, GUIStyle background)
{
UISpriteData sprite = (mAtlas != null) ? mAtlas.GetSprite(NGUISettings.selectedSprite) : null;
if (sprite == null) return;
Texture2D tex = mAtlas.texture as Texture2D;
if (tex != null) NGUIEditorTools.DrawSprite(tex, rect, sprite, Color.white);
}
/// <summary>
/// Add a transparent border around the sprite.
/// </summary>
void AddTransparentBorder (UISpriteData sprite)
{
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(mAtlas, sprites);
UIAtlasMaker.SpriteEntry se = null;
for (int i = 0; i < sprites.Count; ++i)
{
if (sprites[i].name == sprite.name)
{
se = sprites[i];
break;
}
}
if (se != null)
{
int w1 = se.tex.width;
int h1 = se.tex.height;
int w2 = w1 + 2;
int h2 = h1 + 2;
Color32[] c2 = NGUIEditorTools.AddBorder(se.tex.GetPixels32(), w1, h1);
if (se.temporaryTexture) DestroyImmediate(se.tex);
++se.borderLeft;
++se.borderRight;
++se.borderTop;
++se.borderBottom;
se.tex = new Texture2D(w2, h2);
se.tex.name = sprite.name;
se.tex.SetPixels32(c2);
se.tex.Apply();
se.temporaryTexture = true;
UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
DestroyImmediate(se.tex);
se.tex = null;
}
}
/// <summary>
/// Add a border around the sprite that extends the existing edge pixels.
/// </summary>
void AddClampedBorder (UISpriteData sprite)
{
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(mAtlas, sprites);
UIAtlasMaker.SpriteEntry se = null;
for (int i = 0; i < sprites.Count; ++i)
{
if (sprites[i].name == sprite.name)
{
se = sprites[i];
break;
}
}
if (se != null)
{
int w1 = se.tex.width - se.borderLeft - se.borderRight;
int h1 = se.tex.height - se.borderBottom - se.borderTop;
int w2 = se.tex.width + 2;
int h2 = se.tex.height + 2;
Color32[] c1 = se.tex.GetPixels32();
Color32[] c2 = new Color32[w2 * h2];
for (int y2 = 0; y2 < h2; ++y2)
{
int y1 = se.borderBottom + NGUIMath.ClampIndex(y2 - se.borderBottom - 1, h1);
for (int x2 = 0; x2 < w2; ++x2)
{
int x1 = se.borderLeft + NGUIMath.ClampIndex(x2 - se.borderLeft - 1, w1);
c2[x2 + y2 * w2] = c1[x1 + y1 * se.tex.width];
}
}
if (se.temporaryTexture) DestroyImmediate(se.tex);
++se.borderLeft;
++se.borderRight;
++se.borderTop;
++se.borderBottom;
se.tex = new Texture2D(w2, h2);
se.tex.name = sprite.name;
se.tex.SetPixels32(c2);
se.tex.Apply();
se.temporaryTexture = true;
UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
DestroyImmediate(se.tex);
se.tex = null;
}
}
/// <summary>
/// Add a border around the sprite that copies the pixels from the opposite side, making it possible for the sprite to tile without seams.
/// </summary>
void AddTiledBorder (UISpriteData sprite)
{
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(mAtlas, sprites);
UIAtlasMaker.SpriteEntry se = null;
for (int i = 0; i < sprites.Count; ++i)
{
if (sprites[i].name == sprite.name)
{
se = sprites[i];
break;
}
}
if (se != null)
{
int w1 = se.tex.width - se.borderLeft - se.borderRight;
int h1 = se.tex.height - se.borderBottom - se.borderTop;
int w2 = se.tex.width + 2;
int h2 = se.tex.height + 2;
Color32[] c1 = se.tex.GetPixels32();
Color32[] c2 = new Color32[w2 * h2];
for (int y2 = 0; y2 < h2; ++y2)
{
int y1 = se.borderBottom + NGUIMath.RepeatIndex(y2 - se.borderBottom - 1, h1);
for (int x2 = 0; x2 < w2; ++x2)
{
int x1 = se.borderLeft + NGUIMath.RepeatIndex(x2 - se.borderLeft - 1, w1);
c2[x2 + y2 * w2] = c1[x1 + y1 * se.tex.width];
}
}
if (se.temporaryTexture) DestroyImmediate(se.tex);
++se.borderLeft;
++se.borderRight;
++se.borderTop;
++se.borderBottom;
se.tex = new Texture2D(w2, h2);
se.tex.name = sprite.name;
se.tex.SetPixels32(c2);
se.tex.Apply();
se.temporaryTexture = true;
UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
DestroyImmediate(se.tex);
se.tex = null;
}
}
/// <summary>
/// Crop the border pixels around the sprite.
/// </summary>
void CropBorder (UISpriteData sprite)
{
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(mAtlas, sprites);
UIAtlasMaker.SpriteEntry se = null;
for (int i = 0; i < sprites.Count; ++i)
{
if (sprites[i].name == sprite.name)
{
se = sprites[i];
break;
}
}
if (se != null)
{
int w1 = se.tex.width;
int h1 = se.tex.height;
int w2 = w1 - se.borderLeft - se.borderRight;
int h2 = h1 - se.borderTop - se.borderBottom;
Color32[] c1 = se.tex.GetPixels32();
Color32[] c2 = new Color32[w2 * h2];
for (int y2 = 0; y2 < h2; ++y2)
{
int y1 = y2 + se.borderBottom;
for (int x2 = 0; x2 < w2; ++x2)
{
int x1 = x2 + se.borderLeft;
c2[x2 + y2 * w2] = c1[x1 + y1 * w1];
}
}
se.borderLeft = 0;
se.borderRight = 0;
se.borderTop = 0;
se.borderBottom = 0;
if (se.temporaryTexture) DestroyImmediate(se.tex);
se.tex = new Texture2D(w2, h2);
se.tex.name = sprite.name;
se.tex.SetPixels32(c2);
se.tex.Apply();
se.temporaryTexture = true;
UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
DestroyImmediate(se.tex);
se.tex = null;
}
}
/// <summary>
/// Add a dark shadow below and to the right of the sprite.
/// </summary>
void AddShadow (UISpriteData sprite)
{
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(mAtlas, sprites);
UIAtlasMaker.SpriteEntry se = null;
for (int i = 0; i < sprites.Count; ++i)
{
if (sprites[i].name == sprite.name)
{
se = sprites[i];
break;
}
}
if (se != null)
{
int w1 = se.tex.width;
int h1 = se.tex.height;
int w2 = w1 + 2;
int h2 = h1 + 2;
Color32[] c2 = NGUIEditorTools.AddBorder(se.tex.GetPixels32(), w1, h1);
NGUIEditorTools.AddShadow(c2, w2, h2, NGUISettings.backgroundColor);
if (se.temporaryTexture) DestroyImmediate(se.tex);
if ((se.borderLeft | se.borderRight | se.borderBottom | se.borderTop) != 0)
{
++se.borderLeft;
++se.borderRight;
++se.borderTop;
++se.borderBottom;
}
se.tex = new Texture2D(w2, h2);
se.tex.name = sprite.name;
se.tex.SetPixels32(c2);
se.tex.Apply();
se.temporaryTexture = true;
UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
DestroyImmediate(se.tex);
se.tex = null;
}
}
/// <summary>
/// Add a dark shadowy outline around the sprite, giving it some visual depth.
/// </summary>
void AddOutline (UISpriteData sprite)
{
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(mAtlas, sprites);
UIAtlasMaker.SpriteEntry se = null;
for (int i = 0; i < sprites.Count; ++i)
{
if (sprites[i].name == sprite.name)
{
se = sprites[i];
break;
}
}
if (se != null)
{
int w1 = se.tex.width;
int h1 = se.tex.height;
int w2 = w1 + 2;
int h2 = h1 + 2;
Color32[] c2 = NGUIEditorTools.AddBorder(se.tex.GetPixels32(), w1, h1);
NGUIEditorTools.AddDepth(c2, w2, h2, NGUISettings.backgroundColor);
if (se.temporaryTexture) DestroyImmediate(se.tex);
if ((se.borderLeft | se.borderRight | se.borderBottom | se.borderTop) != 0)
{
++se.borderLeft;
++se.borderRight;
++se.borderTop;
++se.borderBottom;
}
se.tex = new Texture2D(w2, h2);
se.tex.name = sprite.name;
se.tex.SetPixels32(c2);
se.tex.Apply();
se.temporaryTexture = true;
UIAtlasMaker.UpdateAtlas(mAtlas, sprites);
DestroyImmediate(se.tex);
se.tex = null;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIAtlasInspector.cs
|
C#
|
asf20
| 17,740
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Panel wizard that allows enabling / disabling and selecting panels in the scene.
/// </summary>
public class UIPanelTool : EditorWindow
{
static public UIPanelTool instance;
enum Visibility
{
Visible,
Hidden,
}
class Entry
{
public UIPanel panel;
public bool isEnabled = false;
public bool widgetsEnabled = false;
public List<UIWidget> widgets = new List<UIWidget>();
}
/// <summary>
/// First sort by depth, then alphabetically, then by instance ID.
/// </summary>
static int Compare (Entry a, Entry b)
{
if (a != b && a != null && b != null)
{
if (a.panel.depth < b.panel.depth) return -1;
if (a.panel.depth > b.panel.depth) return 1;
int val = string.Compare(a.panel.name, b.panel.name);
if (val != 0) return val;
return (a.panel.GetInstanceID() < b.panel.GetInstanceID()) ? -1 : 1;
}
return 0;
}
Vector2 mScroll = Vector2.zero;
void OnEnable () { instance = this; }
void OnDisable () { instance = null; }
void OnSelectionChange () { Repaint(); }
/// <summary>
/// Collect a list of panels.
/// </summary>
static List<UIPanel> GetListOfPanels ()
{
List<UIPanel> panels = NGUIEditorTools.FindAll<UIPanel>();
for (int i = panels.Count; i > 0; )
{
if (!panels[--i].showInPanelTool)
{
panels.RemoveAt(i);
}
}
return panels;
}
/// <summary>
/// Get a list of widgets managed by the specified transform's children.
/// </summary>
static void GetWidgets (Transform t, List<UIWidget> widgets)
{
for (int i = 0; i < t.childCount; ++i)
{
Transform child = t.GetChild(i);
UIWidget w = child.GetComponent<UIWidget>();
if (w != null) widgets.Add(w);
else if (child.GetComponent<UIPanel>() == null) GetWidgets(child, widgets);
}
}
/// <summary>
/// Get a list of widgets managed by the specified panel.
/// </summary>
static List<UIWidget> GetWidgets (UIPanel panel)
{
List<UIWidget> widgets = new List<UIWidget>();
if (panel != null) GetWidgets(panel.transform, widgets);
return widgets;
}
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
List<UIPanel> panels = GetListOfPanels();
if (panels != null && panels.Count > 0)
{
UIPanel selectedPanel = NGUITools.FindInParents<UIPanel>(Selection.activeGameObject);
// First, collect a list of panels with their associated widgets
List<Entry> entries = new List<Entry>();
Entry selectedEntry = null;
bool allEnabled = true;
foreach (UIPanel panel in panels)
{
Entry ent = new Entry();
ent.panel = panel;
ent.widgets = GetWidgets(panel);
ent.isEnabled = panel.enabled && NGUITools.GetActive(panel.gameObject);
ent.widgetsEnabled = ent.isEnabled;
if (ent.widgetsEnabled)
{
foreach (UIWidget w in ent.widgets)
{
if (!NGUITools.GetActive(w.gameObject))
{
allEnabled = false;
ent.widgetsEnabled = false;
break;
}
}
}
else allEnabled = false;
entries.Add(ent);
}
// Sort the list by depth
entries.Sort(Compare);
mScroll = GUILayout.BeginScrollView(mScroll);
NGUIEditorTools.SetLabelWidth(80f);
bool showAll = DrawRow(null, null, allEnabled);
NGUIEditorTools.DrawSeparator();
foreach (Entry ent in entries)
{
if (DrawRow(ent, selectedPanel, ent.widgetsEnabled))
{
selectedEntry = ent;
}
}
GUILayout.EndScrollView();
if (showAll)
{
foreach (Entry ent in entries)
{
NGUITools.SetActive(ent.panel.gameObject, !allEnabled);
}
}
else if (selectedEntry != null)
{
NGUITools.SetActive(selectedEntry.panel.gameObject, !selectedEntry.widgetsEnabled);
}
}
else
{
GUILayout.Label("No UI Panels found in the scene");
}
}
/// <summary>
/// Helper function used to print things in columns.
/// </summary>
bool DrawRow (Entry ent, UIPanel selected, bool isChecked)
{
bool retVal = false;
string panelName, layer, depth, widgetCount, drawCalls, clipping;
if (ent != null)
{
panelName = ent.panel.name;
layer = LayerMask.LayerToName(ent.panel.gameObject.layer);
depth = ent.panel.depth.ToString();
widgetCount = ent.widgets.Count.ToString();
drawCalls = ent.panel.drawCalls.size.ToString();
clipping = (ent.panel.clipping != UIDrawCall.Clipping.None) ? "Yes" : "";
}
else
{
panelName = "Panel's Name";
layer = "Layer";
depth = "DP";
widgetCount = "WG";
drawCalls = "DC";
clipping = "Clip";
}
if (ent != null) GUILayout.Space(-1f);
if (ent != null)
{
GUI.backgroundColor = ent.panel == selected ? Color.white : new Color(0.8f, 0.8f, 0.8f);
GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
GUI.backgroundColor = Color.white;
}
else
{
GUILayout.BeginHorizontal();
}
GUI.contentColor = (ent == null || ent.isEnabled) ? Color.white : new Color(0.7f, 0.7f, 0.7f);
if (isChecked != EditorGUILayout.Toggle(isChecked, GUILayout.Width(20f))) retVal = true;
GUILayout.Label(depth, GUILayout.Width(30f));
if (GUILayout.Button(panelName, EditorStyles.label, GUILayout.MinWidth(100f)))
{
if (ent != null)
{
Selection.activeGameObject = ent.panel.gameObject;
EditorUtility.SetDirty(ent.panel.gameObject);
}
}
GUILayout.Label(layer, GUILayout.Width(ent == null ? 65f : 70f));
GUILayout.Label(widgetCount, GUILayout.Width(30f));
GUILayout.Label(drawCalls, GUILayout.Width(30f));
GUILayout.Label(clipping, GUILayout.Width(30f));
if (ent == null)
{
GUILayout.Label("Stc", GUILayout.Width(24f));
}
else
{
bool val = ent.panel.widgetsAreStatic;
if (val != EditorGUILayout.Toggle(val, GUILayout.Width(20f)))
{
ent.panel.widgetsAreStatic = !val;
EditorUtility.SetDirty(ent.panel.gameObject);
#if !UNITY_3_5
if (NGUITransformInspector.instance != null)
NGUITransformInspector.instance.Repaint();
#endif
}
}
GUI.contentColor = Color.white;
GUILayout.EndHorizontal();
return retVal;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIPanelTool.cs
|
C#
|
asf20
| 6,240
|
using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;
using UnityEngine;
// Source: UIToolkit -- https://github.com/prime31/UIToolkit/blob/master/Assets/Plugins/MiniJSON.cs
// Based on the JSON parser from
// http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
public class NGUIJson
{
private const int TOKEN_NONE = 0;
private const int TOKEN_CURLY_OPEN = 1;
private const int TOKEN_CURLY_CLOSE = 2;
private const int TOKEN_SQUARED_OPEN = 3;
private const int TOKEN_SQUARED_CLOSE = 4;
private const int TOKEN_COLON = 5;
private const int TOKEN_COMMA = 6;
private const int TOKEN_STRING = 7;
private const int TOKEN_NUMBER = 8;
private const int TOKEN_TRUE = 9;
private const int TOKEN_FALSE = 10;
private const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
/// <summary>
/// On decoding, this value holds the position at which the parse failed (-1 = no error).
/// </summary>
protected static int lastErrorIndex = -1;
protected static string lastDecode = "";
/// <summary>
/// Parse the specified JSon file, loading sprite information for the specified atlas.
/// </summary>
static public void LoadSpriteData (UIAtlas atlas, TextAsset asset)
{
if (asset == null || atlas == null) return;
string jsonString = asset.text;
Hashtable decodedHash = jsonDecode(jsonString) as Hashtable;
if (decodedHash == null)
{
Debug.LogWarning("Unable to parse Json file: " + asset.name);
}
else LoadSpriteData(atlas, decodedHash);
asset = null;
Resources.UnloadUnusedAssets();
}
/// <summary>
/// Parse the specified JSon file, loading sprite information for the specified atlas.
/// </summary>
static public void LoadSpriteData (UIAtlas atlas, string jsonData)
{
if (string.IsNullOrEmpty(jsonData) || atlas == null) return;
Hashtable decodedHash = jsonDecode(jsonData) as Hashtable;
if (decodedHash == null)
{
Debug.LogWarning("Unable to parse the provided Json string");
}
else LoadSpriteData(atlas, decodedHash);
}
/// <summary>
/// Parse the specified JSon file, loading sprite information for the specified atlas.
/// </summary>
static void LoadSpriteData (UIAtlas atlas, Hashtable decodedHash)
{
if (decodedHash == null || atlas == null) return;
List<UISpriteData> oldSprites = atlas.spriteList;
atlas.spriteList = new List<UISpriteData>();
Hashtable frames = (Hashtable)decodedHash["frames"];
foreach (System.Collections.DictionaryEntry item in frames)
{
UISpriteData newSprite = new UISpriteData();
newSprite.name = item.Key.ToString();
bool exists = false;
// Check to see if this sprite exists
foreach (UISpriteData oldSprite in oldSprites)
{
if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
{
exists = true;
break;
}
}
// Get rid of the extension if the sprite doesn't exist
// The extension is kept for backwards compatibility so it's still possible to update older atlases.
if (!exists)
{
newSprite.name = newSprite.name.Replace(".png", "");
newSprite.name = newSprite.name.Replace(".tga", "");
}
// Extract the info we need from the TexturePacker json file, mainly uvRect and size
Hashtable table = (Hashtable)item.Value;
Hashtable frame = (Hashtable)table["frame"];
int frameX = int.Parse(frame["x"].ToString());
int frameY = int.Parse(frame["y"].ToString());
int frameW = int.Parse(frame["w"].ToString());
int frameH = int.Parse(frame["h"].ToString());
// Read the rotation value
//newSprite.rotated = (bool)table["rotated"];
newSprite.x = frameX;
newSprite.y = frameY;
newSprite.width = frameW;
newSprite.height = frameH;
// Support for trimmed sprites
Hashtable sourceSize = (Hashtable)table["sourceSize"];
Hashtable spriteSize = (Hashtable)table["spriteSourceSize"];
if (spriteSize != null && sourceSize != null)
{
// TODO: Account for rotated sprites
if (frameW > 0)
{
int spriteX = int.Parse(spriteSize["x"].ToString());
int spriteW = int.Parse(spriteSize["w"].ToString());
int sourceW = int.Parse(sourceSize["w"].ToString());
newSprite.paddingLeft = spriteX;
newSprite.paddingRight = sourceW - (spriteX + spriteW);
}
if (frameH > 0)
{
int spriteY = int.Parse(spriteSize["y"].ToString());
int spriteH = int.Parse(spriteSize["h"].ToString());
int sourceH = int.Parse(sourceSize["h"].ToString());
newSprite.paddingTop = spriteY;
newSprite.paddingBottom = sourceH - (spriteY + spriteH);
}
}
// If the sprite was present before, see if we can copy its inner rect
foreach (UISpriteData oldSprite in oldSprites)
{
if (oldSprite.name.Equals(newSprite.name, StringComparison.OrdinalIgnoreCase))
{
newSprite.borderLeft = oldSprite.borderLeft;
newSprite.borderRight = oldSprite.borderRight;
newSprite.borderBottom = oldSprite.borderBottom;
newSprite.borderTop = oldSprite.borderTop;
}
}
// Add this new sprite
atlas.spriteList.Add(newSprite);
}
// Sort imported sprites alphabetically
atlas.spriteList.Sort(CompareSprites);
Debug.Log("Imported " + atlas.spriteList.Count + " sprites");
}
/// <summary>
/// Sprite comparison function for sorting.
/// </summary>
static int CompareSprites (UISpriteData a, UISpriteData b) { return a.name.CompareTo(b.name); }
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object jsonDecode( string json )
{
// save the string for debug information
NGUIJson.lastDecode = json;
if( json != null )
{
char[] charArray = json.ToCharArray();
int index = 0;
bool success = true;
object value = NGUIJson.parseValue( charArray, ref index, ref success );
if( success )
NGUIJson.lastErrorIndex = -1;
else
NGUIJson.lastErrorIndex = index;
return value;
}
else
{
return null;
}
}
/// <summary>
/// Converts a Hashtable / ArrayList / Dictionary(string,string) object into a JSON string
/// </summary>
/// <param name="json">A Hashtable / ArrayList</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string jsonEncode( object json )
{
var builder = new StringBuilder( BUILDER_CAPACITY );
var success = NGUIJson.serializeValue( json, builder );
return ( success ? builder.ToString() : null );
}
/// <summary>
/// On decoding, this function returns the position at which the parse failed (-1 = no error).
/// </summary>
/// <returns></returns>
public static bool lastDecodeSuccessful()
{
return ( NGUIJson.lastErrorIndex == -1 );
}
/// <summary>
/// On decoding, this function returns the position at which the parse failed (-1 = no error).
/// </summary>
/// <returns></returns>
public static int getLastErrorIndex()
{
return NGUIJson.lastErrorIndex;
}
/// <summary>
/// If a decoding error occurred, this function returns a piece of the JSON string
/// at which the error took place. To ease debugging.
/// </summary>
/// <returns></returns>
public static string getLastErrorSnippet()
{
if( NGUIJson.lastErrorIndex == -1 )
{
return "";
}
else
{
int startIndex = NGUIJson.lastErrorIndex - 5;
int endIndex = NGUIJson.lastErrorIndex + 15;
if( startIndex < 0 )
startIndex = 0;
if( endIndex >= NGUIJson.lastDecode.Length )
endIndex = NGUIJson.lastDecode.Length - 1;
return NGUIJson.lastDecode.Substring( startIndex, endIndex - startIndex + 1 );
}
}
#region Parsing
protected static Hashtable parseObject( char[] json, ref int index )
{
Hashtable table = new Hashtable();
int token;
// {
nextToken( json, ref index );
bool done = false;
while( !done )
{
token = lookAhead( json, index );
if( token == NGUIJson.TOKEN_NONE )
{
return null;
}
else if( token == NGUIJson.TOKEN_COMMA )
{
nextToken( json, ref index );
}
else if( token == NGUIJson.TOKEN_CURLY_CLOSE )
{
nextToken( json, ref index );
return table;
}
else
{
// name
string name = parseString( json, ref index );
if( name == null )
{
return null;
}
// :
token = nextToken( json, ref index );
if( token != NGUIJson.TOKEN_COLON )
return null;
// value
bool success = true;
object value = parseValue( json, ref index, ref success );
if( !success )
return null;
table[name] = value;
}
}
return table;
}
protected static ArrayList parseArray( char[] json, ref int index )
{
ArrayList array = new ArrayList();
// [
nextToken( json, ref index );
bool done = false;
while( !done )
{
int token = lookAhead( json, index );
if( token == NGUIJson.TOKEN_NONE )
{
return null;
}
else if( token == NGUIJson.TOKEN_COMMA )
{
nextToken( json, ref index );
}
else if( token == NGUIJson.TOKEN_SQUARED_CLOSE )
{
nextToken( json, ref index );
break;
}
else
{
bool success = true;
object value = parseValue( json, ref index, ref success );
if( !success )
return null;
array.Add( value );
}
}
return array;
}
protected static object parseValue( char[] json, ref int index, ref bool success )
{
switch( lookAhead( json, index ) )
{
case NGUIJson.TOKEN_STRING:
return parseString( json, ref index );
case NGUIJson.TOKEN_NUMBER:
return parseNumber( json, ref index );
case NGUIJson.TOKEN_CURLY_OPEN:
return parseObject( json, ref index );
case NGUIJson.TOKEN_SQUARED_OPEN:
return parseArray( json, ref index );
case NGUIJson.TOKEN_TRUE:
nextToken( json, ref index );
return Boolean.Parse( "TRUE" );
case NGUIJson.TOKEN_FALSE:
nextToken( json, ref index );
return Boolean.Parse( "FALSE" );
case NGUIJson.TOKEN_NULL:
nextToken( json, ref index );
return null;
case NGUIJson.TOKEN_NONE:
break;
}
success = false;
return null;
}
protected static string parseString( char[] json, ref int index )
{
string s = "";
char c;
eatWhitespace( json, ref index );
// "
c = json[index++];
bool complete = false;
while( !complete )
{
if( index == json.Length )
break;
c = json[index++];
if( c == '"' )
{
complete = true;
break;
}
else if( c == '\\' )
{
if( index == json.Length )
break;
c = json[index++];
if( c == '"' )
{
s += '"';
}
else if( c == '\\' )
{
s += '\\';
}
else if( c == '/' )
{
s += '/';
}
else if( c == 'b' )
{
s += '\b';
}
else if( c == 'f' )
{
s += '\f';
}
else if( c == 'n' )
{
s += '\n';
}
else if( c == 'r' )
{
s += '\r';
}
else if( c == 't' )
{
s += '\t';
}
else if( c == 'u' )
{
int remainingLength = json.Length - index;
if( remainingLength >= 4 )
{
char[] unicodeCharArray = new char[4];
Array.Copy( json, index, unicodeCharArray, 0, 4 );
// Drop in the HTML markup for the unicode character
s += "&#x" + new string( unicodeCharArray ) + ";";
/*
uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber);
// convert the integer codepoint to a unicode char and add to string
s += Char.ConvertFromUtf32((int)codePoint);
*/
// skip 4 chars
index += 4;
}
else
{
break;
}
}
}
else
{
s += c;
}
}
if( !complete )
return null;
return s;
}
protected static double parseNumber( char[] json, ref int index )
{
eatWhitespace( json, ref index );
int lastIndex = getLastIndexOfNumber( json, index );
int charLength = ( lastIndex - index ) + 1;
char[] numberCharArray = new char[charLength];
Array.Copy( json, index, numberCharArray, 0, charLength );
index = lastIndex + 1;
return Double.Parse( new string( numberCharArray ) ); // , CultureInfo.InvariantCulture);
}
protected static int getLastIndexOfNumber( char[] json, int index )
{
int lastIndex;
for( lastIndex = index; lastIndex < json.Length; lastIndex++ )
if( "0123456789+-.eE".IndexOf( json[lastIndex] ) == -1 )
{
break;
}
return lastIndex - 1;
}
protected static void eatWhitespace( char[] json, ref int index )
{
for( ; index < json.Length; index++ )
if( " \t\n\r".IndexOf( json[index] ) == -1 )
{
break;
}
}
protected static int lookAhead( char[] json, int index )
{
int saveIndex = index;
return nextToken( json, ref saveIndex );
}
protected static int nextToken( char[] json, ref int index )
{
eatWhitespace( json, ref index );
if( index == json.Length )
{
return NGUIJson.TOKEN_NONE;
}
char c = json[index];
index++;
switch( c )
{
case '{':
return NGUIJson.TOKEN_CURLY_OPEN;
case '}':
return NGUIJson.TOKEN_CURLY_CLOSE;
case '[':
return NGUIJson.TOKEN_SQUARED_OPEN;
case ']':
return NGUIJson.TOKEN_SQUARED_CLOSE;
case ',':
return NGUIJson.TOKEN_COMMA;
case '"':
return NGUIJson.TOKEN_STRING;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return NGUIJson.TOKEN_NUMBER;
case ':':
return NGUIJson.TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if( remainingLength >= 5 )
{
if( json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e' )
{
index += 5;
return NGUIJson.TOKEN_FALSE;
}
}
// true
if( remainingLength >= 4 )
{
if( json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e' )
{
index += 4;
return NGUIJson.TOKEN_TRUE;
}
}
// null
if( remainingLength >= 4 )
{
if( json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l' )
{
index += 4;
return NGUIJson.TOKEN_NULL;
}
}
return NGUIJson.TOKEN_NONE;
}
#endregion
#region Serialization
protected static bool serializeObjectOrArray( object objectOrArray, StringBuilder builder )
{
if( objectOrArray is Hashtable )
{
return serializeObject( (Hashtable)objectOrArray, builder );
}
else if( objectOrArray is ArrayList )
{
return serializeArray( (ArrayList)objectOrArray, builder );
}
else
{
return false;
}
}
protected static bool serializeObject( Hashtable anObject, StringBuilder builder )
{
builder.Append( "{" );
IDictionaryEnumerator e = anObject.GetEnumerator();
bool first = true;
while( e.MoveNext() )
{
string key = e.Key.ToString();
object value = e.Value;
if( !first )
{
builder.Append( ", " );
}
serializeString( key, builder );
builder.Append( ":" );
if( !serializeValue( value, builder ) )
{
return false;
}
first = false;
}
builder.Append( "}" );
return true;
}
protected static bool serializeDictionary( Dictionary<string,string> dict, StringBuilder builder )
{
builder.Append( "{" );
bool first = true;
foreach( var kv in dict )
{
if( !first )
builder.Append( ", " );
serializeString( kv.Key, builder );
builder.Append( ":" );
serializeString( kv.Value, builder );
first = false;
}
builder.Append( "}" );
return true;
}
protected static bool serializeArray( ArrayList anArray, StringBuilder builder )
{
builder.Append( "[" );
bool first = true;
for( int i = 0; i < anArray.Count; i++ )
{
object value = anArray[i];
if( !first )
{
builder.Append( ", " );
}
if( !serializeValue( value, builder ) )
{
return false;
}
first = false;
}
builder.Append( "]" );
return true;
}
protected static bool serializeValue( object value, StringBuilder builder )
{
// Type t = value.GetType();
// Debug.Log("type: " + t.ToString() + " isArray: " + t.IsArray);
if( value == null )
{
builder.Append( "null" );
}
else if( value.GetType().IsArray )
{
serializeArray( new ArrayList( (ICollection)value ), builder );
}
else if( value is string )
{
serializeString( (string)value, builder );
}
else if( value is Char )
{
serializeString( Convert.ToString( (char)value ), builder );
}
else if( value is Hashtable )
{
serializeObject( (Hashtable)value, builder );
}
else if( value is Dictionary<string,string> )
{
serializeDictionary( (Dictionary<string,string>)value, builder );
}
else if( value is ArrayList )
{
serializeArray( (ArrayList)value, builder );
}
else if( ( value is Boolean ) && ( (Boolean)value == true ) )
{
builder.Append( "true" );
}
else if( ( value is Boolean ) && ( (Boolean)value == false ) )
{
builder.Append( "false" );
}
else if( value.GetType().IsPrimitive )
{
serializeNumber( Convert.ToDouble( value ), builder );
}
else
{
return false;
}
return true;
}
protected static void serializeString( string aString, StringBuilder builder )
{
builder.Append( "\"" );
char[] charArray = aString.ToCharArray();
for( int i = 0; i < charArray.Length; i++ )
{
char c = charArray[i];
if( c == '"' )
{
builder.Append( "\\\"" );
}
else if( c == '\\' )
{
builder.Append( "\\\\" );
}
else if( c == '\b' )
{
builder.Append( "\\b" );
}
else if( c == '\f' )
{
builder.Append( "\\f" );
}
else if( c == '\n' )
{
builder.Append( "\\n" );
}
else if( c == '\r' )
{
builder.Append( "\\r" );
}
else if( c == '\t' )
{
builder.Append( "\\t" );
}
else
{
int codepoint = Convert.ToInt32( c );
if( ( codepoint >= 32 ) && ( codepoint <= 126 ) )
{
builder.Append( c );
}
else
{
builder.Append( "\\u" + Convert.ToString( codepoint, 16 ).PadLeft( 4, '0' ) );
}
}
}
builder.Append( "\"" );
}
protected static void serializeNumber( double number, StringBuilder builder )
{
builder.Append( Convert.ToString( number ) ); // , CultureInfo.InvariantCulture));
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUIJson.cs
|
C#
|
asf20
| 18,740
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// EditorGUILayout.ObjectField doesn't support custom components, so a custom wizard saves the day.
/// Unfortunately this tool only shows components that are being used by the scene, so it's a "recently used" selection tool.
/// </summary>
public class ComponentSelector : ScriptableWizard
{
public delegate void OnSelectionCallback (Object obj);
System.Type mType;
string mTitle;
OnSelectionCallback mCallback;
Object[] mObjects;
bool mSearched = false;
Vector2 mScroll = Vector2.zero;
string[] mExtensions = null;
static string GetName (System.Type t)
{
string s = t.ToString();
s = s.Replace("UnityEngine.", "");
if (s.StartsWith("UI")) s = s.Substring(2);
return s;
}
/// <summary>
/// Draw a button + object selection combo filtering specified types.
/// </summary>
static public void Draw<T> (string buttonName, T obj, OnSelectionCallback cb, bool editButton, params GUILayoutOption[] options) where T : Object
{
GUILayout.BeginHorizontal();
bool show = NGUIEditorTools.DrawPrefixButton(buttonName);
T o = EditorGUILayout.ObjectField(obj, typeof(T), false, options) as T;
if (editButton && o != null && o is MonoBehaviour)
{
Component mb = o as Component;
if (Selection.activeObject != mb.gameObject && GUILayout.Button("Edit", GUILayout.Width(40f)))
Selection.activeObject = mb.gameObject;
}
else if (o != null && GUILayout.Button("X", GUILayout.Width(20f)))
{
o = null;
}
GUILayout.EndHorizontal();
if (show) Show<T>(cb);
else cb(o);
}
/// <summary>
/// Draw a button + object selection combo filtering specified types.
/// </summary>
static public void Draw<T> (T obj, OnSelectionCallback cb, bool editButton, params GUILayoutOption[] options) where T : Object
{
Draw<T>(NGUITools.GetTypeName<T>(), obj, cb, editButton, options);
}
/// <summary>
/// Show the selection wizard.
/// </summary>
static public void Show<T> (OnSelectionCallback cb) where T : Object { Show<T>(cb, new string[] {".prefab"}); }
/// <summary>
/// Show the selection wizard.
/// </summary>
static public void Show<T> (OnSelectionCallback cb, string[] extensions) where T : Object
{
System.Type type = typeof(T);
string title = (type == typeof(UIAtlas) ? "Select an " : "Select a ") + GetName(type);
ComponentSelector comp = ScriptableWizard.DisplayWizard<ComponentSelector>(title);
comp.mTitle = title;
comp.mType = type;
comp.mCallback = cb;
comp.mExtensions = extensions;
comp.mObjects = Resources.FindObjectsOfTypeAll(typeof(T));
if (comp.mObjects == null || comp.mObjects.Length == 0)
{
comp.Search();
}
else
{
// Remove invalid fonts (Lucida Grande etc)
if (typeof(T) == typeof(Font))
{
for (int i = 0; i < comp.mObjects.Length; ++i)
{
Object obj = comp.mObjects[i];
if (obj.name == "Arial") continue;
string path = AssetDatabase.GetAssetPath(obj);
if (string.IsNullOrEmpty(path)) comp.mObjects[i] = null;
}
}
System.Array.Sort(comp.mObjects,
delegate(Object a, Object b)
{
if (a == null) return (b == null) ? 0 : 1;
if (b == null) return -1;
return a.name.CompareTo(b.name);
});
}
}
/// <summary>
/// Search the entire project for required assets.
/// </summary>
void Search ()
{
mSearched = true;
if (mExtensions != null)
{
string[] paths = AssetDatabase.GetAllAssetPaths();
bool isComponent = mType.IsSubclassOf(typeof(Component));
BetterList<Object> list = new BetterList<Object>();
for (int i = 0; i < mObjects.Length; ++i)
if (mObjects[i] != null)
list.Add(mObjects[i]);
for (int i = 0; i < paths.Length; ++i)
{
string path = paths[i];
bool valid = false;
for (int b = 0; b < mExtensions.Length; ++b)
{
if (path.EndsWith(mExtensions[b], System.StringComparison.OrdinalIgnoreCase))
{
valid = true;
break;
}
}
if (!valid) continue;
EditorUtility.DisplayProgressBar("Loading", "Searching assets, please wait...", (float)i / paths.Length);
Object obj = AssetDatabase.LoadMainAssetAtPath(path);
if (obj == null || list.Contains(obj)) continue;
if (!isComponent)
{
System.Type t = obj.GetType();
if (t == mType || t.IsSubclassOf(mType) && !list.Contains(obj))
list.Add(obj);
}
else if (PrefabUtility.GetPrefabType(obj) == PrefabType.Prefab)
{
Object t = (obj as GameObject).GetComponent(mType);
if (t != null && !list.Contains(t)) list.Add(t);
}
}
list.Sort(delegate(Object a, Object b) { return a.name.CompareTo(b.name); });
mObjects = list.ToArray();
}
EditorUtility.ClearProgressBar();
}
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.Label(mTitle, "LODLevelNotifyText");
GUILayout.Space(6f);
if (mObjects == null || mObjects.Length == 0)
{
EditorGUILayout.HelpBox("No " + GetName(mType) + " components found.\nTry creating a new one.", MessageType.Info);
bool isDone = false;
EditorGUILayout.Space();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (mType == typeof(UIFont))
{
if (GUILayout.Button("Open the Font Maker", GUILayout.Width(150f)))
{
EditorWindow.GetWindow<UIFontMaker>(false, "Font Maker", true).Show();
isDone = true;
}
}
else if (mType == typeof(UIAtlas))
{
if (GUILayout.Button("Open the Atlas Maker", GUILayout.Width(150f)))
{
EditorWindow.GetWindow<UIAtlasMaker>(false, "Atlas Maker", true).Show();
isDone = true;
}
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if (isDone) Close();
}
else
{
Object sel = null;
mScroll = GUILayout.BeginScrollView(mScroll);
foreach (Object o in mObjects)
if (DrawObject(o))
sel = o;
GUILayout.EndScrollView();
if (sel != null)
{
mCallback(sel);
Close();
}
}
if (!mSearched)
{
GUILayout.Space(6f);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
bool search = GUILayout.Button("Show All", "LargeButton", GUILayout.Width(120f));
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
if (search) Search();
}
}
/// <summary>
/// Draw details about the specified object in column format.
/// </summary>
bool DrawObject (Object obj)
{
if (obj == null) return false;
bool retVal = false;
Component comp = obj as Component;
GUILayout.BeginHorizontal();
{
string path = AssetDatabase.GetAssetPath(obj);
if (string.IsNullOrEmpty(path))
{
path = "[Embedded]";
GUI.contentColor = new Color(0.7f, 0.7f, 0.7f);
}
else if (comp != null && EditorUtility.IsPersistent(comp.gameObject))
GUI.contentColor = new Color(0.6f, 0.8f, 1f);
retVal |= GUILayout.Button(obj.name, "AS TextArea", GUILayout.Width(160f), GUILayout.Height(20f));
retVal |= GUILayout.Button(path.Replace("Assets/", ""), "AS TextArea", GUILayout.Height(20f));
GUI.contentColor = Color.white;
retVal |= GUILayout.Button("Select", "ButtonLeft", GUILayout.Width(60f), GUILayout.Height(16f));
}
GUILayout.EndHorizontal();
return retVal;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/ComponentSelector.cs
|
C#
|
asf20
| 7,434
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit UIWidgets.
/// </summary>
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIWidget))]
#else
[CustomEditor(typeof(UIWidget), true)]
#endif
public class UIWidgetInspector : UIRectEditor
{
static public UIWidgetInspector instance;
public enum Action
{
None,
Move,
Scale,
Rotate,
}
Action mAction = Action.None;
Action mActionUnderMouse = Action.None;
bool mAllowSelection = true;
protected UIWidget mWidget;
static protected bool mUseShader = false;
static GUIStyle mBlueDot = null;
static GUIStyle mYellowDot = null;
static GUIStyle mRedDot = null;
static GUIStyle mOrangeDot = null;
static GUIStyle mGreenDot = null;
static GUIStyle mGreyDot = null;
static MouseCursor mCursor = MouseCursor.Arrow;
static public UIWidget.Pivot[] pivotPoints =
{
UIWidget.Pivot.BottomLeft,
UIWidget.Pivot.TopLeft,
UIWidget.Pivot.TopRight,
UIWidget.Pivot.BottomRight,
UIWidget.Pivot.Left,
UIWidget.Pivot.Top,
UIWidget.Pivot.Right,
UIWidget.Pivot.Bottom,
};
static int s_Hash = "WidgetHash".GetHashCode();
Vector3 mLocalPos = Vector3.zero;
Vector3 mWorldPos = Vector3.zero;
int mStartWidth = 0;
int mStartHeight = 0;
Vector3 mStartDrag = Vector3.zero;
Vector2 mStartMouse = Vector2.zero;
Vector3 mStartRot = Vector3.zero;
Vector3 mStartDir = Vector3.right;
Vector2 mStartLeft = Vector2.zero;
Vector2 mStartRight = Vector2.zero;
Vector2 mStartBottom = Vector2.zero;
Vector2 mStartTop = Vector2.zero;
UIWidget.Pivot mDragPivot = UIWidget.Pivot.Center;
/// <summary>
/// Raycast into the screen.
/// </summary>
static public bool Raycast (Vector3[] corners, out Vector3 hit)
{
Plane plane = new Plane(corners[0], corners[1], corners[2]);
Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
float dist = 0f;
bool isHit = plane.Raycast(ray, out dist);
hit = isHit ? ray.GetPoint(dist) : Vector3.zero;
return isHit;
}
/// <summary>
/// Color used by the handles based on the current color scheme.
/// </summary>
static public Color handlesColor
{
get
{
if (NGUISettings.colorMode == NGUISettings.ColorMode.Orange)
{
return new Color(1f, 0.5f, 0f);
}
else if (NGUISettings.colorMode == NGUISettings.ColorMode.Green)
{
return Color.green;
}
return Color.white;
}
}
/// <summary>
/// Draw a control dot at the specified world position.
/// </summary>
static public void DrawKnob (Vector3 point, bool selected, bool canResize, int id)
{
if (mGreyDot == null) mGreyDot = "sv_label_0";
if (mBlueDot == null) mBlueDot = "sv_label_1";
if (mGreenDot == null) mGreenDot = "sv_label_3";
if (mYellowDot == null) mYellowDot = "sv_label_4";
if (mOrangeDot == null) mOrangeDot = "sv_label_5";
if (mRedDot == null) mRedDot = "sv_label_6";
Vector2 screenPoint = HandleUtility.WorldToGUIPoint(point);
Rect rect = new Rect(screenPoint.x - 7f, screenPoint.y - 7f, 14f, 14f);
if (selected)
{
if (NGUISettings.colorMode == NGUISettings.ColorMode.Orange)
{
mRedDot.Draw(rect, GUIContent.none, id);
}
else
{
mOrangeDot.Draw(rect, GUIContent.none, id);
}
}
else if (canResize)
{
if (NGUISettings.colorMode == NGUISettings.ColorMode.Orange)
{
mOrangeDot.Draw(rect, GUIContent.none, id);
}
else if (NGUISettings.colorMode == NGUISettings.ColorMode.Green)
{
mGreenDot.Draw(rect, GUIContent.none, id);
}
else
{
mBlueDot.Draw(rect, GUIContent.none, id);
}
}
else mGreyDot.Draw(rect, GUIContent.none, id);
}
/// <summary>
/// Screen-space distance from the mouse position to the specified world position.
/// </summary>
static public float GetScreenDistance (Vector3 worldPos, Vector2 mousePos)
{
Vector2 screenPos = HandleUtility.WorldToGUIPoint(worldPos);
return Vector2.Distance(mousePos, screenPos);
}
/// <summary>
/// Closest screen-space distance from the mouse position to one of the specified world points.
/// </summary>
static public float GetScreenDistance (Vector3[] worldPoints, Vector2 mousePos, out int index)
{
float min = float.MaxValue;
index = 0;
for (int i = 0; i < worldPoints.Length; ++i)
{
float distance = GetScreenDistance(worldPoints[i], mousePos);
if (distance < min)
{
index = i;
min = distance;
}
}
return min;
}
/// <summary>
/// Set the mouse cursor rectangle, refreshing the screen when it gets changed.
/// </summary>
static public void SetCursorRect (Rect rect, MouseCursor cursor)
{
EditorGUIUtility.AddCursorRect(rect, cursor);
if (Event.current.type == EventType.MouseMove)
{
if (mCursor != cursor)
{
mCursor = cursor;
Event.current.Use();
}
}
}
void OnDisable ()
{
NGUIEditorTools.HideMoveTool(false);
instance = null;
}
/// <summary>
/// Convert the specified 4 corners into 8 pivot points (adding left, top, right, bottom -- in that order).
/// </summary>
static public Vector3[] GetHandles (Vector3[] corners)
{
Vector3[] v = new Vector3[8];
v[0] = corners[0];
v[1] = corners[1];
v[2] = corners[2];
v[3] = corners[3];
v[4] = (corners[0] + corners[1]) * 0.5f;
v[5] = (corners[1] + corners[2]) * 0.5f;
v[6] = (corners[2] + corners[3]) * 0.5f;
v[7] = (corners[0] + corners[3]) * 0.5f;
return v;
}
/// <summary>
/// Determine what kind of pivot point is under the mouse and update the cursor accordingly.
/// </summary>
static public UIWidget.Pivot GetPivotUnderMouse (Vector3[] worldPos, Event e, bool[] resizable, bool movable, ref Action action)
{
// Time to figure out what kind of action is underneath the mouse
UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;
if (action == Action.None)
{
int index = 0;
float dist = GetScreenDistance(worldPos, e.mousePosition, out index);
bool alt = (e.modifiers & EventModifiers.Alt) != 0;
if (resizable[index] && dist < 10f)
{
pivotUnderMouse = pivotPoints[index];
action = Action.Scale;
}
else if (!alt && NGUIEditorTools.SceneViewDistanceToRectangle(worldPos, e.mousePosition) == 0f)
{
action = movable ? Action.Move : Action.Rotate;
}
else if (dist < 30f)
{
action = Action.Rotate;
}
}
// Change the mouse cursor to a more appropriate one
#if !UNITY_3_5
{
Vector2[] screenPos = new Vector2[8];
for (int i = 0; i < 8; ++i) screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);
Bounds b = new Bounds(screenPos[0], Vector3.zero);
for (int i = 1; i < 8; ++i) b.Encapsulate(screenPos[i]);
Vector2 min = b.min;
Vector2 max = b.max;
min.x -= 30f;
max.x += 30f;
min.y -= 30f;
max.y += 30f;
Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
if (action == Action.Rotate)
{
SetCursorRect(rect, MouseCursor.RotateArrow);
}
else if (action == Action.Move)
{
SetCursorRect(rect, MouseCursor.MoveArrow);
}
else if (action == Action.Scale)
{
SetCursorRect(rect, MouseCursor.ScaleArrow);
}
else SetCursorRect(rect, MouseCursor.Arrow);
}
#endif
return pivotUnderMouse;
}
/// <summary>
/// Draw the specified anchor point.
/// </summary>
static public void DrawAnchorHandle (UIRect.AnchorPoint anchor, Transform myTrans, Vector3[] myCorners, int side, int id)
{
if (!anchor.target) return;
int i0, i1;
if (side == 0)
{
// Left
i0 = 0;
i1 = 1;
}
else if (side == 1)
{
// Top
i0 = 1;
i1 = 2;
}
else if (side == 2)
{
// Right
i0 = 3;
i1 = 2;
}
else
{
// Bottom
i0 = 0;
i1 = 3;
}
Vector3 myPos = (myCorners[i0] + myCorners[i1]) * 0.5f;
Vector3[] sides = null;
if (anchor.rect != null)
{
sides = anchor.rect.worldCorners;
}
else if (anchor.target.camera != null)
{
sides = anchor.target.camera.GetWorldCorners();
}
Vector3 theirPos;
if (sides != null)
{
Vector3 v0, v1;
if (side == 0 || side == 2)
{
// Left or right
v0 = Vector3.Lerp(sides[0], sides[3], anchor.relative);
v1 = Vector3.Lerp(sides[1], sides[2], anchor.relative);
}
else
{
// Top or bottom
v0 = Vector3.Lerp(sides[0], sides[1], anchor.relative);
v1 = Vector3.Lerp(sides[3], sides[2], anchor.relative);
}
theirPos = HandleUtility.ProjectPointLine(myPos, v0, v1);
}
else
{
theirPos = anchor.target.position;
}
NGUIHandles.DrawShadowedLine(myCorners, myPos, theirPos, Color.yellow);
if (Event.current.GetTypeForControl(id) == EventType.Repaint)
{
Vector2 screenPoint = HandleUtility.WorldToGUIPoint(theirPos);
Rect rect = new Rect(screenPoint.x - 7f, screenPoint.y - 7f, 14f, 14f);
if (mYellowDot == null) mYellowDot = "sv_label_4";
Vector3 v0 = HandleUtility.WorldToGUIPoint(myPos);
Vector3 v1 = HandleUtility.WorldToGUIPoint(theirPos);
Handles.BeginGUI();
mYellowDot.Draw(rect, GUIContent.none, id);
Vector3 diff = v1 - v0;
bool isHorizontal = Mathf.Abs(diff.x) > Mathf.Abs(diff.y);
float mag = diff.magnitude;
if ((isHorizontal && mag > 60f) || (!isHorizontal && mag > 30f))
{
Vector3 pos = (myPos + theirPos) * 0.5f;
string text = anchor.absolute.ToString();
GUI.color = Color.yellow;
if (side == 0)
{
if (theirPos.x < myPos.x)
NGUIHandles.DrawCenteredLabel(pos, text);
}
else if (side == 1)
{
if (theirPos.y > myPos.y)
NGUIHandles.DrawCenteredLabel(pos, text);
}
else if (side == 2)
{
if (theirPos.x > myPos.x)
NGUIHandles.DrawCenteredLabel(pos, text);
}
else if (side == 3)
{
if (theirPos.y < myPos.y)
NGUIHandles.DrawCenteredLabel(pos, text);
}
GUI.color = Color.white;
}
Handles.EndGUI();
}
}
/// <summary>
/// Draw the on-screen selection, knobs, and handle all interaction logic.
/// </summary>
public void OnSceneGUI ()
{
NGUIEditorTools.HideMoveTool(true);
if (!UIWidget.showHandles) return;
mWidget = target as UIWidget;
Transform t = mWidget.cachedTransform;
Event e = Event.current;
int id = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
EventType type = e.GetTypeForControl(id);
Action actionUnderMouse = mAction;
Vector3[] handles = GetHandles(mWidget.worldCorners);
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);
// If the widget is anchored, draw the anchors
if (mWidget.isAnchored)
{
DrawAnchorHandle(mWidget.leftAnchor, mWidget.cachedTransform, handles, 0, id);
DrawAnchorHandle(mWidget.topAnchor, mWidget.cachedTransform, handles, 1, id);
DrawAnchorHandle(mWidget.rightAnchor, mWidget.cachedTransform, handles, 2, id);
DrawAnchorHandle(mWidget.bottomAnchor, mWidget.cachedTransform, handles, 3, id);
}
if (type == EventType.Repaint)
{
bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control) showDetails = true;
if (NGUITools.GetActive(mWidget) && mWidget.parent == null) showDetails = true;
if (showDetails) NGUIHandles.DrawSize(handles, mWidget.width, mWidget.height);
}
// Presence of the legacy stretch component prevents resizing
bool canResize = (mWidget.GetComponent<UIStretch>() == null);
bool[] resizable = new bool[8];
resizable[4] = canResize; // left
resizable[5] = canResize; // top
resizable[6] = canResize; // right
resizable[7] = canResize; // bottom
UILabel lbl = mWidget as UILabel;
if (lbl != null)
{
if (lbl.overflowMethod == UILabel.Overflow.ResizeFreely)
{
resizable[4] = false; // left
resizable[5] = false; // top
resizable[6] = false; // right
resizable[7] = false; // bottom
}
else if (lbl.overflowMethod == UILabel.Overflow.ResizeHeight)
{
resizable[5] = false; // top
resizable[7] = false; // bottom
}
}
if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
{
resizable[4] = false;
resizable[6] = false;
}
else if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnWidth)
{
resizable[5] = false;
resizable[7] = false;
}
resizable[0] = resizable[7] && resizable[4]; // bottom-left
resizable[1] = resizable[5] && resizable[4]; // top-left
resizable[2] = resizable[5] && resizable[6]; // top-right
resizable[3] = resizable[7] && resizable[6]; // bottom-right
UIWidget.Pivot pivotUnderMouse = GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);
switch (type)
{
case EventType.Repaint:
{
Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);
if ((v2 - v0).magnitude > 60f)
{
Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);
Handles.BeginGUI();
{
for (int i = 0; i < 4; ++i)
DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], resizable[i], id);
if ((v1 - v0).magnitude > 80f)
{
if (mWidget.leftAnchor.target == null || mWidget.leftAnchor.absolute != 0)
DrawKnob(handles[4], mWidget.pivot == pivotPoints[4], resizable[4], id);
if (mWidget.rightAnchor.target == null || mWidget.rightAnchor.absolute != 0)
DrawKnob(handles[6], mWidget.pivot == pivotPoints[6], resizable[6], id);
}
if ((v3 - v0).magnitude > 80f)
{
if (mWidget.topAnchor.target == null || mWidget.topAnchor.absolute != 0)
DrawKnob(handles[5], mWidget.pivot == pivotPoints[5], resizable[5], id);
if (mWidget.bottomAnchor.target == null || mWidget.bottomAnchor.absolute != 0)
DrawKnob(handles[7], mWidget.pivot == pivotPoints[7], resizable[7], id);
}
}
Handles.EndGUI();
}
}
break;
case EventType.MouseDown:
{
if (actionUnderMouse != Action.None)
{
mStartMouse = e.mousePosition;
mAllowSelection = true;
if (e.button == 1)
{
if (e.modifiers == 0)
{
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
}
else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(handles, out mStartDrag))
{
mWorldPos = t.position;
mLocalPos = t.localPosition;
mStartRot = t.localRotation.eulerAngles;
mStartDir = mStartDrag - t.position;
mStartWidth = mWidget.width;
mStartHeight = mWidget.height;
mStartLeft.x = mWidget.leftAnchor.relative;
mStartLeft.y = mWidget.leftAnchor.absolute;
mStartRight.x = mWidget.rightAnchor.relative;
mStartRight.y = mWidget.rightAnchor.absolute;
mStartBottom.x = mWidget.bottomAnchor.relative;
mStartBottom.y = mWidget.bottomAnchor.absolute;
mStartTop.x = mWidget.topAnchor.relative;
mStartTop.y = mWidget.topAnchor.absolute;
mDragPivot = pivotUnderMouse;
mActionUnderMouse = actionUnderMouse;
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
}
}
break;
case EventType.MouseDrag:
{
// Prevent selection once the drag operation begins
bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
if (dragStarted) mAllowSelection = false;
if (GUIUtility.hotControl == id)
{
e.Use();
if (mAction != Action.None || mActionUnderMouse != Action.None)
{
Vector3 pos;
if (Raycast(handles, out pos))
{
if (mAction == Action.None && mActionUnderMouse != Action.None)
{
// Wait until the mouse moves by more than a few pixels
if (dragStarted)
{
if (mActionUnderMouse == Action.Move)
{
NGUISnap.Recalculate(mWidget);
}
else if (mActionUnderMouse == Action.Rotate)
{
mStartRot = t.localRotation.eulerAngles;
mStartDir = mStartDrag - t.position;
}
else if (mActionUnderMouse == Action.Scale)
{
mStartWidth = mWidget.width;
mStartHeight = mWidget.height;
mDragPivot = pivotUnderMouse;
}
mAction = actionUnderMouse;
}
}
if (mAction != Action.None)
{
NGUIEditorTools.RegisterUndo("Change Rect", t);
NGUIEditorTools.RegisterUndo("Change Rect", mWidget);
// Reset the widget before adjusting anything
t.position = mWorldPos;
mWidget.width = mStartWidth;
mWidget.height = mStartHeight;
mWidget.leftAnchor.Set(mStartLeft.x, mStartLeft.y);
mWidget.rightAnchor.Set(mStartRight.x, mStartRight.y);
mWidget.bottomAnchor.Set(mStartBottom.x, mStartBottom.y);
mWidget.topAnchor.Set(mStartTop.x, mStartTop.y);
if (mAction == Action.Move)
{
// Move the widget
t.position = mWorldPos + (pos - mStartDrag);
// Snap the widget
Vector3 after = NGUISnap.Snap(t.localPosition, mWidget.localCorners, e.modifiers != EventModifiers.Control);
// Calculate the final delta
Vector3 localDelta = (after - mLocalPos);
// Restore the position
t.position = mWorldPos;
// Adjust the widget by the delta
NGUIMath.MoveRect(mWidget, localDelta.x, localDelta.y);
}
else if (mAction == Action.Rotate)
{
Vector3 dir = pos - t.position;
float angle = Vector3.Angle(mStartDir, dir);
if (angle > 0f)
{
float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
if (dot < 0f) angle = -angle;
angle = mStartRot.z + angle;
angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
}
}
else if (mAction == Action.Scale)
{
// Move the widget
t.position = mWorldPos + (pos - mStartDrag);
// Calculate the final delta
Vector3 localDelta = (t.localPosition - mLocalPos);
// Restore the position
t.position = mWorldPos;
// Adjust the widget's position and scale based on the delta, restricted by the pivot
NGUIMath.ResizeWidget(mWidget, mDragPivot, localDelta.x, localDelta.y, 2, 2);
ReEvaluateAnchorType();
}
}
}
}
}
}
break;
case EventType.MouseUp:
{
if (e.button == 2) break;
if (GUIUtility.hotControl == id)
{
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
if (e.button < 2)
{
bool handled = false;
if (e.button == 1)
{
// Right-click: Open a context menu listing all widgets underneath
NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
handled = true;
}
else if (mAction == Action.None)
{
if (mAllowSelection)
{
// Left-click: Select the topmost widget
NGUIEditorTools.SelectWidget(e.mousePosition);
handled = true;
}
}
else
{
// Finished dragging something
Vector3 pos = t.localPosition;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = Mathf.Round(pos.z);
t.localPosition = pos;
handled = true;
}
if (handled) e.Use();
}
// Clear the actions
mActionUnderMouse = Action.None;
mAction = Action.None;
}
else if (mAllowSelection)
{
BetterList<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
if (widgets.size > 0) Selection.activeGameObject = widgets[0].gameObject;
}
mAllowSelection = true;
}
break;
case EventType.KeyDown:
{
if (e.keyCode == KeyCode.UpArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, 0f, 1f);
e.Use();
}
else if (e.keyCode == KeyCode.DownArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, 0f, -1f);
e.Use();
}
else if (e.keyCode == KeyCode.LeftArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, -1f, 0f);
e.Use();
}
else if (e.keyCode == KeyCode.RightArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, 1f, 0f);
e.Use();
}
else if (e.keyCode == KeyCode.Escape)
{
if (GUIUtility.hotControl == id)
{
if (mAction != Action.None)
Undo.PerformUndo();
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
mActionUnderMouse = Action.None;
mAction = Action.None;
e.Use();
}
else Selection.activeGameObject = null;
}
}
break;
}
}
/// <summary>
/// Cache the reference.
/// </summary>
protected override void OnEnable ()
{
base.OnEnable();
instance = this;
mWidget = target as UIWidget;
}
/// <summary>
/// By default all non-widgets should use their color.
/// </summary>
protected virtual bool drawColor
{
get
{
return (target.GetType() != typeof(UIWidget));
}
}
/// <summary>
/// All widgets have depth, color and make pixel-perfect options
/// </summary>
protected override void DrawCustomProperties ()
{
PrefabType type = PrefabUtility.GetPrefabType(mWidget.gameObject);
if (NGUIEditorTools.DrawHeader("Widget"))
{
NGUIEditorTools.BeginContents();
if (drawColor)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1
// Color tint
GUILayout.BeginHorizontal();
SerializedProperty sp = NGUIEditorTools.DrawProperty("Color", serializedObject, "mColor", GUILayout.MinWidth(20f));
if (GUILayout.Button("Copy", GUILayout.Width(50f)))
NGUISettings.color = sp.colorValue;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
NGUISettings.color = EditorGUILayout.ColorField("Clipboard", NGUISettings.color);
if (GUILayout.Button("Paste", GUILayout.Width(50f)))
sp.colorValue = NGUISettings.color;
GUILayout.EndHorizontal();
GUILayout.Space(6f);
#else
NGUIEditorTools.DrawProperty("Color", serializedObject, "mColor", GUILayout.MinWidth(20f));
#endif
}
else if (serializedObject.isEditingMultipleObjects)
{
NGUIEditorTools.DrawProperty("Alpha", serializedObject, "mColor.a", GUILayout.Width(120f));
}
else
{
GUI.changed = false;
float alpha = EditorGUILayout.Slider("Alpha", mWidget.alpha, 0f, 1f);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Alpha change", mWidget);
mWidget.alpha = alpha;
}
}
DrawPivot();
DrawDepth(type == PrefabType.Prefab);
DrawDimensions(type == PrefabType.Prefab);
SerializedProperty ratio = serializedObject.FindProperty("aspectRatio");
SerializedProperty aspect = serializedObject.FindProperty("keepAspectRatio");
GUILayout.BeginHorizontal();
{
if (!aspect.hasMultipleDifferentValues && aspect.intValue == 0)
{
EditorGUI.BeginDisabledGroup(true);
NGUIEditorTools.DrawProperty("Aspect Ratio", ratio, false, GUILayout.Width(130f));
EditorGUI.EndDisabledGroup();
}
else NGUIEditorTools.DrawProperty("Aspect Ratio", ratio, false, GUILayout.Width(130f));
NGUIEditorTools.DrawProperty("", aspect, false, GUILayout.MinWidth(20f));
}
GUILayout.EndHorizontal();
if (serializedObject.isEditingMultipleObjects || mWidget.hasBoxCollider)
{
GUILayout.BeginHorizontal();
{
NGUIEditorTools.DrawProperty("Box Collider", serializedObject, "autoResizeBoxCollider", GUILayout.Width(100f));
GUILayout.Label("auto-adjust to match");
}
GUILayout.EndHorizontal();
}
NGUIEditorTools.EndContents();
}
}
/// <summary>
/// Draw widget's dimensions.
/// </summary>
void DrawDimensions (bool isPrefab)
{
GUILayout.BeginHorizontal();
{
bool freezeSize = serializedObject.isEditingMultipleObjects;
UILabel lbl = mWidget as UILabel;
if (!freezeSize && lbl) freezeSize = (lbl.overflowMethod == UILabel.Overflow.ResizeFreely);
if (freezeSize)
{
EditorGUI.BeginDisabledGroup(true);
NGUIEditorTools.DrawProperty("Dimensions", serializedObject, "mWidth", GUILayout.MinWidth(100f));
EditorGUI.EndDisabledGroup();
}
else
{
GUI.changed = false;
int val = EditorGUILayout.IntField("Dimensions", mWidget.width, GUILayout.MinWidth(100f));
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Dimensions Change", mWidget);
mWidget.width = val;
}
}
if (!freezeSize && lbl)
{
UILabel.Overflow ov = lbl.overflowMethod;
freezeSize = (ov == UILabel.Overflow.ResizeFreely || ov == UILabel.Overflow.ResizeHeight);
}
NGUIEditorTools.SetLabelWidth(12f);
if (freezeSize)
{
EditorGUI.BeginDisabledGroup(true);
NGUIEditorTools.DrawProperty("x", serializedObject, "mHeight", GUILayout.MinWidth(30f));
EditorGUI.EndDisabledGroup();
}
else
{
GUI.changed = false;
int val = EditorGUILayout.IntField("x", mWidget.height, GUILayout.MinWidth(30f));
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Dimensions Change", mWidget);
mWidget.height = val;
}
}
NGUIEditorTools.SetLabelWidth(80f);
if (isPrefab)
{
GUILayout.Space(70f);
}
else
{
EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
if (GUILayout.Button("Snap", GUILayout.Width(68f)))
{
foreach (GameObject go in Selection.gameObjects)
{
UIWidget w = go.GetComponent<UIWidget>();
if (w != null)
{
NGUIEditorTools.RegisterUndo("Snap Dimensions", w);
NGUIEditorTools.RegisterUndo("Snap Dimensions", w.transform);
w.MakePixelPerfect();
}
}
}
EditorGUI.EndDisabledGroup();
}
}
GUILayout.EndHorizontal();
}
/// <summary>
/// Draw widget's depth.
/// </summary>
void DrawDepth (bool isPrefab)
{
if (isPrefab) return;
GUILayout.Space(2f);
GUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel("Depth");
if (GUILayout.Button("Back", GUILayout.MinWidth(46f)))
{
foreach (GameObject go in Selection.gameObjects)
{
UIWidget w = go.GetComponent<UIWidget>();
if (w != null) w.depth = w.depth - 1;
}
}
NGUIEditorTools.DrawProperty("", serializedObject, "mDepth", GUILayout.MinWidth(20f));
if (GUILayout.Button("Forward", GUILayout.MinWidth(60f)))
{
foreach (GameObject go in Selection.gameObjects)
{
UIWidget w = go.GetComponent<UIWidget>();
if (w != null) w.depth = w.depth + 1;
}
}
}
GUILayout.EndHorizontal();
int matchingDepths = 1;
UIPanel p = mWidget.panel;
if (p != null)
{
for (int i = 0; i < p.widgets.size; ++i)
{
UIWidget w = p.widgets[i];
if (w != mWidget && w.depth == mWidget.depth)
++matchingDepths;
}
}
if (matchingDepths > 1)
{
EditorGUILayout.HelpBox(matchingDepths + " widgets are sharing the depth value of " + mWidget.depth, MessageType.Info);
}
}
/// <summary>
/// Draw the widget's pivot.
/// </summary>
void DrawPivot ()
{
SerializedProperty pv = serializedObject.FindProperty("mPivot");
if (pv.hasMultipleDifferentValues)
{
// TODO: Doing this doesn't keep the widget's position where it was. Another approach is needed.
NGUIEditorTools.DrawProperty("Pivot", serializedObject, "mPivot");
}
else
{
// Pivot point -- the new, more visual style
GUILayout.BeginHorizontal();
GUILayout.Label("Pivot", GUILayout.Width(76f));
#if !UNITY_3_5
Toggle("\u25C4", "ButtonLeft", UIWidget.Pivot.Left, true);
Toggle("\u25AC", "ButtonMid", UIWidget.Pivot.Center, true);
Toggle("\u25BA", "ButtonRight", UIWidget.Pivot.Right, true);
#else
Toggle("<", "ButtonLeft", UIWidget.Pivot.Left, true);
Toggle("--", "ButtonMid", UIWidget.Pivot.Center, true);
Toggle(">", "ButtonRight", UIWidget.Pivot.Right, true);
#endif
Toggle("\u25B2", "ButtonLeft", UIWidget.Pivot.Top, false);
Toggle("\u258C", "ButtonMid", UIWidget.Pivot.Center, false);
Toggle("\u25BC", "ButtonRight", UIWidget.Pivot.Bottom, false);
GUILayout.EndHorizontal();
pv.enumValueIndex = (int)mWidget.pivot;
}
}
/// <summary>
/// Draw a toggle button for the pivot point.
/// </summary>
void Toggle (string text, string style, UIWidget.Pivot pivot, bool isHorizontal)
{
bool isActive = false;
switch (pivot)
{
case UIWidget.Pivot.Left:
isActive = IsLeft(mWidget.pivot);
break;
case UIWidget.Pivot.Right:
isActive = IsRight(mWidget.pivot);
break;
case UIWidget.Pivot.Top:
isActive = IsTop(mWidget.pivot);
break;
case UIWidget.Pivot.Bottom:
isActive = IsBottom(mWidget.pivot);
break;
case UIWidget.Pivot.Center:
isActive = isHorizontal ? pivot == GetHorizontal(mWidget.pivot) : pivot == GetVertical(mWidget.pivot);
break;
}
if (GUILayout.Toggle(isActive, text, style) != isActive)
SetPivot(pivot, isHorizontal);
}
static bool IsLeft (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Left ||
pivot == UIWidget.Pivot.TopLeft ||
pivot == UIWidget.Pivot.BottomLeft;
}
static bool IsRight (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Right ||
pivot == UIWidget.Pivot.TopRight ||
pivot == UIWidget.Pivot.BottomRight;
}
static bool IsTop (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Top ||
pivot == UIWidget.Pivot.TopLeft ||
pivot == UIWidget.Pivot.TopRight;
}
static bool IsBottom (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Bottom ||
pivot == UIWidget.Pivot.BottomLeft ||
pivot == UIWidget.Pivot.BottomRight;
}
static UIWidget.Pivot GetHorizontal (UIWidget.Pivot pivot)
{
if (IsLeft(pivot)) return UIWidget.Pivot.Left;
if (IsRight(pivot)) return UIWidget.Pivot.Right;
return UIWidget.Pivot.Center;
}
static UIWidget.Pivot GetVertical (UIWidget.Pivot pivot)
{
if (IsTop(pivot)) return UIWidget.Pivot.Top;
if (IsBottom(pivot)) return UIWidget.Pivot.Bottom;
return UIWidget.Pivot.Center;
}
static UIWidget.Pivot Combine (UIWidget.Pivot horizontal, UIWidget.Pivot vertical)
{
if (horizontal == UIWidget.Pivot.Left)
{
if (vertical == UIWidget.Pivot.Top) return UIWidget.Pivot.TopLeft;
if (vertical == UIWidget.Pivot.Bottom) return UIWidget.Pivot.BottomLeft;
return UIWidget.Pivot.Left;
}
if (horizontal == UIWidget.Pivot.Right)
{
if (vertical == UIWidget.Pivot.Top) return UIWidget.Pivot.TopRight;
if (vertical == UIWidget.Pivot.Bottom) return UIWidget.Pivot.BottomRight;
return UIWidget.Pivot.Right;
}
return vertical;
}
void SetPivot (UIWidget.Pivot pivot, bool isHorizontal)
{
UIWidget.Pivot horizontal = GetHorizontal(mWidget.pivot);
UIWidget.Pivot vertical = GetVertical(mWidget.pivot);
pivot = isHorizontal ? Combine(pivot, vertical) : Combine(horizontal, pivot);
if (mWidget.pivot != pivot)
{
NGUIEditorTools.RegisterUndo("Pivot change", mWidget);
mWidget.pivot = pivot;
}
}
protected override void OnDrawFinalProperties ()
{
if (mAnchorType == AnchorType.Advanced || !mWidget.isAnchored) return;
SerializedProperty sp = serializedObject.FindProperty("leftAnchor.target");
if (!IsRect(sp))
{
GUILayout.Space(3f);
GUILayout.BeginHorizontal();
GUILayout.Space(6f);
NGUIEditorTools.DrawProperty("", serializedObject, "hideIfOffScreen", GUILayout.Width(18f));
GUILayout.Label("Hide if off-screen", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIWidgetInspector.cs
|
C#
|
asf20
| 32,311
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit UITextures.
/// </summary>
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UITexture))]
#else
[CustomEditor(typeof(UITexture), true)]
#endif
public class UITextureInspector : UIWidgetInspector
{
UITexture mTex;
protected override void OnEnable ()
{
base.OnEnable();
mTex = target as UITexture;
}
protected override bool ShouldDrawProperties ()
{
SerializedProperty sp = NGUIEditorTools.DrawProperty("Texture", serializedObject, "mTexture");
NGUIEditorTools.DrawProperty("Material", serializedObject, "mMat");
NGUISettings.texture = sp.objectReferenceValue as Texture;
if (mTex.material == null || serializedObject.isEditingMultipleObjects)
{
NGUIEditorTools.DrawProperty("Shader", serializedObject, "mShader");
}
NGUIEditorTools.DrawPaddedProperty("Flip", serializedObject, "mFlip");
EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
if (mTex.mainTexture != null)
{
Rect rect = EditorGUILayout.RectField("UV Rectangle", mTex.uvRect);
if (rect != mTex.uvRect)
{
NGUIEditorTools.RegisterUndo("UV Rectangle Change", mTex);
mTex.uvRect = rect;
}
}
EditorGUI.EndDisabledGroup();
return true;
}
/// <summary>
/// Allow the texture to be previewed.
/// </summary>
public override bool HasPreviewGUI ()
{
return (mTex != null) && (mTex.mainTexture as Texture2D != null);
}
/// <summary>
/// Draw the sprite preview.
/// </summary>
public override void OnPreviewGUI (Rect rect, GUIStyle background)
{
Texture2D tex = mTex.mainTexture as Texture2D;
if (tex != null) NGUIEditorTools.DrawTexture(tex, rect, mTex.uvRect, mTex.color);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UITextureInspector.cs
|
C#
|
asf20
| 2,033
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(UIScrollView))]
public class UIScrollViewEditor : Editor
{
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(130f);
GUILayout.Space(3f);
serializedObject.Update();
SerializedProperty sppv = serializedObject.FindProperty("contentPivot");
UIWidget.Pivot before = (UIWidget.Pivot)sppv.intValue;
NGUIEditorTools.DrawProperty("Content Origin", sppv, false);
SerializedProperty sp = NGUIEditorTools.DrawProperty("Movement", serializedObject, "movement");
if (((UIScrollView.Movement)sp.intValue) == UIScrollView.Movement.Custom)
{
NGUIEditorTools.SetLabelWidth(20f);
GUILayout.BeginHorizontal();
GUILayout.Space(114f);
NGUIEditorTools.DrawProperty("X", serializedObject, "customMovement.x", GUILayout.MinWidth(20f));
NGUIEditorTools.DrawProperty("Y", serializedObject, "customMovement.y", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
}
NGUIEditorTools.SetLabelWidth(130f);
NGUIEditorTools.DrawProperty("Drag Effect", serializedObject, "dragEffect");
NGUIEditorTools.DrawProperty("Scroll Wheel Factor", serializedObject, "scrollWheelFactor");
NGUIEditorTools.DrawProperty("Momentum Amount", serializedObject, "momentumAmount");
NGUIEditorTools.DrawProperty("Restrict Within Panel", serializedObject, "restrictWithinPanel");
NGUIEditorTools.DrawProperty("Cancel Drag If Fits", serializedObject, "disableDragIfFits");
NGUIEditorTools.DrawProperty("Smooth Drag Start", serializedObject, "smoothDragStart");
NGUIEditorTools.DrawProperty("IOS Drag Emulation", serializedObject, "iOSDragEmulation");
NGUIEditorTools.SetLabelWidth(100f);
if (NGUIEditorTools.DrawHeader("Scroll Bars"))
{
NGUIEditorTools.BeginContents();
NGUIEditorTools.DrawProperty("Horizontal", serializedObject, "horizontalScrollBar");
NGUIEditorTools.DrawProperty("Vertical", serializedObject, "verticalScrollBar");
NGUIEditorTools.DrawProperty("Show Condition", serializedObject, "showScrollBars");
NGUIEditorTools.EndContents();
}
serializedObject.ApplyModifiedProperties();
if (before != (UIWidget.Pivot)sppv.intValue)
{
(target as UIScrollView).ResetPosition();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIScrollViewEditor.cs
|
C#
|
asf20
| 2,404
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Editor class used to view UIRects.
/// </summary>
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIRect))]
#else
[CustomEditor(typeof(UIRect), true)]
#endif
public class UIRectEditor : Editor
{
static protected string[] PrefixName = new string[] { "Left", "Right", "Bottom", "Top" };
static protected string[] FieldName = new string[] { "leftAnchor", "rightAnchor", "bottomAnchor", "topAnchor" };
static protected string[] HorizontalList = new string[] { "Target's Left", "Target's Center", "Target's Right", "Custom", "Set to Current Position" };
static protected string[] VerticalList = new string[] { "Target's Bottom", "Target's Center", "Target's Top", "Custom", "Set to Current Position" };
static protected bool[] IsHorizontal = new bool[] { true, true, false, false };
protected enum AnchorType
{
None,
Unified,
Advanced,
}
protected AnchorType mAnchorType = AnchorType.None;
protected Transform[] mTarget = new Transform[4];
protected bool[] mCustom = new bool[] { false, false, false, false };
/// <summary>
/// Whether the specified relative offset is a common value (0, 0.5, or 1)
/// </summary>
static protected bool IsCommon (float relative) { return (relative == 0f || relative == 0.5f || relative == 1f); }
/// <summary>
/// Returns 'true' if the specified serialized property reference is a UIRect.
/// </summary>
static protected bool IsRect (SerializedProperty sp)
{
if (sp.hasMultipleDifferentValues) return true;
return (GetRect(sp) != null);
}
/// <summary>
/// Pass something like leftAnchor.target to get its rectangle reference.
/// </summary>
static protected UIRect GetRect (SerializedProperty sp)
{
Transform target = sp.objectReferenceValue as Transform;
if (target == null) return null;
return target.GetComponent<UIRect>();
}
/// <summary>
/// Pass something like leftAnchor.target to get its rectangle reference.
/// </summary>
static protected Camera GetCamera (SerializedProperty sp)
{
Transform target = sp.objectReferenceValue as Transform;
if (target == null) return null;
return target.camera;
}
/// <summary>
/// Determine the initial anchor type.
/// </summary>
protected virtual void OnEnable ()
{
if (serializedObject.isEditingMultipleObjects)
{
mAnchorType = AnchorType.Advanced;
}
else
{
ReEvaluateAnchorType();
}
}
/// <summary>
/// Manually re-evaluate the current anchor type.
/// </summary>
protected void ReEvaluateAnchorType ()
{
UIRect rect = target as UIRect;
if (rect.leftAnchor.target == rect.rightAnchor.target &&
rect.leftAnchor.target == rect.bottomAnchor.target &&
rect.leftAnchor.target == rect.topAnchor.target)
{
if (rect.leftAnchor.target == null)
{
mAnchorType = AnchorType.None;
}
else
{
mAnchorType = AnchorType.Unified;
}
}
else mAnchorType = AnchorType.Advanced;
}
/// <summary>
/// Draw the inspector properties.
/// </summary>
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
EditorGUILayout.Space();
serializedObject.Update();
EditorGUI.BeginDisabledGroup(!ShouldDrawProperties());
DrawCustomProperties();
EditorGUI.EndDisabledGroup();
DrawFinalProperties();
serializedObject.ApplyModifiedProperties();
}
protected virtual bool ShouldDrawProperties () { return true; }
protected virtual void DrawCustomProperties () { }
/// <summary>
/// Draw the "Anchors" property block.
/// </summary>
protected virtual void DrawFinalProperties ()
{
if (NGUIEditorTools.DrawHeader("Anchors"))
{
NGUIEditorTools.BeginContents();
NGUIEditorTools.SetLabelWidth(62f);
EditorGUI.BeginDisabledGroup(!((target as UIRect).canBeAnchored));
GUILayout.BeginHorizontal();
AnchorType type = (AnchorType)EditorGUILayout.EnumPopup("Type", mAnchorType);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
SerializedProperty[] tg = new SerializedProperty[4];
for (int i = 0; i < 4; ++i) tg[i] = serializedObject.FindProperty(FieldName[i] + ".target");
if (mAnchorType == AnchorType.None && type != AnchorType.None)
{
if (type == AnchorType.Unified)
{
if (mTarget[0] == null && mTarget[1] == null && mTarget[2] == null && mTarget[3] == null)
{
UIRect rect = target as UIRect;
UIRect parent = NGUITools.FindInParents<UIRect>(rect.cachedTransform.parent);
if (parent != null)
for (int i = 0; i < 4; ++i)
mTarget[i] = parent.cachedTransform;
}
}
for (int i = 0; i < 4; ++i)
{
tg[i].objectReferenceValue = mTarget[i];
mTarget[i] = null;
}
UpdateAnchors(true);
}
if (type != AnchorType.None)
{
NGUIEditorTools.DrawPaddedProperty("Execute", serializedObject, "updateAnchors");
}
if (type == AnchorType.Advanced)
{
DrawAnchor(0, true);
DrawAnchor(1, true);
DrawAnchor(2, true);
DrawAnchor(3, true);
}
else if (type == AnchorType.Unified)
{
DrawSingleAnchorSelection();
DrawAnchor(0, false);
DrawAnchor(1, false);
DrawAnchor(2, false);
DrawAnchor(3, false);
}
else if (type == AnchorType.None && mAnchorType != type)
{
// Save values to make it easy to "go back"
for (int i = 0; i < 4; ++i)
{
mTarget[i] = tg[i].objectReferenceValue as Transform;
tg[i].objectReferenceValue = null;
}
serializedObject.FindProperty("leftAnchor.relative").floatValue = 0f;
serializedObject.FindProperty("bottomAnchor.relative").floatValue = 0f;
serializedObject.FindProperty("rightAnchor.relative").floatValue = 1f;
serializedObject.FindProperty("topAnchor.relative").floatValue = 1f;
}
mAnchorType = type;
OnDrawFinalProperties();
EditorGUI.EndDisabledGroup();
NGUIEditorTools.EndContents();
}
}
protected virtual void OnDrawFinalProperties () { }
/// <summary>
/// Draw a selection for a single target (one target sets all 4 sides)
/// </summary>
protected SerializedProperty DrawSingleAnchorSelection ()
{
SerializedProperty sp = serializedObject.FindProperty("leftAnchor.target");
Object before = sp.objectReferenceValue;
GUILayout.Space(3f);
NGUIEditorTools.DrawProperty("Target", sp, false);
Object after = sp.objectReferenceValue;
serializedObject.FindProperty("rightAnchor.target").objectReferenceValue = after;
serializedObject.FindProperty("bottomAnchor.target").objectReferenceValue = after;
serializedObject.FindProperty("topAnchor.target").objectReferenceValue = after;
if (after != null || sp.hasMultipleDifferentValues)
{
if (before != after && after != null)
UpdateAnchors(true);
}
return sp;
}
/// <summary>
/// Helper function that draws the suffix after the relative fields.
/// </summary>
protected void DrawAnchor (int index, bool targetSelection)
{
if (targetSelection) GUILayout.Space(3f);
NGUIEditorTools.SetLabelWidth(16f);
GUILayout.BeginHorizontal();
GUILayout.Label(PrefixName[index], GUILayout.Width(56f));
UIRect myRect = serializedObject.targetObject as UIRect;
string name = FieldName[index];
SerializedProperty tar = serializedObject.FindProperty(name + ".target");
SerializedProperty rel = serializedObject.FindProperty(name + ".relative");
SerializedProperty abs = serializedObject.FindProperty(name + ".absolute");
if (targetSelection)
{
Object before = tar.objectReferenceValue;
NGUIEditorTools.DrawProperty("", tar, false);
Object after = tar.objectReferenceValue;
if (after != null || tar.hasMultipleDifferentValues)
{
if (before != after && after != null)
UpdateAnchor(index, true);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(64f);
}
UIRect targetRect = GetRect(tar);
Camera targetCam = GetCamera(tar);
float relative = rel.floatValue;
bool isCommon = (targetRect == null && targetCam == null) || IsCommon(relative);
int previousOrigin = 1;
if (targetRect != null || targetCam != null)
{
if (mCustom[index] || !isCommon) previousOrigin = 3;
else if (relative == 0f) previousOrigin = 0;
else if (relative == 1f) previousOrigin = 2;
}
// Draw the origin selection list
EditorGUI.BeginDisabledGroup(targetRect == null && targetCam == null);
int newOrigin = IsHorizontal[index] ?
EditorGUILayout.Popup(previousOrigin, HorizontalList, GUILayout.MinWidth(110f)) :
EditorGUILayout.Popup(previousOrigin, VerticalList, GUILayout.MinWidth(110f));
EditorGUI.EndDisabledGroup();
// "Set to Current" choice
if (newOrigin == 4)
{
newOrigin = 3;
Vector3[] sides = targetRect.GetSides(myRect.cachedTransform);
float f0, f1;
if (IsHorizontal[index])
{
f0 = sides[0].x;
f1 = sides[2].x;
}
else
{
f0 = sides[3].y;
f1 = sides[1].y;
}
// Final position after both relative and absolute values are taken into consideration
float final = Mathf.Floor(0.5f + Mathf.Lerp(0f, f1 - f0, rel.floatValue) + abs.intValue);
rel.floatValue = final / (f1 - f0);
abs.intValue = 0;
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
mCustom[index] = (newOrigin == 3);
// If the origin changes
if (newOrigin != 3 && previousOrigin != newOrigin)
{
// Desired relative value
if (newOrigin == 0) relative = 0f;
else if (newOrigin == 2) relative = 1f;
else relative = 0.5f;
Vector3[] sides = (targetRect != null) ?
targetRect.GetSides(myRect.cachedTransform) :
targetCam.GetSides(myRect.cachedTransform);
// Calculate the current position based from the bottom-left
float f0, f1;
if (IsHorizontal[index])
{
f0 = sides[0].x;
f1 = sides[2].x;
}
else
{
f0 = sides[3].y;
f1 = sides[1].y;
}
// Final position after both relative and absolute values are taken into consideration
float final = Mathf.Floor(0.5f + Mathf.Lerp(f0, f1, rel.floatValue) + abs.intValue);
rel.floatValue = relative;
abs.intValue = Mathf.FloorToInt(final + 0.5f - Mathf.Lerp(f0, f1, relative));
serializedObject.ApplyModifiedProperties();
serializedObject.Update();
}
if (!mCustom[index])
{
// Draw the absolute value
NGUIEditorTools.SetLabelWidth(16f);
NGUIEditorTools.DrawProperty("+", abs, true, GUILayout.MinWidth(10f));
}
else
{
// Draw the relative value
NGUIEditorTools.SetLabelWidth(16f);
NGUIEditorTools.DrawProperty(" ", rel, true, GUILayout.MinWidth(10f));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Space(64f);
relative = rel.floatValue;
bool isOutside01 = relative < 0f || relative > 1f;
// Horizontal slider for relative values, for convenience
EditorGUI.BeginDisabledGroup(isOutside01);
{
float val = GUILayout.HorizontalSlider(relative, 0f, 1f, GUILayout.MinWidth(110f));
if (!isOutside01 && val != relative)
{
Vector3[] sides = (targetRect != null) ?
targetRect.GetSides(myRect.cachedTransform) :
targetCam.GetSides(myRect.cachedTransform);
// Calculate the current position based from the bottom-left
float f0, f1;
if (IsHorizontal[index])
{
f0 = sides[0].x;
f1 = sides[2].x;
}
else
{
f0 = sides[3].y;
f1 = sides[1].y;
}
float size = (f1 - f0);
int intVal = Mathf.FloorToInt(val * size + 0.5f);
//intVal = ((intVal >> 1) << 1);
rel.floatValue = (size > 0f) ? intVal / size : 0.5f;
}
}
EditorGUI.EndDisabledGroup();
// Draw the absolute value
NGUIEditorTools.DrawProperty("+", abs, true, GUILayout.MinWidth(10f));
}
GUILayout.EndHorizontal();
NGUIEditorTools.SetLabelWidth(62f);
}
/// <summary>
/// Convenience function that switches the anchor mode and ensures that dimensions are kept intact.
/// </summary>
protected void UpdateAnchors (bool resetRelative)
{
serializedObject.ApplyModifiedProperties();
Object[] objs = serializedObject.targetObjects;
for (int i = 0; i < objs.Length; ++i)
{
UIRect rect = objs[i] as UIRect;
if (rect)
{
UpdateHorizontalAnchor(rect, rect.leftAnchor, resetRelative);
UpdateHorizontalAnchor(rect, rect.rightAnchor, resetRelative);
UpdateVerticalAnchor(rect, rect.bottomAnchor, resetRelative);
UpdateVerticalAnchor(rect, rect.topAnchor, resetRelative);
NGUITools.SetDirty(rect);
}
}
serializedObject.Update();
}
/// <summary>
/// Convenience function that switches the anchor mode and ensures that dimensions are kept intact.
/// </summary>
protected void UpdateAnchor (int index, bool resetRelative)
{
serializedObject.ApplyModifiedProperties();
Object[] objs = serializedObject.targetObjects;
for (int i = 0; i < objs.Length; ++i)
{
UIRect rect = objs[i] as UIRect;
if (rect)
{
if (index == 0) UpdateHorizontalAnchor(rect, rect.leftAnchor, resetRelative);
if (index == 1) UpdateHorizontalAnchor(rect, rect.rightAnchor, resetRelative);
if (index == 2) UpdateVerticalAnchor(rect, rect.bottomAnchor, resetRelative);
if (index == 3) UpdateVerticalAnchor(rect, rect.topAnchor, resetRelative);
NGUITools.SetDirty(rect);
}
}
serializedObject.Update();
}
/// <summary>
/// Convenience function that switches the anchor mode and ensures that dimensions are kept intact.
/// </summary>
static public void UpdateHorizontalAnchor (UIRect r, UIRect.AnchorPoint anchor, bool resetRelative)
{
// Update the target
if (anchor.target == null) return;
// Update the rect
anchor.rect = anchor.target.GetComponent<UIRect>();
// Continue only if we have a parent to work with
Transform parent = r.cachedTransform.parent;
if (parent == null) return;
bool inverted = (anchor == r.rightAnchor);
int i0 = inverted ? 2 : 0;
int i1 = inverted ? 3 : 1;
// Calculate the left side
Vector3[] myCorners = r.worldCorners;
Vector3 localPos = parent.InverseTransformPoint(Vector3.Lerp(myCorners[i0], myCorners[i1], 0.5f));
if (anchor.rect != null)
{
// Anchored to a rectangle -- must anchor to the same side
Vector3[] targetCorners = anchor.rect.worldCorners;
// We want to choose the side with the shortest offset
Vector3 side0 = parent.InverseTransformPoint(Vector3.Lerp(targetCorners[0], targetCorners[1], 0.5f));
Vector3 side1 = parent.InverseTransformPoint(Vector3.Lerp(targetCorners[2], targetCorners[3], 0.5f));
float val0 = localPos.x - side0.x;
float val2 = localPos.x - side1.x;
if (resetRelative)
{
float val1 = localPos.x - Vector3.Lerp(side0, side1, 0.5f).x;
anchor.SetToNearest(val0, val1, val2);
}
else
{
float val = localPos.x - Vector3.Lerp(side0, side1, anchor.relative).x;
anchor.Set(anchor.relative, val);
}
}
else if (anchor.target.camera != null)
{
Vector3[] sides = anchor.target.camera.GetSides(parent);
Vector3 side0 = sides[0];
Vector3 side1 = sides[2];
float val0 = localPos.x - side0.x;
float val2 = localPos.x - side1.x;
if (resetRelative)
{
float val1 = localPos.x - Vector3.Lerp(side0, side1, 0.5f).x;
anchor.SetToNearest(val0, val1, val2);
}
else
{
float val = localPos.x - Vector3.Lerp(side0, side1, anchor.relative).x;
anchor.Set(anchor.relative, val);
}
}
else
{
// Anchored to a simple transform
Vector3 remotePos = anchor.target.position;
if (anchor.targetCam != null) remotePos = anchor.targetCam.WorldToViewportPoint(remotePos);
if (r.anchorCamera != null) remotePos = r.anchorCamera.ViewportToWorldPoint(remotePos);
remotePos = parent.InverseTransformPoint(remotePos);
anchor.absolute = Mathf.FloorToInt(localPos.x - remotePos.x + 0.5f);
anchor.relative = inverted ? 1f : 0f;
}
}
/// <summary>
/// Convenience function that switches the anchor mode and ensures that dimensions are kept intact.
/// </summary>
static public void UpdateVerticalAnchor (UIRect r, UIRect.AnchorPoint anchor, bool resetRelative)
{
// Update the target
if (anchor.target == null) return;
// Update the rect
anchor.rect = anchor.target.GetComponent<UIRect>();
// Continue only if we have a parent to work with
Transform parent = r.cachedTransform.parent;
if (parent == null) return;
bool inverted = (anchor == r.topAnchor);
int i0 = inverted ? 1 : 0;
int i1 = inverted ? 2 : 3;
// Calculate the bottom side
Vector3[] myCorners = r.worldCorners;
Vector3 localPos = parent.InverseTransformPoint(Vector3.Lerp(myCorners[i0], myCorners[i1], 0.5f));
if (anchor.rect != null)
{
// Anchored to a rectangle -- must anchor to the same side
Vector3[] targetCorners = anchor.rect.worldCorners;
// We want to choose the side with the shortest offset
Vector3 side0 = parent.InverseTransformPoint(Vector3.Lerp(targetCorners[0], targetCorners[3], 0.5f));
Vector3 side1 = parent.InverseTransformPoint(Vector3.Lerp(targetCorners[1], targetCorners[2], 0.5f));
float val0 = localPos.y - side0.y;
float val2 = localPos.y - side1.y;
if (resetRelative)
{
float val1 = localPos.y - Vector3.Lerp(side0, side1, 0.5f).y;
anchor.SetToNearest(val0, val1, val2);
}
else
{
float val = localPos.y - Vector3.Lerp(side0, side1, anchor.relative).y;
anchor.Set(anchor.relative, val);
}
}
else if (anchor.target.camera != null)
{
Vector3[] sides = anchor.target.camera.GetSides(parent);
Vector3 side0 = sides[3];
Vector3 side1 = sides[1];
float val0 = localPos.y - side0.y;
float val2 = localPos.y - side1.y;
if (resetRelative)
{
float val1 = localPos.y - Vector3.Lerp(side0, side1, 0.5f).y;
anchor.SetToNearest(val0, val1, val2);
}
else
{
float val = localPos.y - Vector3.Lerp(side0, side1, anchor.relative).y;
anchor.Set(anchor.relative, val);
}
}
else
{
// Anchored to a simple transform
Vector3 remotePos = anchor.target.position;
if (anchor.targetCam != null) remotePos = anchor.targetCam.WorldToViewportPoint(remotePos);
if (r.anchorCamera != null) remotePos = r.anchorCamera.ViewportToWorldPoint(remotePos);
remotePos = parent.InverseTransformPoint(remotePos);
anchor.absolute = Mathf.FloorToInt(localPos.y - remotePos.y + 0.5f);
anchor.relative = inverted ? 1f : 0f;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIRectEditor.cs
|
C#
|
asf20
| 18,517
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Text;
/// <summary>
/// Helper class that takes care of loading BMFont's glyph information from the specified byte array.
/// This functionality is not a part of BMFont anymore because Flash export option can't handle System.IO functions.
/// </summary>
public static class BMFontReader
{
/// <summary>
/// Helper function that retrieves the string value of the key=value pair.
/// </summary>
static string GetString (string s)
{
int idx = s.IndexOf('=');
return (idx == -1) ? "" : s.Substring(idx + 1);
}
/// <summary>
/// Helper function that retrieves the integer value of the key=value pair.
/// </summary>
static int GetInt (string s)
{
int val = 0;
string text = GetString(s);
#if UNITY_FLASH
try { val = int.Parse(text); } catch (System.Exception) { }
#else
int.TryParse(text, out val);
#endif
return val;
}
/// <summary>
/// Reload the font data.
/// </summary>
static public void Load (BMFont font, string name, byte[] bytes)
{
font.Clear();
if (bytes != null)
{
ByteReader reader = new ByteReader(bytes);
char[] separator = new char[] { ' ' };
while (reader.canRead)
{
string line = reader.ReadLine();
if (string.IsNullOrEmpty(line)) break;
string[] split = line.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
int len = split.Length;
if (split[0] == "char")
{
// Expected data style:
// char id=13 x=506 y=62 width=3 height=3 xoffset=-1 yoffset=50 xadvance=0 page=0 chnl=15
int channel = (len > 10) ? GetInt(split[10]) : 15;
if (len > 9 && GetInt(split[9]) > 0)
{
Debug.LogError("Your font was exported with more than one texture. Only one texture is supported by NGUI.\n" +
"You need to re-export your font, enlarging the texture's dimensions until everything fits into just one texture.");
break;
}
if (len > 8)
{
int id = GetInt(split[1]);
BMGlyph glyph = font.GetGlyph(id, true);
if (glyph != null)
{
glyph.x = GetInt(split[2]);
glyph.y = GetInt(split[3]);
glyph.width = GetInt(split[4]);
glyph.height = GetInt(split[5]);
glyph.offsetX = GetInt(split[6]);
glyph.offsetY = GetInt(split[7]);
glyph.advance = GetInt(split[8]);
glyph.channel = channel;
}
else Debug.Log("Char: " + split[1] + " (" + id + ") is NULL");
}
else
{
Debug.LogError("Unexpected number of entries for the 'char' field (" + name + ", " + split.Length + "):\n" + line);
break;
}
}
else if (split[0] == "kerning")
{
// Expected data style:
// kerning first=84 second=244 amount=-5
if (len > 3)
{
int first = GetInt(split[1]);
int second = GetInt(split[2]);
int amount = GetInt(split[3]);
BMGlyph glyph = font.GetGlyph(second, true);
if (glyph != null) glyph.SetKerning(first, amount);
}
else
{
Debug.LogError("Unexpected number of entries for the 'kerning' field (" +
name + ", " + split.Length + "):\n" + line);
break;
}
}
else if (split[0] == "common")
{
// Expected data style:
// common lineHeight=64 base=51 scaleW=512 scaleH=512 pages=1 packed=0 alphaChnl=1 redChnl=4 greenChnl=4 blueChnl=4
if (len > 5)
{
font.charSize = GetInt(split[1]);
font.baseOffset = GetInt(split[2]);
font.texWidth = GetInt(split[3]);
font.texHeight = GetInt(split[4]);
int pages = GetInt(split[5]);
if (pages != 1)
{
Debug.LogError("Font '" + name + "' must be created with only 1 texture, not " + pages);
break;
}
}
else
{
Debug.LogError("Unexpected number of entries for the 'common' field (" +
name + ", " + split.Length + "):\n" + line);
break;
}
}
else if (split[0] == "page")
{
// Expected data style:
// page id=0 file="textureName.png"
if (len > 2)
{
font.spriteName = GetString(split[2]).Replace("\"", "");
font.spriteName = font.spriteName.Replace(".png", "");
font.spriteName = font.spriteName.Replace(".tga", "");
}
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/BMFontReader.cs
|
C#
|
asf20
| 4,436
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UICamera))]
public class UICameraEditor : Editor
{
public override void OnInspectorGUI ()
{
UICamera cam = target as UICamera;
GUILayout.Space(3f);
serializedObject.Update();
if (UICamera.eventHandler != cam)
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("eventType"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("eventReceiverMask"), new GUIContent("Event Mask"));
serializedObject.ApplyModifiedProperties();
EditorGUILayout.HelpBox("All other settings are inherited from the First Camera.", MessageType.Info);
if (GUILayout.Button("Select the First Camera"))
{
Selection.activeGameObject = UICamera.eventHandler.gameObject;
}
}
else
{
SerializedProperty mouse = serializedObject.FindProperty("useMouse");
SerializedProperty touch = serializedObject.FindProperty("useTouch");
SerializedProperty keyboard = serializedObject.FindProperty("useKeyboard");
SerializedProperty controller = serializedObject.FindProperty("useController");
EditorGUILayout.PropertyField(serializedObject.FindProperty("eventType"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("eventReceiverMask"), new GUIContent("Event Mask"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("debug"));
EditorGUI.BeginDisabledGroup(!mouse.boolValue && !touch.boolValue);
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("allowMultiTouch"));
}
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(!mouse.boolValue);
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("stickyTooltip"));
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(serializedObject.FindProperty("tooltipDelay"));
GUILayout.Label("seconds", GUILayout.MinWidth(60f));
GUILayout.EndHorizontal();
}
EditorGUI.EndDisabledGroup();
GUILayout.BeginHorizontal();
SerializedProperty rd = serializedObject.FindProperty("rangeDistance");
EditorGUILayout.PropertyField(rd, new GUIContent("Raycast Range"));
GUILayout.Label(rd.floatValue < 0f ? "unlimited" : "units", GUILayout.MinWidth(60f));
GUILayout.EndHorizontal();
NGUIEditorTools.SetLabelWidth(80f);
if (NGUIEditorTools.DrawHeader("Event Sources"))
{
NGUIEditorTools.BeginContents();
{
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(mouse, new GUIContent("Mouse"), GUILayout.MinWidth(100f));
EditorGUILayout.PropertyField(touch, new GUIContent("Touch"), GUILayout.MinWidth(100f));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(keyboard, new GUIContent("Keyboard"), GUILayout.MinWidth(100f));
EditorGUILayout.PropertyField(controller, new GUIContent("Controller"), GUILayout.MinWidth(100f));
GUILayout.EndHorizontal();
}
NGUIEditorTools.EndContents();
}
if ((mouse.boolValue || touch.boolValue) && NGUIEditorTools.DrawHeader("Thresholds"))
{
NGUIEditorTools.BeginContents();
{
EditorGUI.BeginDisabledGroup(!mouse.boolValue);
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(serializedObject.FindProperty("mouseDragThreshold"), new GUIContent("Mouse Drag"), GUILayout.Width(120f));
GUILayout.Label("pixels");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(serializedObject.FindProperty("mouseClickThreshold"), new GUIContent("Mouse Click"), GUILayout.Width(120f));
GUILayout.Label("pixels");
GUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(!touch.boolValue);
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(serializedObject.FindProperty("touchDragThreshold"), new GUIContent("Touch Drag"), GUILayout.Width(120f));
GUILayout.Label("pixels");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(serializedObject.FindProperty("touchClickThreshold"), new GUIContent("Touch Tap"), GUILayout.Width(120f));
GUILayout.Label("pixels");
GUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
}
NGUIEditorTools.EndContents();
}
if ((mouse.boolValue || keyboard.boolValue || controller.boolValue) && NGUIEditorTools.DrawHeader("Axes and Keys"))
{
NGUIEditorTools.BeginContents();
{
EditorGUILayout.PropertyField(serializedObject.FindProperty("horizontalAxisName"), new GUIContent("Horizontal"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("verticalAxisName"), new GUIContent("Vertical"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("scrollAxisName"), new GUIContent("Scroll"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("submitKey0"), new GUIContent("Submit 1"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("submitKey1"), new GUIContent("Submit 2"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("cancelKey0"), new GUIContent("Cancel 1"));
EditorGUILayout.PropertyField(serializedObject.FindProperty("cancelKey1"), new GUIContent("Cancel 2"));
}
NGUIEditorTools.EndContents();
}
serializedObject.ApplyModifiedProperties();
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UICameraEditor.cs
|
C#
|
asf20
| 5,531
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
/// <summary>
/// Widget containers are classes that are meant to hold more than one widget inside, but should still be easily movable using the mouse.
/// </summary>
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIWidgetContainer))]
#else
[CustomEditor(typeof(UIWidgetContainer), true)]
#endif
public class UIWidgetContainerEditor : Editor
{
static int mHash = "WidgetContainer".GetHashCode();
Vector3 mStartPos = Vector3.zero;
Vector3 mStartDrag = Vector3.zero;
Vector2 mStartMouse = Vector2.zero;
bool mCanDrag = false;
bool mAllowSelection = true;
bool mIsDragging = false;
void OnDisable () { NGUIEditorTools.HideMoveTool(false); }
/// <summary>
/// Make it possible to easily drag the transform around.
/// </summary>
public void OnSceneGUI ()
{
NGUIEditorTools.HideMoveTool(true);
if (!UIWidget.showHandles) return;
if (UnityEditor.Tools.current != Tool.Move) return;
MonoBehaviour mb = target as MonoBehaviour;
if (mb.GetComponent<UIWidget>() != null) return;
if (mb.GetComponent<UIPanel>() != null) return;
Transform t = mb.transform;
UIWidget[] widgets = t.GetComponentsInChildren<UIWidget>();
Event e = Event.current;
int id = GUIUtility.GetControlID(mHash, FocusType.Passive);
EventType type = e.GetTypeForControl(id);
bool isWithinRect = false;
Vector3[] corners = null;
Vector3[] handles = null;
if (widgets.Length > 0)
{
Matrix4x4 worldToLocal = t.worldToLocalMatrix;
Matrix4x4 localToWorld = t.localToWorldMatrix;
Bounds bounds = new Bounds();
// Calculate the local bounds
for (int i = 0; i < widgets.Length; ++i)
{
Vector3[] wcs = widgets[i].worldCorners;
for (int b = 0; b < 4; ++b)
{
wcs[b] = worldToLocal.MultiplyPoint3x4(wcs[b]);
if (i == 0 && b == 0) bounds = new Bounds(wcs[b], Vector3.zero);
else bounds.Encapsulate(wcs[b]);
}
}
// Calculate the 4 local corners
Vector3 v0 = bounds.min;
Vector3 v1 = bounds.max;
float z = Mathf.Min(v0.z, v1.z);
corners = new Vector3[4];
corners[0] = new Vector3(v0.x, v0.y, z);
corners[1] = new Vector3(v0.x, v1.y, z);
corners[2] = new Vector3(v1.x, v1.y, z);
corners[3] = new Vector3(v1.x, v0.y, z);
// Transform the 4 corners into world space
for (int i = 0; i < 4; ++i)
corners[i] = localToWorld.MultiplyPoint3x4(corners[i]);
handles = new Vector3[8];
handles[0] = corners[0];
handles[1] = corners[1];
handles[2] = corners[2];
handles[3] = corners[3];
handles[4] = (corners[0] + corners[1]) * 0.5f;
handles[5] = (corners[1] + corners[2]) * 0.5f;
handles[6] = (corners[2] + corners[3]) * 0.5f;
handles[7] = (corners[0] + corners[3]) * 0.5f;
Color handlesColor = UIWidgetInspector.handlesColor;
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);
isWithinRect = mIsDragging || (e.modifiers == 0 &&
NGUIEditorTools.SceneViewDistanceToRectangle(corners, e.mousePosition) == 0f);
#if !UNITY_3_5
// Change the mouse cursor to a more appropriate one
Vector2[] screenPos = new Vector2[8];
for (int i = 0; i < 8; ++i) screenPos[i] = HandleUtility.WorldToGUIPoint(handles[i]);
bounds = new Bounds(screenPos[0], Vector3.zero);
for (int i = 1; i < 8; ++i) bounds.Encapsulate(screenPos[i]);
// Change the cursor to a move arrow when it's within the screen rectangle
Vector2 min = bounds.min;
Vector2 max = bounds.max;
Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
UIWidgetInspector.SetCursorRect(rect, isWithinRect ? MouseCursor.MoveArrow : MouseCursor.Arrow);
#endif
}
switch (type)
{
case EventType.Repaint:
{
if (handles != null)
{
Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);
if ((v2 - v0).magnitude > 60f)
{
Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);
Handles.BeginGUI();
{
for (int i = 0; i < 4; ++i)
UIWidgetInspector.DrawKnob(handles[i], false, false, id);
if (Mathf.Abs(v1.y - v0.y) > 80f)
{
UIWidgetInspector.DrawKnob(handles[4], false, false, id);
UIWidgetInspector.DrawKnob(handles[6], false, false, id);
}
if (Mathf.Abs(v3.x - v0.x) > 80f)
{
UIWidgetInspector.DrawKnob(handles[5], false, false, id);
UIWidgetInspector.DrawKnob(handles[7], false, false, id);
}
}
Handles.EndGUI();
}
}
}
break;
case EventType.MouseDown:
{
mAllowSelection = true;
mStartMouse = e.mousePosition;
if (e.button == 1 && isWithinRect)
{
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
else if (e.button == 0 && isWithinRect && corners != null && UIWidgetInspector.Raycast(corners, out mStartDrag))
{
mCanDrag = true;
mStartPos = t.position;
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
}
break;
case EventType.MouseDrag:
{
// Prevent selection once the drag operation begins
bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
if (dragStarted) mAllowSelection = false;
if (GUIUtility.hotControl == id)
{
e.Use();
if (mCanDrag)
{
Vector3 pos;
if (corners != null & UIWidgetInspector.Raycast(corners, out pos))
{
// Wait until the mouse moves by more than a few pixels
if (!mIsDragging && dragStarted)
{
NGUIEditorTools.RegisterUndo("Move " + t.name, t);
mStartPos = t.position;
mIsDragging = true;
}
if (mIsDragging)
{
t.position = mStartPos + (pos - mStartDrag);
pos = t.localPosition;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = Mathf.Round(pos.z);
t.localPosition = pos;
}
}
}
}
}
break;
case EventType.MouseUp:
{
if (GUIUtility.hotControl == id)
{
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
if (e.button == 0)
{
if (mIsDragging)
{
mIsDragging = false;
Vector3 pos = t.localPosition;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = Mathf.Round(pos.z);
t.localPosition = pos;
}
else if (mAllowSelection)
{
// Left-click: Select the topmost widget
NGUIEditorTools.SelectWidget(e.mousePosition);
e.Use();
}
e.Use();
}
else
{
// Right-click: Open a context menu listing all widgets underneath
NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
e.Use();
}
mCanDrag = false;
}
}
break;
case EventType.KeyDown:
{
if (e.keyCode == KeyCode.UpArrow)
{
Vector3 pos = t.localPosition;
pos.y += 1f;
t.localPosition = pos;
e.Use();
}
else if (e.keyCode == KeyCode.DownArrow)
{
Vector3 pos = t.localPosition;
pos.y -= 1f;
t.localPosition = pos;
e.Use();
}
else if (e.keyCode == KeyCode.LeftArrow)
{
Vector3 pos = t.localPosition;
pos.x -= 1f;
t.localPosition = pos;
e.Use();
}
else if (e.keyCode == KeyCode.RightArrow)
{
Vector3 pos = t.localPosition;
pos.x += 1f;
t.localPosition = pos;
e.Use();
}
else if (e.keyCode == KeyCode.Escape)
{
if (GUIUtility.hotControl == id)
{
if (mIsDragging)
{
mIsDragging = false;
t.position = mStartPos;
}
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
e.Use();
}
else
{
Selection.activeGameObject = null;
}
}
}
break;
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIWidgetContainerEditor.cs
|
C#
|
asf20
| 8,301
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
/// <summary>
/// Tools for the editor
/// </summary>
public class NGUIEditorTools
{
static Texture2D mBackdropTex;
static Texture2D mContrastTex;
static Texture2D mGradientTex;
static GameObject mPrevious;
/// <summary>
/// Returns a blank usable 1x1 white texture.
/// </summary>
static public Texture2D blankTexture
{
get
{
return EditorGUIUtility.whiteTexture;
}
}
/// <summary>
/// Returns a usable texture that looks like a dark checker board.
/// </summary>
static public Texture2D backdropTexture
{
get
{
if (mBackdropTex == null) mBackdropTex = CreateCheckerTex(
new Color(0.1f, 0.1f, 0.1f, 0.5f),
new Color(0.2f, 0.2f, 0.2f, 0.5f));
return mBackdropTex;
}
}
/// <summary>
/// Returns a usable texture that looks like a high-contrast checker board.
/// </summary>
static public Texture2D contrastTexture
{
get
{
if (mContrastTex == null) mContrastTex = CreateCheckerTex(
new Color(0f, 0.0f, 0f, 0.5f),
new Color(1f, 1f, 1f, 0.5f));
return mContrastTex;
}
}
/// <summary>
/// Gradient texture is used for title bars / headers.
/// </summary>
static public Texture2D gradientTexture
{
get
{
if (mGradientTex == null) mGradientTex = CreateGradientTex();
return mGradientTex;
}
}
/// <summary>
/// Create a white dummy texture.
/// </summary>
static Texture2D CreateDummyTex ()
{
Texture2D tex = new Texture2D(1, 1);
tex.name = "[Generated] Dummy Texture";
tex.hideFlags = HideFlags.DontSave;
tex.filterMode = FilterMode.Point;
tex.SetPixel(0, 0, Color.white);
tex.Apply();
return tex;
}
/// <summary>
/// Create a checker-background texture
/// </summary>
static Texture2D CreateCheckerTex (Color c0, Color c1)
{
Texture2D tex = new Texture2D(16, 16);
tex.name = "[Generated] Checker Texture";
tex.hideFlags = HideFlags.DontSave;
for (int y = 0; y < 8; ++y) for (int x = 0; x < 8; ++x) tex.SetPixel(x, y, c1);
for (int y = 8; y < 16; ++y) for (int x = 0; x < 8; ++x) tex.SetPixel(x, y, c0);
for (int y = 0; y < 8; ++y) for (int x = 8; x < 16; ++x) tex.SetPixel(x, y, c0);
for (int y = 8; y < 16; ++y) for (int x = 8; x < 16; ++x) tex.SetPixel(x, y, c1);
tex.Apply();
tex.filterMode = FilterMode.Point;
return tex;
}
/// <summary>
/// Create a gradient texture
/// </summary>
static Texture2D CreateGradientTex ()
{
Texture2D tex = new Texture2D(1, 16);
tex.name = "[Generated] Gradient Texture";
tex.hideFlags = HideFlags.DontSave;
Color c0 = new Color(1f, 1f, 1f, 0f);
Color c1 = new Color(1f, 1f, 1f, 0.4f);
for (int i = 0; i < 16; ++i)
{
float f = Mathf.Abs((i / 15f) * 2f - 1f);
f *= f;
tex.SetPixel(0, i, Color.Lerp(c0, c1, f));
}
tex.Apply();
tex.filterMode = FilterMode.Bilinear;
return tex;
}
/// <summary>
/// Draws the tiled texture. Like GUI.DrawTexture() but tiled instead of stretched.
/// </summary>
static public void DrawTiledTexture (Rect rect, Texture tex)
{
GUI.BeginGroup(rect);
{
int width = Mathf.RoundToInt(rect.width);
int height = Mathf.RoundToInt(rect.height);
for (int y = 0; y < height; y += tex.height)
{
for (int x = 0; x < width; x += tex.width)
{
GUI.DrawTexture(new Rect(x, y, tex.width, tex.height), tex);
}
}
}
GUI.EndGroup();
}
/// <summary>
/// Draw a single-pixel outline around the specified rectangle.
/// </summary>
static public void DrawOutline (Rect rect)
{
if (Event.current.type == EventType.Repaint)
{
Texture2D tex = contrastTexture;
GUI.color = Color.white;
DrawTiledTexture(new Rect(rect.xMin, rect.yMax, 1f, -rect.height), tex);
DrawTiledTexture(new Rect(rect.xMax, rect.yMax, 1f, -rect.height), tex);
DrawTiledTexture(new Rect(rect.xMin, rect.yMin, rect.width, 1f), tex);
DrawTiledTexture(new Rect(rect.xMin, rect.yMax, rect.width, 1f), tex);
}
}
/// <summary>
/// Draw a single-pixel outline around the specified rectangle.
/// </summary>
static public void DrawOutline (Rect rect, Color color)
{
if (Event.current.type == EventType.Repaint)
{
Texture2D tex = blankTexture;
GUI.color = color;
GUI.DrawTexture(new Rect(rect.xMin, rect.yMin, 1f, rect.height), tex);
GUI.DrawTexture(new Rect(rect.xMax, rect.yMin, 1f, rect.height), tex);
GUI.DrawTexture(new Rect(rect.xMin, rect.yMin, rect.width, 1f), tex);
GUI.DrawTexture(new Rect(rect.xMin, rect.yMax, rect.width, 1f), tex);
GUI.color = Color.white;
}
}
/// <summary>
/// Draw a selection outline around the specified rectangle.
/// </summary>
static public void DrawOutline (Rect rect, Rect relative, Color color)
{
if (Event.current.type == EventType.Repaint)
{
// Calculate where the outer rectangle would be
float x = rect.xMin + rect.width * relative.xMin;
float y = rect.yMax - rect.height * relative.yMin;
float width = rect.width * relative.width;
float height = -rect.height * relative.height;
relative = new Rect(x, y, width, height);
// Draw the selection
DrawOutline(relative, color);
}
}
/// <summary>
/// Draw a selection outline around the specified rectangle.
/// </summary>
static public void DrawOutline (Rect rect, Rect relative)
{
if (Event.current.type == EventType.Repaint)
{
// Calculate where the outer rectangle would be
float x = rect.xMin + rect.width * relative.xMin;
float y = rect.yMax - rect.height * relative.yMin;
float width = rect.width * relative.width;
float height = -rect.height * relative.height;
relative = new Rect(x, y, width, height);
// Draw the selection
DrawOutline(relative);
}
}
/// <summary>
/// Draw a 9-sliced outline.
/// </summary>
static public void DrawOutline (Rect rect, Rect outer, Rect inner)
{
if (Event.current.type == EventType.Repaint)
{
Color green = new Color(0.4f, 1f, 0f, 1f);
DrawOutline(rect, new Rect(outer.x, inner.y, outer.width, inner.height));
DrawOutline(rect, new Rect(inner.x, outer.y, inner.width, outer.height));
DrawOutline(rect, outer, green);
}
}
/// <summary>
/// Draw a checkered background for the specified texture.
/// </summary>
static public Rect DrawBackground (Texture2D tex, float ratio)
{
Rect rect = GUILayoutUtility.GetRect(0f, 0f);
rect.width = Screen.width - rect.xMin;
rect.height = rect.width * ratio;
GUILayout.Space(rect.height);
if (Event.current.type == EventType.Repaint)
{
Texture2D blank = blankTexture;
Texture2D check = backdropTexture;
// Lines above and below the texture rectangle
GUI.color = new Color(0f, 0f, 0f, 0.2f);
GUI.DrawTexture(new Rect(rect.xMin, rect.yMin - 1, rect.width, 1f), blank);
GUI.DrawTexture(new Rect(rect.xMin, rect.yMax, rect.width, 1f), blank);
GUI.color = Color.white;
// Checker background
DrawTiledTexture(rect, check);
}
return rect;
}
/// <summary>
/// Draw a visible separator in addition to adding some padding.
/// </summary>
static public void DrawSeparator ()
{
GUILayout.Space(12f);
if (Event.current.type == EventType.Repaint)
{
Texture2D tex = blankTexture;
Rect rect = GUILayoutUtility.GetLastRect();
GUI.color = new Color(0f, 0f, 0f, 0.25f);
GUI.DrawTexture(new Rect(0f, rect.yMin + 6f, Screen.width, 4f), tex);
GUI.DrawTexture(new Rect(0f, rect.yMin + 6f, Screen.width, 1f), tex);
GUI.DrawTexture(new Rect(0f, rect.yMin + 9f, Screen.width, 1f), tex);
GUI.color = Color.white;
}
}
/// <summary>
/// Convenience function that displays a list of sprites and returns the selected value.
/// </summary>
static public string DrawList (string field, string[] list, string selection, params GUILayoutOption[] options)
{
if (list != null && list.Length > 0)
{
int index = 0;
if (string.IsNullOrEmpty(selection)) selection = list[0];
// We need to find the sprite in order to have it selected
if (!string.IsNullOrEmpty(selection))
{
for (int i = 0; i < list.Length; ++i)
{
if (selection.Equals(list[i], System.StringComparison.OrdinalIgnoreCase))
{
index = i;
break;
}
}
}
// Draw the sprite selection popup
index = string.IsNullOrEmpty(field) ?
EditorGUILayout.Popup(index, list, options) :
EditorGUILayout.Popup(field, index, list, options);
return list[index];
}
return null;
}
/// <summary>
/// Convenience function that displays a list of sprites and returns the selected value.
/// </summary>
static public string DrawAdvancedList (string field, string[] list, string selection, params GUILayoutOption[] options)
{
if (list != null && list.Length > 0)
{
int index = 0;
if (string.IsNullOrEmpty(selection)) selection = list[0];
// We need to find the sprite in order to have it selected
if (!string.IsNullOrEmpty(selection))
{
for (int i = 0; i < list.Length; ++i)
{
if (selection.Equals(list[i], System.StringComparison.OrdinalIgnoreCase))
{
index = i;
break;
}
}
}
// Draw the sprite selection popup
index = string.IsNullOrEmpty(field) ?
DrawPrefixList(index, list, options) :
DrawPrefixList(field, index, list, options);
return list[index];
}
return null;
}
/// <summary>
/// Helper function that returns the selected root object.
/// </summary>
static public GameObject SelectedRoot () { return SelectedRoot(false); }
/// <summary>
/// Helper function that returns the selected root object.
/// </summary>
static public GameObject SelectedRoot (bool createIfMissing)
{
GameObject go = Selection.activeGameObject;
// Only use active objects
if (go != null && !NGUITools.GetActive(go)) go = null;
// Try to find a panel
UIPanel p = (go != null) ? NGUITools.FindInParents<UIPanel>(go) : null;
// No selection? Try to find the root automatically
if (p == null)
{
UIPanel[] panels = NGUITools.FindActive<UIPanel>();
if (panels.Length > 0) go = panels[0].gameObject;
}
if (createIfMissing && go == null)
{
// No object specified -- find the first panel
if (go == null)
{
UIPanel panel = GameObject.FindObjectOfType(typeof(UIPanel)) as UIPanel;
if (panel != null) go = panel.gameObject;
}
// No UI present -- create a new one
if (go == null) go = UICreateNewUIWizard.CreateNewUI(UICreateNewUIWizard.CameraType.Simple2D);
}
return go;
}
/// <summary>
/// Helper function that checks to see if this action would break the prefab connection.
/// </summary>
static public bool WillLosePrefab (GameObject root)
{
if (root == null) return false;
if (root.transform != null)
{
// Check if the selected object is a prefab instance and display a warning
PrefabType type = PrefabUtility.GetPrefabType(root);
if (type == PrefabType.PrefabInstance)
{
return EditorUtility.DisplayDialog("Losing prefab",
"This action will lose the prefab connection. Are you sure you wish to continue?",
"Continue", "Cancel");
}
}
return true;
}
/// <summary>
/// Change the import settings of the specified texture asset, making it readable.
/// </summary>
static public bool MakeTextureReadable (string path, bool force)
{
if (string.IsNullOrEmpty(path)) return false;
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
if (ti == null) return false;
TextureImporterSettings settings = new TextureImporterSettings();
ti.ReadTextureSettings(settings);
if (force || !settings.readable || settings.npotScale != TextureImporterNPOTScale.None
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1
|| settings.alphaIsTransparency
#endif
)
{
settings.readable = true;
settings.textureFormat = TextureImporterFormat.ARGB32;
settings.npotScale = TextureImporterNPOTScale.None;
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1
settings.alphaIsTransparency = false;
#endif
ti.SetTextureSettings(settings);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
}
return true;
}
/// <summary>
/// Change the import settings of the specified texture asset, making it suitable to be used as a texture atlas.
/// </summary>
static bool MakeTextureAnAtlas (string path, bool force, bool alphaTransparency)
{
if (string.IsNullOrEmpty(path)) return false;
TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter;
if (ti == null) return false;
TextureImporterSettings settings = new TextureImporterSettings();
ti.ReadTextureSettings(settings);
if (force ||
settings.readable ||
settings.maxTextureSize < 4096 ||
settings.wrapMode != TextureWrapMode.Clamp ||
settings.npotScale != TextureImporterNPOTScale.ToNearest)
{
settings.readable = false;
settings.maxTextureSize = 4096;
settings.wrapMode = TextureWrapMode.Clamp;
settings.npotScale = TextureImporterNPOTScale.ToNearest;
settings.textureFormat = TextureImporterFormat.ARGB32;
settings.filterMode = FilterMode.Trilinear;
settings.aniso = 4;
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1
settings.alphaIsTransparency = alphaTransparency;
#endif
ti.SetTextureSettings(settings);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);
}
return true;
}
/// <summary>
/// Fix the import settings for the specified texture, re-importing it if necessary.
/// </summary>
static public Texture2D ImportTexture (string path, bool forInput, bool force, bool alphaTransparency)
{
if (!string.IsNullOrEmpty(path))
{
if (forInput) { if (!MakeTextureReadable(path, force)) return null; }
else if (!MakeTextureAnAtlas(path, force, alphaTransparency)) return null;
//return AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
Texture2D tex = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
return tex;
}
return null;
}
/// <summary>
/// Fix the import settings for the specified texture, re-importing it if necessary.
/// </summary>
static public Texture2D ImportTexture (Texture tex, bool forInput, bool force, bool alphaTransparency)
{
if (tex != null)
{
string path = AssetDatabase.GetAssetPath(tex.GetInstanceID());
return ImportTexture(path, forInput, force, alphaTransparency);
}
return null;
}
/// <summary>
/// Figures out the saveable filename for the texture of the specified atlas.
/// </summary>
static public string GetSaveableTexturePath (UIAtlas atlas)
{
// Path where the texture atlas will be saved
string path = "";
// If the atlas already has a texture, overwrite its texture
if (atlas.texture != null)
{
path = AssetDatabase.GetAssetPath(atlas.texture.GetInstanceID());
if (!string.IsNullOrEmpty(path))
{
int dot = path.LastIndexOf('.');
return path.Substring(0, dot) + ".png";
}
}
// No texture to use -- figure out a name using the atlas
path = AssetDatabase.GetAssetPath(atlas.GetInstanceID());
path = string.IsNullOrEmpty(path) ? "Assets/" + atlas.name + ".png" : path.Replace(".prefab", ".png");
return path;
}
/// <summary>
/// Helper function that returns the folder where the current selection resides.
/// </summary>
static public string GetSelectionFolder ()
{
if (Selection.activeObject != null)
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject.GetInstanceID());
if (!string.IsNullOrEmpty(path))
{
int dot = path.LastIndexOf('.');
int slash = Mathf.Max(path.LastIndexOf('/'), path.LastIndexOf('\\'));
if (slash > 0) return (dot > slash) ? path.Substring(0, slash + 1) : path + "/";
}
}
return "Assets/";
}
/// <summary>
/// Struct type for the integer vector field below.
/// </summary>
public struct IntVector
{
public int x;
public int y;
}
/// <summary>
/// Integer vector field.
/// </summary>
static public IntVector IntPair (string prefix, string leftCaption, string rightCaption, int x, int y)
{
GUILayout.BeginHorizontal();
if (string.IsNullOrEmpty(prefix))
{
GUILayout.Space(82f);
}
else
{
GUILayout.Label(prefix, GUILayout.Width(74f));
}
NGUIEditorTools.SetLabelWidth(48f);
IntVector retVal;
retVal.x = EditorGUILayout.IntField(leftCaption, x, GUILayout.MinWidth(30f));
retVal.y = EditorGUILayout.IntField(rightCaption, y, GUILayout.MinWidth(30f));
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.EndHorizontal();
return retVal;
}
/// <summary>
/// Integer rectangle field.
/// </summary>
static public Rect IntRect (string prefix, Rect rect)
{
int left = Mathf.RoundToInt(rect.xMin);
int top = Mathf.RoundToInt(rect.yMin);
int width = Mathf.RoundToInt(rect.width);
int height = Mathf.RoundToInt(rect.height);
NGUIEditorTools.IntVector a = NGUIEditorTools.IntPair(prefix, "Left", "Top", left, top);
NGUIEditorTools.IntVector b = NGUIEditorTools.IntPair(null, "Width", "Height", width, height);
return new Rect(a.x, a.y, b.x, b.y);
}
/// <summary>
/// Integer vector field.
/// </summary>
static public Vector4 IntPadding (string prefix, Vector4 v)
{
int left = Mathf.RoundToInt(v.x);
int top = Mathf.RoundToInt(v.y);
int right = Mathf.RoundToInt(v.z);
int bottom = Mathf.RoundToInt(v.w);
NGUIEditorTools.IntVector a = NGUIEditorTools.IntPair(prefix, "Left", "Top", left, top);
NGUIEditorTools.IntVector b = NGUIEditorTools.IntPair(null, "Right", "Bottom", right, bottom);
return new Vector4(a.x, a.y, b.x, b.y);
}
/// <summary>
/// Find all scene components, active or inactive.
/// </summary>
static public List<T> FindAll<T> () where T : Component
{
T[] comps = Resources.FindObjectsOfTypeAll(typeof(T)) as T[];
List<T> list = new List<T>();
foreach (T comp in comps)
{
if (comp.gameObject.hideFlags == 0)
{
string path = AssetDatabase.GetAssetPath(comp.gameObject);
if (string.IsNullOrEmpty(path)) list.Add(comp);
}
}
return list;
}
static public bool DrawPrefixButton (string text)
{
return GUILayout.Button(text, "DropDown", GUILayout.Width(76f));
}
static public bool DrawPrefixButton (string text, params GUILayoutOption[] options)
{
return GUILayout.Button(text, "DropDown", options);
}
static public int DrawPrefixList (int index, string[] list, params GUILayoutOption[] options)
{
return EditorGUILayout.Popup(index, list, "DropDown", options);
}
static public int DrawPrefixList (string text, int index, string[] list, params GUILayoutOption[] options)
{
return EditorGUILayout.Popup(text, index, list, "DropDown", options);
}
/// <summary>
/// Draw a sprite preview.
/// </summary>
static public void DrawSprite (Texture2D tex, Rect rect, UISpriteData sprite, Color color)
{
DrawSprite(tex, rect, sprite, color, null);
}
/// <summary>
/// Draw a sprite preview.
/// </summary>
static public void DrawSprite (Texture2D tex, Rect drawRect, UISpriteData sprite, Color color, Material mat)
{
if (!tex || sprite == null) return;
// Create the texture rectangle that is centered inside rect.
Rect outerRect = drawRect;
outerRect.width = sprite.width;
outerRect.height = sprite.height;
if (sprite.width > 0)
{
float f = drawRect.width / outerRect.width;
outerRect.width *= f;
outerRect.height *= f;
}
if (drawRect.height > outerRect.height)
{
outerRect.y += (drawRect.height - outerRect.height) * 0.5f;
}
else if (outerRect.height > drawRect.height)
{
float f = drawRect.height / outerRect.height;
outerRect.width *= f;
outerRect.height *= f;
}
if (drawRect.width > outerRect.width) outerRect.x += (drawRect.width - outerRect.width) * 0.5f;
// Draw the background
NGUIEditorTools.DrawTiledTexture(outerRect, NGUIEditorTools.backdropTexture);
// Draw the sprite
GUI.color = color;
if (mat == null)
{
Rect uv = new Rect(sprite.x, sprite.y, sprite.width, sprite.height);
uv = NGUIMath.ConvertToTexCoords(uv, tex.width, tex.height);
GUI.DrawTextureWithTexCoords(outerRect, tex, uv, true);
}
else
{
// NOTE: There is an issue in Unity that prevents it from clipping the drawn preview
// using BeginGroup/EndGroup, and there is no way to specify a UV rect... le'suq.
UnityEditor.EditorGUI.DrawPreviewTexture(outerRect, tex, mat);
}
// Draw the border indicator lines
GUI.BeginGroup(outerRect);
{
tex = NGUIEditorTools.contrastTexture;
GUI.color = Color.white;
if (sprite.borderLeft > 0)
{
float x0 = (float)sprite.borderLeft / sprite.width * outerRect.width - 1;
NGUIEditorTools.DrawTiledTexture(new Rect(x0, 0f, 1f, outerRect.height), tex);
}
if (sprite.borderRight > 0)
{
float x1 = (float)(sprite.width - sprite.borderRight) / sprite.width * outerRect.width - 1;
NGUIEditorTools.DrawTiledTexture(new Rect(x1, 0f, 1f, outerRect.height), tex);
}
if (sprite.borderBottom > 0)
{
float y0 = (float)(sprite.height - sprite.borderBottom) / sprite.height * outerRect.height - 1;
NGUIEditorTools.DrawTiledTexture(new Rect(0f, y0, outerRect.width, 1f), tex);
}
if (sprite.borderTop > 0)
{
float y1 = (float)sprite.borderTop / sprite.height * outerRect.height - 1;
NGUIEditorTools.DrawTiledTexture(new Rect(0f, y1, outerRect.width, 1f), tex);
}
}
GUI.EndGroup();
// Draw the lines around the sprite
Handles.color = Color.black;
Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMin, outerRect.yMax));
Handles.DrawLine(new Vector3(outerRect.xMax, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMax));
Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMin));
Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMax), new Vector3(outerRect.xMax, outerRect.yMax));
// Sprite size label
string text = string.Format("Sprite Size: {0}x{1}", Mathf.RoundToInt(sprite.width), Mathf.RoundToInt(sprite.height));
EditorGUI.DropShadowLabel(GUILayoutUtility.GetRect(Screen.width, 18f), text);
}
/// <summary>
/// Draw the specified sprite.
/// </summary>
public static void DrawTexture (Texture2D tex, Rect rect, Rect uv, Color color)
{
DrawTexture(tex, rect, uv, color, null);
}
/// <summary>
/// Draw the specified sprite.
/// </summary>
public static void DrawTexture (Texture2D tex, Rect rect, Rect uv, Color color, Material mat)
{
int w = Mathf.RoundToInt(tex.width * uv.width);
int h = Mathf.RoundToInt(tex.height * uv.height);
// Create the texture rectangle that is centered inside rect.
Rect outerRect = rect;
outerRect.width = w;
outerRect.height = h;
if (outerRect.width > 0f)
{
float f = rect.width / outerRect.width;
outerRect.width *= f;
outerRect.height *= f;
}
if (rect.height > outerRect.height)
{
outerRect.y += (rect.height - outerRect.height) * 0.5f;
}
else if (outerRect.height > rect.height)
{
float f = rect.height / outerRect.height;
outerRect.width *= f;
outerRect.height *= f;
}
if (rect.width > outerRect.width) outerRect.x += (rect.width - outerRect.width) * 0.5f;
// Draw the background
NGUIEditorTools.DrawTiledTexture(outerRect, NGUIEditorTools.backdropTexture);
// Draw the sprite
GUI.color = color;
if (mat == null)
{
GUI.DrawTextureWithTexCoords(outerRect, tex, uv, true);
}
else
{
// NOTE: There is an issue in Unity that prevents it from clipping the drawn preview
// using BeginGroup/EndGroup, and there is no way to specify a UV rect... le'suq.
UnityEditor.EditorGUI.DrawPreviewTexture(outerRect, tex, mat);
}
GUI.color = Color.white;
// Draw the lines around the sprite
Handles.color = Color.black;
Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMin, outerRect.yMax));
Handles.DrawLine(new Vector3(outerRect.xMax, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMax));
Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMin), new Vector3(outerRect.xMax, outerRect.yMin));
Handles.DrawLine(new Vector3(outerRect.xMin, outerRect.yMax), new Vector3(outerRect.xMax, outerRect.yMax));
// Sprite size label
string text = string.Format("Texture Size: {0}x{1}", w, h);
EditorGUI.DropShadowLabel(GUILayoutUtility.GetRect(Screen.width, 18f), text);
}
/// <summary>
/// Draw a sprite selection field.
/// </summary>
static public void DrawSpriteField (string label, UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label, GUILayout.Width(76f));
if (GUILayout.Button(spriteName, "MiniPullDown", options))
{
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
SpriteSelector.Show(callback);
}
GUILayout.EndHorizontal();
}
/// <summary>
/// Draw a sprite selection field.
/// </summary>
static public void DrawPaddedSpriteField (string label, UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label, GUILayout.Width(76f));
if (GUILayout.Button(spriteName, "MiniPullDown", options))
{
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
SpriteSelector.Show(callback);
}
GUILayout.Space(18f);
GUILayout.EndHorizontal();
}
/// <summary>
/// Draw a sprite selection field.
/// </summary>
static public void DrawSpriteField (string label, string caption, UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label, GUILayout.Width(76f));
if (atlas.GetSprite(spriteName) == null)
spriteName = "";
if (GUILayout.Button(spriteName, "MiniPullDown", options))
{
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
SpriteSelector.Show(callback);
}
if (!string.IsNullOrEmpty(caption))
{
GUILayout.Space(20f);
GUILayout.Label(caption);
}
GUILayout.EndHorizontal();
}
/// <summary>
/// Draw a simple sprite selection button.
/// </summary>
static public bool DrawSpriteField (UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, params GUILayoutOption[] options)
{
if (atlas.GetSprite(spriteName) == null)
spriteName = "";
if (NGUIEditorTools.DrawPrefixButton(spriteName, options))
{
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
SpriteSelector.Show(callback);
return true;
}
return false;
}
static string mEditedName = null;
static string mLastSprite = null;
/// <summary>
/// Draw a sprite selection field.
/// </summary>
static public void DrawSpriteField (string label, SerializedObject ob, string spriteField, params GUILayoutOption[] options)
{
DrawSpriteField(label, ob, ob.FindProperty("atlas"), ob.FindProperty(spriteField), 76f, false, false, options);
}
/// <summary>
/// Draw a sprite selection field.
/// </summary>
static public void DrawSpriteField (string label, SerializedObject ob, SerializedProperty atlas, SerializedProperty sprite, params GUILayoutOption[] options)
{
DrawSpriteField(label, ob, atlas, sprite, 76f, false, false, options);
}
/// <summary>
/// Draw a sprite selection field.
/// </summary>
static public void DrawSpriteField (string label, SerializedObject ob, SerializedProperty atlas, SerializedProperty sprite, bool removable, params GUILayoutOption[] options)
{
DrawSpriteField(label, ob, atlas, sprite, 76f, false, removable, options);
}
/// <summary>
/// Draw a sprite selection field.
/// </summary>
static public void DrawSpriteField (string label, SerializedObject ob, SerializedProperty atlas, SerializedProperty sprite, float width, bool padded, bool removable, params GUILayoutOption[] options)
{
if (atlas != null && atlas.objectReferenceValue != null)
{
GUILayout.BeginHorizontal();
GUILayout.Label(label, GUILayout.Width(width));
if (sprite == null)
{
GUILayout.Label("Invalid field name");
}
else
{
string spriteName = sprite.hasMultipleDifferentValues ? "-" : sprite.stringValue;
GUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(atlas.hasMultipleDifferentValues);
{
if (GUILayout.Button(spriteName, "MiniPullDown", options))
SpriteSelector.Show(ob, sprite, atlas.objectReferenceValue as UIAtlas);
}
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(!removable);
#if UNITY_3_5
if (GUILayout.Button("X", GUILayout.Width(20f))) sprite.stringValue = "";
#else
if (GUILayout.Button("", "ToggleMixed", GUILayout.Width(20f))) sprite.stringValue = "";
#endif
EditorGUI.EndDisabledGroup();
if (padded) GUILayout.Space(18f);
GUILayout.EndHorizontal();
}
GUILayout.EndHorizontal();
}
}
/// <summary>
/// Convenience function that displays a list of sprites and returns the selected value.
/// </summary>
static public void DrawAdvancedSpriteField (UIAtlas atlas, string spriteName, SpriteSelector.Callback callback, bool editable,
params GUILayoutOption[] options)
{
if (atlas == null) return;
// Give the user a warning if there are no sprites in the atlas
if (atlas.spriteList.Count == 0)
{
EditorGUILayout.HelpBox("No sprites found", MessageType.Warning);
return;
}
// Sprite selection drop-down list
GUILayout.BeginHorizontal();
{
if (NGUIEditorTools.DrawPrefixButton("Sprite"))
{
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
SpriteSelector.Show(callback);
}
if (editable)
{
if (!string.Equals(spriteName, mLastSprite))
{
mLastSprite = spriteName;
mEditedName = null;
}
string newName = GUILayout.TextField(string.IsNullOrEmpty(mEditedName) ? spriteName : mEditedName);
if (newName != spriteName)
{
mEditedName = newName;
if (GUILayout.Button("Rename", GUILayout.Width(60f)))
{
UISpriteData sprite = atlas.GetSprite(spriteName);
if (sprite != null)
{
NGUIEditorTools.RegisterUndo("Edit Sprite Name", atlas);
sprite.name = newName;
List<UISprite> sprites = FindAll<UISprite>();
for (int i = 0; i < sprites.Count; ++i)
{
UISprite sp = sprites[i];
if (sp.atlas == atlas && sp.spriteName == spriteName)
{
NGUIEditorTools.RegisterUndo("Edit Sprite Name", sp);
sp.spriteName = newName;
}
}
mLastSprite = newName;
spriteName = newName;
mEditedName = null;
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
}
}
}
}
else
{
GUILayout.BeginHorizontal();
GUILayout.Label(spriteName, "HelpBox", GUILayout.Height(18f));
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (GUILayout.Button("Edit", GUILayout.Width(40f)))
{
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
Select(atlas.gameObject);
}
}
}
GUILayout.EndHorizontal();
}
/// <summary>
/// Repaints all inspector windows related to sprite drawing.
/// </summary>
static public void RepaintSprites ()
{
if (UIAtlasInspector.instance != null)
UIAtlasInspector.instance.Repaint();
if (UIAtlasMaker.instance != null)
UIAtlasMaker.instance.Repaint();
if (SpriteSelector.instance != null)
SpriteSelector.instance.Repaint();
}
/// <summary>
/// Select the specified sprite within the currently selected atlas.
/// </summary>
static public void SelectSprite (string spriteName)
{
if (NGUISettings.atlas != null)
{
NGUISettings.selectedSprite = spriteName;
NGUIEditorTools.Select(NGUISettings.atlas.gameObject);
RepaintSprites();
}
}
/// <summary>
/// Select the specified atlas and sprite.
/// </summary>
static public void SelectSprite (UIAtlas atlas, string spriteName)
{
if (atlas != null)
{
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = spriteName;
NGUIEditorTools.Select(atlas.gameObject);
RepaintSprites();
}
}
/// <summary>
/// Select the specified game object and remember what was selected before.
/// </summary>
static public void Select (GameObject go)
{
mPrevious = Selection.activeGameObject;
Selection.activeGameObject = go;
}
/// <summary>
/// Select the previous game object.
/// </summary>
static public void SelectPrevious ()
{
if (mPrevious != null)
{
Selection.activeGameObject = mPrevious;
mPrevious = null;
}
}
/// <summary>
/// Previously selected game object.
/// </summary>
static public GameObject previousSelection { get { return mPrevious; } }
/// <summary>
/// Helper function that checks to see if the scale is uniform.
/// </summary>
static public bool IsUniform (Vector3 scale)
{
return Mathf.Approximately(scale.x, scale.y) && Mathf.Approximately(scale.x, scale.z);
}
/// <summary>
/// Check to see if the specified game object has a uniform scale.
/// </summary>
static public bool IsUniform (GameObject go)
{
if (go == null) return true;
if (go.GetComponent<UIWidget>() != null)
{
Transform parent = go.transform.parent;
return parent == null || IsUniform(parent.gameObject);
}
return IsUniform(go.transform.lossyScale);
}
/// <summary>
/// Fix uniform scaling of the specified object.
/// </summary>
static public void FixUniform (GameObject go)
{
Transform t = go.transform;
while (t != null && t.gameObject.GetComponent<UIRoot>() == null)
{
if (!NGUIEditorTools.IsUniform(t.localScale))
{
NGUIEditorTools.RegisterUndo("Uniform scaling fix", t);
t.localScale = Vector3.one;
EditorUtility.SetDirty(t);
}
t = t.parent;
}
}
/// <summary>
/// Draw a distinctly different looking header label
/// </summary>
static public bool DrawHeader (string text) { return DrawHeader(text, text, false); }
/// <summary>
/// Draw a distinctly different looking header label
/// </summary>
static public bool DrawHeader (string text, string key) { return DrawHeader(text, key, false); }
/// <summary>
/// Draw a distinctly different looking header label
/// </summary>
static public bool DrawHeader (string text, bool forceOn) { return DrawHeader(text, text, forceOn); }
/// <summary>
/// Draw a distinctly different looking header label
/// </summary>
static public bool DrawHeader (string text, string key, bool forceOn)
{
bool state = EditorPrefs.GetBool(key, true);
GUILayout.Space(3f);
if (!forceOn && !state) GUI.backgroundColor = new Color(0.8f, 0.8f, 0.8f);
GUILayout.BeginHorizontal();
GUILayout.Space(3f);
GUI.changed = false;
#if UNITY_3_5
if (state) text = "\u25B2 " + text;
else text = "\u25BC " + text;
if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) state = !state;
#else
text = "<b><size=11>" + text + "</size></b>";
if (state) text = "\u25B2 " + text;
else text = "\u25BC " + text;
if (!GUILayout.Toggle(true, text, "dragtab", GUILayout.MinWidth(20f))) state = !state;
#endif
if (GUI.changed) EditorPrefs.SetBool(key, state);
GUILayout.Space(2f);
GUILayout.EndHorizontal();
GUI.backgroundColor = Color.white;
if (!forceOn && !state) GUILayout.Space(3f);
return state;
}
/// <summary>
/// Begin drawing the content area.
/// </summary>
static public void BeginContents ()
{
GUILayout.BeginHorizontal();
GUILayout.Space(4f);
EditorGUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(10f));
GUILayout.BeginVertical();
GUILayout.Space(2f);
}
/// <summary>
/// End drawing the content area.
/// </summary>
static public void EndContents ()
{
GUILayout.Space(3f);
GUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
GUILayout.Space(3f);
GUILayout.EndHorizontal();
GUILayout.Space(3f);
}
/// <summary>
/// Draw a list of fields for the specified list of delegates.
/// </summary>
static public void DrawEvents (string text, Object undoObject, List<EventDelegate> list)
{
DrawEvents(text, undoObject, list, null, null);
}
/// <summary>
/// Draw a list of fields for the specified list of delegates.
/// </summary>
static public void DrawEvents (string text, Object undoObject, List<EventDelegate> list, string noTarget, string notValid)
{
if (!NGUIEditorTools.DrawHeader(text)) return;
NGUIEditorTools.BeginContents();
EventDelegateEditor.Field(undoObject, list, notValid, notValid);
NGUIEditorTools.EndContents();
}
/// <summary>
/// Helper function that draws a serialized property.
/// </summary>
static public SerializedProperty DrawProperty (SerializedObject serializedObject, string property, params GUILayoutOption[] options)
{
return DrawProperty(null, serializedObject, property, false, options);
}
/// <summary>
/// Helper function that draws a serialized property.
/// </summary>
static public SerializedProperty DrawProperty (string label, SerializedObject serializedObject, string property, params GUILayoutOption[] options)
{
return DrawProperty(label, serializedObject, property, false, options);
}
/// <summary>
/// Helper function that draws a serialized property.
/// </summary>
static public SerializedProperty DrawPaddedProperty (SerializedObject serializedObject, string property, params GUILayoutOption[] options)
{
return DrawProperty(null, serializedObject, property, true, options);
}
/// <summary>
/// Helper function that draws a serialized property.
/// </summary>
static public SerializedProperty DrawPaddedProperty (string label, SerializedObject serializedObject, string property, params GUILayoutOption[] options)
{
return DrawProperty(label, serializedObject, property, true, options);
}
/// <summary>
/// Helper function that draws a serialized property.
/// </summary>
static public SerializedProperty DrawProperty (string label, SerializedObject serializedObject, string property, bool padding, params GUILayoutOption[] options)
{
SerializedProperty sp = serializedObject.FindProperty(property);
if (sp != null)
{
if (padding) EditorGUILayout.BeginHorizontal();
if (label != null) EditorGUILayout.PropertyField(sp, new GUIContent(label), options);
else EditorGUILayout.PropertyField(sp, options);
if (padding)
{
GUILayout.Space(18f);
EditorGUILayout.EndHorizontal();
}
}
return sp;
}
/// <summary>
/// Helper function that draws a serialized property.
/// </summary>
static public void DrawProperty (string label, SerializedProperty sp, params GUILayoutOption[] options)
{
DrawProperty(label, sp, true, options);
}
/// <summary>
/// Helper function that draws a serialized property.
/// </summary>
static public void DrawProperty (string label, SerializedProperty sp, bool padding, params GUILayoutOption[] options)
{
if (sp != null)
{
if (padding) EditorGUILayout.BeginHorizontal();
if (label != null) EditorGUILayout.PropertyField(sp, new GUIContent(label), options);
else EditorGUILayout.PropertyField(sp, options);
if (padding)
{
GUILayout.Space(18f);
EditorGUILayout.EndHorizontal();
}
}
}
/// <summary>
/// Determine the distance from the mouse position to the world rectangle specified by the 4 points.
/// </summary>
static public float SceneViewDistanceToRectangle (Vector3[] worldPoints, Vector2 mousePos)
{
Vector2[] screenPoints = new Vector2[4];
for (int i = 0; i < 4; ++i)
screenPoints[i] = HandleUtility.WorldToGUIPoint(worldPoints[i]);
return NGUIMath.DistanceToRectangle(screenPoints, mousePos);
}
/// <summary>
/// Raycast into the specified panel, returning a list of widgets.
/// Just like NGUIMath.Raycast, but doesn't rely on having a camera.
/// </summary>
static public BetterList<UIWidget> SceneViewRaycast (Vector2 mousePos)
{
BetterList<UIWidget> list = new BetterList<UIWidget>();
for (int i = 0; i < UIPanel.list.size; ++i)
{
UIPanel p = UIPanel.list.buffer[i];
for (int b = 0; b < p.widgets.size; ++b)
{
UIWidget w = p.widgets.buffer[b];
Vector3[] corners = w.worldCorners;
if (SceneViewDistanceToRectangle(corners, mousePos) == 0f)
list.Add(w);
}
}
list.Sort(UIWidget.FullCompareFunc);
return list;
}
/// <summary>
/// Select the topmost widget underneath the specified screen coordinate.
/// </summary>
static public bool SelectWidget (Vector2 pos) { return SelectWidget(null, pos, true); }
/// <summary>
/// Select the next widget in line.
/// </summary>
static public bool SelectWidget (GameObject start, Vector2 pos, bool inFront)
{
GameObject go = null;
BetterList<UIWidget> widgets = SceneViewRaycast(pos);
if (widgets == null || widgets.size == 0) return false;
bool found = false;
if (!inFront)
{
if (start != null)
{
for (int i = 0; i < widgets.size; ++i)
{
UIWidget w = widgets[i];
if (w.cachedGameObject == start)
{
found = true;
break;
}
go = w.cachedGameObject;
}
}
if (!found) go = widgets[0].cachedGameObject;
}
else
{
if (start != null)
{
for (int i = widgets.size; i > 0; )
{
UIWidget w = widgets[--i];
if (w.cachedGameObject == start)
{
found = true;
break;
}
go = w.cachedGameObject;
}
}
if (!found) go = widgets[widgets.size - 1].cachedGameObject;
}
if (go != null && go != start)
{
Selection.activeGameObject = go;
return true;
}
return false;
}
/// <summary>
/// Unity 4.3 changed the way LookLikeControls works.
/// </summary>
static public void SetLabelWidth (float width)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
EditorGUIUtility.LookLikeControls(width);
#else
EditorGUIUtility.labelWidth = width;
#endif
}
/// <summary>
/// Create an undo point for the specified objects.
/// </summary>
static public void RegisterUndo (string name, params Object[] objects)
{
if (objects != null && objects.Length > 0)
{
#if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2
UnityEditor.Undo.RegisterUndo(objects, name);
#else
UnityEditor.Undo.RecordObjects(objects, name);
#endif
foreach (Object obj in objects)
{
if (obj == null) continue;
EditorUtility.SetDirty(obj);
}
}
}
/// <summary>
/// Unity 4.5+ makes it possible to hide the move tool.
/// </summary>
static public void HideMoveTool (bool hide)
{
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3
UnityEditor.Tools.hidden = hide && (UnityEditor.Tools.current == UnityEditor.Tool.Move);
#endif
}
/// <summary>
/// Gets the internal class ID of the specified type.
/// </summary>
static public int GetClassID (System.Type type)
{
GameObject go = EditorUtility.CreateGameObjectWithHideFlags("Temp", HideFlags.HideAndDontSave);
Component uiSprite = go.AddComponent(type);
SerializedObject ob = new SerializedObject(uiSprite);
int classID = ob.FindProperty("m_Script").objectReferenceInstanceIDValue;
NGUITools.DestroyImmediate(go);
return classID;
}
/// <summary>
/// Gets the internal class ID of the specified type.
/// </summary>
static public int GetClassID<T> () where T : MonoBehaviour { return GetClassID(typeof(T)); }
/// <summary>
/// Convenience function that replaces the specified MonoBehaviour with one of specified type.
/// </summary>
static public SerializedObject ReplaceClass (MonoBehaviour mb, System.Type type)
{
int id = GetClassID(type);
SerializedObject ob = new SerializedObject(mb);
ob.Update();
ob.FindProperty("m_Script").objectReferenceInstanceIDValue = id;
ob.ApplyModifiedProperties();
ob.Update();
return ob;
}
/// <summary>
/// Convenience function that replaces the specified MonoBehaviour with one of specified class ID.
/// </summary>
static public SerializedObject ReplaceClass (MonoBehaviour mb, int classID)
{
SerializedObject ob = new SerializedObject(mb);
ob.Update();
ob.FindProperty("m_Script").objectReferenceInstanceIDValue = classID;
ob.ApplyModifiedProperties();
ob.Update();
return ob;
}
/// <summary>
/// Convenience function that replaces the specified MonoBehaviour with one of specified class ID.
/// </summary>
static public void ReplaceClass (SerializedObject ob, int classID)
{
ob.FindProperty("m_Script").objectReferenceInstanceIDValue = classID;
ob.ApplyModifiedProperties();
ob.Update();
}
/// <summary>
/// Convenience function that replaces the specified MonoBehaviour with one of specified class ID.
/// </summary>
static public void ReplaceClass (SerializedObject ob, System.Type type)
{
ob.FindProperty("m_Script").objectReferenceInstanceIDValue = GetClassID(type);
ob.ApplyModifiedProperties();
ob.Update();
}
/// <summary>
/// Convenience function that replaces the specified MonoBehaviour with one of specified type.
/// </summary>
static public T ReplaceClass<T> (MonoBehaviour mb) where T : MonoBehaviour { return ReplaceClass(mb, typeof(T)).targetObject as T; }
/// <summary>
/// Automatically upgrade all of the UITextures in the scene to Sprites if they can be found within the specified atlas.
/// </summary>
static public void UpgradeTexturesToSprites (UIAtlas atlas)
{
if (atlas == null) return;
List<UITexture> uits = FindAll<UITexture>();
if (uits.Count > 0)
{
UIWidget selectedTex = (UIWidgetInspector.instance != null && UIWidgetInspector.instance.target != null) ?
UIWidgetInspector.instance.target as UITexture : null;
// Determine the object instance ID of the UISprite class
int spriteID = GetClassID<UISprite>();
// Run through all the UI textures and change them to sprites
for (int i = 0; i < uits.Count; ++i)
{
UIWidget uiTexture = uits[i];
if (uiTexture != null && uiTexture.mainTexture != null)
{
UISpriteData atlasSprite = atlas.GetSprite(uiTexture.mainTexture.name);
if (atlasSprite != null)
{
SerializedObject ob = ReplaceClass(uiTexture, spriteID);
ob.FindProperty("mSpriteName").stringValue = uiTexture.mainTexture.name;
ob.FindProperty("mAtlas").objectReferenceValue = NGUISettings.atlas;
ob.ApplyModifiedProperties();
}
}
}
if (selectedTex != null)
{
// Repaint() doesn't work in this case because Unity doesn't realize that the underlying
// script type has changed and that a new editor script needs to be chosen.
//UIWidgetInspector.instance.Repaint();
Selection.activeGameObject = null;
}
}
}
class MenuEntry
{
public string name;
public GameObject go;
public MenuEntry (string name, GameObject go) { this.name = name; this.go = go; }
}
/// <summary>
/// Show a sprite selection context menu listing all sprites under the specified screen position.
/// </summary>
static public void ShowSpriteSelectionMenu (Vector2 screenPos)
{
BetterList<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(screenPos);
BetterList<UIWidgetContainer> containers = new BetterList<UIWidgetContainer>();
BetterList<MenuEntry> entries = new BetterList<MenuEntry>();
BetterList<UIPanel> panels = new BetterList<UIPanel>();
bool divider = false;
UIWidget topWidget = null;
UIPanel topPanel = null;
// Process widgets and their containers in the raycast order
for (int i = 0; i < widgets.size; ++i)
{
UIWidget w = widgets[i];
if (topWidget == null) topWidget = w;
UIPanel panel = w.panel;
if (topPanel == null) topPanel = panel;
if (panel != null && !panels.Contains(panel))
{
panels.Add(panel);
if (!divider)
{
entries.Add(null);
divider = true;
}
entries.Add(new MenuEntry(panel.name + " (panel)", panel.gameObject));
}
UIWidgetContainer wc = NGUITools.FindInParents<UIWidgetContainer>(w.cachedGameObject);
// If we get a new container, we should add it to the list
if (wc != null && !containers.Contains(wc))
{
containers.Add(wc);
// Only proceed if there is no widget on the container
if (wc.gameObject != w.cachedGameObject)
{
if (!divider)
{
entries.Add(null);
divider = true;
}
entries.Add(new MenuEntry(wc.name + " (container)", wc.gameObject));
}
}
string name = (i + 1 == widgets.size) ? (w.name + " (top-most)") : w.name;
entries.Add(new MenuEntry(name, w.gameObject));
divider = false;
}
// Common items used by NGUI
NGUIContextMenu.AddCommonItems(Selection.activeGameObject);
// Add widgets to the menu in the reverse order so that they are shown with the top-most widget first (on top)
for (int i = entries.size; i > 0; )
{
MenuEntry ent = entries[--i];
if (ent != null)
{
NGUIContextMenu.AddItem("Select/" + ent.name, Selection.activeGameObject == ent.go,
delegate(object go) { Selection.activeGameObject = (GameObject)go; }, ent.go);
}
else if (!divider)
{
NGUIContextMenu.AddSeparator("Select/");
}
}
NGUIContextMenu.AddHelp(Selection.activeGameObject, true);
NGUIContextMenu.Show();
}
/// <summary>
/// Load the asset at the specified path.
/// </summary>
static public Object LoadAsset (string path)
{
if (string.IsNullOrEmpty(path)) return null;
return AssetDatabase.LoadMainAssetAtPath(path);
}
/// <summary>
/// Convenience function to load an asset of specified type, given the full path to it.
/// </summary>
static public T LoadAsset<T> (string path) where T: Object
{
Object obj = LoadAsset(path);
if (obj == null) return null;
T val = obj as T;
if (val != null) return val;
if (typeof(T).IsSubclassOf(typeof(Component)))
{
if (obj.GetType() == typeof(GameObject))
{
GameObject go = obj as GameObject;
return go.GetComponent(typeof(T)) as T;
}
}
return null;
}
/// <summary>
/// Get the specified object's GUID.
/// </summary>
static public string ObjectToGUID (Object obj)
{
string path = AssetDatabase.GetAssetPath(obj);
return (!string.IsNullOrEmpty(path)) ? AssetDatabase.AssetPathToGUID(path) : null;
}
#if !UNITY_3_5
static MethodInfo s_GetInstanceIDFromGUID;
#endif
/// <summary>
/// Convert the specified GUID to an object reference.
/// </summary>
static public Object GUIDToObject (string guid)
{
if (string.IsNullOrEmpty(guid)) return null;
#if !UNITY_3_5
// This method is not going to be available in Unity 3.5
if (s_GetInstanceIDFromGUID == null)
s_GetInstanceIDFromGUID = typeof(AssetDatabase).GetMethod("GetInstanceIDFromGUID", BindingFlags.Static | BindingFlags.NonPublic);
int id = (int)s_GetInstanceIDFromGUID.Invoke(null, new object[] { guid });
if (id != 0) return EditorUtility.InstanceIDToObject(id);
#endif
string path = AssetDatabase.GUIDToAssetPath(guid);
if (string.IsNullOrEmpty(path)) return null;
return AssetDatabase.LoadAssetAtPath(path, typeof(Object));
}
/// <summary>
/// Convert the specified GUID to an object reference of specified type.
/// </summary>
static public T GUIDToObject<T> (string guid) where T : Object
{
Object obj = GUIDToObject(guid);
if (obj == null) return null;
System.Type objType = obj.GetType();
if (objType == typeof(T) || objType.IsSubclassOf(typeof(T))) return obj as T;
if (objType == typeof(GameObject) && typeof(T).IsSubclassOf(typeof(Component)))
{
GameObject go = obj as GameObject;
return go.GetComponent(typeof(T)) as T;
}
return null;
}
/// <summary>
/// Add a border around the specified color buffer with the width and height of a single pixel all around.
/// The returned color buffer will have its width and height increased by 2.
/// </summary>
static public Color32[] AddBorder (Color32[] colors, int width, int height)
{
int w2 = width + 2;
int h2 = height + 2;
Color32[] c2 = new Color32[w2 * h2];
for (int y2 = 0; y2 < h2; ++y2)
{
int y1 = NGUIMath.ClampIndex(y2 - 1, height);
for (int x2 = 0; x2 < w2; ++x2)
{
int x1 = NGUIMath.ClampIndex(x2 - 1, width);
int i2 = x2 + y2 * w2;
c2[i2] = colors[x1 + y1 * width];
if (x2 == 0 || x2 + 1 == w2 || y2 == 0 || y2 + 1 == h2)
c2[i2].a = 0;
}
}
return c2;
}
/// <summary>
/// Add a soft shadow to the specified color buffer.
/// The buffer must have some padding around the edges in order for this to work properly.
/// </summary>
static public void AddShadow (Color32[] colors, int width, int height, Color shadow)
{
Color sh = shadow;
sh.a = 1f;
for (int y2 = 0; y2 < height; ++y2)
{
for (int x2 = 0; x2 < width; ++x2)
{
int index = x2 + y2 * width;
Color32 uc = colors[index];
if (uc.a == 255) continue;
Color original = uc;
float val = original.a;
int count = 1;
float div1 = 1f / 255f;
float div2 = 2f / 255f;
float div3 = 3f / 255f;
// Left
if (x2 != 0)
{
val += colors[x2 - 1 + y2 * width].a * div1;
count += 1;
}
// Top
if (y2 + 1 != height)
{
val += colors[x2 + (y2 + 1) * width].a * div2;
count += 2;
}
// Top-left
if (x2 != 0 && y2 + 1 != height)
{
val += colors[x2 - 1 + (y2 + 1) * width].a * div3;
count += 3;
}
val /= count;
Color c = Color.Lerp(original, sh, shadow.a * val);
colors[index] = Color.Lerp(c, original, original.a);
}
}
}
/// <summary>
/// Add a visual depth effect to the specified color buffer.
/// The buffer must have some padding around the edges in order for this to work properly.
/// </summary>
static public void AddDepth (Color32[] colors, int width, int height, Color shadow)
{
Color sh = shadow;
sh.a = 1f;
for (int y2 = 0; y2 < height; ++y2)
{
for (int x2 = 0; x2 < width; ++x2)
{
int index = x2 + y2 * width;
Color32 uc = colors[index];
if (uc.a == 255) continue;
Color original = uc;
float val = original.a * 4f;
int count = 4;
float div1 = 1f / 255f;
float div2 = 2f / 255f;
if (x2 != 0)
{
val += colors[x2 - 1 + y2 * width].a * div2;
count += 2;
}
if (x2 + 1 != width)
{
val += colors[x2 + 1 + y2 * width].a * div2;
count += 2;
}
if (y2 != 0)
{
val += colors[x2 + (y2 - 1) * width].a * div2;
count += 2;
}
if (y2 + 1 != height)
{
val += colors[x2 + (y2 + 1) * width].a * div2;
count += 2;
}
if (x2 != 0 && y2 != 0)
{
val += colors[x2 - 1 + (y2 - 1) * width].a * div1;
++count;
}
if (x2 != 0 && y2 + 1 != height)
{
val += colors[x2 - 1 + (y2 + 1) * width].a * div1;
++count;
}
if (x2 + 1 != width && y2 != 0)
{
val += colors[x2 + 1 + (y2 - 1) * width].a * div1;
++count;
}
if (x2 + 1 != width && y2 + 1 != height)
{
val += colors[x2 + 1 + (y2 + 1) * width].a * div1;
++count;
}
val /= count;
Color c = Color.Lerp(original, sh, shadow.a * val);
colors[index] = Color.Lerp(c, original, original.a);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUIEditorTools.cs
|
C#
|
asf20
| 55,303
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
/// <summary>
/// Inspector class used to edit UISpriteAnimations.
/// </summary>
[CustomEditor(typeof(UISpriteAnimation))]
public class UISpriteAnimationInspector : Editor
{
/// <summary>
/// Draw the inspector widget.
/// </summary>
public override void OnInspectorGUI ()
{
NGUIEditorTools.DrawSeparator();
NGUIEditorTools.SetLabelWidth(80f);
UISpriteAnimation anim = target as UISpriteAnimation;
int fps = EditorGUILayout.IntField("Framerate", anim.framesPerSecond);
fps = Mathf.Clamp(fps, 0, 60);
if (anim.framesPerSecond != fps)
{
NGUIEditorTools.RegisterUndo("Sprite Animation Change", anim);
anim.framesPerSecond = fps;
EditorUtility.SetDirty(anim);
}
string namePrefix = EditorGUILayout.TextField("Name Prefix", (anim.namePrefix != null) ? anim.namePrefix : "");
if (anim.namePrefix != namePrefix)
{
NGUIEditorTools.RegisterUndo("Sprite Animation Change", anim);
anim.namePrefix = namePrefix;
EditorUtility.SetDirty(anim);
}
bool loop = EditorGUILayout.Toggle("Loop", anim.loop);
if (anim.loop != loop)
{
NGUIEditorTools.RegisterUndo("Sprite Animation Change", anim);
anim.loop = loop;
EditorUtility.SetDirty(anim);
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UISpriteAnimationInspector.cs
|
C#
|
asf20
| 1,428
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIToggle))]
public class UIToggleInspector : UIWidgetContainerEditor
{
enum Transition
{
Smooth,
Instant,
}
public override void OnInspectorGUI ()
{
serializedObject.Update();
NGUIEditorTools.SetLabelWidth(100f);
UIToggle toggle = target as UIToggle;
GUILayout.Space(6f);
GUI.changed = false;
GUILayout.BeginHorizontal();
NGUIEditorTools.DrawProperty("Group", serializedObject, "group", GUILayout.Width(120f));
GUILayout.Label(" - zero means 'none'");
GUILayout.EndHorizontal();
NGUIEditorTools.DrawProperty("Starting State", serializedObject, "startsActive");
NGUIEditorTools.SetLabelWidth(80f);
if (NGUIEditorTools.DrawHeader("State Transition"))
{
NGUIEditorTools.BeginContents();
NGUIEditorTools.DrawProperty("Sprite", serializedObject, "activeSprite");
NGUIEditorTools.DrawProperty("Animation", serializedObject, "activeAnimation");
if (serializedObject.isEditingMultipleObjects)
{
NGUIEditorTools.DrawProperty("Instant", serializedObject, "instantTween");
}
else
{
GUI.changed = false;
Transition tr = toggle.instantTween ? Transition.Instant : Transition.Smooth;
GUILayout.BeginHorizontal();
tr = (Transition)EditorGUILayout.EnumPopup("Transition", tr);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Toggle Change", toggle);
toggle.instantTween = (tr == Transition.Instant);
NGUITools.SetDirty(toggle);
}
}
NGUIEditorTools.EndContents();
}
NGUIEditorTools.DrawEvents("On Value Change", toggle, toggle.onChange);
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIToggleInspector.cs
|
C#
|
asf20
| 1,924
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIWrapContent))]
#else
[CustomEditor(typeof(UIWrapContent), true)]
#endif
public class UIWrapContentEditor : Editor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(90f);
string fieldName = "Item Size";
string error = null;
UIScrollView sv = null;
if (!serializedObject.isEditingMultipleObjects)
{
UIWrapContent list = target as UIWrapContent;
sv = NGUITools.FindInParents<UIScrollView>(list.gameObject);
if (sv == null)
{
error = "UIWrappedList needs a Scroll View on its parent in order to work properly";
}
else if (sv.movement == UIScrollView.Movement.Horizontal) fieldName = "Item Width";
else if (sv.movement == UIScrollView.Movement.Vertical) fieldName = "Item Height";
else
{
error = "Scroll View needs to be using Horizontal or Vertical movement";
}
}
serializedObject.Update();
GUILayout.BeginHorizontal();
NGUIEditorTools.DrawProperty(fieldName, serializedObject, "itemSize", GUILayout.Width(130f));
GUILayout.Label("pixels");
GUILayout.EndHorizontal();
NGUIEditorTools.DrawProperty("Cull Content", serializedObject, "cullContent");
if (!string.IsNullOrEmpty(error))
{
EditorGUILayout.HelpBox(error, MessageType.Error);
if (sv != null && GUILayout.Button("Select the Scroll View"))
Selection.activeGameObject = sv.gameObject;
}
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIWrapContentEditor.cs
|
C#
|
asf20
| 1,708
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_3_5
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(Transform))]
public class NGUITransformInspector : Editor
{
/// <summary>
/// Draw the inspector widget.
/// </summary>
public override void OnInspectorGUI ()
{
Transform trans = target as Transform;
NGUIEditorTools.SetLabelWidth(15f);
Vector3 pos;
Vector3 rot;
Vector3 scale;
// Position
EditorGUILayout.BeginHorizontal();
{
if (DrawButton("P", "Reset Position", IsResetPositionValid(trans), 20f))
{
NGUIEditorTools.RegisterUndo("Reset Position", trans);
trans.localPosition = Vector3.zero;
}
pos = DrawVector3(trans.localPosition);
}
EditorGUILayout.EndHorizontal();
// Rotation
EditorGUILayout.BeginHorizontal();
{
if (DrawButton("R", "Reset Rotation", IsResetRotationValid(trans), 20f))
{
NGUIEditorTools.RegisterUndo("Reset Rotation", trans);
trans.localEulerAngles = Vector3.zero;
}
rot = DrawVector3(trans.localEulerAngles);
}
EditorGUILayout.EndHorizontal();
// Scale
EditorGUILayout.BeginHorizontal();
{
if (DrawButton("S", "Reset Scale", IsResetScaleValid(trans), 20f))
{
NGUIEditorTools.RegisterUndo("Reset Scale", trans);
trans.localScale = Vector3.one;
}
scale = DrawVector3(trans.localScale);
}
EditorGUILayout.EndHorizontal();
// If something changes, set the transform values
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Transform Change", trans);
trans.localPosition = Validate(pos);
trans.localEulerAngles = Validate(rot);
trans.localScale = Validate(scale);
}
}
/// <summary>
/// Helper function that draws a button in an enabled or disabled state.
/// </summary>
static bool DrawButton (string title, string tooltip, bool enabled, float width)
{
if (enabled)
{
// Draw a regular button
return GUILayout.Button(new GUIContent(title, tooltip), GUILayout.Width(width));
}
else
{
// Button should be disabled -- draw it darkened and ignore its return value
Color color = GUI.color;
GUI.color = new Color(1f, 1f, 1f, 0.25f);
GUILayout.Button(new GUIContent(title, tooltip), GUILayout.Width(width));
GUI.color = color;
return false;
}
}
/// <summary>
/// Helper function that draws a field of 3 floats.
/// </summary>
static Vector3 DrawVector3 (Vector3 value)
{
GUILayoutOption opt = GUILayout.MinWidth(30f);
value.x = EditorGUILayout.FloatField("X", value.x, opt);
value.y = EditorGUILayout.FloatField("Y", value.y, opt);
value.z = EditorGUILayout.FloatField("Z", value.z, opt);
return value;
}
/// <summary>
/// Helper function that determines whether its worth it to show the reset position button.
/// </summary>
static bool IsResetPositionValid (Transform targetTransform)
{
Vector3 v = targetTransform.localPosition;
return (v.x != 0f || v.y != 0f || v.z != 0f);
}
/// <summary>
/// Helper function that determines whether its worth it to show the reset rotation button.
/// </summary>
static bool IsResetRotationValid (Transform targetTransform)
{
Vector3 v = targetTransform.localEulerAngles;
return (v.x != 0f || v.y != 0f || v.z != 0f);
}
/// <summary>
/// Helper function that determines whether its worth it to show the reset scale button.
/// </summary>
static bool IsResetScaleValid (Transform targetTransform)
{
Vector3 v = targetTransform.localScale;
return (v.x != 1f || v.y != 1f || v.z != 1f);
}
/// <summary>
/// Helper function that removes not-a-number values from the vector.
/// </summary>
static Vector3 Validate (Vector3 vector)
{
vector.x = float.IsNaN(vector.x) ? 0f : vector.x;
vector.y = float.IsNaN(vector.y) ? 0f : vector.y;
vector.z = float.IsNaN(vector.z) ? 0f : vector.z;
return vector;
}
}
#else
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(Transform), true)]
public class NGUITransformInspector : Editor
{
static public NGUITransformInspector instance;
SerializedProperty mPos;
SerializedProperty mRot;
SerializedProperty mScale;
void OnEnable ()
{
instance = this;
mPos = serializedObject.FindProperty("m_LocalPosition");
mRot = serializedObject.FindProperty("m_LocalRotation");
mScale = serializedObject.FindProperty("m_LocalScale");
}
void OnDestroy () { instance = null; }
/// <summary>
/// Draw the inspector widget.
/// </summary>
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(15f);
serializedObject.Update();
bool widgets = false;
foreach (Object obj in serializedObject.targetObjects)
{
Transform t = obj as Transform;
if (t.GetComponent<UIWidget>() != null)
{
widgets = true;
break;
}
}
DrawPosition();
DrawRotation(widgets);
DrawScale(widgets);
serializedObject.ApplyModifiedProperties();
}
void DrawPosition ()
{
GUILayout.BeginHorizontal();
{
bool reset = GUILayout.Button("P", GUILayout.Width(20f));
EditorGUILayout.PropertyField(mPos.FindPropertyRelative("x"));
EditorGUILayout.PropertyField(mPos.FindPropertyRelative("y"));
EditorGUILayout.PropertyField(mPos.FindPropertyRelative("z"));
if (reset) mPos.vector3Value = Vector3.zero;
}
GUILayout.EndHorizontal();
}
void DrawScale (bool isWidget)
{
GUILayout.BeginHorizontal();
{
bool reset = GUILayout.Button("S", GUILayout.Width(20f));
if (isWidget) GUI.color = new Color(0.7f, 0.7f, 0.7f);
EditorGUILayout.PropertyField(mScale.FindPropertyRelative("x"));
EditorGUILayout.PropertyField(mScale.FindPropertyRelative("y"));
EditorGUILayout.PropertyField(mScale.FindPropertyRelative("z"));
if (isWidget) GUI.color = Color.white;
if (reset) mScale.vector3Value = Vector3.one;
}
GUILayout.EndHorizontal();
}
#region Rotation is ugly as hell... since there is no native support for quaternion property drawing
enum Axes : int
{
None = 0,
X = 1,
Y = 2,
Z = 4,
All = 7,
}
Axes CheckDifference (Transform t, Vector3 original)
{
Vector3 next = t.localEulerAngles;
Axes axes = Axes.None;
if (Differs(next.x, original.x)) axes |= Axes.X;
if (Differs(next.y, original.y)) axes |= Axes.Y;
if (Differs(next.z, original.z)) axes |= Axes.Z;
return axes;
}
Axes CheckDifference (SerializedProperty property)
{
Axes axes = Axes.None;
if (property.hasMultipleDifferentValues)
{
Vector3 original = property.quaternionValue.eulerAngles;
foreach (Object obj in serializedObject.targetObjects)
{
axes |= CheckDifference(obj as Transform, original);
if (axes == Axes.All) break;
}
}
return axes;
}
/// <summary>
/// Draw an editable float field.
/// </summary>
/// <param name="hidden">Whether to replace the value with a dash</param>
/// <param name="greyedOut">Whether the value should be greyed out or not</param>
static bool FloatField (string name, ref float value, bool hidden, bool greyedOut, GUILayoutOption opt)
{
float newValue = value;
GUI.changed = false;
if (!hidden)
{
if (greyedOut)
{
GUI.color = new Color(0.7f, 0.7f, 0.7f);
newValue = EditorGUILayout.FloatField(name, newValue, opt);
GUI.color = Color.white;
}
else
{
newValue = EditorGUILayout.FloatField(name, newValue, opt);
}
}
else if (greyedOut)
{
GUI.color = new Color(0.7f, 0.7f, 0.7f);
float.TryParse(EditorGUILayout.TextField(name, "--", opt), out newValue);
GUI.color = Color.white;
}
else
{
float.TryParse(EditorGUILayout.TextField(name, "--", opt), out newValue);
}
if (GUI.changed && Differs(newValue, value))
{
value = newValue;
return true;
}
return false;
}
/// <summary>
/// Because Mathf.Approximately is too sensitive.
/// </summary>
static bool Differs (float a, float b) { return Mathf.Abs(a - b) > 0.0001f; }
void DrawRotation (bool isWidget)
{
GUILayout.BeginHorizontal();
{
bool reset = GUILayout.Button("R", GUILayout.Width(20f));
Vector3 visible = (serializedObject.targetObject as Transform).localEulerAngles;
visible.x = NGUIMath.WrapAngle(visible.x);
visible.y = NGUIMath.WrapAngle(visible.y);
visible.z = NGUIMath.WrapAngle(visible.z);
Axes changed = CheckDifference(mRot);
Axes altered = Axes.None;
GUILayoutOption opt = GUILayout.MinWidth(30f);
if (FloatField("X", ref visible.x, (changed & Axes.X) != 0, isWidget, opt)) altered |= Axes.X;
if (FloatField("Y", ref visible.y, (changed & Axes.Y) != 0, isWidget, opt)) altered |= Axes.Y;
if (FloatField("Z", ref visible.z, (changed & Axes.Z) != 0, false, opt)) altered |= Axes.Z;
if (reset)
{
mRot.quaternionValue = Quaternion.identity;
}
else if (altered != Axes.None)
{
NGUIEditorTools.RegisterUndo("Change Rotation", serializedObject.targetObjects);
foreach (Object obj in serializedObject.targetObjects)
{
Transform t = obj as Transform;
Vector3 v = t.localEulerAngles;
if ((altered & Axes.X) != 0) v.x = visible.x;
if ((altered & Axes.Y) != 0) v.y = visible.y;
if ((altered & Axes.Z) != 0) v.z = visible.z;
t.localEulerAngles = v;
}
}
}
GUILayout.EndHorizontal();
}
#endregion
}
#endif
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUITransformInspector.cs
|
C#
|
asf20
| 9,324
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIDragObject))]
public class UIDragObjectEditor : Editor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
serializedObject.Update();
NGUIEditorTools.SetLabelWidth(100f);
SerializedProperty sp = NGUIEditorTools.DrawProperty("Target", serializedObject, "target");
EditorGUI.BeginDisabledGroup(sp.objectReferenceValue == null);
{
GUILayout.BeginHorizontal();
GUILayout.Label("Movement", GUILayout.Width(78f));
NGUIEditorTools.DrawPaddedProperty("", serializedObject, "scale");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Scroll Wheel", GUILayout.Width(78f));
NGUIEditorTools.DrawPaddedProperty("", serializedObject, "scrollMomentum");
GUILayout.EndHorizontal();
sp = NGUIEditorTools.DrawPaddedProperty("Drag Effect", serializedObject, "dragEffect");
if (sp.hasMultipleDifferentValues || (UIDragObject.DragEffect)sp.intValue != UIDragObject.DragEffect.None)
{
NGUIEditorTools.DrawProperty(" Momentum", serializedObject, "momentumAmount", GUILayout.Width(140f));
}
sp = NGUIEditorTools.DrawProperty("Keep Visible", serializedObject, "restrictWithinPanel");
if (sp.hasMultipleDifferentValues || sp.boolValue)
{
NGUIEditorTools.DrawProperty(" Content Rect", serializedObject, "contentRect");
}
}
EditorGUI.EndDisabledGroup();
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIDragObjectEditor.cs
|
C#
|
asf20
| 1,666
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Atlas maker lets you create atlases from a bunch of small textures. It's an alternative to using the external Texture Packer.
/// </summary>
public class UIAtlasMaker : EditorWindow
{
static public UIAtlasMaker instance;
public class SpriteEntry : UISpriteData
{
// Sprite texture -- original texture or a temporary texture
public Texture2D tex;
// Whether the texture is temporary and should be deleted
public bool temporaryTexture = false;
}
Vector2 mScroll = Vector2.zero;
List<string> mDelNames = new List<string>();
UIAtlas mLastAtlas;
void OnEnable () { instance = this; }
void OnDisable () { instance = null; }
/// <summary>
/// Atlas selection callback.
/// </summary>
void OnSelectAtlas (Object obj)
{
if (NGUISettings.atlas != obj)
{
NGUISettings.atlas = obj as UIAtlas;
Repaint();
}
}
/// <summary>
/// Refresh the window on selection.
/// </summary>
void OnSelectionChange () { mDelNames.Clear(); Repaint(); }
/// <summary>
/// Helper function that retrieves the list of currently selected textures.
/// </summary>
List<Texture> GetSelectedTextures ()
{
List<Texture> textures = new List<Texture>();
if (Selection.objects != null && Selection.objects.Length > 0)
{
Object[] objects = EditorUtility.CollectDependencies(Selection.objects);
foreach (Object o in objects)
{
Texture tex = o as Texture;
if (tex == null || tex.name == "Font Texture") continue;
if (NGUISettings.atlas == null || NGUISettings.atlas.texture != tex) textures.Add(tex);
}
}
return textures;
}
/// <summary>
/// Load the specified list of textures as Texture2Ds, fixing their import properties as necessary.
/// </summary>
static List<Texture2D> LoadTextures (List<Texture> textures)
{
List<Texture2D> list = new List<Texture2D>();
foreach (Texture tex in textures)
{
Texture2D t2 = NGUIEditorTools.ImportTexture(tex, true, false, true);
if (t2 != null) list.Add(t2);
}
return list;
}
/// <summary>
/// Used to sort the sprites by pixels used
/// </summary>
static int Compare (SpriteEntry a, SpriteEntry b)
{
// A is null b is not b is greater so put it at the front of the list
if (a == null && b != null) return 1;
// A is not null b is null a is greater so put it at the front of the list
if (a != null && b == null) return -1;
// Get the total pixels used for each sprite
int aPixels = a.width * a.height;
int bPixels = b.width * b.height;
if (aPixels > bPixels) return -1;
else if (aPixels < bPixels) return 1;
return 0;
}
/// <summary>
/// Pack all of the specified sprites into a single texture, updating the outer and inner rects of the sprites as needed.
/// </summary>
static bool PackTextures (Texture2D tex, List<SpriteEntry> sprites)
{
Texture2D[] textures = new Texture2D[sprites.Count];
Rect[] rects;
#if UNITY_3_5 || UNITY_4_0
int maxSize = 4096;
#else
int maxSize = SystemInfo.maxTextureSize;
#endif
#if UNITY_ANDROID || UNITY_IPHONE
maxSize = Mathf.Min(maxSize, NGUISettings.allow4096 ? 4096 : 2048);
#endif
if (NGUISettings.unityPacking)
{
for (int i = 0; i < sprites.Count; ++i) textures[i] = sprites[i].tex;
rects = tex.PackTextures(textures, NGUISettings.atlasPadding, maxSize);
}
else
{
sprites.Sort(Compare);
for (int i = 0; i < sprites.Count; ++i) textures[i] = sprites[i].tex;
rects = UITexturePacker.PackTextures(tex, textures, 4, 4, NGUISettings.atlasPadding, maxSize);
}
for (int i = 0; i < sprites.Count; ++i)
{
Rect rect = NGUIMath.ConvertToPixels(rects[i], tex.width, tex.height, true);
// Make sure that we don't shrink the textures
if (Mathf.RoundToInt(rect.width) != textures[i].width) return false;
SpriteEntry se = sprites[i];
se.x = Mathf.RoundToInt(rect.x);
se.y = Mathf.RoundToInt(rect.y);
se.width = Mathf.RoundToInt(rect.width);
se.height = Mathf.RoundToInt(rect.height);
}
return true;
}
/// <summary>
/// Helper function that creates a single sprite list from both the atlas's sprites as well as selected textures.
/// Dictionary value meaning:
/// 0 = No change
/// 1 = Update
/// 2 = Add
/// </summary>
Dictionary<string, int> GetSpriteList (List<Texture> textures)
{
Dictionary<string, int> spriteList = new Dictionary<string, int>();
if (NGUISettings.atlas != null)
{
BetterList<string> spriteNames = NGUISettings.atlas.GetListOfSprites();
foreach (string sp in spriteNames) spriteList.Add(sp, 0);
}
// If we have textures to work with, include them as well
if (textures.Count > 0)
{
List<string> texNames = new List<string>();
foreach (Texture tex in textures) texNames.Add(tex.name);
texNames.Sort();
foreach (string tex in texNames)
{
if (spriteList.ContainsKey(tex)) spriteList[tex] = 1;
else spriteList.Add(tex, 2);
}
}
return spriteList;
}
/// <summary>
/// Add a new sprite to the atlas, given the texture it's coming from and the packed rect within the atlas.
/// </summary>
static public UISpriteData AddSprite (List<UISpriteData> sprites, SpriteEntry se)
{
// See if this sprite already exists
foreach (UISpriteData sp in sprites)
{
if (sp.name == se.name)
{
sp.CopyFrom(se);
return sp;
}
}
UISpriteData sprite = new UISpriteData();
sprite.CopyFrom(se);
sprites.Add(sprite);
return sprite;
}
/// <summary>
/// Create a list of sprites using the specified list of textures.
/// </summary>
static public List<SpriteEntry> CreateSprites (List<Texture> textures)
{
List<SpriteEntry> list = new List<SpriteEntry>();
foreach (Texture tex in textures)
{
Texture2D oldTex = NGUIEditorTools.ImportTexture(tex, true, false, true);
if (oldTex == null) oldTex = tex as Texture2D;
if (oldTex == null) continue;
// If we aren't doing trimming, just use the texture as-is
if (!NGUISettings.atlasTrimming && !NGUISettings.atlasPMA)
{
SpriteEntry sprite = new SpriteEntry();
sprite.SetRect(0, 0, oldTex.width, oldTex.height);
sprite.tex = oldTex;
sprite.name = oldTex.name;
sprite.temporaryTexture = false;
list.Add(sprite);
continue;
}
// If we want to trim transparent pixels, there is more work to be done
Color32[] pixels = oldTex.GetPixels32();
int xmin = oldTex.width;
int xmax = 0;
int ymin = oldTex.height;
int ymax = 0;
int oldWidth = oldTex.width;
int oldHeight = oldTex.height;
// Find solid pixels
if (NGUISettings.atlasTrimming)
{
for (int y = 0, yw = oldHeight; y < yw; ++y)
{
for (int x = 0, xw = oldWidth; x < xw; ++x)
{
Color32 c = pixels[y * xw + x];
if (c.a != 0)
{
if (y < ymin) ymin = y;
if (y > ymax) ymax = y;
if (x < xmin) xmin = x;
if (x > xmax) xmax = x;
}
}
}
}
else
{
xmin = 0;
xmax = oldWidth - 1;
ymin = 0;
ymax = oldHeight - 1;
}
int newWidth = (xmax - xmin) + 1;
int newHeight = (ymax - ymin) + 1;
if (newWidth > 0 && newHeight > 0)
{
SpriteEntry sprite = new SpriteEntry();
sprite.x = 0;
sprite.y = 0;
sprite.width = oldTex.width;
sprite.height = oldTex.height;
// If the dimensions match, then nothing was actually trimmed
if (!NGUISettings.atlasPMA && (newWidth == oldWidth && newHeight == oldHeight))
{
sprite.tex = oldTex;
sprite.name = oldTex.name;
sprite.temporaryTexture = false;
}
else
{
// Copy the non-trimmed texture data into a temporary buffer
Color32[] newPixels = new Color32[newWidth * newHeight];
for (int y = 0; y < newHeight; ++y)
{
for (int x = 0; x < newWidth; ++x)
{
int newIndex = y * newWidth + x;
int oldIndex = (ymin + y) * oldWidth + (xmin + x);
if (NGUISettings.atlasPMA) newPixels[newIndex] = NGUITools.ApplyPMA(pixels[oldIndex]);
else newPixels[newIndex] = pixels[oldIndex];
}
}
// Create a new texture
sprite.temporaryTexture = true;
sprite.name = oldTex.name;
sprite.tex = new Texture2D(newWidth, newHeight);
sprite.tex.SetPixels32(newPixels);
sprite.tex.Apply();
// Remember the padding offset
sprite.SetPadding(xmin, ymin, oldWidth - newWidth - xmin, oldHeight - newHeight - ymin);
}
list.Add(sprite);
}
}
return list;
}
/// <summary>
/// Release all temporary textures created for the sprites.
/// </summary>
static public void ReleaseSprites (List<SpriteEntry> sprites)
{
foreach (SpriteEntry se in sprites)
{
if (se.temporaryTexture)
{
NGUITools.Destroy(se.tex);
se.tex = null;
}
}
Resources.UnloadUnusedAssets();
}
/// <summary>
/// Replace the sprites within the atlas.
/// </summary>
static public void ReplaceSprites (UIAtlas atlas, List<SpriteEntry> sprites)
{
// Get the list of sprites we'll be updating
List<UISpriteData> spriteList = atlas.spriteList;
List<UISpriteData> kept = new List<UISpriteData>();
// Run through all the textures we added and add them as sprites to the atlas
for (int i = 0; i < sprites.Count; ++i)
{
SpriteEntry se = sprites[i];
UISpriteData sprite = AddSprite(spriteList, se);
kept.Add(sprite);
}
// Remove unused sprites
for (int i = spriteList.Count; i > 0; )
{
UISpriteData sp = spriteList[--i];
if (!kept.Contains(sp)) spriteList.RemoveAt(i);
}
// Sort the sprites so that they are alphabetical within the atlas
atlas.SortAlphabetically();
atlas.MarkAsChanged();
}
/// <summary>
/// Duplicate the specified sprite.
/// </summary>
static public SpriteEntry DuplicateSprite (UIAtlas atlas, string spriteName)
{
if (atlas == null || atlas.texture == null) return null;
UISpriteData sd = atlas.GetSprite(spriteName);
if (sd == null) return null;
Texture2D tex = NGUIEditorTools.ImportTexture(atlas.texture, true, true, false);
SpriteEntry se = ExtractSprite(sd, tex);
if (se != null)
{
se.name = se.name + " (Copy)";
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(atlas, sprites);
sprites.Add(se);
UIAtlasMaker.UpdateAtlas(atlas, sprites);
if (se.temporaryTexture) DestroyImmediate(se.tex);
}
else NGUIEditorTools.ImportTexture(atlas.texture, false, false, !atlas.premultipliedAlpha);
return se;
}
/// <summary>
/// Extract the specified sprite from the atlas.
/// </summary>
static public SpriteEntry ExtractSprite (UIAtlas atlas, string spriteName)
{
if (atlas.texture == null) return null;
UISpriteData sd = atlas.GetSprite(spriteName);
if (sd == null) return null;
Texture2D tex = NGUIEditorTools.ImportTexture(atlas.texture, true, true, false);
SpriteEntry se = ExtractSprite(sd, tex);
NGUIEditorTools.ImportTexture(atlas.texture, false, false, !atlas.premultipliedAlpha);
return se;
}
/// <summary>
/// Extract the specified sprite from the atlas texture.
/// </summary>
static SpriteEntry ExtractSprite (UISpriteData es, Texture2D tex)
{
return (tex != null) ? ExtractSprite(es, tex.GetPixels32(), tex.width, tex.height) : null;
}
/// <summary>
/// Extract the specified sprite from the atlas texture.
/// </summary>
static SpriteEntry ExtractSprite (UISpriteData es, Color32[] oldPixels, int oldWidth, int oldHeight)
{
int xmin = Mathf.Clamp(es.x, 0, oldWidth);
int ymin = Mathf.Clamp(es.y, 0, oldHeight);
int xmax = Mathf.Min(xmin + es.width, oldWidth - 1);
int ymax = Mathf.Min(ymin + es.height, oldHeight - 1);
int newWidth = Mathf.Clamp(es.width, 0, oldWidth);
int newHeight = Mathf.Clamp(es.height, 0, oldHeight);
if (newWidth == 0 || newHeight == 0) return null;
Color32[] newPixels = new Color32[newWidth * newHeight];
for (int y = 0; y < newHeight; ++y)
{
int cy = ymin + y;
if (cy > ymax) cy = ymax;
for (int x = 0; x < newWidth; ++x)
{
int cx = xmin + x;
if (cx > xmax) cx = xmax;
int newIndex = (newHeight - 1 - y) * newWidth + x;
int oldIndex = (oldHeight - 1 - cy) * oldWidth + cx;
newPixels[newIndex] = oldPixels[oldIndex];
}
}
// Create a new sprite
SpriteEntry sprite = new SpriteEntry();
sprite.CopyFrom(es);
sprite.SetRect(0, 0, newWidth, newHeight);
sprite.temporaryTexture = true;
sprite.tex = new Texture2D(newWidth, newHeight);
sprite.tex.SetPixels32(newPixels);
sprite.tex.Apply();
return sprite;
}
/// <summary>
/// Extract sprites from the atlas, adding them to the list.
/// </summary>
static public void ExtractSprites (UIAtlas atlas, List<SpriteEntry> finalSprites)
{
ShowProgress(0f);
// Make the atlas texture readable
Texture2D tex = NGUIEditorTools.ImportTexture(atlas.texture, true, true, false);
if (tex != null)
{
Color32[] pixels = null;
int width = tex.width;
int height = tex.height;
List<UISpriteData> sprites = atlas.spriteList;
float count = sprites.Count;
int index = 0;
foreach (UISpriteData es in sprites)
{
ShowProgress((index++) / count);
bool found = false;
foreach (SpriteEntry fs in finalSprites)
{
if (es.name == fs.name)
{
fs.CopyBorderFrom(es);
found = true;
break;
}
}
if (!found)
{
if (pixels == null) pixels = tex.GetPixels32();
SpriteEntry sprite = ExtractSprite(es, pixels, width, height);
if (sprite != null) finalSprites.Add(sprite);
}
}
}
// The atlas no longer needs to be readable
NGUIEditorTools.ImportTexture(atlas.texture, false, false, !atlas.premultipliedAlpha);
ShowProgress(1f);
}
/// <summary>
/// Combine all sprites into a single texture and save it to disk.
/// </summary>
static public bool UpdateTexture (UIAtlas atlas, List<SpriteEntry> sprites)
{
// Get the texture for the atlas
Texture2D tex = atlas.texture as Texture2D;
string oldPath = (tex != null) ? AssetDatabase.GetAssetPath(tex.GetInstanceID()) : "";
string newPath = NGUIEditorTools.GetSaveableTexturePath(atlas);
// Clear the read-only flag in texture file attributes
if (System.IO.File.Exists(newPath))
{
#if !UNITY_4_1 && !UNITY_4_0 && !UNITY_3_5
if (!AssetDatabase.IsOpenForEdit(newPath))
{
Debug.LogError(newPath + " is not editable. Did you forget to do a check out?");
return false;
}
#endif
System.IO.FileAttributes newPathAttrs = System.IO.File.GetAttributes(newPath);
newPathAttrs &= ~System.IO.FileAttributes.ReadOnly;
System.IO.File.SetAttributes(newPath, newPathAttrs);
}
bool newTexture = (tex == null || oldPath != newPath);
if (newTexture)
{
// Create a new texture for the atlas
tex = new Texture2D(1, 1, TextureFormat.ARGB32, false);
}
else
{
// Make the atlas readable so we can save it
tex = NGUIEditorTools.ImportTexture(oldPath, true, false, false);
}
// Pack the sprites into this texture
if (PackTextures(tex, sprites))
{
byte[] bytes = tex.EncodeToPNG();
System.IO.File.WriteAllBytes(newPath, bytes);
bytes = null;
// Load the texture we just saved as a Texture2D
AssetDatabase.SaveAssets();
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
tex = NGUIEditorTools.ImportTexture(newPath, false, true, !atlas.premultipliedAlpha);
// Update the atlas texture
if (newTexture)
{
if (tex == null) Debug.LogError("Failed to load the created atlas saved as " + newPath);
else atlas.spriteMaterial.mainTexture = tex;
ReleaseSprites(sprites);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
}
return true;
}
else
{
if (!newTexture) NGUIEditorTools.ImportTexture(oldPath, false, true, !atlas.premultipliedAlpha);
//Debug.LogError("Operation canceled: The selected sprites can't fit into the atlas.\n" +
// "Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead.");
EditorUtility.DisplayDialog("Operation Canceled", "The selected sprites can't fit into the atlas.\n" +
"Keep large sprites outside the atlas (use UITexture), and/or use multiple atlases instead", "OK");
return false;
}
}
/// <summary>
/// Show a progress bar.
/// </summary>
static public void ShowProgress (float val)
{
EditorUtility.DisplayProgressBar("Updating", "Updating the atlas, please wait...", val);
}
/// <summary>
/// Add the specified texture to the atlas, or update an existing one.
/// </summary>
static public void AddOrUpdate (UIAtlas atlas, Texture2D tex)
{
if (atlas != null && tex != null)
{
List<Texture> textures = new List<Texture>();
textures.Add(tex);
List<SpriteEntry> sprites = CreateSprites(textures);
ExtractSprites(atlas, sprites);
UpdateAtlas(atlas, sprites);
}
}
/// <summary>
/// Add the specified texture to the atlas, or update an existing one.
/// </summary>
static public void AddOrUpdate (UIAtlas atlas, SpriteEntry se)
{
if (atlas != null && se != null)
{
List<SpriteEntry> sprites = new List<SpriteEntry>();
sprites.Add(se);
ExtractSprites(atlas, sprites);
UpdateAtlas(atlas, sprites);
}
}
/// <summary>
/// Update the sprites within the texture atlas, preserving the sprites that have not been selected.
/// </summary>
void UpdateAtlas (List<Texture> textures, bool keepSprites)
{
// Create a list of sprites using the collected textures
List<SpriteEntry> sprites = CreateSprites(textures);
if (sprites.Count > 0)
{
// Extract sprites from the atlas, filling in the missing pieces
if (keepSprites) ExtractSprites(NGUISettings.atlas, sprites);
// NOTE: It doesn't seem to be possible to undo writing to disk, and there also seems to be no way of
// detecting an Undo event. Without either of these it's not possible to restore the texture saved to disk,
// so the undo process doesn't work right. Because of this I'd rather disable it altogether until a solution is found.
// The ability to undo this action is always useful
//NGUIEditorTools.RegisterUndo("Update Atlas", UISettings.atlas, UISettings.atlas.texture, UISettings.atlas.material);
// Update the atlas
UpdateAtlas(NGUISettings.atlas, sprites);
}
else if (!keepSprites)
{
UpdateAtlas(NGUISettings.atlas, sprites);
}
}
/// <summary>
/// Update the sprite atlas, keeping only the sprites that are on the specified list.
/// </summary>
static public void UpdateAtlas (UIAtlas atlas, List<SpriteEntry> sprites)
{
if (sprites.Count > 0)
{
// Combine all sprites into a single texture and save it
if (UpdateTexture(atlas, sprites))
{
// Replace the sprites within the atlas
ReplaceSprites(atlas, sprites);
}
// Release the temporary textures
ReleaseSprites(sprites);
EditorUtility.ClearProgressBar();
return;
}
else
{
atlas.spriteList.Clear();
string path = NGUIEditorTools.GetSaveableTexturePath(atlas);
atlas.spriteMaterial.mainTexture = null;
if (!string.IsNullOrEmpty(path)) AssetDatabase.DeleteAsset(path);
}
atlas.MarkAsChanged();
Selection.activeGameObject = (NGUISettings.atlas != null) ? NGUISettings.atlas.gameObject : null;
EditorUtility.ClearProgressBar();
}
/// <summary>
/// Draw the UI for this tool.
/// </summary>
void OnGUI ()
{
if (mLastAtlas != NGUISettings.atlas)
mLastAtlas = NGUISettings.atlas;
bool update = false;
bool replace = false;
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.Space(3f);
NGUIEditorTools.DrawHeader("Input");
NGUIEditorTools.BeginContents();
GUILayout.BeginHorizontal();
{
ComponentSelector.Draw<UIAtlas>("Atlas", NGUISettings.atlas, OnSelectAtlas, true, GUILayout.MinWidth(80f));
EditorGUI.BeginDisabledGroup(NGUISettings.atlas == null);
if (GUILayout.Button("New", GUILayout.Width(40f)))
NGUISettings.atlas = null;
EditorGUI.EndDisabledGroup();
}
GUILayout.EndHorizontal();
List<Texture> textures = GetSelectedTextures();
if (NGUISettings.atlas != null)
{
Material mat = NGUISettings.atlas.spriteMaterial;
Texture tex = NGUISettings.atlas.texture;
// Material information
GUILayout.BeginHorizontal();
{
if (mat != null)
{
if (GUILayout.Button("Material", GUILayout.Width(76f))) Selection.activeObject = mat;
GUILayout.Label(" " + mat.name);
}
else
{
GUI.color = Color.grey;
GUILayout.Button("Material", GUILayout.Width(76f));
GUI.color = Color.white;
GUILayout.Label(" N/A");
}
}
GUILayout.EndHorizontal();
// Texture atlas information
GUILayout.BeginHorizontal();
{
if (tex != null)
{
if (GUILayout.Button("Texture", GUILayout.Width(76f))) Selection.activeObject = tex;
GUILayout.Label(" " + tex.width + "x" + tex.height);
}
else
{
GUI.color = Color.grey;
GUILayout.Button("Texture", GUILayout.Width(76f));
GUI.color = Color.white;
GUILayout.Label(" N/A");
}
}
GUILayout.EndHorizontal();
}
GUILayout.BeginHorizontal();
NGUISettings.atlasPadding = Mathf.Clamp(EditorGUILayout.IntField("Padding", NGUISettings.atlasPadding, GUILayout.Width(100f)), 0, 8);
GUILayout.Label((NGUISettings.atlasPadding == 1 ? "pixel" : "pixels") + " between sprites");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
NGUISettings.atlasTrimming = EditorGUILayout.Toggle("Trim Alpha", NGUISettings.atlasTrimming, GUILayout.Width(100f));
GUILayout.Label("Remove empty space");
GUILayout.EndHorizontal();
bool fixedShader = false;
if (NGUISettings.atlas != null)
{
Material mat = NGUISettings.atlas.spriteMaterial;
if (mat != null)
{
Shader shader = mat.shader;
if (shader != null)
{
if (shader.name == "Unlit/Transparent Colored")
{
NGUISettings.atlasPMA = false;
fixedShader = true;
}
else if (shader.name == "Unlit/Premultiplied Colored")
{
NGUISettings.atlasPMA = true;
fixedShader = true;
}
}
}
}
if (!fixedShader)
{
GUILayout.BeginHorizontal();
NGUISettings.atlasPMA = EditorGUILayout.Toggle("PMA Shader", NGUISettings.atlasPMA, GUILayout.Width(100f));
GUILayout.Label("Pre-multiplied alpha", GUILayout.MinWidth(70f));
GUILayout.EndHorizontal();
}
GUILayout.BeginHorizontal();
NGUISettings.unityPacking = EditorGUILayout.Toggle("Unity Packer", NGUISettings.unityPacking, GUILayout.Width(100f));
GUILayout.Label("or custom packer", GUILayout.MinWidth(70f));
GUILayout.EndHorizontal();
if (!NGUISettings.unityPacking)
{
GUILayout.BeginHorizontal();
NGUISettings.forceSquareAtlas = EditorGUILayout.Toggle("Force Square", NGUISettings.forceSquareAtlas, GUILayout.Width(100f));
GUILayout.Label("if on, forces a square atlas texture", GUILayout.MinWidth(70f));
GUILayout.EndHorizontal();
}
#if UNITY_IPHONE || UNITY_ANDROID
GUILayout.BeginHorizontal();
NGUISettings.allow4096 = EditorGUILayout.Toggle("4096x4096", NGUISettings.allow4096, GUILayout.Width(100f));
GUILayout.Label("if off, limit atlases to 2048x2048");
GUILayout.EndHorizontal();
#endif
NGUIEditorTools.EndContents();
if (NGUISettings.atlas != null)
{
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
if (textures.Count > 0)
{
update = GUILayout.Button("Add/Update");
}
else if (GUILayout.Button("View Sprites"))
{
SpriteSelector.ShowSelected();
}
GUILayout.Space(20f);
GUILayout.EndHorizontal();
}
else
{
EditorGUILayout.HelpBox("You can create a new atlas by selecting one or more textures in the Project View window, then clicking \"Create\".", MessageType.Info);
EditorGUI.BeginDisabledGroup(textures.Count == 0);
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
bool create = GUILayout.Button("Create");
GUILayout.Space(20f);
GUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
if (create)
{
string prefabPath = EditorUtility.SaveFilePanelInProject("Save As", "New Atlas.prefab", "prefab", "Save atlas as...");
if (!string.IsNullOrEmpty(prefabPath))
{
GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
string matPath = prefabPath.Replace(".prefab", ".mat");
replace = true;
// Try to load the material
Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
// If the material doesn't exist, create it
if (mat == null)
{
Shader shader = Shader.Find(NGUISettings.atlasPMA ? "Unlit/Premultiplied Colored" : "Unlit/Transparent Colored");
mat = new Material(shader);
// Save the material
AssetDatabase.CreateAsset(mat, matPath);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// Load the material so it's usable
mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
}
// Create a new prefab for the atlas
Object prefab = (go != null) ? go : PrefabUtility.CreateEmptyPrefab(prefabPath);
// Create a new game object for the atlas
string atlasName = prefabPath.Replace(".prefab", "");
atlasName = atlasName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
go = new GameObject(atlasName);
go.AddComponent<UIAtlas>().spriteMaterial = mat;
// Update the prefab
PrefabUtility.ReplacePrefab(go, prefab);
DestroyImmediate(go);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// Select the atlas
go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
NGUISettings.atlas = go.GetComponent<UIAtlas>();
Selection.activeGameObject = go;
}
}
}
string selection = null;
Dictionary<string, int> spriteList = GetSpriteList(textures);
if (spriteList.Count > 0)
{
NGUIEditorTools.DrawHeader("Sprites", true);
{
GUILayout.BeginHorizontal();
GUILayout.Space(3f);
GUILayout.BeginVertical();
mScroll = GUILayout.BeginScrollView(mScroll);
bool delete = false;
int index = 0;
foreach (KeyValuePair<string, int> iter in spriteList)
{
++index;
GUILayout.Space(-1f);
bool highlight = (UIAtlasInspector.instance != null) && (NGUISettings.selectedSprite == iter.Key);
GUI.backgroundColor = highlight ? Color.white : new Color(0.8f, 0.8f, 0.8f);
GUILayout.BeginHorizontal("AS TextArea", GUILayout.MinHeight(20f));
GUI.backgroundColor = Color.white;
GUILayout.Label(index.ToString(), GUILayout.Width(24f));
if (GUILayout.Button(iter.Key, "OL TextField", GUILayout.Height(20f)))
selection = iter.Key;
if (iter.Value == 2)
{
GUI.color = Color.green;
GUILayout.Label("Add", GUILayout.Width(27f));
GUI.color = Color.white;
}
else if (iter.Value == 1)
{
GUI.color = Color.cyan;
GUILayout.Label("Update", GUILayout.Width(45f));
GUI.color = Color.white;
}
else
{
if (mDelNames.Contains(iter.Key))
{
GUI.backgroundColor = Color.red;
if (GUILayout.Button("Delete", GUILayout.Width(60f)))
{
delete = true;
}
GUI.backgroundColor = Color.green;
if (GUILayout.Button("X", GUILayout.Width(22f)))
{
mDelNames.Remove(iter.Key);
delete = false;
}
GUI.backgroundColor = Color.white;
}
else
{
// If we have not yet selected a sprite for deletion, show a small "X" button
if (GUILayout.Button("X", GUILayout.Width(22f))) mDelNames.Add(iter.Key);
}
}
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
GUILayout.Space(3f);
GUILayout.EndHorizontal();
// If this sprite was marked for deletion, remove it from the atlas
if (delete)
{
List<SpriteEntry> sprites = new List<SpriteEntry>();
ExtractSprites(NGUISettings.atlas, sprites);
for (int i = sprites.Count; i > 0; )
{
SpriteEntry ent = sprites[--i];
if (mDelNames.Contains(ent.name))
sprites.RemoveAt(i);
}
UpdateAtlas(NGUISettings.atlas, sprites);
mDelNames.Clear();
NGUIEditorTools.RepaintSprites();
}
else if (update) UpdateAtlas(textures, true);
else if (replace) UpdateAtlas(textures, false);
if (NGUISettings.atlas != null && !string.IsNullOrEmpty(selection))
{
NGUIEditorTools.SelectSprite(selection);
}
else if (update || replace)
{
NGUIEditorTools.UpgradeTexturesToSprites(NGUISettings.atlas);
NGUIEditorTools.RepaintSprites();
}
}
}
if (NGUISettings.atlas != null && textures.Count == 0)
EditorGUILayout.HelpBox("You can reveal more options by selecting one or more textures in the Project View window.", MessageType.Info);
// Uncomment this line if you want to be able to force-sort the atlas
//if (NGUISettings.atlas != null && GUILayout.Button("Sort Alphabetically")) NGUISettings.atlas.SortAlphabetically();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIAtlasMaker.cs
|
C#
|
asf20
| 29,321
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_BLACKBERRY
#define MOBILE
#endif
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIInput))]
#else
[CustomEditor(typeof(UIInput), true)]
#endif
public class UIInputEditor : UIWidgetContainerEditor
{
public override void OnInspectorGUI ()
{
UIInput input = target as UIInput;
serializedObject.Update();
GUILayout.Space(3f);
NGUIEditorTools.SetLabelWidth(110f);
//NGUIEditorTools.DrawProperty(serializedObject, "m_Script");
EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
SerializedProperty label = NGUIEditorTools.DrawProperty(serializedObject, "label");
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(label == null || label.objectReferenceValue == null);
{
if (Application.isPlaying) NGUIEditorTools.DrawPaddedProperty("Value", serializedObject, "mValue");
else NGUIEditorTools.DrawPaddedProperty("Starting Value", serializedObject, "mValue");
NGUIEditorTools.DrawPaddedProperty(serializedObject, "savedAs");
NGUIEditorTools.DrawProperty("Active Text Color", serializedObject, "activeTextColor");
EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
{
if (label != null && label.objectReferenceValue != null)
{
SerializedObject ob = new SerializedObject(label.objectReferenceValue);
ob.Update();
NGUIEditorTools.DrawProperty("Inactive Color", ob, "mColor");
ob.ApplyModifiedProperties();
}
else EditorGUILayout.ColorField("Inactive Color", Color.white);
}
EditorGUI.EndDisabledGroup();
NGUIEditorTools.DrawProperty("Caret Color", serializedObject, "caretColor");
NGUIEditorTools.DrawProperty("Selection Color", serializedObject, "selectionColor");
#if !MOBILE
NGUIEditorTools.DrawProperty(serializedObject, "selectOnTab");
#endif
NGUIEditorTools.DrawPaddedProperty(serializedObject, "inputType");
#if MOBILE
NGUIEditorTools.DrawPaddedProperty(serializedObject, "keyboardType");
#endif
NGUIEditorTools.DrawPaddedProperty(serializedObject, "validation");
SerializedProperty sp = serializedObject.FindProperty("characterLimit");
GUILayout.BeginHorizontal();
if (sp.hasMultipleDifferentValues || input.characterLimit > 0)
{
EditorGUILayout.PropertyField(sp);
GUILayout.Space(18f);
}
else
{
EditorGUILayout.PropertyField(sp);
GUILayout.Label("unlimited");
}
GUILayout.EndHorizontal();
NGUIEditorTools.SetLabelWidth(80f);
EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
NGUIEditorTools.DrawEvents("On Submit", input, input.onSubmit);
NGUIEditorTools.DrawEvents("On Change", input, input.onChange);
EditorGUI.EndDisabledGroup();
}
EditorGUI.EndDisabledGroup();
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIInputEditor.cs
|
C#
|
asf20
| 3,048
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIScrollBar))]
public class UIScrollBarEditor : UIProgressBarEditor
{
protected override void DrawLegacyFields ()
{
UIScrollBar sb = target as UIScrollBar;
float val = EditorGUILayout.Slider("Value", sb.value, 0f, 1f);
float size = EditorGUILayout.Slider("Size", sb.barSize, 0f, 1f);
float alpha = EditorGUILayout.Slider("Alpha", sb.alpha, 0f, 1f);
if (sb.value != val ||
sb.barSize != size ||
sb.alpha != alpha)
{
NGUIEditorTools.RegisterUndo("Scroll Bar Change", sb);
sb.value = val;
sb.barSize = size;
sb.alpha = alpha;
NGUITools.SetDirty(sb);
for (int i = 0; i < UIScrollView.list.size; ++i)
{
UIScrollView sv = UIScrollView.list[i];
if (sv.horizontalScrollBar == sb || sv.verticalScrollBar == sb)
{
NGUIEditorTools.RegisterUndo("Scroll Bar Change", sv);
sv.UpdatePosition();
}
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIScrollBarEditor.cs
|
C#
|
asf20
| 1,136
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenOrthoSize))]
public class TweenOrthoSizeEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenOrthoSize tw = target as TweenOrthoSize;
GUI.changed = false;
float from = EditorGUILayout.FloatField("From", tw.from);
float to = EditorGUILayout.FloatField("To", tw.to);
if (from < 0f) from = 0f;
if (to < 0f) to = 0f;
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenOrthoSizeEditor.cs
|
C#
|
asf20
| 835
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIProgressBar))]
#else
[CustomEditor(typeof(UIProgressBar), true)]
#endif
public class UIProgressBarEditor : UIWidgetContainerEditor
{
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
serializedObject.Update();
GUILayout.Space(3f);
DrawLegacyFields();
GUILayout.BeginHorizontal();
SerializedProperty sp = NGUIEditorTools.DrawProperty("Steps", serializedObject, "numberOfSteps", GUILayout.Width(110f));
if (sp.intValue == 0) GUILayout.Label("= unlimited");
GUILayout.EndHorizontal();
OnDrawExtraFields();
if (NGUIEditorTools.DrawHeader("Appearance"))
{
NGUIEditorTools.BeginContents();
NGUIEditorTools.DrawProperty("Foreground", serializedObject, "mFG");
NGUIEditorTools.DrawProperty("Background", serializedObject, "mBG");
NGUIEditorTools.DrawProperty("Thumb", serializedObject, "thumb");
GUILayout.BeginHorizontal();
NGUIEditorTools.DrawProperty("Direction", serializedObject, "mFill");
GUILayout.Space(18f);
GUILayout.EndHorizontal();
OnDrawAppearance();
NGUIEditorTools.EndContents();
}
UIProgressBar sb = target as UIProgressBar;
NGUIEditorTools.DrawEvents("On Value Change", sb, sb.onChange);
serializedObject.ApplyModifiedProperties();
}
protected virtual void DrawLegacyFields()
{
UIProgressBar sb = target as UIProgressBar;
float val = EditorGUILayout.Slider("Value", sb.value, 0f, 1f);
float alpha = EditorGUILayout.Slider("Alpha", sb.alpha, 0f, 1f);
if (sb.value != val ||
sb.alpha != alpha)
{
NGUIEditorTools.RegisterUndo("Progress Bar Change", sb);
sb.value = val;
sb.alpha = alpha;
NGUITools.SetDirty(sb);
for (int i = 0; i < UIScrollView.list.size; ++i)
{
UIScrollView sv = UIScrollView.list[i];
if (sv.horizontalScrollBar == sb || sv.verticalScrollBar == sb)
{
NGUIEditorTools.RegisterUndo("Progress Bar Change", sv);
sv.UpdatePosition();
}
}
}
}
protected virtual void OnDrawExtraFields () { }
protected virtual void OnDrawAppearance () { }
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIProgressBarEditor.cs
|
C#
|
asf20
| 2,314
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenVolume))]
public class TweenVolumeEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenVolume tw = target as TweenVolume;
GUI.changed = false;
float from = EditorGUILayout.Slider("From", tw.from, 0f, 1f);
float to = EditorGUILayout.Slider("To", tw.to, 0f, 1f);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenVolumeEditor.cs
|
C#
|
asf20
| 778
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIKeyNavigation))]
#else
[CustomEditor(typeof(UIKeyNavigation), true)]
#endif
public class UIKeyNavigationEditor : Editor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
serializedObject.Update();
NGUIEditorTools.DrawProperty("Starts Selected", serializedObject, "startsSelected");
NGUIEditorTools.DrawProperty("Select on Click", serializedObject, "onClick");
NGUIEditorTools.DrawProperty("Constraint", serializedObject, "constraint");
if (NGUIEditorTools.DrawHeader("Override"))
{
NGUIEditorTools.SetLabelWidth(60f);
NGUIEditorTools.BeginContents();
NGUIEditorTools.DrawProperty("Left", serializedObject, "onLeft");
NGUIEditorTools.DrawProperty("Right", serializedObject, "onRight");
NGUIEditorTools.DrawProperty("Up", serializedObject, "onUp");
NGUIEditorTools.DrawProperty("Down", serializedObject, "onDown");
NGUIEditorTools.EndContents();
}
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIKeyNavigationEditor.cs
|
C#
|
asf20
| 1,277
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenScale))]
public class TweenScaleEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenScale tw = target as TweenScale;
GUI.changed = false;
Vector3 from = EditorGUILayout.Vector3Field("From", tw.from);
Vector3 to = EditorGUILayout.Vector3Field("To", tw.to);
bool table = EditorGUILayout.Toggle("Update Table", tw.updateTable);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
tw.updateTable = table;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenScaleEditor.cs
|
C#
|
asf20
| 872
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using System;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;
/// <summary>
/// FreeType library is a C++ library used to print text from TrueType fonts.
/// Since the code is in a native C++ DLL, you will need Unity Pro in order to use it.
/// FreeType project is open source and can be obtained from http://www.freetype.org/
///
/// A big thank you goes to Amplitude Studios for coming up with the idea on how to do
/// this in the first place. As a side note, their game "Endless Space" is pretty awesome!
/// http://www.amplitude-studios.com/
///
/// If you are curious where all these values come from, check the FreeType docs:
/// http://www.freetype.org/freetype2/docs/reference/ft2-base_interface.html
/// </summary>
static public class FreeType
{
public const int Err_Cannot_Open_Resource = 1;
public const int Err_Unknown_File_Format = 2;
public const int Err_Invalid_File_Format = 3;
public const int Err_Invalid_Version = 4;
public const int Err_Lower_Module_Version = 5;
public const int Err_Invalid_Argument = 6;
public const int Err_Unimplemented_Feature = 7;
public const int Err_Invalid_Table = 8;
public const int Err_Invalid_Offset = 9;
public const int Err_Invalid_Glyph_Index = 16;
public const int Err_Invalid_Character_Code = 17;
public const int Err_Invalid_Glyph_Format = 18;
public const int Err_Cannot_Render_Glyph = 19;
public const int Err_Invalid_Outline = 20;
public const int Err_Invalid_Composite = 21;
public const int Err_Too_Many_Hints = 22;
public const int Err_Invalid_Pixel_Size = 23;
public const int Err_Invalid_Handle = 32;
public const int Err_Invalid_Library_Handle = 33;
public const int Err_Invalid_Driver_Handle = 34;
public const int Err_Invalid_Face_Handle = 35;
public const int Err_Invalid_Size_Handle = 36;
public const int Err_Invalid_Slot_Handle = 37;
public const int Err_Invalid_CharMap_Handle = 38;
public const int Err_Invalid_Cache_Handle = 39;
public const int Err_Invalid_Stream_Handle = 40;
public const int Err_Too_Many_Drivers = 48;
public const int Err_Too_Many_Extensions = 49;
public const int Err_Out_Of_Memory = 64;
public const int Err_Unlisted_Object = 65;
public const int Err_Cannot_Open_Stream = 81;
public const int Err_Invalid_Stream_Seek = 82;
public const int Err_Invalid_Stream_Skip = 83;
public const int Err_Invalid_Stream_Read = 84;
public const int Err_Invalid_Stream_Operation = 85;
public const int Err_Invalid_Frame_Operation = 86;
public const int Err_Nested_Frame_Access = 87;
public const int Err_Invalid_Frame_Read = 88;
public const int Err_Raster_Uninitialized = 96;
public const int Err_Raster_Corrupted = 97;
public const int Err_Raster_Overflow = 98;
public const int Err_Raster_Negative_Height = 99;
public const int Err_Too_Many_Caches = 112;
public const int Err_Invalid_Opcode = 128;
public const int Err_Too_Few_Arguments = 129;
public const int Err_Stack_Overflow = 130;
public const int Err_Code_Overflow = 131;
public const int Err_Bad_Argument = 132;
public const int Err_Divide_By_Zero = 133;
public const int Err_Invalid_Reference = 134;
public const int Err_Debug_OpCode = 135;
public const int Err_ENDF_In_Exec_Stream = 136;
public const int Err_Nested_DEFS = 137;
public const int Err_Invalid_CodeRange = 138;
public const int Err_Execution_Too_Long = 139;
public const int Err_Too_Many_Function_Defs = 140;
public const int Err_Too_Many_Instruction_Defs = 141;
public const int Err_Table_Missing = 142;
public const int Err_Horiz_Header_Missing = 143;
public const int Err_Locations_Missing = 144;
public const int Err_Name_Table_Missing = 145;
public const int Err_CMap_Table_Missing = 146;
public const int Err_Hmtx_Table_Missing = 147;
public const int Err_Post_Table_Missing = 148;
public const int Err_Invalid_Horiz_Metrics = 149;
public const int Err_Invalid_CharMap_Format = 150;
public const int Err_Invalid_PPem = 151;
public const int Err_Invalid_Vert_Metrics = 152;
public const int Err_Could_Not_Find_Context = 153;
public const int Err_Invalid_Post_Table_Format = 154;
public const int Err_Invalid_Post_Table = 155;
public const int Err_Syntax_Error = 160;
public const int Err_Stack_Underflow = 161;
public const int Err_Ignore = 162;
public const int Err_Missing_Startfont_Field = 176;
public const int Err_Missing_Font_Field = 177;
public const int Err_Missing_Size_Field = 178;
public const int Err_Missing_Chars_Field = 179;
public const int Err_Missing_Startchar_Field = 180;
public const int Err_Missing_Encoding_Field = 181;
public const int Err_Missing_Bbx_Field = 182;
public const int FT_LOAD_CROP_BITMAP = 64;
public const int FT_LOAD_DEFAULT = 0;
public const int FT_LOAD_FORCE_AUTOHINT = 32;
public const int FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH = 512;
public const int FT_LOAD_IGNORE_TRANSFORM = 2048;
public const int FT_LOAD_LINEAR_DESIGN = 8192;
public const int FT_LOAD_MONOCHROME = 4096;
public const int FT_LOAD_NO_BITMAP = 8;
public const int FT_LOAD_NO_HINTING = 2;
public const int FT_LOAD_NO_RECURSE = 1024;
public const int FT_LOAD_NO_SCALE = 1;
public const int FT_LOAD_PEDANTIC = 128;
public const int FT_LOAD_RENDER = 4;
public const int FT_LOAD_SBITS_ONLY = 16384;
public const int FT_LOAD_VERTICAL_LAYOUT = 16;
public enum FT_Glyph_Format
{
FT_GLYPH_FORMAT_NONE,
FT_GLYPH_FORMAT_COMPOSITE = 1668246896,
FT_GLYPH_FORMAT_BITMAP = 1651078259,
FT_GLYPH_FORMAT_OUTLINE = 1869968492,
FT_GLYPH_FORMAT_PLOTTER = 1886154612
}
public enum FT_Render_Mode
{
FT_RENDER_MODE_NORMAL,
FT_RENDER_MODE_LIGHT,
FT_RENDER_MODE_MONO,
FT_RENDER_MODE_LCD,
FT_RENDER_MODE_LCD_V,
FT_RENDER_MODE_MAX
}
public struct FT_BBox
{
public int xMin;
public int yMin;
public int xMax;
public int yMax;
}
public struct FT_Bitmap
{
public int rows;
public int width;
public int pitch;
public IntPtr buffer;
public short num_grays;
public sbyte pixel_mode;
public sbyte palette_mode;
public IntPtr palette;
}
public struct FT_FaceRec
{
public int num_faces;
public int face_index;
public int face_flags;
public int style_flags;
public int num_glyphs;
public IntPtr family_name;
public IntPtr style_name;
public int num_fixed_sizes;
public IntPtr available_sizes;
public int num_charmaps;
public IntPtr charmaps;
public FT_Generic generic;
public FT_BBox bbox;
public ushort units_per_EM;
public short ascender;
public short descender;
public short height;
public short max_advance_width;
public short max_advance_height;
public short underline_position;
public short underline_thickness;
public IntPtr glyph;
public IntPtr size;
public IntPtr charmap;
public IntPtr driver;
public IntPtr memory;
public IntPtr stream;
public FT_ListRec sizes_list;
public FT_Generic autohint;
public IntPtr extensions;
public IntPtr _internal;
}
public struct FT_Generic
{
public IntPtr data;
public IntPtr finalizer;
}
public struct FT_Glyph_Metrics
{
public int width;
public int height;
public int horiBearingX;
public int horiBearingY;
public int horiAdvance;
public int vertBearingX;
public int vertBearingY;
public int vertAdvance;
}
public struct FT_GlyphSlotRec
{
public IntPtr library;
public IntPtr face;
public IntPtr next;
public uint reserved;
public FT_Generic generic;
public FT_Glyph_Metrics metrics;
public int linearHoriAdvance;
public int linearVertAdvance;
public FT_Vector advance;
public FT_Glyph_Format format;
public FT_Bitmap bitmap;
public int bitmap_left;
public int bitmap_top;
public FT_Outline outline;
public uint num_subglyphs;
public IntPtr subglyphs;
public IntPtr control_data;
public int control_len;
public int lsb_delta;
public int rsb_delta;
public IntPtr other;
public IntPtr _internal;
}
public struct FT_ListRec
{
public IntPtr head;
public IntPtr tail;
}
public struct FT_Outline
{
public short n_contours;
public short n_points;
public IntPtr points;
public IntPtr tags;
public IntPtr contours;
public int flags;
}
public struct FT_Size_Metrics
{
public ushort x_ppem;
public ushort y_ppem;
public int x_scale;
public int y_scale;
public int ascender;
public int descender;
public int height;
public int max_advance;
}
public struct FT_SizeRec
{
public IntPtr face;
public FT_Generic generic;
public FT_Size_Metrics metrics;
public IntPtr _internal;
}
public struct FT_Vector
{
public int x;
public int y;
}
const string libName = "FreeType";
static bool mFound = false;
/// <summary>
/// Whether the freetype library will be usable.
/// </summary>
static public bool isPresent
{
get
{
// According to Unity's documentation, placing the DLL into the Editor folder should make it possible
// to use it from within the editor. However from all my testing, that does not appear to be the case.
// The DLL has to be explicitly loaded first, or Unity doesn't seem to pick it up at all.
// On Mac OS it doesn't seem to be possible to load it at all, unless it's located in /usr/local/lib.
if (!mFound)
{
if (Application.platform == RuntimePlatform.WindowsEditor)
{
string path = NGUISettings.pathToFreeType;
mFound = File.Exists(path);
if (mFound) LoadLibrary(path);
}
else if (File.Exists("/usr/local/lib/FreeType.dylib"))
{
mFound = true;
}
else
{
string path = NGUISettings.pathToFreeType;
if (File.Exists(path))
{
try
{
if (!System.IO.Directory.Exists("/usr/local/lib"))
System.IO.Directory.CreateDirectory("/usr/local/lib");
UnityEditor.FileUtil.CopyFileOrDirectory(path, "/usr/local/lib/FreeType.dylib");
mFound = true;
}
catch (Exception ex)
{
Debug.LogWarning("Unable to copy FreeType.dylib to /usr/local/lib:\n" + ex.Message);
}
}
}
}
return mFound;
}
}
/// <summary>
/// Load the specified library.
/// </summary>
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr LoadLibrary (string lpFileName);
/// <summary>
/// Initialize the FreeType library. Must be called first before doing anything else.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_Init_FreeType (out IntPtr library);
/// <summary>
/// Return the glyph index of a given character code. This function uses a charmap object to do the mapping.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern uint FT_Get_Char_Index (IntPtr face, uint charcode);
/// <summary>
/// This function calls FT_Open_Face to open a font by its pathname.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_New_Face (IntPtr library, string filepathname, int face_index, out IntPtr face);
/// <summary>
/// Discard a given face object, as well as all of its child slots and sizes.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_Done_Face (IntPtr face);
/// <summary>
/// A function used to load a single glyph into the glyph slot of a face object.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_Load_Glyph (IntPtr face, uint glyph_index, int load_flags);
/// <summary>
/// Convert a given glyph image to a bitmap.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_Render_Glyph (ref FT_GlyphSlotRec slot, FT_Render_Mode render_mode);
/// <summary>
/// Retrieve kerning information for the specified pair of characters.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_Get_Kerning (IntPtr face, uint left, uint right, uint kern_mode, out FT_Vector kerning);
/// <summary>
/// This function calls FT_Request_Size to request the nominal size (in pixels).
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_Set_Pixel_Sizes (IntPtr face, uint pixel_width, uint pixel_height);
/// <summary>
/// Notify FreeType that you are done using the library. Should be called at the end.
/// </summary>
[DllImport(libName, CallingConvention = CallingConvention.Cdecl)]
static extern int FT_Done_FreeType (IntPtr library);
/// <summary>
/// Retrieve the list of faces from the specified font. For example: regular, bold, italic.
/// </summary>
static public string[] GetFaces (Font font)
{
if (font == null || !isPresent) return null;
string[] names = null;
IntPtr lib = IntPtr.Zero;
IntPtr face = IntPtr.Zero;
if (FT_Init_FreeType(out lib) != 0)
{
Debug.LogError("Failed to initialize FreeType");
return null;
}
string fileName = Application.dataPath.Substring(0, Application.dataPath.Length - "Assets".Length) +
UnityEditor.AssetDatabase.GetAssetPath(font);
if (File.Exists(fileName))
{
if (FT_New_Face(lib, fileName, 0, out face) != 0)
{
Debug.LogError("Unable to use the chosen font (FT_New_Face).");
}
else
{
FT_FaceRec record = (FT_FaceRec)Marshal.PtrToStructure(face, typeof(FT_FaceRec));
names = new string[record.num_faces];
for (int i = 0; i < record.num_faces; i++)
{
IntPtr ptr = IntPtr.Zero;
if (FT_New_Face(lib, fileName, i, out ptr) == 0)
{
string family = Marshal.PtrToStringAnsi(record.family_name);
string style = Marshal.PtrToStringAnsi(record.style_name);
names[i] = family + " - " + style;
FT_Done_Face(ptr);
}
}
}
}
if (face != IntPtr.Zero) FT_Done_Face(face);
#if !UNITY_3_5
if (lib != IntPtr.Zero) FT_Done_FreeType(lib);
#endif
return names;
}
/// <summary>
/// Create a bitmap font from the specified dynamic font.
/// </summary>
static public bool CreateFont (Font ttf, int size, int faceIndex, string characters, out BMFont font, out Texture2D tex)
{
font = null;
tex = null;
if (ttf == null || !isPresent) return false;
IntPtr lib = IntPtr.Zero;
IntPtr face = IntPtr.Zero;
if (FT_Init_FreeType(out lib) != 0)
{
Debug.LogError("Failed to initialize FreeType");
return false;
}
string fileName = Application.dataPath.Substring(0, Application.dataPath.Length - "Assets".Length) +
UnityEditor.AssetDatabase.GetAssetPath(ttf);
if (!File.Exists(fileName))
{
Debug.LogError("Unable to use the chosen font.");
}
else if (FT_New_Face(lib, fileName, faceIndex, out face) != 0)
{
Debug.LogError("Unable to use the chosen font (FT_New_Face).");
}
else
{
font = new BMFont();
font.charSize = size;
Color32 white = Color.white;
BetterList<int> entries = new BetterList<int>();
BetterList<Texture2D> textures = new BetterList<Texture2D>();
FT_FaceRec faceRec = (FT_FaceRec)Marshal.PtrToStructure(face, typeof(FT_FaceRec));
FT_Set_Pixel_Sizes(face, 0, (uint)size);
// Calculate the baseline value that would let the printed font be centered vertically
//int ascender = (faceRec.met.ascender >> 6);
//int descender = (faceRec.descender >> 6);
//int baseline = ((ascender - descender) >> 1);
//if ((baseline & 1) == 1) --baseline;
//Debug.Log(ascender + " " + descender + " " + baseline);
// Space character is not renderable
FT_Load_Glyph(face, FT_Get_Char_Index(face, 32), FT_LOAD_DEFAULT);
FT_GlyphSlotRec space = (FT_GlyphSlotRec)Marshal.PtrToStructure(faceRec.glyph, typeof(FT_GlyphSlotRec));
// Space is not visible and doesn't have a texture
BMGlyph spaceGlyph = font.GetGlyph(32, true);
spaceGlyph.offsetX = 0;
spaceGlyph.offsetY = 0;
spaceGlyph.advance = (space.metrics.horiAdvance >> 6);
spaceGlyph.channel = 15;
spaceGlyph.x = 0;
spaceGlyph.y = 0;
spaceGlyph.width = 0;
spaceGlyph.height = 0;
// Save kerning information
for (int b = 0; b < characters.Length; ++b)
{
uint ch2 = characters[b];
if (ch2 == 32) continue;
FT_Vector vec;
if (FT_Get_Kerning(face, ch2, 32, 0, out vec) != 0) continue;
int offset = (vec.x >> 6);
if (offset != 0) spaceGlyph.SetKerning((int)ch2, offset);
}
// Run through all requested characters
foreach (char ch in characters)
{
uint charIndex = FT_Get_Char_Index(face, (uint)ch);
FT_Load_Glyph(face, charIndex, FT_LOAD_DEFAULT);
FT_GlyphSlotRec glyph = (FT_GlyphSlotRec)Marshal.PtrToStructure(faceRec.glyph, typeof(FT_GlyphSlotRec));
FT_Render_Glyph(ref glyph, FT_Render_Mode.FT_RENDER_MODE_NORMAL);
if (glyph.bitmap.width > 0 && glyph.bitmap.rows > 0)
{
byte[] buffer = new byte[glyph.bitmap.width * glyph.bitmap.rows];
Marshal.Copy(glyph.bitmap.buffer, buffer, 0, buffer.Length);
Texture2D texture = new Texture2D(glyph.bitmap.width, glyph.bitmap.rows, UnityEngine.TextureFormat.ARGB32, false);
Color32[] colors = new Color32[buffer.Length];
for (int i = 0, y = 0; y < glyph.bitmap.rows; ++y)
{
for (int x = 0; x < glyph.bitmap.width; ++x)
{
white.a = buffer[i++];
colors[x + glyph.bitmap.width * (glyph.bitmap.rows - y - 1)] = white;
}
}
// Save the texture
texture.SetPixels32(colors);
texture.Apply();
textures.Add(texture);
entries.Add(ch);
// Record the metrics
BMGlyph bmg = font.GetGlyph(ch, true);
bmg.offsetX = (glyph.metrics.horiBearingX >> 6);
bmg.offsetY = -(glyph.metrics.horiBearingY >> 6);
bmg.advance = (glyph.metrics.horiAdvance >> 6);
bmg.channel = 15;
// Save kerning information
for (int b = 0; b < characters.Length; ++b)
{
uint ch2 = characters[b];
if (ch2 == ch) continue;
FT_Vector vec;
if (FT_Get_Kerning(face, ch2, ch, 0, out vec) != 0) continue;
int offset = (vec.x / 64);
if (offset != 0) bmg.SetKerning((int)ch2, offset);
}
}
}
// Create a packed texture with all the characters
tex = new Texture2D(32, 32, TextureFormat.ARGB32, false);
Rect[] rects = tex.PackTextures(textures.ToArray(), 1);
// Make the RGB channel pure white
Color32[] cols = tex.GetPixels32();
for (int i = 0, imax = cols.Length; i < imax; ++i)
{
Color32 c = cols[i];
c.r = 255;
c.g = 255;
c.b = 255;
cols[i] = c;
}
tex.SetPixels32(cols);
tex.Apply();
font.texWidth = tex.width;
font.texHeight = tex.height;
int min = int.MaxValue;
int max = int.MinValue;
// Other glyphs are visible and need to be added
for (int i = 0; i < entries.size; ++i)
{
// Destroy the texture now that it's a part of an atlas
UnityEngine.Object.DestroyImmediate(textures[i]);
textures[i] = null;
Rect rect = rects[i];
// Set the texture coordinates
BMGlyph glyph = font.GetGlyph(entries[i], true);
glyph.x = Mathf.RoundToInt(rect.x * font.texWidth);
glyph.y = Mathf.RoundToInt(rect.y * font.texHeight);
glyph.width = Mathf.RoundToInt(rect.width * font.texWidth);
glyph.height = Mathf.RoundToInt(rect.height * font.texHeight);
// Flip the Y since the UV coordinate system is different
glyph.y = font.texHeight - glyph.y - glyph.height;
max = Mathf.Max(max, -glyph.offsetY);
min = Mathf.Min(min, -glyph.offsetY - glyph.height);
}
int baseline = size + min;
baseline += ((max - min - size) >> 1);
// Offset all glyphs so that they are not using the baseline
for (int i = 0; i < entries.size; ++i)
{
BMGlyph glyph = font.GetGlyph(entries[i], true);
glyph.offsetY += baseline;
}
}
if (face != IntPtr.Zero) FT_Done_Face(face);
#if !UNITY_3_5
if (lib != IntPtr.Zero) FT_Done_FreeType(lib);
#endif
return (tex != null);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/FreeType.cs
|
C#
|
asf20
| 20,032
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
#if UNITY_3_5
[CustomEditor(typeof(UIButton))]
#else
[CustomEditor(typeof(UIButton), true)]
#endif
public class UIButtonEditor : UIButtonColorEditor
{
enum Highlight
{
DoNothing,
Press,
}
protected override void DrawProperties ()
{
SerializedProperty sp = serializedObject.FindProperty("dragHighlight");
Highlight ht = sp.boolValue ? Highlight.Press : Highlight.DoNothing;
GUILayout.BeginHorizontal();
bool highlight = (Highlight)EditorGUILayout.EnumPopup("Drag Over", ht) == Highlight.Press;
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (sp.boolValue != highlight) sp.boolValue = highlight;
DrawTransition();
DrawColors();
UIButton btn = target as UIButton;
if (btn.tweenTarget != null)
{
UISprite sprite = btn.tweenTarget.GetComponent<UISprite>();
if (sprite != null)
{
if (NGUIEditorTools.DrawHeader("Sprites"))
{
NGUIEditorTools.BeginContents();
EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
{
SerializedObject obj = new SerializedObject(sprite);
obj.Update();
SerializedProperty atlas = obj.FindProperty("mAtlas");
NGUIEditorTools.DrawSpriteField("Normal", obj, atlas, obj.FindProperty("mSpriteName"));
obj.ApplyModifiedProperties();
NGUIEditorTools.DrawSpriteField("Hover", serializedObject, atlas, serializedObject.FindProperty("hoverSprite"), true);
NGUIEditorTools.DrawSpriteField("Pressed", serializedObject, atlas, serializedObject.FindProperty("pressedSprite"), true);
NGUIEditorTools.DrawSpriteField("Disabled", serializedObject, atlas, serializedObject.FindProperty("disabledSprite"), true);
}
EditorGUI.EndDisabledGroup();
NGUIEditorTools.DrawProperty("Pixel Snap", serializedObject, "pixelSnap");
NGUIEditorTools.EndContents();
}
}
}
UIButton button = target as UIButton;
NGUIEditorTools.DrawEvents("On Click", button, button.onClick);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIButtonEditor.cs
|
C#
|
asf20
| 2,193
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIRoot))]
public class UIRootEditor : Editor
{
public override void OnInspectorGUI ()
{
serializedObject.Update();
SerializedProperty sp = NGUIEditorTools.DrawProperty("Scaling Style", serializedObject, "scalingStyle");
UIRoot.Scaling scaling = (UIRoot.Scaling)sp.intValue;
if (scaling != UIRoot.Scaling.PixelPerfect)
{
NGUIEditorTools.DrawProperty("Manual Height", serializedObject, "manualHeight");
}
if (scaling != UIRoot.Scaling.FixedSize)
{
NGUIEditorTools.DrawProperty("Minimum Height", serializedObject, "minimumHeight");
NGUIEditorTools.DrawProperty("Maximum Height", serializedObject, "maximumHeight");
}
NGUIEditorTools.DrawProperty("Shrink Portrait UI", serializedObject, "shrinkPortraitUI");
NGUIEditorTools.DrawProperty("Adjust by DPI", serializedObject, "adjustByDPI");
serializedObject.ApplyModifiedProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIRootEditor.cs
|
C#
|
asf20
| 1,143
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Reflection;
using System.Collections.Generic;
using Entry = PropertyReferenceDrawer.Entry;
public static class EventDelegateEditor
{
/// <summary>
/// Collect a list of usable delegates from the specified target game object.
/// </summary>
static List<Entry> GetMethods (GameObject target)
{
MonoBehaviour[] comps = target.GetComponents<MonoBehaviour>();
List<Entry> list = new List<Entry>();
for (int i = 0, imax = comps.Length; i < imax; ++i)
{
MonoBehaviour mb = comps[i];
if (mb == null) continue;
MethodInfo[] methods = mb.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public);
for (int b = 0; b < methods.Length; ++b)
{
MethodInfo mi = methods[b];
if (mi.ReturnType == typeof(void))
{
string name = mi.Name;
if (name == "Invoke") continue;
if (name == "InvokeRepeating") continue;
if (name == "CancelInvoke") continue;
if (name == "StopCoroutine") continue;
if (name == "StopAllCoroutines") continue;
if (name == "BroadcastMessage") continue;
if (name.StartsWith("SendMessage")) continue;
if (name.StartsWith("set_")) continue;
Entry ent = new Entry();
ent.target = mb;
ent.name = mi.Name;
list.Add(ent);
}
}
}
return list;
}
/// <summary>
/// Draw an editor field for the Unity Delegate.
/// </summary>
static public bool Field (Object undoObject, EventDelegate del)
{
return Field(undoObject, del, true);
}
/// <summary>
/// Draw an editor field for the Unity Delegate.
/// </summary>
static public bool Field (Object undoObject, EventDelegate del, bool removeButton)
{
if (del == null) return false;
bool prev = GUI.changed;
GUI.changed = false;
bool retVal = false;
MonoBehaviour target = del.target;
bool remove = false;
if (removeButton && (del.target != null || del.isValid))
{
if (del.target == null && del.isValid)
{
EditorGUILayout.LabelField("Notify", del.ToString());
}
else
{
target = EditorGUILayout.ObjectField("Notify", del.target, typeof(MonoBehaviour), true) as MonoBehaviour;
}
GUILayout.Space(-20f);
GUILayout.BeginHorizontal();
GUILayout.Space(64f);
#if UNITY_3_5
if (GUILayout.Button("X", GUILayout.Width(20f)))
#else
if (GUILayout.Button("", "ToggleMixed", GUILayout.Width(20f)))
#endif
{
target = null;
remove = true;
}
GUILayout.EndHorizontal();
}
else
{
target = EditorGUILayout.ObjectField("Notify", del.target, typeof(MonoBehaviour), true) as MonoBehaviour;
}
if (remove)
{
NGUIEditorTools.RegisterUndo("Delegate Selection", undoObject);
del.Clear();
EditorUtility.SetDirty(undoObject);
}
else if (del.target != target)
{
NGUIEditorTools.RegisterUndo("Delegate Selection", undoObject);
del.target = target;
EditorUtility.SetDirty(undoObject);
}
if (del.target != null && del.target.gameObject != null)
{
GameObject go = del.target.gameObject;
List<Entry> list = GetMethods(go);
int index = 0;
string[] names = PropertyReferenceDrawer.GetNames(list, del.ToString(), out index);
int choice = 0;
GUILayout.BeginHorizontal();
choice = EditorGUILayout.Popup("Method", index, names);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (choice > 0 && choice != index)
{
Entry entry = list[choice - 1];
NGUIEditorTools.RegisterUndo("Delegate Selection", undoObject);
del.target = entry.target as MonoBehaviour;
del.methodName = entry.name;
EditorUtility.SetDirty(undoObject);
retVal = true;
}
GUI.changed = false;
EventDelegate.Parameter[] ps = del.parameters;
if (ps != null)
{
for (int i = 0; i < ps.Length; ++i)
{
EventDelegate.Parameter param = ps[i];
Object obj = EditorGUILayout.ObjectField(" Arg " + i, param.obj, typeof(Object), true);
if (GUI.changed)
{
GUI.changed = false;
param.obj = obj;
EditorUtility.SetDirty(undoObject);
}
if (obj == null) continue;
System.Type type = obj.GetType();
GameObject selGO = null;
if (type == typeof(GameObject)) selGO = obj as GameObject;
else if (type.IsSubclassOf(typeof(Component))) selGO = (obj as Component).gameObject;
if (selGO != null)
{
// Parameters must be exact -- they can't be converted like property bindings
PropertyReferenceDrawer.filter = param.expectedType;
PropertyReferenceDrawer.canConvert = false;
List<PropertyReferenceDrawer.Entry> ents = PropertyReferenceDrawer.GetProperties(selGO, true, false);
int selection;
string[] props = GetNames(ents, NGUITools.GetFuncName(param.obj, param.field), out selection);
GUILayout.BeginHorizontal();
int newSel = EditorGUILayout.Popup(" ", selection, props);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (GUI.changed)
{
GUI.changed = false;
if (newSel == 0)
{
param.obj = selGO;
param.field = null;
}
else
{
param.obj = ents[newSel - 1].target;
param.field = ents[newSel - 1].name;
}
EditorUtility.SetDirty(undoObject);
}
}
else if (!string.IsNullOrEmpty(param.field))
{
param.field = null;
EditorUtility.SetDirty(undoObject);
}
PropertyReferenceDrawer.filter = typeof(void);
PropertyReferenceDrawer.canConvert = true;
}
}
}
else retVal = GUI.changed;
GUI.changed = prev;
return retVal;
}
/// <summary>
/// Convert the specified list of delegate entries into a string array.
/// </summary>
static string[] GetNames (List<Entry> list, string choice, out int index)
{
index = 0;
string[] names = new string[list.Count + 1];
names[0] = "<GameObject>";
for (int i = 0; i < list.Count; )
{
Entry ent = list[i];
string del = NGUITools.GetFuncName(ent.target, ent.name);
names[++i] = del;
if (index == 0 && string.Equals(del, choice))
index = i;
}
return names;
}
/// <summary>
/// Draw a list of fields for the specified list of delegates.
/// </summary>
static public void Field (Object undoObject, List<EventDelegate> list)
{
Field(undoObject, list, null, null);
}
/// <summary>
/// Draw a list of fields for the specified list of delegates.
/// </summary>
static public void Field (Object undoObject, List<EventDelegate> list, string noTarget, string notValid)
{
bool targetPresent = false;
bool isValid = false;
// Draw existing delegates
for (int i = 0; i < list.Count; )
{
EventDelegate del = list[i];
if (del == null || (del.target == null && !del.isValid))
{
list.RemoveAt(i);
continue;
}
Field(undoObject, del);
EditorGUILayout.Space();
if (del.target == null && !del.isValid)
{
list.RemoveAt(i);
continue;
}
else
{
if (del.target != null) targetPresent = true;
isValid = true;
}
++i;
}
// Draw a new delegate
EventDelegate newDel = new EventDelegate();
Field(undoObject, newDel);
if (newDel.target != null)
{
targetPresent = true;
list.Add(newDel);
}
if (!targetPresent)
{
if (!string.IsNullOrEmpty(noTarget))
{
GUILayout.Space(6f);
EditorGUILayout.HelpBox(noTarget, MessageType.Info, true);
GUILayout.Space(6f);
}
}
else if (!isValid)
{
if (!string.IsNullOrEmpty(notValid))
{
GUILayout.Space(6f);
EditorGUILayout.HelpBox(notValid, MessageType.Warning, true);
GUILayout.Space(6f);
}
}
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/EventDelegateEditor.cs
|
C#
|
asf20
| 7,758
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
// Dynamic font support contributed by the NGUI community members:
// Unisip, zh4ox, Mudwiz, Nicki, DarkMagicCK.
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to view and edit UIFonts.
/// </summary>
[CustomEditor(typeof(UIFont))]
public class UIFontInspector : Editor
{
enum View
{
Nothing,
Atlas,
Font,
}
enum FontType
{
Bitmap,
Reference,
Dynamic,
}
static View mView = View.Font;
static bool mUseShader = false;
UIFont mFont;
FontType mType = FontType.Bitmap;
UIFont mReplacement = null;
string mSymbolSequence = "";
string mSymbolSprite = "";
BMSymbol mSelectedSymbol = null;
AnimationCurve mCurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(1f, 1f));
public override bool HasPreviewGUI () { return mView != View.Nothing; }
void OnSelectFont (Object obj)
{
// Undo doesn't work correctly in this case... so I won't bother.
//NGUIEditorTools.RegisterUndo("Font Change");
//NGUIEditorTools.RegisterUndo("Font Change", mFont);
mFont.replacement = obj as UIFont;
mReplacement = mFont.replacement;
NGUITools.SetDirty(mFont);
}
void OnSelectAtlas (Object obj)
{
if (mFont != null && mFont.atlas != obj)
{
NGUIEditorTools.RegisterUndo("Font Atlas", mFont);
mFont.atlas = obj as UIAtlas;
MarkAsChanged();
}
}
void MarkAsChanged ()
{
List<UILabel> labels = NGUIEditorTools.FindAll<UILabel>();
foreach (UILabel lbl in labels)
{
if (UIFont.CheckIfRelated(lbl.bitmapFont, mFont))
{
lbl.bitmapFont = null;
lbl.bitmapFont = mFont;
}
}
}
public override void OnInspectorGUI ()
{
mFont = target as UIFont;
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.Space(6f);
if (mFont.replacement != null)
{
mType = FontType.Reference;
mReplacement = mFont.replacement;
}
else if (mFont.dynamicFont != null)
{
mType = FontType.Dynamic;
}
GUI.changed = false;
GUILayout.BeginHorizontal();
mType = (FontType)EditorGUILayout.EnumPopup("Font Type", mType);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (GUI.changed)
{
if (mType == FontType.Bitmap)
OnSelectFont(null);
if (mType != FontType.Dynamic && mFont.dynamicFont != null)
mFont.dynamicFont = null;
}
if (mType == FontType.Reference)
{
ComponentSelector.Draw<UIFont>(mFont.replacement, OnSelectFont, true);
GUILayout.Space(6f);
EditorGUILayout.HelpBox("You can have one font simply point to " +
"another one. This is useful if you want to be " +
"able to quickly replace the contents of one " +
"font with another one, for example for " +
"swapping an SD font with an HD one, or " +
"replacing an English font with a Chinese " +
"one. All the labels referencing this font " +
"will update their references to the new one.", MessageType.Info);
if (mReplacement != mFont && mFont.replacement != mReplacement)
{
NGUIEditorTools.RegisterUndo("Font Change", mFont);
mFont.replacement = mReplacement;
NGUITools.SetDirty(mFont);
}
return;
}
else if (mType == FontType.Dynamic)
{
#if UNITY_3_5
EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
Font fnt = EditorGUILayout.ObjectField("TTF Font", mFont.dynamicFont, typeof(Font), false) as Font;
if (fnt != mFont.dynamicFont)
{
NGUIEditorTools.RegisterUndo("Font change", mFont);
mFont.dynamicFont = fnt;
}
Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;
if (mFont.material != mat)
{
NGUIEditorTools.RegisterUndo("Font Material", mFont);
mFont.material = mat;
}
GUILayout.BeginHorizontal();
int size = EditorGUILayout.IntField("Default Size", mFont.defaultSize, GUILayout.Width(120f));
FontStyle style = (FontStyle)EditorGUILayout.EnumPopup(mFont.dynamicFontStyle);
GUILayout.Space(18f);
GUILayout.EndHorizontal();
if (size != mFont.defaultSize)
{
NGUIEditorTools.RegisterUndo("Font change", mFont);
mFont.defaultSize = size;
}
if (style != mFont.dynamicFontStyle)
{
NGUIEditorTools.RegisterUndo("Font change", mFont);
mFont.dynamicFontStyle = style;
}
#endif
}
else
{
ComponentSelector.Draw<UIAtlas>(mFont.atlas, OnSelectAtlas, true);
if (mFont.atlas != null)
{
if (mFont.bmFont.isValid)
{
NGUIEditorTools.DrawAdvancedSpriteField(mFont.atlas, mFont.spriteName, SelectSprite, false);
}
EditorGUILayout.Space();
}
else
{
// No atlas specified -- set the material and texture rectangle directly
Material mat = EditorGUILayout.ObjectField("Material", mFont.material, typeof(Material), false) as Material;
if (mFont.material != mat)
{
NGUIEditorTools.RegisterUndo("Font Material", mFont);
mFont.material = mat;
}
}
// For updating the font's data when importing from an external source, such as the texture packer
bool resetWidthHeight = false;
if (mFont.atlas != null || mFont.material != null)
{
TextAsset data = EditorGUILayout.ObjectField("Import Data", null, typeof(TextAsset), false) as TextAsset;
if (data != null)
{
NGUIEditorTools.RegisterUndo("Import Font Data", mFont);
BMFontReader.Load(mFont.bmFont, NGUITools.GetHierarchy(mFont.gameObject), data.bytes);
mFont.MarkAsChanged();
resetWidthHeight = true;
Debug.Log("Imported " + mFont.bmFont.glyphCount + " characters");
}
}
if (mFont.bmFont.isValid)
{
Texture2D tex = mFont.texture;
if (tex != null && mFont.atlas == null)
{
// Pixels are easier to work with than UVs
Rect pixels = NGUIMath.ConvertToPixels(mFont.uvRect, tex.width, tex.height, false);
// Automatically set the width and height of the rectangle to be the original font texture's dimensions
if (resetWidthHeight)
{
pixels.width = mFont.texWidth;
pixels.height = mFont.texHeight;
}
// Font sprite rectangle
pixels = EditorGUILayout.RectField("Pixel Rect", pixels);
// Convert the pixel coordinates back to UV coordinates
Rect uvRect = NGUIMath.ConvertToTexCoords(pixels, tex.width, tex.height);
if (mFont.uvRect != uvRect)
{
NGUIEditorTools.RegisterUndo("Font Pixel Rect", mFont);
mFont.uvRect = uvRect;
}
//NGUIEditorTools.DrawSeparator();
EditorGUILayout.Space();
}
}
}
// Dynamic fonts don't support emoticons
if (!mFont.isDynamic && mFont.bmFont.isValid)
{
if (mFont.atlas != null)
{
if (NGUIEditorTools.DrawHeader("Symbols and Emoticons"))
{
NGUIEditorTools.BeginContents();
List<BMSymbol> symbols = mFont.symbols;
for (int i = 0; i < symbols.Count; )
{
BMSymbol sym = symbols[i];
GUILayout.BeginHorizontal();
GUILayout.Label(sym.sequence, GUILayout.Width(40f));
if (NGUIEditorTools.DrawSpriteField(mFont.atlas, sym.spriteName, ChangeSymbolSprite, GUILayout.MinWidth(100f)))
mSelectedSymbol = sym;
if (GUILayout.Button("Edit", GUILayout.Width(40f)))
{
if (mFont.atlas != null)
{
NGUISettings.atlas = mFont.atlas;
NGUISettings.selectedSprite = sym.spriteName;
NGUIEditorTools.Select(mFont.atlas.gameObject);
}
}
GUI.backgroundColor = Color.red;
if (GUILayout.Button("X", GUILayout.Width(22f)))
{
NGUIEditorTools.RegisterUndo("Remove symbol", mFont);
mSymbolSequence = sym.sequence;
mSymbolSprite = sym.spriteName;
symbols.Remove(sym);
mFont.MarkAsChanged();
}
GUI.backgroundColor = Color.white;
GUILayout.EndHorizontal();
GUILayout.Space(4f);
++i;
}
if (symbols.Count > 0)
{
GUILayout.Space(6f);
}
GUILayout.BeginHorizontal();
mSymbolSequence = EditorGUILayout.TextField(mSymbolSequence, GUILayout.Width(40f));
NGUIEditorTools.DrawSpriteField(mFont.atlas, mSymbolSprite, SelectSymbolSprite);
bool isValid = !string.IsNullOrEmpty(mSymbolSequence) && !string.IsNullOrEmpty(mSymbolSprite);
GUI.backgroundColor = isValid ? Color.green : Color.grey;
if (GUILayout.Button("Add", GUILayout.Width(40f)) && isValid)
{
NGUIEditorTools.RegisterUndo("Add symbol", mFont);
mFont.AddSymbol(mSymbolSequence, mSymbolSprite);
mFont.MarkAsChanged();
mSymbolSequence = "";
mSymbolSprite = "";
}
GUI.backgroundColor = Color.white;
GUILayout.EndHorizontal();
if (symbols.Count == 0)
{
EditorGUILayout.HelpBox("Want to add an emoticon to your font? In the field above type ':)', choose a sprite, then hit the Add button.", MessageType.Info);
}
else GUILayout.Space(4f);
NGUIEditorTools.EndContents();
}
}
}
if (mFont.bmFont != null && mFont.bmFont.isValid)
{
if (NGUIEditorTools.DrawHeader("Modify"))
{
NGUIEditorTools.BeginContents();
UISpriteData sd = mFont.sprite;
bool disable = (sd != null && (sd.paddingLeft != 0 || sd.paddingBottom != 0));
EditorGUI.BeginDisabledGroup(disable || mFont.packedFontShader);
EditorGUILayout.BeginHorizontal();
GUILayout.Space(20f);
EditorGUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUILayout.BeginVertical();
NGUISettings.foregroundColor = EditorGUILayout.ColorField("Foreground", NGUISettings.foregroundColor);
NGUISettings.backgroundColor = EditorGUILayout.ColorField("Background", NGUISettings.backgroundColor);
GUILayout.EndVertical();
mCurve = EditorGUILayout.CurveField("", mCurve, GUILayout.Width(40f), GUILayout.Height(40f));
GUILayout.EndHorizontal();
if (GUILayout.Button("Add a Shadow")) ApplyEffect(Effect.Shadow, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
if (GUILayout.Button("Add a Soft Outline")) ApplyEffect(Effect.Outline, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
if (GUILayout.Button("Rebalance Colors")) ApplyEffect(Effect.Rebalance, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
if (GUILayout.Button("Apply Curve to Alpha")) ApplyEffect(Effect.AlphaCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
if (GUILayout.Button("Apply Curve to Foreground")) ApplyEffect(Effect.ForegroundCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
if (GUILayout.Button("Apply Curve to Background")) ApplyEffect(Effect.BackgroundCurve, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
GUILayout.Space(10f);
if (GUILayout.Button("Add Transparent Border (+1)")) ApplyEffect(Effect.Border, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
if (GUILayout.Button("Remove Border (-1)")) ApplyEffect(Effect.Crop, NGUISettings.foregroundColor, NGUISettings.backgroundColor);
EditorGUILayout.EndVertical();
GUILayout.Space(20f);
EditorGUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
if (disable)
{
GUILayout.Space(3f);
EditorGUILayout.HelpBox("The sprite used by this font has been trimmed and is not suitable for modification. " +
"Try re-adding this sprite with 'Trim Alpha' disabled.", MessageType.Warning);
}
NGUIEditorTools.EndContents();
}
}
// The font must be valid at this point for the rest of the options to show up
if (mFont.isDynamic || mFont.bmFont.isValid)
{
if (mFont.atlas == null)
{
mView = View.Font;
mUseShader = false;
}
}
// Preview option
if (!mFont.isDynamic && mFont.atlas != null)
{
GUILayout.BeginHorizontal();
{
mView = (View)EditorGUILayout.EnumPopup("Preview", mView);
GUILayout.Label("Shader", GUILayout.Width(45f));
mUseShader = EditorGUILayout.Toggle(mUseShader, GUILayout.Width(20f));
}
GUILayout.EndHorizontal();
}
}
/// <summary>
/// "New Sprite" selection.
/// </summary>
void SelectSymbolSprite (string spriteName)
{
mSymbolSprite = spriteName;
Repaint();
}
/// <summary>
/// Existing sprite selection.
/// </summary>
void ChangeSymbolSprite (string spriteName)
{
if (mSelectedSymbol != null && mFont != null)
{
NGUIEditorTools.RegisterUndo("Change symbol", mFont);
mSelectedSymbol.spriteName = spriteName;
Repaint();
mFont.MarkAsChanged();
}
}
/// <summary>
/// Draw the font preview window.
/// </summary>
public override void OnPreviewGUI (Rect rect, GUIStyle background)
{
mFont = target as UIFont;
if (mFont == null) return;
Texture2D tex = mFont.texture;
if (mView != View.Nothing && tex != null)
{
Material m = (mUseShader ? mFont.material : null);
if (mView == View.Font && mFont.atlas != null && mFont.sprite != null)
{
NGUIEditorTools.DrawSprite(tex, rect, mFont.sprite, Color.white, m);
}
else
{
NGUIEditorTools.DrawTexture(tex, rect, new Rect(0f, 0f, 1f, 1f), Color.white, m);
}
}
}
/// <summary>
/// Sprite selection callback.
/// </summary>
void SelectSprite (string spriteName)
{
NGUIEditorTools.RegisterUndo("Font Sprite", mFont);
mFont.spriteName = spriteName;
Repaint();
}
enum Effect
{
Rebalance,
ForegroundCurve,
BackgroundCurve,
AlphaCurve,
Border,
Shadow,
Outline,
Crop,
}
/// <summary>
/// Apply an effect to the font.
/// </summary>
void ApplyEffect (Effect effect, Color foreground, Color background)
{
BMFont bf = mFont.bmFont;
int offsetX = 0;
int offsetY = 0;
if (mFont.atlas != null)
{
UISpriteData sd = mFont.atlas.GetSprite(bf.spriteName);
if (sd == null) return;
offsetX = sd.x;
offsetY = sd.y + mFont.texHeight - sd.paddingTop;
}
string path = AssetDatabase.GetAssetPath(mFont.texture);
Texture2D bfTex = NGUIEditorTools.ImportTexture(path, true, true, false);
Color32[] atlas = bfTex.GetPixels32();
// First we need to extract textures for all the glyphs, making them bigger in the process
List<BMGlyph> glyphs = bf.glyphs;
List<Texture2D> glyphTextures = new List<Texture2D>(glyphs.Count);
for (int i = 0, imax = glyphs.Count; i < imax; ++i)
{
BMGlyph glyph = glyphs[i];
if (glyph.width < 1 || glyph.height < 1) continue;
int width = glyph.width;
int height = glyph.height;
if (effect == Effect.Outline || effect == Effect.Shadow || effect == Effect.Border)
{
width += 2;
height += 2;
--glyph.offsetX;
--glyph.offsetY;
}
else if (effect == Effect.Crop && width > 2 && height > 2)
{
width -= 2;
height -= 2;
++glyph.offsetX;
++glyph.offsetY;
}
int size = width * height;
Color32[] colors = new Color32[size];
Color32 clear = background;
clear.a = 0;
for (int b = 0; b < size; ++b) colors[b] = clear;
if (effect == Effect.Crop)
{
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
int fx = x + glyph.x + offsetX + 1;
int fy = y + (mFont.texHeight - glyph.y - glyph.height) + 1;
if (mFont.atlas != null) fy += bfTex.height - offsetY;
colors[x + y * width] = atlas[fx + fy * bfTex.width];
}
}
}
else
{
for (int y = 0; y < glyph.height; ++y)
{
for (int x = 0; x < glyph.width; ++x)
{
int fx = x + glyph.x + offsetX;
int fy = y + (mFont.texHeight - glyph.y - glyph.height);
if (mFont.atlas != null) fy += bfTex.height - offsetY;
Color c = atlas[fx + fy * bfTex.width];
if (effect == Effect.Border)
{
colors[x + 1 + (y + 1) * width] = c;
}
else
{
if (effect == Effect.AlphaCurve) c.a = Mathf.Clamp01(mCurve.Evaluate(c.a));
Color bg = background;
bg.a = (effect == Effect.BackgroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a;
Color fg = foreground;
fg.a = (effect == Effect.ForegroundCurve) ? Mathf.Clamp01(mCurve.Evaluate(c.a)) : c.a;
if (effect == Effect.Outline || effect == Effect.Shadow)
{
colors[x + 1 + (y + 1) * width] = Color.Lerp(bg, c, c.a);
}
else
{
colors[x + y * width] = Color.Lerp(bg, fg, c.a);
}
}
}
}
// Apply the appropriate affect
if (effect == Effect.Shadow) NGUIEditorTools.AddShadow(colors, width, height, NGUISettings.backgroundColor);
else if (effect == Effect.Outline) NGUIEditorTools.AddDepth(colors, width, height, NGUISettings.backgroundColor);
}
Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
tex.SetPixels32(colors);
tex.Apply();
glyphTextures.Add(tex);
}
// Pack all glyphs into a new texture
Texture2D final = new Texture2D(bfTex.width, bfTex.height, TextureFormat.ARGB32, false);
Rect[] rects = final.PackTextures(glyphTextures.ToArray(), 1);
final.Apply();
// Make RGB channel use the background color (Unity makes it black by default)
Color32[] fcs = final.GetPixels32();
Color32 bc = background;
for (int i = 0, imax = fcs.Length; i < imax; ++i)
{
if (fcs[i].a == 0)
{
fcs[i].r = bc.r;
fcs[i].g = bc.g;
fcs[i].b = bc.b;
}
}
final.SetPixels32(fcs);
final.Apply();
// Update the glyph rectangles
int index = 0;
int tw = final.width;
int th = final.height;
for (int i = 0, imax = glyphs.Count; i < imax; ++i)
{
BMGlyph glyph = glyphs[i];
if (glyph.width < 1 || glyph.height < 1) continue;
Rect rect = rects[index++];
glyph.x = Mathf.RoundToInt(rect.x * tw);
glyph.y = Mathf.RoundToInt(rect.y * th);
glyph.width = Mathf.RoundToInt(rect.width * tw);
glyph.height = Mathf.RoundToInt(rect.height * th);
glyph.y = th - glyph.y - glyph.height;
}
// Update the font's texture dimensions
mFont.texWidth = final.width;
mFont.texHeight = final.height;
if (mFont.atlas == null)
{
// Save the final texture
byte[] bytes = final.EncodeToPNG();
NGUITools.DestroyImmediate(final);
System.IO.File.WriteAllBytes(path, bytes);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
}
else
{
// Update the atlas
final.name = mFont.spriteName;
bool val = NGUISettings.atlasTrimming;
NGUISettings.atlasTrimming = false;
UIAtlasMaker.AddOrUpdate(mFont.atlas, final);
NGUISettings.atlasTrimming = val;
NGUITools.DestroyImmediate(final);
}
// Cleanup
for (int i = 0; i < glyphTextures.Count; ++i)
NGUITools.DestroyImmediate(glyphTextures[i]);
// Refresh all labels
mFont.MarkAsChanged();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIFontInspector.cs
|
C#
|
asf20
| 18,659
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenTransform))]
public class TweenTransformEditor : UITweenerEditor
{
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenTransformEditor.cs
|
C#
|
asf20
| 318
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Text;
using System.IO;
/// <summary>
/// Font maker lets you create font prefabs with a single click of a button.
/// </summary>
public class UIFontMaker : EditorWindow
{
enum FontType
{
GeneratedBitmap, // Bitmap font, created from a dynamic font using FreeType
ImportedBitmap, // Imported bitmap font, created using BMFont or another external tool
Dynamic, // Dynamic font, used as-is
}
enum Create
{
None,
Bitmap, // Bitmap font, created from a dynamic font using FreeType
Import, // Imported bitmap font
Dynamic, // Dynamic font, used as-is
}
enum CharacterMap
{
Numeric, // 0 through 9
Ascii, // Character IDs 32 through 127
Latin, // Ascii + various accented character such as "é"
Custom, // Only explicitly specified characters will be included
}
FontType mType = FontType.GeneratedBitmap;
int mFaceIndex = 0;
/// <summary>
/// Type of character map chosen for export.
/// </summary>
static CharacterMap characterMap
{
get { return (CharacterMap)NGUISettings.GetInt("NGUI Character Map", (int)CharacterMap.Ascii); }
set { NGUISettings.SetInt("NGUI Character Map", (int)value); }
}
/// <summary>
/// Update all labels associated with this font.
/// </summary>
void MarkAsChanged ()
{
if (NGUISettings.ambigiousFont != null)
{
List<UILabel> labels = NGUIEditorTools.FindAll<UILabel>();
foreach (UILabel lbl in labels)
{
if (lbl.ambigiousFont == NGUISettings.ambigiousFont)
{
lbl.ambigiousFont = null;
lbl.ambigiousFont = NGUISettings.ambigiousFont;
}
}
}
}
/// <summary>
/// Atlas selection callback.
/// </summary>
void OnSelectAtlas (Object obj)
{
if (NGUISettings.atlas != obj)
{
NGUISettings.atlas = obj as UIAtlas;
Repaint();
}
}
/// <summary>
/// Refresh the window on selection.
/// </summary>
void OnSelectionChange () { Repaint(); }
void OnUnityFont (Object obj) { NGUISettings.ambigiousFont = obj; }
/// <summary>
/// Draw the UI for this tool.
/// </summary>
void OnGUI ()
{
Object fnt = NGUISettings.ambigiousFont;
UIFont uiFont = (fnt as UIFont);
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.Space(3f);
NGUIEditorTools.DrawHeader("Input", true);
NGUIEditorTools.BeginContents();
GUILayout.BeginHorizontal();
mType = (FontType)EditorGUILayout.EnumPopup("Type", mType, GUILayout.MinWidth(200f));
GUILayout.Space(18f);
GUILayout.EndHorizontal();
Create create = Create.None;
if (mType == FontType.ImportedBitmap)
{
NGUISettings.fontData = EditorGUILayout.ObjectField("Font Data", NGUISettings.fontData, typeof(TextAsset), false) as TextAsset;
NGUISettings.fontTexture = EditorGUILayout.ObjectField("Texture", NGUISettings.fontTexture, typeof(Texture2D), false, GUILayout.Width(140f)) as Texture2D;
NGUIEditorTools.EndContents();
// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
{
NGUIEditorTools.DrawHeader("Output", true);
NGUIEditorTools.BeginContents();
ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
NGUIEditorTools.EndContents();
}
EditorGUI.EndDisabledGroup();
if (NGUISettings.fontData == null)
{
EditorGUILayout.HelpBox("To create a font from a previously exported FNT file, you need to use BMFont on " +
"Windows or your choice of Glyph Designer or the less expensive bmGlyph on the Mac.\n\n" +
"Either of these tools will create a FNT file for you that you will drag & drop into the field above.", MessageType.Info);
}
else if (NGUISettings.fontTexture == null)
{
EditorGUILayout.HelpBox("When exporting your font, you should get two files: the FNT, and the texture. Only one texture can be used per font.", MessageType.Info);
}
else if (NGUISettings.atlas == null)
{
EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
}
EditorGUI.BeginDisabledGroup(NGUISettings.fontData == null || NGUISettings.fontTexture == null);
{
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
if (GUILayout.Button("Create the Font")) create = Create.Import;
GUILayout.Space(20f);
GUILayout.EndHorizontal();
}
EditorGUI.EndDisabledGroup();
}
else
{
GUILayout.BeginHorizontal();
if (NGUIEditorTools.DrawPrefixButton("Source"))
ComponentSelector.Show<Font>(OnUnityFont, new string[] { ".ttf", ".otf" });
Font ttf = EditorGUILayout.ObjectField(NGUISettings.ambigiousFont as Font, typeof(Font), false) as Font;
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
{
NGUISettings.fontSize = EditorGUILayout.IntField("Size", NGUISettings.fontSize, GUILayout.Width(120f));
if (mType == FontType.Dynamic)
{
NGUISettings.fontStyle = (FontStyle)EditorGUILayout.EnumPopup(NGUISettings.fontStyle);
GUILayout.Space(18f);
}
}
GUILayout.EndHorizontal();
// Choose the font style if there are multiple faces present
if (mType == FontType.GeneratedBitmap)
{
if (!FreeType.isPresent)
{
string filename = (Application.platform == RuntimePlatform.WindowsEditor) ? "FreeType.dll" : "FreeType.dylib";
EditorGUILayout.HelpBox("Assets/NGUI/Editor/" + filename + " is missing", MessageType.Error);
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
if (GUILayout.Button("Find " + filename))
{
string path = EditorUtility.OpenFilePanel("Find " + filename, "Assets",
(Application.platform == RuntimePlatform.WindowsEditor) ? "dll" : "dylib");
if (!string.IsNullOrEmpty(path))
{
if (System.IO.Path.GetFileName(path) == filename)
{
NGUISettings.pathToFreeType = path;
}
else Debug.LogError("The library must be named '" + filename + "'");
}
}
GUILayout.Space(20f);
GUILayout.EndHorizontal();
}
else if (ttf != null)
{
string[] faces = FreeType.GetFaces(ttf);
if (faces != null)
{
if (mFaceIndex >= faces.Length) mFaceIndex = 0;
if (faces.Length > 1)
{
GUILayout.Label("Style", EditorStyles.boldLabel);
for (int i = 0; i < faces.Length; ++i)
{
GUILayout.BeginHorizontal();
GUILayout.Space(10f);
if (DrawOption(i == mFaceIndex, " " + faces[i]))
mFaceIndex = i;
GUILayout.EndHorizontal();
}
}
}
GUILayout.Label("Characters", EditorStyles.boldLabel);
CharacterMap cm = characterMap;
GUILayout.BeginHorizontal(GUILayout.Width(100f));
GUILayout.BeginVertical();
GUI.changed = false;
if (DrawOption(cm == CharacterMap.Numeric, " Numeric")) cm = CharacterMap.Numeric;
if (DrawOption(cm == CharacterMap.Ascii, " ASCII")) cm = CharacterMap.Ascii;
if (DrawOption(cm == CharacterMap.Latin, " Latin")) cm = CharacterMap.Latin;
if (DrawOption(cm == CharacterMap.Custom, " Custom")) cm = CharacterMap.Custom;
if (GUI.changed) characterMap = cm;
GUILayout.EndVertical();
EditorGUI.BeginDisabledGroup(cm != CharacterMap.Custom);
{
if (cm != CharacterMap.Custom)
{
string chars = "";
if (cm == CharacterMap.Ascii)
{
for (int i = 33; i < 127; ++i)
chars += System.Convert.ToChar(i);
}
else if (cm == CharacterMap.Numeric)
{
chars = "01234567890";
}
else if (cm == CharacterMap.Latin)
{
for (int i = 33; i < 127; ++i)
chars += System.Convert.ToChar(i);
for (int i = 161; i < 256; ++i)
chars += System.Convert.ToChar(i);
}
NGUISettings.charsToInclude = chars;
}
GUI.changed = false;
string text = NGUISettings.charsToInclude;
if (cm == CharacterMap.Custom)
{
text = EditorGUILayout.TextArea(text, GUI.skin.textArea,
GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
}
else
{
GUILayout.Label(text, GUI.skin.textArea,
GUILayout.Height(80f), GUILayout.Width(Screen.width - 100f));
}
if (GUI.changed)
{
string final = "";
for (int i = 0; i < text.Length; ++i)
{
char c = text[i];
if (c < 33) continue;
string s = c.ToString();
if (!final.Contains(s)) final += s;
}
if (final.Length > 0)
{
char[] chars = final.ToCharArray();
System.Array.Sort(chars);
final = new string(chars);
}
else final = "";
NGUISettings.charsToInclude = final;
}
}
EditorGUI.EndDisabledGroup();
GUILayout.EndHorizontal();
}
}
NGUIEditorTools.EndContents();
if (mType == FontType.Dynamic)
{
EditorGUI.BeginDisabledGroup(ttf == null);
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
if (GUILayout.Button("Create the Font")) create = Create.Dynamic;
GUILayout.Space(20f);
GUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
#if UNITY_3_5
EditorGUILayout.HelpBox("Dynamic fonts require Unity 4.0 or higher.", MessageType.Error);
#else
// Helpful info
if (ttf == null)
{
EditorGUILayout.HelpBox("You don't have to create a UIFont to use dynamic fonts. You can just reference the Unity Font directly on the label.", MessageType.Info);
}
EditorGUILayout.HelpBox("Please note that dynamic fonts can't be made a part of an atlas, and using dynamic fonts will result in at least one extra draw call.", MessageType.Warning);
#endif
}
else
{
bool isBuiltIn = (ttf != null) && string.IsNullOrEmpty(UnityEditor.AssetDatabase.GetAssetPath(ttf));
// Draw the atlas selection only if we have the font data and texture specified, just to make it easier
EditorGUI.BeginDisabledGroup(ttf == null || isBuiltIn || !FreeType.isPresent);
{
NGUIEditorTools.DrawHeader("Output", true);
NGUIEditorTools.BeginContents();
ComponentSelector.Draw<UIAtlas>(NGUISettings.atlas, OnSelectAtlas, false);
NGUIEditorTools.EndContents();
if (ttf == null)
{
EditorGUILayout.HelpBox("You can create a bitmap font by specifying a dynamic font to use as the source.", MessageType.Info);
}
else if (isBuiltIn)
{
EditorGUILayout.HelpBox("You chose an embedded font. You can't create a bitmap font from an embedded resource.", MessageType.Warning);
}
else if (NGUISettings.atlas == null)
{
EditorGUILayout.HelpBox("You can create a font that doesn't use a texture atlas. This will mean that the text " +
"labels using this font will generate an extra draw call.\n\nIf you do specify an atlas, the font's texture will be added to it automatically.", MessageType.Info);
}
GUILayout.BeginHorizontal();
GUILayout.Space(20f);
if (GUILayout.Button("Create the Font")) create = Create.Bitmap;
GUILayout.Space(20f);
GUILayout.EndHorizontal();
}
EditorGUI.EndDisabledGroup();
}
}
if (create == Create.None) return;
// Open the "Save As" file dialog
string prefabPath = EditorUtility.SaveFilePanelInProject("Save As", "New Font.prefab", "prefab", "Save font as...");
if (string.IsNullOrEmpty(prefabPath)) return;
// Load the font's prefab
GameObject go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
Object prefab = null;
string fontName;
// Font doesn't exist yet
if (go == null || go.GetComponent<UIFont>() == null)
{
// Create a new prefab for the atlas
prefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
fontName = prefabPath.Replace(".prefab", "");
fontName = fontName.Substring(prefabPath.LastIndexOfAny(new char[] { '/', '\\' }) + 1);
// Create a new game object for the font
go = new GameObject(fontName);
uiFont = go.AddComponent<UIFont>();
}
else
{
uiFont = go.GetComponent<UIFont>();
fontName = go.name;
}
if (create == Create.Dynamic)
{
uiFont.atlas = null;
uiFont.dynamicFont = NGUISettings.dynamicFont;
uiFont.dynamicFontStyle = NGUISettings.fontStyle;
uiFont.defaultSize = NGUISettings.fontSize;
}
else if (create == Create.Import)
{
Material mat = null;
if (NGUISettings.atlas != null)
{
// Add the font's texture to the atlas
UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, NGUISettings.fontTexture);
}
else
{
// Create a material for the font
string matPath = prefabPath.Replace(".prefab", ".mat");
mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
// If the material doesn't exist, create it
if (mat == null)
{
Shader shader = Shader.Find("Unlit/Transparent Colored");
mat = new Material(shader);
// Save the material
AssetDatabase.CreateAsset(mat, matPath);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// Load the material so it's usable
mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
}
mat.mainTexture = NGUISettings.fontTexture;
}
uiFont.dynamicFont = null;
BMFontReader.Load(uiFont.bmFont, NGUITools.GetHierarchy(uiFont.gameObject), NGUISettings.fontData.bytes);
if (NGUISettings.atlas == null)
{
uiFont.atlas = null;
uiFont.material = mat;
}
else
{
uiFont.spriteName = NGUISettings.fontTexture.name;
uiFont.atlas = NGUISettings.atlas;
}
NGUISettings.fontSize = uiFont.defaultSize;
}
else if (create == Create.Bitmap)
{
// Create the bitmap font
BMFont bmFont;
Texture2D tex;
if (FreeType.CreateFont(
NGUISettings.dynamicFont,
NGUISettings.fontSize, mFaceIndex,
NGUISettings.charsToInclude, out bmFont, out tex))
{
uiFont.bmFont = bmFont;
tex.name = fontName;
if (NGUISettings.atlas != null)
{
// Add this texture to the atlas and destroy it
UIAtlasMaker.AddOrUpdate(NGUISettings.atlas, tex);
NGUITools.DestroyImmediate(tex);
NGUISettings.fontTexture = null;
tex = null;
uiFont.atlas = NGUISettings.atlas;
uiFont.spriteName = fontName;
}
else
{
string texPath = prefabPath.Replace(".prefab", ".png");
string matPath = prefabPath.Replace(".prefab", ".mat");
byte[] png = tex.EncodeToPNG();
FileStream fs = File.OpenWrite(texPath);
fs.Write(png, 0, png.Length);
fs.Close();
// See if the material already exists
Material mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
// If the material doesn't exist, create it
if (mat == null)
{
Shader shader = Shader.Find("Unlit/Transparent Colored");
mat = new Material(shader);
// Save the material
AssetDatabase.CreateAsset(mat, matPath);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// Load the material so it's usable
mat = AssetDatabase.LoadAssetAtPath(matPath, typeof(Material)) as Material;
}
else AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// Re-load the texture
tex = AssetDatabase.LoadAssetAtPath(texPath, typeof(Texture2D)) as Texture2D;
// Assign the texture
mat.mainTexture = tex;
NGUISettings.fontTexture = tex;
uiFont.atlas = null;
uiFont.material = mat;
}
}
else return;
}
if (prefab != null)
{
// Update the prefab
PrefabUtility.ReplacePrefab(go, prefab);
DestroyImmediate(go);
AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
// Select the atlas
go = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject;
uiFont = go.GetComponent<UIFont>();
}
if (uiFont != null) NGUISettings.ambigiousFont = uiFont;
MarkAsChanged();
Selection.activeGameObject = go;
}
/// <summary>
/// Helper function that draws a slightly padded toggle
/// </summary>
static bool DrawOption (bool state, string text, params GUILayoutOption[] options)
{
GUILayout.BeginHorizontal();
GUILayout.Space(10f);
bool val = GUILayout.Toggle(state, text, EditorStyles.radioButton, options);
GUILayout.EndHorizontal();
return val;
}
/// <summary>
/// Create the specified font.
/// </summary>
static void ImportFont (UIFont font, Create create, Material mat)
{
// New bitmap font
font.dynamicFont = null;
BMFontReader.Load(font.bmFont, NGUITools.GetHierarchy(font.gameObject), NGUISettings.fontData.bytes);
if (NGUISettings.atlas == null)
{
font.atlas = null;
font.material = mat;
}
else
{
font.spriteName = NGUISettings.fontTexture.name;
font.atlas = NGUISettings.atlas;
}
NGUISettings.fontSize = font.defaultSize;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIFontMaker.cs
|
C#
|
asf20
| 17,254
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
#if UNITY_3_5
[CustomEditor(typeof(UITweener))]
#else
[CustomEditor(typeof(UITweener), true)]
#endif
public class UITweenerEditor : Editor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(110f);
base.OnInspectorGUI();
DrawCommonProperties();
}
protected void DrawCommonProperties ()
{
UITweener tw = target as UITweener;
if (NGUIEditorTools.DrawHeader("Tweener"))
{
NGUIEditorTools.BeginContents();
NGUIEditorTools.SetLabelWidth(110f);
GUI.changed = false;
UITweener.Style style = (UITweener.Style)EditorGUILayout.EnumPopup("Play Style", tw.style);
AnimationCurve curve = EditorGUILayout.CurveField("Animation Curve", tw.animationCurve, GUILayout.Width(170f), GUILayout.Height(62f));
//UITweener.Method method = (UITweener.Method)EditorGUILayout.EnumPopup("Play Method", tw.method);
GUILayout.BeginHorizontal();
float dur = EditorGUILayout.FloatField("Duration", tw.duration, GUILayout.Width(170f));
GUILayout.Label("seconds");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
float del = EditorGUILayout.FloatField("Start Delay", tw.delay, GUILayout.Width(170f));
GUILayout.Label("seconds");
GUILayout.EndHorizontal();
int tg = EditorGUILayout.IntField("Tween Group", tw.tweenGroup, GUILayout.Width(170f));
bool ts = EditorGUILayout.Toggle("Ignore TimeScale", tw.ignoreTimeScale);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.animationCurve = curve;
//tw.method = method;
tw.style = style;
tw.ignoreTimeScale = ts;
tw.tweenGroup = tg;
tw.duration = dur;
tw.delay = del;
NGUITools.SetDirty(tw);
}
NGUIEditorTools.EndContents();
}
NGUIEditorTools.SetLabelWidth(80f);
NGUIEditorTools.DrawEvents("On Finished", tw, tw.onFinished);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UITweenerEditor.cs
|
C#
|
asf20
| 2,065
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(ActiveAnimation))]
public class ActiveAnimationEditor : Editor
{
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
ActiveAnimation aa = target as ActiveAnimation;
GUILayout.Space(3f);
NGUIEditorTools.DrawEvents("On Finished", aa, aa.onFinished);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/ActiveAnimationEditor.cs
|
C#
|
asf20
| 532
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public class NGUISelectionTools
{
[MenuItem("GameObject/Selection/Force Delete")]
static void ForceDelete()
{
Object[] gos = Selection.GetFiltered(typeof(GameObject), SelectionMode.TopLevel);
if (gos != null && gos.Length > 0)
{
for (int i = 0; i < gos.Length; ++i)
{
Object go = gos[i];
NGUITools.DestroyImmediate(go);
}
}
}
[MenuItem("GameObject/Selection/Toggle 'Active' #&a")]
static void ActivateDeactivate()
{
if (HasValidTransform())
{
GameObject[] gos = Selection.gameObjects;
bool val = !NGUITools.GetActive(Selection.activeGameObject);
foreach (GameObject go in gos) NGUITools.SetActive(go, val);
}
}
[MenuItem("GameObject/Selection/Clear Local Transform")]
static void ClearLocalTransform()
{
if (HasValidTransform())
{
Transform t = Selection.activeTransform;
NGUIEditorTools.RegisterUndo("Clear Local Transform", t);
t.localPosition = Vector3.zero;
t.localRotation = Quaternion.identity;
t.localScale = Vector3.one;
}
}
[MenuItem("GameObject/Selection/Add New Child #&n")]
static void CreateLocalGameObject ()
{
if (PrefabCheck())
{
// Make this action undoable
NGUIEditorTools.RegisterUndo("Add New Child");
// Create our new GameObject
GameObject newGameObject = new GameObject();
newGameObject.name = "GameObject";
// If there is a selected object in the scene then make the new object its child.
if (Selection.activeTransform != null)
{
newGameObject.transform.parent = Selection.activeTransform;
newGameObject.name = "Child";
// Place the new GameObject at the same position as the parent.
newGameObject.transform.localPosition = Vector3.zero;
newGameObject.transform.localRotation = Quaternion.identity;
newGameObject.transform.localScale = new Vector3(1f, 1f, 1f);
newGameObject.layer = Selection.activeGameObject.layer;
}
// Select our newly created GameObject
Selection.activeGameObject = newGameObject;
}
}
[MenuItem("GameObject/Selection/List Dependencies")]
static void ListDependencies()
{
if (HasValidSelection())
{
Debug.Log("Selection depends on the following assets:\n\n" + GetDependencyText(Selection.objects, false));
}
}
//========================================================================================================
#region Helper Functions
class AssetEntry
{
public string path;
public List<System.Type> types = new List<System.Type>();
}
/// <summary>
/// Helper function that checks to see if there are objects selected.
/// </summary>
static bool HasValidSelection()
{
if (Selection.objects == null || Selection.objects.Length == 0)
{
Debug.LogWarning("You must select an object first");
return false;
}
return true;
}
/// <summary>
/// Helper function that checks to see if there is an object with a Transform component selected.
/// </summary>
static bool HasValidTransform()
{
if (Selection.activeTransform == null)
{
Debug.LogWarning("You must select an object first");
return false;
}
return true;
}
/// <summary>
/// Helper function that checks to see if a prefab is currently selected.
/// </summary>
static bool PrefabCheck()
{
if (Selection.activeTransform != null)
{
// Check if the selected object is a prefab instance and display a warning
PrefabType type = PrefabUtility.GetPrefabType(Selection.activeGameObject);
if (type == PrefabType.PrefabInstance)
{
return EditorUtility.DisplayDialog("Losing prefab",
"This action will lose the prefab connection. Are you sure you wish to continue?",
"Continue", "Cancel");
}
}
return true;
}
/// <summary>
/// Function that collects a list of file dependencies from the specified list of objects.
/// </summary>
static List<AssetEntry> GetDependencyList (Object[] objects, bool reverse)
{
Object[] deps = reverse ? EditorUtility.CollectDeepHierarchy(objects) : EditorUtility.CollectDependencies(objects);
List<AssetEntry> list = new List<AssetEntry>();
foreach (Object obj in deps)
{
string path = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(path))
{
bool found = false;
System.Type type = obj.GetType();
foreach (AssetEntry ent in list)
{
if (ent.path.Equals(path))
{
if (!ent.types.Contains(type)) ent.types.Add(type);
found = true;
break;
}
}
if (!found)
{
AssetEntry ent = new AssetEntry();
ent.path = path;
ent.types.Add(type);
list.Add(ent);
}
}
}
deps = null;
objects = null;
return list;
}
/// <summary>
/// Helper function that removes the Unity class prefix from the specified string.
/// </summary>
static string RemovePrefix (string text)
{
text = text.Replace("UnityEngine.", "");
text = text.Replace("UnityEditor.", "");
return text;
}
/// <summary>
/// Helper function that gets the dependencies of specified objects and returns them in text format.
/// </summary>
static string GetDependencyText (Object[] objects, bool reverse)
{
List<AssetEntry> dependencies = GetDependencyList(objects, reverse);
List<string> list = new List<string>();
string text = "";
foreach (AssetEntry ae in dependencies)
{
text = ae.path.Replace("Assets/", "");
if (ae.types.Count > 1)
{
text += " (" + RemovePrefix(ae.types[0].ToString());
for (int i = 1; i < ae.types.Count; ++i)
{
text += ", " + RemovePrefix(ae.types[i].ToString());
}
text += ")";
}
list.Add(text);
}
list.Sort();
text = "";
foreach (string s in list) text += s + "\n";
list.Clear();
list = null;
dependencies.Clear();
dependencies = null;
return text;
}
#endregion
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/NGUISelectionTools.cs
|
C#
|
asf20
| 6,044
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenPosition))]
public class TweenPositionEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenPosition tw = target as TweenPosition;
GUI.changed = false;
Vector3 from = EditorGUILayout.Vector3Field("From", tw.from);
Vector3 to = EditorGUILayout.Vector3Field("To", tw.to);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenPositionEditor.cs
|
C#
|
asf20
| 786
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIAnchor))]
public class UIAnchorEditor : Editor
{
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIAnchorEditor.cs
|
C#
|
asf20
| 322
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenWidth))]
public class TweenWidthEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenWidth tw = target as TweenWidth;
GUI.changed = false;
int from = EditorGUILayout.IntField("From", tw.from);
int to = EditorGUILayout.IntField("To", tw.to);
bool table = EditorGUILayout.Toggle("Update Table", tw.updateTable);
if (from < 0) from = 0;
if (to < 0) to = 0;
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
tw.updateTable = table;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenWidthEditor.cs
|
C#
|
asf20
| 905
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2
#define USE_MECANIM
#endif
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(UIPlayAnimation))]
public class UIPlayAnimationEditor : Editor
{
enum ResetOnPlay
{
Continue,
StartFromBeginning,
}
enum SelectedObject
{
KeepCurrent,
SetToNothing,
}
public override void OnInspectorGUI ()
{
NGUIEditorTools.SetLabelWidth(120f);
UIPlayAnimation pa = target as UIPlayAnimation;
GUILayout.Space(6f);
GUI.changed = false;
#if USE_MECANIM
EditorGUI.BeginDisabledGroup(pa.target);
Animator animator = (Animator)EditorGUILayout.ObjectField("Animator", pa.animator, typeof(Animator), true);
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(pa.animator);
#endif
Animation anim = (Animation)EditorGUILayout.ObjectField("Animation", pa.target, typeof(Animation), true);
#if USE_MECANIM
EditorGUI.EndDisabledGroup();
EditorGUI.BeginDisabledGroup(anim == null && animator == null);
string clipName = EditorGUILayout.TextField("State Name", pa.clipName);
#else
EditorGUI.BeginDisabledGroup(anim == null);
string clipName = EditorGUILayout.TextField("Clip Name", pa.clipName);
#endif
AnimationOrTween.Trigger trigger = (AnimationOrTween.Trigger)EditorGUILayout.EnumPopup("Trigger condition", pa.trigger);
#if USE_MECANIM
EditorGUI.BeginDisabledGroup(animator != null && !string.IsNullOrEmpty(clipName));
AnimationOrTween.Direction dir = (AnimationOrTween.Direction)EditorGUILayout.EnumPopup("Play direction", pa.playDirection);
EditorGUI.EndDisabledGroup();
#else
AnimationOrTween.Direction dir = (AnimationOrTween.Direction)EditorGUILayout.EnumPopup("Play direction", pa.playDirection);
#endif
SelectedObject so = pa.clearSelection ? SelectedObject.SetToNothing : SelectedObject.KeepCurrent;
bool clear = (SelectedObject)EditorGUILayout.EnumPopup("Selected object", so) == SelectedObject.SetToNothing;
AnimationOrTween.EnableCondition enab = (AnimationOrTween.EnableCondition)EditorGUILayout.EnumPopup("If disabled on start", pa.ifDisabledOnPlay);
ResetOnPlay rs = pa.resetOnPlay ? ResetOnPlay.StartFromBeginning : ResetOnPlay.Continue;
bool reset = (ResetOnPlay)EditorGUILayout.EnumPopup("If already playing", rs) == ResetOnPlay.StartFromBeginning;
AnimationOrTween.DisableCondition dis = (AnimationOrTween.DisableCondition)EditorGUILayout.EnumPopup("When finished", pa.disableWhenFinished);
EditorGUI.EndDisabledGroup();
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("PlayAnimation Change", pa);
pa.target = anim;
#if USE_MECANIM
pa.animator = animator;
#endif
pa.clipName = clipName;
pa.trigger = trigger;
pa.playDirection = dir;
pa.clearSelection = clear;
pa.ifDisabledOnPlay = enab;
pa.resetOnPlay = reset;
pa.disableWhenFinished = dis;
NGUITools.SetDirty(pa);
}
NGUIEditorTools.SetLabelWidth(80f);
NGUIEditorTools.DrawEvents("On Finished", pa, pa.onFinished);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIPlayAnimationEditor.cs
|
C#
|
asf20
| 3,136
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIButtonMessage))]
public class UIButtonMessageEditor : Editor
{
public override void OnInspectorGUI ()
{
EditorGUILayout.HelpBox("This is a legacy component. Consider using the Event Trigger instead.", MessageType.Warning);
base.OnInspectorGUI();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIButtonMessageEditor.cs
|
C#
|
asf20
| 528
|
/*
Based on the Public Domain MaxRectsBinPack.cpp source by Jukka Jylänki
https://github.com/juj/RectangleBinPack/
Ported to C# by Sven Magnus
This version is also public domain - do whatever you want with it.
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class UITexturePacker
{
public int binWidth = 0;
public int binHeight = 0;
public bool allowRotations;
public List<Rect> usedRectangles = new List<Rect>();
public List<Rect> freeRectangles = new List<Rect>();
public enum FreeRectChoiceHeuristic
{
RectBestShortSideFit, ///< -BSSF: Positions the rectangle against the short side of a free rectangle into which it fits the best.
RectBestLongSideFit, ///< -BLSF: Positions the rectangle against the long side of a free rectangle into which it fits the best.
RectBestAreaFit, ///< -BAF: Positions the rectangle into the smallest free rect into which it fits.
RectBottomLeftRule, ///< -BL: Does the Tetris placement.
RectContactPointRule ///< -CP: Choosest the placement where the rectangle touches other rects as much as possible.
};
public UITexturePacker (int width, int height, bool rotations)
{
Init(width, height, rotations);
}
public void Init (int width, int height, bool rotations)
{
binWidth = width;
binHeight = height;
allowRotations = rotations;
Rect n = new Rect();
n.x = 0;
n.y = 0;
n.width = width;
n.height = height;
usedRectangles.Clear();
freeRectangles.Clear();
freeRectangles.Add(n);
}
private struct Storage
{
public Rect rect;
public bool paddingX;
public bool paddingY;
}
public static Rect[] PackTextures (Texture2D texture, Texture2D[] textures, int width, int height, int padding, int maxSize)
{
if (width > maxSize && height > maxSize) return null;
if (width > maxSize || height > maxSize) { int temp = width; width = height; height = temp; }
// Force square by sizing up
if (NGUISettings.forceSquareAtlas)
{
if (width > height)
height = width;
else if (height > width)
width = height;
}
UITexturePacker bp = new UITexturePacker(width, height, false);
Storage[] storage = new Storage[textures.Length];
for (int i = 0; i < textures.Length; i++)
{
Texture2D tex = textures[i];
if (!tex) continue;
Rect rect = new Rect();
int xPadding = 1;
int yPadding = 1;
for (xPadding = 1; xPadding >= 0; --xPadding)
{
for (yPadding = 1; yPadding >= 0; --yPadding)
{
rect = bp.Insert(tex.width + (xPadding * padding), tex.height + (yPadding * padding),
UITexturePacker.FreeRectChoiceHeuristic.RectBestAreaFit);
if (rect.width != 0 && rect.height != 0) break;
// After having no padding if it still doesn't fit -- increase texture size.
else if (xPadding == 0 && yPadding == 0)
{
return PackTextures(texture, textures, width * (width <= height ? 2 : 1),
height * (height < width ? 2 : 1), padding, maxSize);
}
}
if (rect.width != 0 && rect.height != 0) break;
}
storage[i] = new Storage();
storage[i].rect = rect;
storage[i].paddingX = (xPadding != 0);
storage[i].paddingY = (yPadding != 0);
}
texture.Resize(width, height);
texture.SetPixels(new Color[width * height]);
// The returned rects
Rect[] rects = new Rect[textures.Length];
for (int i = 0; i < textures.Length; i++)
{
Texture2D tex = textures[i];
if (!tex) continue;
Rect rect = storage[i].rect;
int xPadding = (storage[i].paddingX ? padding : 0);
int yPadding = (storage[i].paddingY ? padding : 0);
Color[] colors = tex.GetPixels();
// Would be used to rotate the texture if need be.
if (rect.width != tex.width + xPadding)
{
Color[] newColors = tex.GetPixels();
for (int x = 0; x < rect.width; x++)
{
for (int y = 0; y < rect.height; y++)
{
int prevIndex = ((int)rect.height - (y + 1)) + x * (int)tex.width;
newColors[x + y * (int)rect.width] = colors[prevIndex];
}
}
colors = newColors;
}
texture.SetPixels((int)rect.x, (int)rect.y, (int)rect.width - xPadding, (int)rect.height - yPadding, colors);
rect.x /= width;
rect.y /= height;
rect.width = (rect.width - xPadding) / width;
rect.height = (rect.height - yPadding) / height;
rects[i] = rect;
}
texture.Apply();
return rects;
}
public Rect Insert (int width, int height, FreeRectChoiceHeuristic method)
{
Rect newNode = new Rect();
int score1 = 0; // Unused in this function. We don't need to know the score after finding the position.
int score2 = 0;
switch (method)
{
case FreeRectChoiceHeuristic.RectBestShortSideFit: newNode = FindPositionForNewNodeBestShortSideFit(width, height, ref score1, ref score2); break;
case FreeRectChoiceHeuristic.RectBottomLeftRule: newNode = FindPositionForNewNodeBottomLeft(width, height, ref score1, ref score2); break;
case FreeRectChoiceHeuristic.RectContactPointRule: newNode = FindPositionForNewNodeContactPoint(width, height, ref score1); break;
case FreeRectChoiceHeuristic.RectBestLongSideFit: newNode = FindPositionForNewNodeBestLongSideFit(width, height, ref score2, ref score1); break;
case FreeRectChoiceHeuristic.RectBestAreaFit: newNode = FindPositionForNewNodeBestAreaFit(width, height, ref score1, ref score2); break;
}
if (newNode.height == 0)
return newNode;
int numRectanglesToProcess = freeRectangles.Count;
for (int i = 0; i < numRectanglesToProcess; ++i)
{
if (SplitFreeNode(freeRectangles[i], ref newNode))
{
freeRectangles.RemoveAt(i);
--i;
--numRectanglesToProcess;
}
}
PruneFreeList();
usedRectangles.Add(newNode);
return newNode;
}
public void Insert (List<Rect> rects, List<Rect> dst, FreeRectChoiceHeuristic method)
{
dst.Clear();
while (rects.Count > 0)
{
int bestScore1 = int.MaxValue;
int bestScore2 = int.MaxValue;
int bestRectIndex = -1;
Rect bestNode = new Rect();
for (int i = 0; i < rects.Count; ++i)
{
int score1 = 0;
int score2 = 0;
Rect newNode = ScoreRect((int)rects[i].width, (int)rects[i].height, method, ref score1, ref score2);
if (score1 < bestScore1 || (score1 == bestScore1 && score2 < bestScore2))
{
bestScore1 = score1;
bestScore2 = score2;
bestNode = newNode;
bestRectIndex = i;
}
}
if (bestRectIndex == -1)
return;
PlaceRect(bestNode);
rects.RemoveAt(bestRectIndex);
}
}
void PlaceRect (Rect node)
{
int numRectanglesToProcess = freeRectangles.Count;
for (int i = 0; i < numRectanglesToProcess; ++i)
{
if (SplitFreeNode(freeRectangles[i], ref node))
{
freeRectangles.RemoveAt(i);
--i;
--numRectanglesToProcess;
}
}
PruneFreeList();
usedRectangles.Add(node);
}
Rect ScoreRect (int width, int height, FreeRectChoiceHeuristic method, ref int score1, ref int score2)
{
Rect newNode = new Rect();
score1 = int.MaxValue;
score2 = int.MaxValue;
switch (method)
{
case FreeRectChoiceHeuristic.RectBestShortSideFit: newNode = FindPositionForNewNodeBestShortSideFit(width, height, ref score1, ref score2); break;
case FreeRectChoiceHeuristic.RectBottomLeftRule: newNode = FindPositionForNewNodeBottomLeft(width, height, ref score1, ref score2); break;
case FreeRectChoiceHeuristic.RectContactPointRule: newNode = FindPositionForNewNodeContactPoint(width, height, ref score1);
score1 = -score1; // Reverse since we are minimizing, but for contact point score bigger is better.
break;
case FreeRectChoiceHeuristic.RectBestLongSideFit: newNode = FindPositionForNewNodeBestLongSideFit(width, height, ref score2, ref score1); break;
case FreeRectChoiceHeuristic.RectBestAreaFit: newNode = FindPositionForNewNodeBestAreaFit(width, height, ref score1, ref score2); break;
}
// Cannot fit the current rectangle.
if (newNode.height == 0)
{
score1 = int.MaxValue;
score2 = int.MaxValue;
}
return newNode;
}
/// Computes the ratio of used surface area.
public float Occupancy ()
{
ulong usedSurfaceArea = 0;
for (int i = 0; i < usedRectangles.Count; ++i)
usedSurfaceArea += (uint)usedRectangles[i].width * (uint)usedRectangles[i].height;
return (float)usedSurfaceArea / (binWidth * binHeight);
}
Rect FindPositionForNewNodeBottomLeft (int width, int height, ref int bestY, ref int bestX)
{
Rect bestNode = new Rect();
//memset(bestNode, 0, sizeof(Rect));
bestY = int.MaxValue;
for (int i = 0; i < freeRectangles.Count; ++i)
{
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width && freeRectangles[i].height >= height)
{
int topSideY = (int)freeRectangles[i].y + height;
if (topSideY < bestY || (topSideY == bestY && freeRectangles[i].x < bestX))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = width;
bestNode.height = height;
bestY = topSideY;
bestX = (int)freeRectangles[i].x;
}
}
if (allowRotations && freeRectangles[i].width >= height && freeRectangles[i].height >= width)
{
int topSideY = (int)freeRectangles[i].y + width;
if (topSideY < bestY || (topSideY == bestY && freeRectangles[i].x < bestX))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = height;
bestNode.height = width;
bestY = topSideY;
bestX = (int)freeRectangles[i].x;
}
}
}
return bestNode;
}
Rect FindPositionForNewNodeBestShortSideFit (int width, int height, ref int bestShortSideFit, ref int bestLongSideFit)
{
Rect bestNode = new Rect();
//memset(&bestNode, 0, sizeof(Rect));
bestShortSideFit = int.MaxValue;
for (int i = 0; i < freeRectangles.Count; ++i)
{
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width && freeRectangles[i].height >= height)
{
int leftoverHoriz = Mathf.Abs((int)freeRectangles[i].width - width);
int leftoverVert = Mathf.Abs((int)freeRectangles[i].height - height);
int shortSideFit = Mathf.Min(leftoverHoriz, leftoverVert);
int longSideFit = Mathf.Max(leftoverHoriz, leftoverVert);
if (shortSideFit < bestShortSideFit || (shortSideFit == bestShortSideFit && longSideFit < bestLongSideFit))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = width;
bestNode.height = height;
bestShortSideFit = shortSideFit;
bestLongSideFit = longSideFit;
}
}
if (allowRotations && freeRectangles[i].width >= height && freeRectangles[i].height >= width)
{
int flippedLeftoverHoriz = Mathf.Abs((int)freeRectangles[i].width - height);
int flippedLeftoverVert = Mathf.Abs((int)freeRectangles[i].height - width);
int flippedShortSideFit = Mathf.Min(flippedLeftoverHoriz, flippedLeftoverVert);
int flippedLongSideFit = Mathf.Max(flippedLeftoverHoriz, flippedLeftoverVert);
if (flippedShortSideFit < bestShortSideFit || (flippedShortSideFit == bestShortSideFit && flippedLongSideFit < bestLongSideFit))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = height;
bestNode.height = width;
bestShortSideFit = flippedShortSideFit;
bestLongSideFit = flippedLongSideFit;
}
}
}
return bestNode;
}
Rect FindPositionForNewNodeBestLongSideFit (int width, int height, ref int bestShortSideFit, ref int bestLongSideFit)
{
Rect bestNode = new Rect();
//memset(&bestNode, 0, sizeof(Rect));
bestLongSideFit = int.MaxValue;
for (int i = 0; i < freeRectangles.Count; ++i)
{
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width && freeRectangles[i].height >= height)
{
int leftoverHoriz = Mathf.Abs((int)freeRectangles[i].width - width);
int leftoverVert = Mathf.Abs((int)freeRectangles[i].height - height);
int shortSideFit = Mathf.Min(leftoverHoriz, leftoverVert);
int longSideFit = Mathf.Max(leftoverHoriz, leftoverVert);
if (longSideFit < bestLongSideFit || (longSideFit == bestLongSideFit && shortSideFit < bestShortSideFit))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = width;
bestNode.height = height;
bestShortSideFit = shortSideFit;
bestLongSideFit = longSideFit;
}
}
if (allowRotations && freeRectangles[i].width >= height && freeRectangles[i].height >= width)
{
int leftoverHoriz = Mathf.Abs((int)freeRectangles[i].width - height);
int leftoverVert = Mathf.Abs((int)freeRectangles[i].height - width);
int shortSideFit = Mathf.Min(leftoverHoriz, leftoverVert);
int longSideFit = Mathf.Max(leftoverHoriz, leftoverVert);
if (longSideFit < bestLongSideFit || (longSideFit == bestLongSideFit && shortSideFit < bestShortSideFit))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = height;
bestNode.height = width;
bestShortSideFit = shortSideFit;
bestLongSideFit = longSideFit;
}
}
}
return bestNode;
}
Rect FindPositionForNewNodeBestAreaFit (int width, int height, ref int bestAreaFit, ref int bestShortSideFit)
{
Rect bestNode = new Rect();
//memset(&bestNode, 0, sizeof(Rect));
bestAreaFit = int.MaxValue;
for (int i = 0; i < freeRectangles.Count; ++i)
{
int areaFit = (int)freeRectangles[i].width * (int)freeRectangles[i].height - width * height;
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width && freeRectangles[i].height >= height)
{
int leftoverHoriz = Mathf.Abs((int)freeRectangles[i].width - width);
int leftoverVert = Mathf.Abs((int)freeRectangles[i].height - height);
int shortSideFit = Mathf.Min(leftoverHoriz, leftoverVert);
if (areaFit < bestAreaFit || (areaFit == bestAreaFit && shortSideFit < bestShortSideFit))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = width;
bestNode.height = height;
bestShortSideFit = shortSideFit;
bestAreaFit = areaFit;
}
}
if (allowRotations && freeRectangles[i].width >= height && freeRectangles[i].height >= width)
{
int leftoverHoriz = Mathf.Abs((int)freeRectangles[i].width - height);
int leftoverVert = Mathf.Abs((int)freeRectangles[i].height - width);
int shortSideFit = Mathf.Min(leftoverHoriz, leftoverVert);
if (areaFit < bestAreaFit || (areaFit == bestAreaFit && shortSideFit < bestShortSideFit))
{
bestNode.x = freeRectangles[i].x;
bestNode.y = freeRectangles[i].y;
bestNode.width = height;
bestNode.height = width;
bestShortSideFit = shortSideFit;
bestAreaFit = areaFit;
}
}
}
return bestNode;
}
/// Returns 0 if the two intervals i1 and i2 are disjoint, or the length of their overlap otherwise.
int CommonIntervalLength (int i1start, int i1end, int i2start, int i2end)
{
if (i1end < i2start || i2end < i1start)
return 0;
return Mathf.Min(i1end, i2end) - Mathf.Max(i1start, i2start);
}
int ContactPointScoreNode (int x, int y, int width, int height)
{
int score = 0;
if (x == 0 || x + width == binWidth)
score += height;
if (y == 0 || y + height == binHeight)
score += width;
for (int i = 0; i < usedRectangles.Count; ++i)
{
if (usedRectangles[i].x == x + width || usedRectangles[i].x + usedRectangles[i].width == x)
score += CommonIntervalLength((int)usedRectangles[i].y, (int)usedRectangles[i].y + (int)usedRectangles[i].height, y, y + height);
if (usedRectangles[i].y == y + height || usedRectangles[i].y + usedRectangles[i].height == y)
score += CommonIntervalLength((int)usedRectangles[i].x, (int)usedRectangles[i].x + (int)usedRectangles[i].width, x, x + width);
}
return score;
}
Rect FindPositionForNewNodeContactPoint (int width, int height, ref int bestContactScore)
{
Rect bestNode = new Rect();
//memset(&bestNode, 0, sizeof(Rect));
bestContactScore = -1;
for (int i = 0; i < freeRectangles.Count; ++i)
{
// Try to place the rectangle in upright (non-flipped) orientation.
if (freeRectangles[i].width >= width && freeRectangles[i].height >= height)
{
int score = ContactPointScoreNode((int)freeRectangles[i].x, (int)freeRectangles[i].y, width, height);
if (score > bestContactScore)
{
bestNode.x = (int)freeRectangles[i].x;
bestNode.y = (int)freeRectangles[i].y;
bestNode.width = width;
bestNode.height = height;
bestContactScore = score;
}
}
if (allowRotations && freeRectangles[i].width >= height && freeRectangles[i].height >= width)
{
int score = ContactPointScoreNode((int)freeRectangles[i].x, (int)freeRectangles[i].y, height, width);
if (score > bestContactScore)
{
bestNode.x = (int)freeRectangles[i].x;
bestNode.y = (int)freeRectangles[i].y;
bestNode.width = height;
bestNode.height = width;
bestContactScore = score;
}
}
}
return bestNode;
}
bool SplitFreeNode (Rect freeNode, ref Rect usedNode)
{
// Test with SAT if the rectangles even intersect.
if (usedNode.x >= freeNode.x + freeNode.width || usedNode.x + usedNode.width <= freeNode.x ||
usedNode.y >= freeNode.y + freeNode.height || usedNode.y + usedNode.height <= freeNode.y)
return false;
if (usedNode.x < freeNode.x + freeNode.width && usedNode.x + usedNode.width > freeNode.x)
{
// New node at the top side of the used node.
if (usedNode.y > freeNode.y && usedNode.y < freeNode.y + freeNode.height)
{
Rect newNode = freeNode;
newNode.height = usedNode.y - newNode.y;
freeRectangles.Add(newNode);
}
// New node at the bottom side of the used node.
if (usedNode.y + usedNode.height < freeNode.y + freeNode.height)
{
Rect newNode = freeNode;
newNode.y = usedNode.y + usedNode.height;
newNode.height = freeNode.y + freeNode.height - (usedNode.y + usedNode.height);
freeRectangles.Add(newNode);
}
}
if (usedNode.y < freeNode.y + freeNode.height && usedNode.y + usedNode.height > freeNode.y)
{
// New node at the left side of the used node.
if (usedNode.x > freeNode.x && usedNode.x < freeNode.x + freeNode.width)
{
Rect newNode = freeNode;
newNode.width = usedNode.x - newNode.x;
freeRectangles.Add(newNode);
}
// New node at the right side of the used node.
if (usedNode.x + usedNode.width < freeNode.x + freeNode.width)
{
Rect newNode = freeNode;
newNode.x = usedNode.x + usedNode.width;
newNode.width = freeNode.x + freeNode.width - (usedNode.x + usedNode.width);
freeRectangles.Add(newNode);
}
}
return true;
}
void PruneFreeList ()
{
for (int i = 0; i < freeRectangles.Count; ++i)
for (int j = i + 1; j < freeRectangles.Count; ++j)
{
if (IsContainedIn(freeRectangles[i], freeRectangles[j]))
{
freeRectangles.RemoveAt(i);
--i;
break;
}
if (IsContainedIn(freeRectangles[j], freeRectangles[i]))
{
freeRectangles.RemoveAt(j);
--j;
}
}
}
bool IsContainedIn (Rect a, Rect b)
{
return a.x >= b.x && a.y >= b.y
&& a.x + a.width <= b.x + b.width
&& a.y + a.height <= b.y + b.height;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UITexturePacker.cs
|
C#
|
asf20
| 19,318
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
#if UNITY_3_5
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIGrid))]
public class UIGridEditor : UIWidgetContainerEditor
{
}
#endif
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIGridEditor.cs
|
C#
|
asf20
| 359
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenAlpha))]
public class TweenAlphaEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenAlpha tw = target as TweenAlpha;
GUI.changed = false;
float from = EditorGUILayout.Slider("From", tw.from, 0f, 1f);
float to = EditorGUILayout.Slider("To", tw.to, 0f, 1f);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenAlphaEditor.cs
|
C#
|
asf20
| 774
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenFOV))]
public class TweenFOVEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenFOV tw = target as TweenFOV;
GUI.changed = false;
float from = EditorGUILayout.Slider("From", tw.from, 1f, 180f);
float to = EditorGUILayout.Slider("To", tw.to, 1f, 180f);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenFOVEditor.cs
|
C#
|
asf20
| 770
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// UI Creation Wizard. This tool has been made obsolete with NGUI 3.0.6.
/// </summary>
public class UICreateNewUIWizard : EditorWindow
{
public enum CameraType
{
None,
Simple2D,
Advanced3D,
}
static public CameraType camType = CameraType.Simple2D;
/// <summary>
/// Refresh the window on selection.
/// </summary>
void OnSelectionChange () { Repaint(); }
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
GUILayout.Label("Create a new UI with the following parameters:");
NGUIEditorTools.DrawSeparator();
GUILayout.BeginHorizontal();
NGUISettings.layer = EditorGUILayout.LayerField("Layer", NGUISettings.layer, GUILayout.Width(200f));
GUILayout.Space(20f);
GUILayout.Label("This is the layer your UI will reside on");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
camType = (CameraType)EditorGUILayout.EnumPopup("Camera", camType, GUILayout.Width(200f));
GUILayout.Space(20f);
GUILayout.Label("Should this UI have a camera?");
GUILayout.EndHorizontal();
NGUIEditorTools.DrawSeparator();
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("When ready,");
bool create = GUILayout.Button("Create Your UI", GUILayout.Width(120f));
GUILayout.EndHorizontal();
if (create) CreateNewUI(camType);
EditorGUILayout.HelpBox("This tool has become obsolete with NGUI 3.0.6. You can create UIs from the NGUI -> Create menu.", MessageType.Warning);
}
/// <summary>
/// Create a brand-new UI hierarchy.
/// </summary>
static public GameObject CreateNewUI (CameraType type)
{
UIPanel p = NGUITools.CreateUI(type == CameraType.Advanced3D, NGUISettings.layer);
Selection.activeGameObject = p.gameObject;
return Selection.activeGameObject;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UICreateNewUIWizard.cs
|
C#
|
asf20
| 2,057
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// Editor component used to display a list of sprites.
/// </summary>
public class SpriteSelector : ScriptableWizard
{
static public SpriteSelector instance;
void OnEnable () { instance = this; }
void OnDisable () { instance = null; }
public delegate void Callback (string sprite);
SerializedObject mObject;
SerializedProperty mProperty;
UISprite mSprite;
Vector2 mPos = Vector2.zero;
Callback mCallback;
float mClickTime = 0f;
/// <summary>
/// Draw the custom wizard.
/// </summary>
void OnGUI ()
{
NGUIEditorTools.SetLabelWidth(80f);
if (NGUISettings.atlas == null)
{
GUILayout.Label("No Atlas selected.", "LODLevelNotifyText");
}
else
{
UIAtlas atlas = NGUISettings.atlas;
bool close = false;
GUILayout.Label(atlas.name + " Sprites", "LODLevelNotifyText");
NGUIEditorTools.DrawSeparator();
GUILayout.BeginHorizontal();
GUILayout.Space(84f);
string before = NGUISettings.partialSprite;
string after = EditorGUILayout.TextField("", before, "SearchTextField");
NGUISettings.partialSprite = after;
if (GUILayout.Button("", "SearchCancelButton", GUILayout.Width(18f)))
{
NGUISettings.partialSprite = "";
GUIUtility.keyboardControl = 0;
}
GUILayout.Space(84f);
GUILayout.EndHorizontal();
Texture2D tex = atlas.texture as Texture2D;
if (tex == null)
{
GUILayout.Label("The atlas doesn't have a texture to work with");
return;
}
BetterList<string> sprites = atlas.GetListOfSprites(NGUISettings.partialSprite);
float size = 80f;
float padded = size + 10f;
int columns = Mathf.FloorToInt(Screen.width / padded);
if (columns < 1) columns = 1;
int offset = 0;
Rect rect = new Rect(10f, 0, size, size);
GUILayout.Space(10f);
mPos = GUILayout.BeginScrollView(mPos);
int rows = 1;
while (offset < sprites.size)
{
GUILayout.BeginHorizontal();
{
int col = 0;
rect.x = 10f;
for (; offset < sprites.size; ++offset)
{
UISpriteData sprite = atlas.GetSprite(sprites[offset]);
if (sprite == null) continue;
// Button comes first
if (GUI.Button(rect, ""))
{
if (Event.current.button == 0)
{
float delta = Time.realtimeSinceStartup - mClickTime;
mClickTime = Time.realtimeSinceStartup;
if (NGUISettings.selectedSprite != sprite.name)
{
if (mSprite != null)
{
NGUIEditorTools.RegisterUndo("Atlas Selection", mSprite);
mSprite.MakePixelPerfect();
EditorUtility.SetDirty(mSprite.gameObject);
}
NGUISettings.selectedSprite = sprite.name;
NGUIEditorTools.RepaintSprites();
if (mCallback != null) mCallback(sprite.name);
}
else if (delta < 0.5f) close = true;
}
else
{
NGUIContextMenu.AddItem("Edit", false, EditSprite, sprite);
NGUIContextMenu.AddItem("Delete", false, DeleteSprite, sprite);
NGUIContextMenu.Show();
}
}
if (Event.current.type == EventType.Repaint)
{
// On top of the button we have a checkboard grid
NGUIEditorTools.DrawTiledTexture(rect, NGUIEditorTools.backdropTexture);
Rect uv = new Rect(sprite.x, sprite.y, sprite.width, sprite.height);
uv = NGUIMath.ConvertToTexCoords(uv, tex.width, tex.height);
// Calculate the texture's scale that's needed to display the sprite in the clipped area
float scaleX = rect.width / uv.width;
float scaleY = rect.height / uv.height;
// Stretch the sprite so that it will appear proper
float aspect = (scaleY / scaleX) / ((float)tex.height / tex.width);
Rect clipRect = rect;
if (aspect != 1f)
{
if (aspect < 1f)
{
// The sprite is taller than it is wider
float padding = size * (1f - aspect) * 0.5f;
clipRect.xMin += padding;
clipRect.xMax -= padding;
}
else
{
// The sprite is wider than it is taller
float padding = size * (1f - 1f / aspect) * 0.5f;
clipRect.yMin += padding;
clipRect.yMax -= padding;
}
}
GUI.DrawTextureWithTexCoords(clipRect, tex, uv);
// Draw the selection
if (NGUISettings.selectedSprite == sprite.name)
{
NGUIEditorTools.DrawOutline(rect, new Color(0.4f, 1f, 0f, 1f));
}
}
GUI.backgroundColor = new Color(1f, 1f, 1f, 0.5f);
GUI.contentColor = new Color(1f, 1f, 1f, 0.7f);
GUI.Label(new Rect(rect.x, rect.y + rect.height, rect.width, 32f), sprite.name, "ProgressBarBack");
GUI.contentColor = Color.white;
GUI.backgroundColor = Color.white;
if (++col >= columns)
{
++offset;
break;
}
rect.x += padded;
}
}
GUILayout.EndHorizontal();
GUILayout.Space(padded);
rect.y += padded + 26;
++rows;
}
GUILayout.Space(rows * 26);
GUILayout.EndScrollView();
if (close) Close();
}
}
/// <summary>
/// Edit the sprite (context menu selection)
/// </summary>
void EditSprite (object obj)
{
if (this == null) return;
UISpriteData sd = obj as UISpriteData;
NGUIEditorTools.SelectSprite(sd.name);
Close();
}
/// <summary>
/// Delete the sprite (context menu selection)
/// </summary>
void DeleteSprite (object obj)
{
if (this == null) return;
UISpriteData sd = obj as UISpriteData;
List<UIAtlasMaker.SpriteEntry> sprites = new List<UIAtlasMaker.SpriteEntry>();
UIAtlasMaker.ExtractSprites(NGUISettings.atlas, sprites);
for (int i = sprites.Count; i > 0; )
{
UIAtlasMaker.SpriteEntry ent = sprites[--i];
if (ent.name == sd.name)
sprites.RemoveAt(i);
}
UIAtlasMaker.UpdateAtlas(NGUISettings.atlas, sprites);
NGUIEditorTools.RepaintSprites();
}
/// <summary>
/// Property-based selection result.
/// </summary>
void OnSpriteSelection (string sp)
{
if (mObject != null && mProperty != null)
{
mObject.Update();
mProperty.stringValue = sp;
mObject.ApplyModifiedProperties();
}
}
/// <summary>
/// Show the sprite selection wizard.
/// </summary>
static public void ShowSelected ()
{
if (NGUISettings.atlas != null)
{
Show(delegate(string sel) { NGUIEditorTools.SelectSprite(sel); });
}
}
/// <summary>
/// Show the sprite selection wizard.
/// </summary>
static public void Show (SerializedObject ob, SerializedProperty pro, UIAtlas atlas)
{
if (instance != null)
{
instance.Close();
instance = null;
}
if (ob != null && pro != null && atlas != null)
{
SpriteSelector comp = ScriptableWizard.DisplayWizard<SpriteSelector>("Select a Sprite");
NGUISettings.atlas = atlas;
NGUISettings.selectedSprite = pro.hasMultipleDifferentValues ? null : pro.stringValue;
comp.mSprite = null;
comp.mObject = ob;
comp.mProperty = pro;
comp.mCallback = comp.OnSpriteSelection;
}
}
/// <summary>
/// Show the selection wizard.
/// </summary>
static public void Show (Callback callback)
{
if (instance != null)
{
instance.Close();
instance = null;
}
SpriteSelector comp = ScriptableWizard.DisplayWizard<SpriteSelector>("Select a Sprite");
comp.mSprite = null;
comp.mCallback = callback;
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/SpriteSelector.cs
|
C#
|
asf20
| 7,557
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(TweenRotation))]
public class TweenRotationEditor : UITweenerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(120f);
TweenRotation tw = target as TweenRotation;
GUI.changed = false;
Vector3 from = EditorGUILayout.Vector3Field("From", tw.from);
Vector3 to = EditorGUILayout.Vector3Field("To", tw.to);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Tween Change", tw);
tw.from = from;
tw.to = to;
NGUITools.SetDirty(tw);
}
DrawCommonProperties();
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/TweenRotationEditor.cs
|
C#
|
asf20
| 786
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
[CanEditMultipleObjects]
[CustomEditor(typeof(UIStretch))]
public class UIStretchEditor : Editor
{
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIStretchEditor.cs
|
C#
|
asf20
| 324
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using UnityEditor;
#if UNITY_3_5
[CustomEditor(typeof(UIButtonColor))]
#else
[CustomEditor(typeof(UIButtonColor), true)]
#endif
public class UIButtonColorEditor : UIWidgetContainerEditor
{
public override void OnInspectorGUI ()
{
GUILayout.Space(6f);
NGUIEditorTools.SetLabelWidth(86f);
serializedObject.Update();
NGUIEditorTools.DrawProperty("Tween Target", serializedObject, "tweenTarget");
DrawProperties();
serializedObject.ApplyModifiedProperties();
if (target.GetType() == typeof(UIButtonColor))
{
GUILayout.Space(3f);
if (GUILayout.Button("Upgrade to a Button"))
{
NGUIEditorTools.ReplaceClass(serializedObject, typeof(UIButton));
Selection.activeGameObject = null;
}
}
}
protected virtual void DrawProperties ()
{
DrawTransition();
DrawColors();
}
protected void DrawColors ()
{
if (serializedObject.FindProperty("tweenTarget").objectReferenceValue == null) return;
if (NGUIEditorTools.DrawHeader("Colors"))
{
NGUIEditorTools.BeginContents();
UIButtonColor btn = target as UIButtonColor;
if (btn.tweenTarget != null)
{
UIWidget widget = btn.tweenTarget.GetComponent<UIWidget>();
if (widget != null)
{
EditorGUI.BeginDisabledGroup(serializedObject.isEditingMultipleObjects);
{
SerializedObject obj = new SerializedObject(widget);
obj.Update();
NGUIEditorTools.DrawProperty("Normal", obj, "mColor");
obj.ApplyModifiedProperties();
}
EditorGUI.EndDisabledGroup();
}
}
NGUIEditorTools.DrawProperty("Hover", serializedObject, "hover");
NGUIEditorTools.DrawProperty("Pressed", serializedObject, "pressed");
NGUIEditorTools.DrawProperty("Disabled", serializedObject, "disabledColor");
NGUIEditorTools.EndContents();
}
}
protected void DrawTransition ()
{
GUILayout.BeginHorizontal();
NGUIEditorTools.DrawProperty("Transition", serializedObject, "duration", GUILayout.Width(120f));
GUILayout.Label("seconds");
GUILayout.EndHorizontal();
GUILayout.Space(3f);
}
}
|
zzzstrawhatzzz
|
trunk/client/Assets/NGUI/Scripts/Editor/UIButtonColorEditor.cs
|
C#
|
asf20
| 2,235
|