CurvedUIVertexEffect.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. #if UNITY_EDITOR
  6. using UnityEditor;
  7. #endif
  8. #if CURVEDUI_TMP || TMP_PRESENT
  9. using TMPro;
  10. #endif
  11. [assembly: CurvedUI.OptionalDependency("TMPro.TextMeshProUGUI", "CURVEDUI_TMP")]
  12. namespace CurvedUI
  13. {
  14. //Added to every UI object by CurvedUISettings.
  15. //This is the script that subdivides and modifies the shape of the canvas object it is attached to.
  16. //
  17. //Requires Unity 5.3 or later
  18. public partial class CurvedUIVertexEffect : BaseMeshEffect
  19. {
  20. #region VARIABLES
  21. //public settings
  22. [Tooltip("Check to skip tesselation pass on this object. CurvedUI will not create additional vertices to make this object have a smoother curve. Checking this can solve some issues if you create your own procedural mesh for this object. Default false.")]
  23. public bool DoNotTesselate = false;
  24. //stored references
  25. Canvas myCanvas;
  26. CurvedUISettings mySettings;
  27. Graphic myGraphic;
  28. Text myText;
  29. #if CURVEDUI_TMP || TMP_PRESENT
  30. TextMeshProUGUI myTMP;
  31. CurvedUITMPSubmesh myTMPSubMesh;
  32. #endif
  33. //variables we operate on
  34. bool m_tesselationRequired = true;
  35. bool tesselationRequired {
  36. get { return m_tesselationRequired; }
  37. set { m_tesselationRequired = value;
  38. //Debug.Log(this.gameObject.name + " settting tess to " + value, this.gameObject);
  39. }
  40. }
  41. bool curvingRequired = true;
  42. bool TransformMisaligned = false;
  43. Matrix4x4 CanvasToWorld;
  44. Matrix4x4 CanvasToLocal;
  45. Matrix4x4 MyToWorld;
  46. Matrix4x4 MyToLocal;
  47. List<UIVertex> m_tesselatedVerts = new List<UIVertex>();
  48. List<UIVertex> m_curvedVerts = new List<UIVertex>();
  49. List<UIVertex> m_vertsInQuads = new List<UIVertex>();
  50. UIVertex m_ret;
  51. UIVertex[] m_quad = new UIVertex[4];
  52. float[] m_weights = new float[4];
  53. [SerializeField] [HideInInspector] Vector3 savedPos;
  54. [SerializeField] [HideInInspector] Vector3 savedUp;
  55. [SerializeField] [HideInInspector] Vector2 savedRectSize;
  56. [SerializeField] [HideInInspector] Color savedColor;
  57. #if UNITY_2020_2_OR_NEWER
  58. [SerializeField] [HideInInspector] Vector4 savedTextUV0;
  59. #else
  60. [SerializeField] [HideInInspector] Vector2 savedTextUV0;
  61. #endif
  62. [SerializeField] [HideInInspector] float savedFill;
  63. #endregion
  64. #region LIFECYCLE
  65. protected override void Awake()
  66. {
  67. base.Awake();
  68. myGraphic = GetComponent<Graphic>();
  69. myText = GetComponent<Text>();
  70. #if CURVEDUI_TMP || TMP_PRESENT
  71. myTMP = GetComponent<TextMeshProUGUI>();
  72. myTMPSubMesh = GetComponent<CurvedUITMPSubmesh>();
  73. #endif
  74. }
  75. protected override void OnEnable()
  76. {
  77. //find the settings object and its canvas.
  78. FindParentSettings();
  79. //If there is an update to the graphic, we cant reuse old vertices, so new tesselation will be required
  80. if (myGraphic)
  81. {
  82. myGraphic.RegisterDirtyMaterialCallback(TesselationRequiredCallback);
  83. myGraphic.SetVerticesDirty();
  84. }
  85. //add text events and callbacks
  86. if (myText)
  87. {
  88. myText.RegisterDirtyVerticesCallback(TesselationRequiredCallback);
  89. Font.textureRebuilt += FontTextureRebuiltCallback;
  90. }
  91. }
  92. /// <summary>
  93. /// Start is executed after OnEnable
  94. /// </summary>
  95. protected override void Start()
  96. {
  97. base.Start();
  98. //if we have an interactable component, make sure its inside the canvas and it's Z position is 0 in relation to the canvas.
  99. //Otherwise the interactions on it will not be accurate, or it may not work at all!
  100. //This is because, in order to save performance, CurvedUI creates a collider only for the space inside the Canvas rectangle.
  101. if (myCanvas && GetComponent<Selectable>())
  102. {
  103. Vector3 myPosOnCanvas = myCanvas.transform.worldToLocalMatrix.MultiplyPoint3x4(this.transform.position);
  104. RectTransform canvasRect = (myCanvas.transform as RectTransform);
  105. if (myPosOnCanvas.x.Abs() > canvasRect.rect.width / 2.0f || myPosOnCanvas.y.Abs() > canvasRect.rect.height / 2.0f)
  106. {
  107. Debug.LogWarning("CurvedUI: " + GetComponent<Selectable>().GetType().Name + " \"" + this.gameObject.name + "\" is outside of the canvas. It will not be interactable. Move it inside the canvas rectangle (white border in scene view) for it to work.", this.gameObject);
  108. }
  109. if (myPosOnCanvas.z.Abs() > 0.1f)
  110. {
  111. Debug.LogWarning("CurvedUI: The Z position of \"" + this.gameObject.name + "\" " + GetComponent<Selectable>().GetType().Name + ", or one of its parents is not 0 in relation to the canvas. The interactions may not be accurate.", this.gameObject);
  112. }
  113. }
  114. }
  115. protected override void OnDisable()
  116. {
  117. //If there is an update to the graphic, we cant reuse old vertices, so new tesselation will be required
  118. if (myGraphic)
  119. myGraphic.UnregisterDirtyMaterialCallback(TesselationRequiredCallback);
  120. if (myText)
  121. {
  122. myText.UnregisterDirtyVerticesCallback(TesselationRequiredCallback);
  123. Font.textureRebuilt -= FontTextureRebuiltCallback;
  124. }
  125. }
  126. /// <summary>
  127. /// Subscribed to graphic componenet to find out when vertex information changes and we need to create new geometry based on that.
  128. /// </summary>
  129. void TesselationRequiredCallback()
  130. {
  131. tesselationRequired = true;
  132. }
  133. /// <summary>
  134. /// Called by Font class to let us know font atlas has ben rebuilt and we need to update our vertices.
  135. /// </summary>
  136. void FontTextureRebuiltCallback(Font fontie)
  137. {
  138. if (myText.font == fontie)
  139. tesselationRequired = true;
  140. }
  141. void LateUpdate()
  142. {
  143. #if CURVEDUI_TMP || TMP_PRESENT // CurvedUITMP handles updates for TextMeshPro objects.
  144. if (myTMP || myTMPSubMesh) return;
  145. #endif
  146. //Find if the change in transform requires us to retesselate the UI
  147. // do not perform the check it it will happen anyway
  148. if (!tesselationRequired)
  149. {
  150. if ((transform as RectTransform).rect.size != savedRectSize)
  151. {
  152. //the size of this RectTransform has changed, we have to tesselate again!
  153. tesselationRequired = true;
  154. }
  155. else if (myGraphic != null)//test for color changes if it has a graphic component
  156. {
  157. if (myGraphic.color != savedColor)
  158. {
  159. tesselationRequired = true;
  160. savedColor = myGraphic.color;
  161. }
  162. else if (myGraphic is Image)
  163. {
  164. if ((myGraphic as Image).fillAmount != savedFill)
  165. {
  166. tesselationRequired = true;
  167. savedFill = (myGraphic as Image).fillAmount;
  168. }
  169. }
  170. }
  171. }
  172. if (!tesselationRequired && !curvingRequired) // do not perform a check if we're already tesselating or curving. Tesselation includes curving.
  173. {
  174. //test if position in canvas's local space has been changed. We would need to recalculate vertices again
  175. Vector3 testedPos = mySettings.transform.worldToLocalMatrix.MultiplyPoint3x4(this.transform.position);
  176. if (!testedPos.AlmostEqual(savedPos))
  177. {
  178. //we dont have to curve vertices if we only moved the object vertically in a cylinder.
  179. if (mySettings.Shape != CurvedUISettings.CurvedUIShape.CYLINDER || Mathf.Pow(testedPos.x - savedPos.x, 2) > 0.00001 || Mathf.Pow(testedPos.z - savedPos.z, 2) > 0.00001)
  180. {
  181. savedPos = testedPos;
  182. curvingRequired = true;
  183. //Debug.Log("crv req - tested pos: " + testedPos, this.gameObject);
  184. }
  185. }
  186. //test this object's rotation in relation to canvas.
  187. Vector3 testedUp = mySettings.transform.worldToLocalMatrix.MultiplyVector(this.transform.up).normalized;
  188. if (!savedUp.AlmostEqual(testedUp, 0.0001))
  189. {
  190. bool testedEqual = testedUp.AlmostEqual(Vector3.up.normalized);
  191. bool savedEqual = savedUp.AlmostEqual(Vector3.up.normalized);
  192. //special case - if we change the z angle from or to 0, we need to retesselate to properly display geometry in cyllinder
  193. if ((!testedEqual && savedEqual) || (testedEqual && !savedEqual))
  194. tesselationRequired = true;
  195. savedUp = testedUp;
  196. curvingRequired = true;
  197. //Debug.Log("crv req - tested up: " + testedUp);
  198. }
  199. }
  200. ////if we find we need to make a change in the mesh, set vertices dirty to trigger BaseMeshEffect firing.
  201. if (myGraphic && (tesselationRequired || curvingRequired)) myGraphic.SetVerticesDirty();
  202. }
  203. #endregion
  204. #region MESH EFFECT
  205. //This is called by canvas after UI object's mesh is generated, but before it is rendered.
  206. //Best place to modify the vertices of the object.
  207. public override void ModifyMesh(VertexHelper vh)
  208. {
  209. if (!ShouldModify()) return;
  210. //check for changes in text font material that would mean a retesselation in required to get fresh UV's
  211. CheckTextFontMaterial();
  212. //TESSELATING VERTICES--------------------------------------------------------//
  213. //tesselate (subdivide) the vertices of the UI object if we need more of them
  214. //to display nice curvature. Save them to a list, so we don't have to retesselate
  215. //if RectTransform's size has not changed.
  216. if (tesselationRequired || !Application.isPlaying)
  217. {
  218. //Prepare a list and get vertices from the vertex stream. These come as triangles.
  219. if (m_tesselatedVerts == null)
  220. m_tesselatedVerts = new List<UIVertex>();
  221. else
  222. m_tesselatedVerts.Clear();
  223. vh.GetUIVertexStream(m_tesselatedVerts);
  224. //subdivide them
  225. TesselateGeometry(m_tesselatedVerts);
  226. //save the transform properties we last tesselated for.
  227. savedRectSize = (transform as RectTransform).rect.size;
  228. //set flag
  229. tesselationRequired = false;
  230. curvingRequired = true;
  231. }
  232. //CURVING VERTICES ---------------------------------------------------------//
  233. if (curvingRequired)
  234. {
  235. //update transformation matrices we're going to use in curving the verts.
  236. CanvasToWorld = myCanvas.transform.localToWorldMatrix;
  237. CanvasToLocal = myCanvas.transform.worldToLocalMatrix;
  238. MyToWorld = transform.localToWorldMatrix;
  239. MyToLocal = transform.worldToLocalMatrix;
  240. //prepare list
  241. if (m_curvedVerts == null)
  242. m_curvedVerts = new List<UIVertex>();
  243. //Debug.Log("verts:" + m_curvedVerts.Count + " tess'd:" + m_tesselatedVerts.Count);
  244. if (m_curvedVerts.Count == m_tesselatedVerts.Count)
  245. {
  246. //Debug.Log("count equal");
  247. for (int i = 0; i < m_curvedVerts.Count; i++)
  248. m_curvedVerts[i] = CurveVertex(m_tesselatedVerts[i], mySettings.Angle, mySettings.GetCyllinderRadiusInCanvasSpace(), (myCanvas.transform as RectTransform).rect.size);
  249. }
  250. else
  251. {
  252. m_curvedVerts.Clear();
  253. for (int i = 0; i < m_tesselatedVerts.Count; i++)
  254. m_curvedVerts.Add(CurveVertex(m_tesselatedVerts[i], mySettings.Angle, mySettings.GetCyllinderRadiusInCanvasSpace(), (myCanvas.transform as RectTransform).rect.size));
  255. }
  256. //set flags
  257. curvingRequired = false;
  258. }
  259. //SAVE CURVED VERTICES TO THE VERTEX HELPER------------------------//
  260. //They can come as quads or as triangles.
  261. vh.Clear();
  262. if (m_curvedVerts.Count % 4 == 0)
  263. {
  264. for (int i = 0; i < m_curvedVerts.Count; i += 4)
  265. {
  266. for (int v = 0; v < 4; v++)//create a quad
  267. m_quad[v] = m_curvedVerts[i + v];
  268. vh.AddUIVertexQuad(m_quad); // add it to the list
  269. }
  270. }
  271. else vh.AddUIVertexTriangleStream(m_curvedVerts);
  272. }
  273. //This is called by canvas after UI object's mesh is generated, but before it is rendered.
  274. //Best place to modify the vertices of the object.
  275. public void ModifyTMPMesh(ref List<UIVertex> vertexList)
  276. {
  277. if (!ShouldModify()) return;
  278. //check for changes in text font material that would mean a retesselation in required to get fresh UV's
  279. CheckTextFontMaterial();
  280. //TESSELATING VERTICES--------------------------------------------------------//
  281. //not needed in TMP object, skip to curving
  282. tesselationRequired = false;
  283. curvingRequired = true;
  284. //CURVING VERTICES ---------------------------------------------------------//
  285. if (curvingRequired)
  286. {
  287. //update transformation matrices we're going to use in curving the verts.
  288. CanvasToWorld = myCanvas.transform.localToWorldMatrix;
  289. CanvasToLocal = myCanvas.transform.worldToLocalMatrix;
  290. MyToWorld = transform.localToWorldMatrix;
  291. MyToLocal = transform.worldToLocalMatrix;
  292. //Debug.Log("verts:" + m_curvedVerts.Count + " tess'd:" + m_tesselatedVerts.Count);
  293. for (int i = 0; i < vertexList.Count; i++)
  294. vertexList[i] = CurveVertex(vertexList[i], mySettings.Angle, mySettings.GetCyllinderRadiusInCanvasSpace(), (myCanvas.transform as RectTransform).rect.size);
  295. //set flags
  296. curvingRequired = false;
  297. }
  298. }
  299. #endregion
  300. #region HELPERS
  301. bool ShouldModify()
  302. {
  303. if (!this.IsActive()) return false;
  304. if (mySettings == null) FindParentSettings();
  305. if (mySettings == null || !mySettings.enabled || mySettings.Angle == 1) return false;
  306. return true;
  307. }
  308. void CheckTextFontMaterial()
  309. {
  310. //we check for a sudden change in text's fontMaterialTexture. This is a very hacky way, but the only one working reliably for now.
  311. if (myText)
  312. {
  313. if (myText.cachedTextGenerator.verts.Count > 0 && myText.cachedTextGenerator.verts[0].uv0 != savedTextUV0)
  314. {
  315. //Debug.Log("tess req - texture");
  316. savedTextUV0 = myText.cachedTextGenerator.verts[0].uv0;
  317. tesselationRequired = true;
  318. }
  319. }
  320. }
  321. public CurvedUISettings FindParentSettings(bool forceNew = false)
  322. {
  323. if (mySettings == null || forceNew)
  324. {
  325. mySettings = GetComponentInParent<CurvedUISettings>();
  326. if (mySettings == null) return null;
  327. else
  328. {
  329. myCanvas = mySettings.GetComponent<Canvas>();
  330. }
  331. }
  332. return mySettings;
  333. }
  334. #endregion
  335. #region CURVING
  336. /// <summary>
  337. /// Map position of a vertex to a section of a circle. calculated in canvas's local space
  338. /// </summary>
  339. UIVertex CurveVertex(UIVertex input, float cylinder_angle, float radius, Vector2 canvasSize)
  340. {
  341. Vector3 pos = input.position;
  342. //calculated in canvas local space version:
  343. pos = CanvasToLocal.MultiplyPoint3x4(MyToWorld.MultiplyPoint3x4(pos));
  344. // pos = mySettings.VertexPositionToCurvedCanvas(pos);
  345. if (mySettings.Shape == CurvedUISettings.CurvedUIShape.CYLINDER && mySettings.Angle != 0)
  346. {
  347. float theta = (pos.x / canvasSize.x) * cylinder_angle * Mathf.Deg2Rad;
  348. radius += pos.z; // change the radius depending on how far the element is moved in z direction from canvas plane
  349. pos.x = Mathf.Sin(theta) * radius;
  350. pos.z += Mathf.Cos(theta) * radius - radius;
  351. }
  352. else if (mySettings.Shape == CurvedUISettings.CurvedUIShape.CYLINDER_VERTICAL && mySettings.Angle != 0)
  353. {
  354. float theta = (pos.y / canvasSize.y) * cylinder_angle * Mathf.Deg2Rad;
  355. radius += pos.z; // change the radius depending on how far the element is moved in z direction from canvas plane
  356. pos.y = Mathf.Sin(theta) * radius;
  357. pos.z += Mathf.Cos(theta) * radius - radius;
  358. }
  359. else if (mySettings.Shape == CurvedUISettings.CurvedUIShape.RING)
  360. {
  361. float angleOffset = 0;
  362. float r = pos.y.Remap(canvasSize.y * 0.5f * (mySettings.RingFlipVertical ? 1 : -1), -canvasSize.y * 0.5f * (mySettings.RingFlipVertical ? 1 : -1), mySettings.RingExternalDiameter * (1 - mySettings.RingFill) * 0.5f, mySettings.RingExternalDiameter * 0.5f);
  363. float theta = (pos.x / canvasSize.x).Remap(-0.5f, 0.5f, Mathf.PI / 2.0f, cylinder_angle * Mathf.Deg2Rad + Mathf.PI / 2.0f) - angleOffset;
  364. pos.x = r * Mathf.Cos(theta);
  365. pos.y = r * Mathf.Sin(theta);
  366. }
  367. else if (mySettings.Shape == CurvedUISettings.CurvedUIShape.SPHERE && mySettings.Angle != 0)
  368. {
  369. float vangle = mySettings.VerticalAngle;
  370. float savedZ = -pos.z;
  371. if (mySettings.PreserveAspect)
  372. {
  373. vangle = cylinder_angle * (canvasSize.y / canvasSize.x);
  374. }
  375. else
  376. {
  377. radius = canvasSize.x / 2.0f;
  378. if (vangle == 0) return input;
  379. }
  380. //convert planar coordinates to spherical coordinates
  381. float theta = (pos.x / canvasSize.x).Remap(-0.5f, 0.5f, (180 - cylinder_angle) / 2.0f - 90, 180 - (180 - cylinder_angle) / 2.0f - 90);
  382. theta *= Mathf.Deg2Rad;
  383. float gamma = (pos.y / canvasSize.y).Remap(-0.5f, 0.5f, (180 - vangle) / 2.0f, 180 - (180 - vangle) / 2.0f);
  384. gamma *= Mathf.Deg2Rad;
  385. pos.z = Mathf.Sin(gamma) * Mathf.Cos(theta) * (radius + savedZ);
  386. pos.y = -(radius + savedZ) * Mathf.Cos(gamma);
  387. pos.x = Mathf.Sin(gamma) * Mathf.Sin(theta) * (radius + savedZ);
  388. if (mySettings.PreserveAspect)
  389. pos.z -= radius;
  390. }
  391. //4. write output
  392. input.position = MyToLocal.MultiplyPoint3x4(CanvasToWorld.MultiplyPoint3x4(pos));
  393. return input;
  394. }
  395. #endregion
  396. #region TESSELATION
  397. void TesselateGeometry(List<UIVertex> verts)
  398. {
  399. Vector2 tessellatedSize = mySettings.GetTesslationSize();
  400. //find if we are aligned with canvas main axis
  401. TransformMisaligned = !(savedUp.AlmostEqual(Vector3.up.normalized));
  402. // Convert the list from triangles to quads to be used by the tesselation
  403. TrisToQuads(verts);
  404. //do not tesselate text verts. Text usually is small and has plenty of verts already.
  405. #if CURVEDUI_TMP || TMP_PRESENT
  406. if (myText == null && myTMP == null && !DoNotTesselate)
  407. {
  408. #else
  409. if (myText == null && !DoNotTesselate)
  410. {
  411. #endif
  412. // Tesselate quads and apply transformation
  413. int startingVertexCount = verts.Count;
  414. for (int i = 0; i < startingVertexCount; i += 4)
  415. ModifyQuad(verts, i, tessellatedSize);
  416. // Remove old quads
  417. verts.RemoveRange(0, startingVertexCount);
  418. }
  419. }
  420. void ModifyQuad(List<UIVertex> verts, int vertexIndex, Vector2 requiredSize)
  421. {
  422. // Read the existing quad vertices
  423. for (int i = 0; i < 4; i++)
  424. m_quad[i] = verts[vertexIndex + i];
  425. // horizotal and vertical directions of a quad. We're going to tesselate parallel to these.
  426. Vector3 horizontalDir = m_quad[2].position - m_quad[1].position;
  427. Vector3 verticalDir = m_quad[1].position - m_quad[0].position;
  428. //To make sure filled image is properly tesselated, were going to find the bigger side of the quad.
  429. if (myGraphic != null && (myGraphic is Image) && (myGraphic as Image).type == Image.Type.Filled)
  430. {
  431. horizontalDir = (horizontalDir).x > (m_quad[3].position - m_quad[0].position).x ? horizontalDir : m_quad[3].position - m_quad[0].position;
  432. verticalDir = (verticalDir).y > (m_quad[2].position - m_quad[3].position).y ? verticalDir : m_quad[2].position - m_quad[3].position;
  433. }
  434. // Find how many quads we need to create
  435. int horizontalQuads = 1;
  436. int verticalQuads = 1;
  437. // Tesselate vertically only if the recttransform (or parent) is rotated
  438. // This cuts down the time needed to tesselate by 90% in some cases.
  439. if (TransformMisaligned || mySettings.Shape == CurvedUISettings.CurvedUIShape.SPHERE || mySettings.Shape == CurvedUISettings.CurvedUIShape.CYLINDER_VERTICAL)
  440. verticalQuads = Mathf.CeilToInt(verticalDir.magnitude * (1.0f / Mathf.Max(0.0001f, requiredSize.y)));
  441. if (TransformMisaligned || mySettings.Shape != CurvedUISettings.CurvedUIShape.CYLINDER_VERTICAL)
  442. {
  443. horizontalQuads = Mathf.CeilToInt(horizontalDir.magnitude * (1.0f / Mathf.Max(0.0001f, requiredSize.x)));
  444. }
  445. //Debug.Log(this.transform.root.name + "'s panel: hori size:" + horizontalDir.magnitude + " req:" + requiredSize.x + " divs:"+horizontalQuads);
  446. bool oneVert = false;
  447. bool oneHori = false;
  448. // Create the quads!
  449. float yStart = 0.0f;
  450. for (int y = 0; y < verticalQuads || !oneVert; ++y)
  451. {
  452. oneVert = true;
  453. float yEnd = (y + 1.0f) / verticalQuads;
  454. float xStart = 0.0f;
  455. for (int x = 0; x < horizontalQuads || !oneHori; ++x)
  456. {
  457. oneHori = true;
  458. float xEnd = (x + 1.0f) / horizontalQuads;
  459. //Add new quads to list
  460. verts.Add(TesselateQuad(xStart, yStart));
  461. verts.Add(TesselateQuad(xStart, yEnd));
  462. verts.Add(TesselateQuad(xEnd, yEnd));
  463. verts.Add(TesselateQuad(xEnd, yStart));
  464. //begin the next quad where we ened this one
  465. xStart = xEnd;
  466. }
  467. //begin the next row where we ended this one
  468. yStart = yEnd;
  469. }
  470. }
  471. /// <summary>
  472. /// Converts a List of triangle mesh vertices to a list of quad mesh vertices
  473. /// </summary>
  474. void TrisToQuads(List<UIVertex> verts)
  475. {
  476. int vertsInTrisCount = verts.Count;
  477. m_vertsInQuads.Clear();
  478. for (int i = 0; i < vertsInTrisCount; i += 6)
  479. {
  480. // Get four corners from two triangles. Basic UI always comes in quads anyway.
  481. m_vertsInQuads.Add(verts[i + 0]);
  482. m_vertsInQuads.Add(verts[i + 1]);
  483. m_vertsInQuads.Add(verts[i + 2]);
  484. m_vertsInQuads.Add(verts[i + 4]);
  485. }
  486. //add quads to the list and remove the triangles
  487. verts.AddRange(m_vertsInQuads);
  488. verts.RemoveRange(0, vertsInTrisCount);
  489. }
  490. /// <summary>
  491. /// Subdivides a quad into 4 quads.
  492. /// </summary>
  493. /// <returns>The quad.</returns>
  494. /// <param name="quad">Quad.</param>
  495. /// <param name="x">The x coordinate.</param>
  496. /// <param name="y">The y coordinate.</param>
  497. #if UNITY_2020_2_OR_NEWER
  498. private Vector4 _uv0;
  499. private Vector4 _uv1;
  500. #else
  501. private Vector2 _uv0;
  502. private Vector2 _uv1;
  503. #endif
  504. private Vector3 _pos;
  505. UIVertex TesselateQuad(float x, float y)
  506. {
  507. //1. calculate weighting factors
  508. m_weights[0] = (1 - x) * (1 - y);
  509. m_weights[1] = (1 - x) * y;
  510. m_weights[2] = x * y;
  511. m_weights[3] = x * (1 - y);
  512. //2. interpolate all the vertex properties using weighting factors
  513. _uv0 = _uv1 = Vector2.zero;
  514. _pos = Vector3.zero;
  515. for (int i = 0; i < 4; i++)
  516. {
  517. _uv0 += m_quad[i].uv0 * m_weights[i];
  518. _uv1 += m_quad[i].uv1 * m_weights[i];
  519. _pos += m_quad[i].position * m_weights[i];
  520. //normal += quad[i].normal * weights[i]; // normals should be recalculated to take the curve into account. Skipped to save performance.
  521. //tan += quad[i].tangent * weights[i]; // tangents should be recalculated to take the curve into account. Skipped to save performance.
  522. }
  523. //4. return output
  524. m_ret.position = _pos;
  525. //ret.color = Color32.Lerp(Color32.Lerp(quad[3].color, quad[1].color, y), Color32.Lerp(quad[0].color, quad[2].color, y), x);
  526. m_ret.color = m_quad[0].color; //used instead to save performance. Color lerps are expensive.
  527. m_ret.uv0 = _uv0;
  528. m_ret.uv1 = _uv1;
  529. m_ret.normal = m_quad[0].normal;
  530. m_ret.tangent = m_quad[0].tangent;
  531. return m_ret;
  532. }
  533. #endregion
  534. #region PUBLIC
  535. /// <summary>
  536. /// Force Mesh to be rebuild during canvas' next update loop.
  537. /// </summary>
  538. public void SetDirty()
  539. {
  540. TesselationRequired = true;
  541. }
  542. /// <summary>
  543. /// Force vertices to be tesselated again from original vertices.
  544. /// Set by CurvedUIVertexEffect when updating object's visual property.
  545. /// </summary>
  546. public bool TesselationRequired
  547. {
  548. get { return tesselationRequired; }
  549. set { tesselationRequired = value; }
  550. }
  551. /// <summary>
  552. /// Force vertices to be repositioned on the curved canvas.
  553. /// set by CurvedUIVertexEffect when moving UI objects on canvas.
  554. /// </summary>
  555. public bool CurvingRequired
  556. {
  557. get { return curvingRequired; }
  558. set { curvingRequired = value; }
  559. }
  560. #endregion
  561. }// end of class
  562. } //end of namespace