RectMask2D.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine.EventSystems;
  4. namespace UnityEngine.UI
  5. {
  6. [AddComponentMenu("UI/Rect Mask 2D", 13)]
  7. [ExecuteAlways]
  8. [DisallowMultipleComponent]
  9. [RequireComponent(typeof(RectTransform))]
  10. /// <summary>
  11. /// A 2D rectangular mask that allows for clipping / masking of areas outside the mask.
  12. /// </summary>
  13. /// <remarks>
  14. /// The RectMask2D behaves in a similar way to a standard Mask component. It differs though in some of the restrictions that it has.
  15. /// A RectMask2D:
  16. /// *Only works in the 2D plane
  17. /// *Requires elements on the mask to be coplanar.
  18. /// *Does not require stencil buffer / extra draw calls
  19. /// *Requires fewer draw calls
  20. /// *Culls elements that are outside the mask area.
  21. /// </remarks>
  22. public class RectMask2D : UIBehaviour, IClipper, ICanvasRaycastFilter
  23. {
  24. [NonSerialized]
  25. private readonly RectangularVertexClipper m_VertexClipper = new RectangularVertexClipper();
  26. [NonSerialized]
  27. private RectTransform m_RectTransform;
  28. [NonSerialized]
  29. private HashSet<MaskableGraphic> m_MaskableTargets = new HashSet<MaskableGraphic>();
  30. [NonSerialized]
  31. private HashSet<IClippable> m_ClipTargets = new HashSet<IClippable>();
  32. [NonSerialized]
  33. private bool m_ShouldRecalculateClipRects;
  34. [NonSerialized]
  35. private List<RectMask2D> m_Clippers = new List<RectMask2D>();
  36. [NonSerialized]
  37. private Rect m_LastClipRectCanvasSpace;
  38. [NonSerialized]
  39. private bool m_ForceClip;
  40. [SerializeField]
  41. private Vector4 m_Padding = new Vector4();
  42. /// <summary>
  43. /// Padding to be applied to the masking
  44. /// X = Left
  45. /// Y = Bottom
  46. /// Z = Right
  47. /// W = Top
  48. /// </summary>
  49. public Vector4 padding
  50. {
  51. get { return m_Padding; }
  52. set
  53. {
  54. m_Padding = value;
  55. MaskUtilities.Notify2DMaskStateChanged(this);
  56. }
  57. }
  58. [SerializeField]
  59. private Vector2Int m_Softness;
  60. /// <summary>
  61. /// The softness to apply to the horizontal and vertical axis.
  62. /// </summary>
  63. public Vector2Int softness
  64. {
  65. get { return m_Softness; }
  66. set
  67. {
  68. m_Softness.x = Mathf.Max(0, value.x);
  69. m_Softness.y = Mathf.Max(0, value.y);
  70. MaskUtilities.Notify2DMaskStateChanged(this);
  71. }
  72. }
  73. /// <remarks>
  74. /// Returns a non-destroyed instance or a null reference.
  75. /// </remarks>
  76. [NonSerialized] private Canvas m_Canvas;
  77. private Canvas Canvas
  78. {
  79. get
  80. {
  81. if (m_Canvas == null)
  82. {
  83. var list = ListPool<Canvas>.Get();
  84. gameObject.GetComponentsInParent(false, list);
  85. if (list.Count > 0)
  86. m_Canvas = list[list.Count - 1];
  87. else
  88. m_Canvas = null;
  89. ListPool<Canvas>.Release(list);
  90. }
  91. return m_Canvas;
  92. }
  93. }
  94. /// <summary>
  95. /// Get the Rect for the mask in canvas space.
  96. /// </summary>
  97. public Rect canvasRect
  98. {
  99. get
  100. {
  101. return m_VertexClipper.GetCanvasRect(rectTransform, Canvas);
  102. }
  103. }
  104. /// <summary>
  105. /// Helper function to get the RectTransform for the mask.
  106. /// </summary>
  107. public RectTransform rectTransform
  108. {
  109. get { return m_RectTransform ?? (m_RectTransform = GetComponent<RectTransform>()); }
  110. }
  111. protected RectMask2D()
  112. {}
  113. protected override void OnEnable()
  114. {
  115. base.OnEnable();
  116. m_ShouldRecalculateClipRects = true;
  117. ClipperRegistry.Register(this);
  118. MaskUtilities.Notify2DMaskStateChanged(this);
  119. }
  120. protected override void OnDisable()
  121. {
  122. // we call base OnDisable first here
  123. // as we need to have the IsActive return the
  124. // correct value when we notify the children
  125. // that the mask state has changed.
  126. base.OnDisable();
  127. m_ClipTargets.Clear();
  128. m_MaskableTargets.Clear();
  129. m_Clippers.Clear();
  130. ClipperRegistry.Unregister(this);
  131. MaskUtilities.Notify2DMaskStateChanged(this);
  132. }
  133. #if UNITY_EDITOR
  134. protected override void OnValidate()
  135. {
  136. base.OnValidate();
  137. m_ShouldRecalculateClipRects = true;
  138. // Dont allow negative softness.
  139. m_Softness.x = Mathf.Max(0, m_Softness.x);
  140. m_Softness.y = Mathf.Max(0, m_Softness.y);
  141. if (!IsActive())
  142. return;
  143. MaskUtilities.Notify2DMaskStateChanged(this);
  144. }
  145. #endif
  146. public virtual bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
  147. {
  148. if (!isActiveAndEnabled)
  149. return true;
  150. return RectTransformUtility.RectangleContainsScreenPoint(rectTransform, sp, eventCamera, m_Padding);
  151. }
  152. private Vector3[] m_Corners = new Vector3[4];
  153. private Rect rootCanvasRect
  154. {
  155. get
  156. {
  157. rectTransform.GetWorldCorners(m_Corners);
  158. if (!ReferenceEquals(Canvas, null))
  159. {
  160. Canvas rootCanvas = Canvas.rootCanvas;
  161. for (int i = 0; i < 4; ++i)
  162. m_Corners[i] = rootCanvas.transform.InverseTransformPoint(m_Corners[i]);
  163. }
  164. return new Rect(m_Corners[0].x, m_Corners[0].y, m_Corners[2].x - m_Corners[0].x, m_Corners[2].y - m_Corners[0].y);
  165. }
  166. }
  167. public virtual void PerformClipping()
  168. {
  169. if (ReferenceEquals(Canvas, null))
  170. {
  171. return;
  172. }
  173. //TODO See if an IsActive() test would work well here or whether it might cause unexpected side effects (re case 776771)
  174. // if the parents are changed
  175. // or something similar we
  176. // do a recalculate here
  177. if (m_ShouldRecalculateClipRects)
  178. {
  179. MaskUtilities.GetRectMasksForClip(this, m_Clippers);
  180. m_ShouldRecalculateClipRects = false;
  181. }
  182. // get the compound rects from
  183. // the clippers that are valid
  184. bool validRect = true;
  185. Rect clipRect = Clipping.FindCullAndClipWorldRect(m_Clippers, out validRect);
  186. // If the mask is in ScreenSpaceOverlay/Camera render mode, its content is only rendered when its rect
  187. // overlaps that of the root canvas.
  188. RenderMode renderMode = Canvas.rootCanvas.renderMode;
  189. bool maskIsCulled =
  190. (renderMode == RenderMode.ScreenSpaceCamera || renderMode == RenderMode.ScreenSpaceOverlay) &&
  191. !clipRect.Overlaps(rootCanvasRect, true);
  192. if (maskIsCulled)
  193. {
  194. // Children are only displayed when inside the mask. If the mask is culled, then the children
  195. // inside the mask are also culled. In that situation, we pass an invalid rect to allow callees
  196. // to avoid some processing.
  197. clipRect = Rect.zero;
  198. validRect = false;
  199. }
  200. if (clipRect != m_LastClipRectCanvasSpace)
  201. {
  202. foreach (IClippable clipTarget in m_ClipTargets)
  203. {
  204. clipTarget.SetClipRect(clipRect, validRect);
  205. }
  206. foreach (MaskableGraphic maskableTarget in m_MaskableTargets)
  207. {
  208. maskableTarget.SetClipRect(clipRect, validRect);
  209. maskableTarget.Cull(clipRect, validRect);
  210. }
  211. }
  212. else if (m_ForceClip)
  213. {
  214. foreach (IClippable clipTarget in m_ClipTargets)
  215. {
  216. clipTarget.SetClipRect(clipRect, validRect);
  217. }
  218. foreach (MaskableGraphic maskableTarget in m_MaskableTargets)
  219. {
  220. maskableTarget.SetClipRect(clipRect, validRect);
  221. if (maskableTarget.canvasRenderer.hasMoved)
  222. maskableTarget.Cull(clipRect, validRect);
  223. }
  224. }
  225. else
  226. {
  227. foreach (MaskableGraphic maskableTarget in m_MaskableTargets)
  228. {
  229. //Case 1170399 - hasMoved is not a valid check when animating on pivot of the object
  230. maskableTarget.Cull(clipRect, validRect);
  231. }
  232. }
  233. m_LastClipRectCanvasSpace = clipRect;
  234. m_ForceClip = false;
  235. UpdateClipSoftness();
  236. }
  237. public virtual void UpdateClipSoftness()
  238. {
  239. if (ReferenceEquals(Canvas, null))
  240. {
  241. return;
  242. }
  243. foreach (IClippable clipTarget in m_ClipTargets)
  244. {
  245. clipTarget.SetClipSoftness(m_Softness);
  246. }
  247. foreach (MaskableGraphic maskableTarget in m_MaskableTargets)
  248. {
  249. maskableTarget.SetClipSoftness(m_Softness);
  250. }
  251. }
  252. /// <summary>
  253. /// Add a IClippable to be tracked by the mask.
  254. /// </summary>
  255. /// <param name="clippable">Add the clippable object for this mask</param>
  256. public void AddClippable(IClippable clippable)
  257. {
  258. if (clippable == null)
  259. return;
  260. m_ShouldRecalculateClipRects = true;
  261. MaskableGraphic maskable = clippable as MaskableGraphic;
  262. if (maskable == null)
  263. m_ClipTargets.Add(clippable);
  264. else
  265. m_MaskableTargets.Add(maskable);
  266. m_ForceClip = true;
  267. }
  268. /// <summary>
  269. /// Remove an IClippable from being tracked by the mask.
  270. /// </summary>
  271. /// <param name="clippable">Remove the clippable object from this mask</param>
  272. public void RemoveClippable(IClippable clippable)
  273. {
  274. if (clippable == null)
  275. return;
  276. m_ShouldRecalculateClipRects = true;
  277. clippable.SetClipRect(new Rect(), false);
  278. MaskableGraphic maskable = clippable as MaskableGraphic;
  279. if (maskable == null)
  280. m_ClipTargets.Remove(clippable);
  281. else
  282. m_MaskableTargets.Remove(maskable);
  283. m_ForceClip = true;
  284. }
  285. protected override void OnTransformParentChanged()
  286. {
  287. base.OnTransformParentChanged();
  288. m_ShouldRecalculateClipRects = true;
  289. }
  290. protected override void OnCanvasHierarchyChanged()
  291. {
  292. m_Canvas = null;
  293. base.OnCanvasHierarchyChanged();
  294. m_ShouldRecalculateClipRects = true;
  295. }
  296. }
  297. }