SpriteMeshDataController.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. using System;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEditor.U2D.Sprites;
  5. namespace UnityEditor.U2D.Animation
  6. {
  7. internal struct WeightedTriangle : IComparable<WeightedTriangle>
  8. {
  9. public int p1;
  10. public int p2;
  11. public int p3;
  12. public float weight;
  13. public int CompareTo(WeightedTriangle other)
  14. {
  15. return weight.CompareTo(other.weight);
  16. }
  17. }
  18. internal class SpriteMeshDataController
  19. {
  20. public ISpriteMeshData spriteMeshData;
  21. private List<Vector2> m_VerticesTemp = new List<Vector2>();
  22. private List<Edge> m_EdgesTemp = new List<Edge>();
  23. public void CreateVertex(Vector2 position)
  24. {
  25. CreateVertex(position, -1);
  26. }
  27. public void CreateVertex(Vector2 position, int edgeIndex)
  28. {
  29. Debug.Assert(spriteMeshData != null);
  30. spriteMeshData.AddVertex(position, default(BoneWeight));
  31. if (edgeIndex != -1)
  32. {
  33. Edge edge = spriteMeshData.edges[edgeIndex];
  34. RemoveEdge(edge);
  35. CreateEdge(edge.index1, spriteMeshData.vertexCount - 1);
  36. CreateEdge(edge.index2, spriteMeshData.vertexCount - 1);
  37. }
  38. }
  39. public void CreateEdge(int index1, int index2)
  40. {
  41. Debug.Assert(spriteMeshData != null);
  42. Debug.Assert(index1 >= 0);
  43. Debug.Assert(index2 >= 0);
  44. Debug.Assert(index1 < spriteMeshData.vertexCount);
  45. Debug.Assert(index2 < spriteMeshData.vertexCount);
  46. Debug.Assert(index1 != index2);
  47. Edge newEdge = new Edge(index1, index2);
  48. if (!spriteMeshData.edges.Contains(newEdge))
  49. spriteMeshData.edges.Add(newEdge);
  50. }
  51. public void RemoveVertex(int index)
  52. {
  53. Debug.Assert(spriteMeshData != null);
  54. //We need to delete the edges that reference the index
  55. List<Edge> edgesWithIndex;
  56. if (FindEdgesContainsIndex(index, out edgesWithIndex))
  57. {
  58. //If there are 2 edges referencing the same index we are removing, we can create a new one that connects the endpoints ("Unsplit").
  59. if (edgesWithIndex.Count == 2)
  60. {
  61. Edge first = edgesWithIndex[0];
  62. Edge second = edgesWithIndex[1];
  63. int index1 = first.index1 != index ? first.index1 : first.index2;
  64. int index2 = second.index1 != index ? second.index1 : second.index2;
  65. CreateEdge(index1, index2);
  66. }
  67. //remove found edges
  68. for (int i = 0; i < edgesWithIndex.Count; i++)
  69. {
  70. RemoveEdge(edgesWithIndex[i]);
  71. }
  72. }
  73. //Fix indices in edges greater than the one we are removing
  74. for (int i = 0; i < spriteMeshData.edges.Count; i++)
  75. {
  76. Edge edge = spriteMeshData.edges[i];
  77. if (edge.index1 > index)
  78. edge.index1--;
  79. if (edge.index2 > index)
  80. edge.index2--;
  81. spriteMeshData.edges[i] = edge;
  82. }
  83. spriteMeshData.RemoveVertex(index);
  84. }
  85. public void RemoveVertex(IEnumerable<int> indices)
  86. {
  87. List<int> sortedIndexList = new List<int>(indices);
  88. if (sortedIndexList.Count == 0)
  89. return;
  90. sortedIndexList.Sort();
  91. for (int i = sortedIndexList.Count - 1; i >= 0; --i)
  92. {
  93. RemoveVertex(sortedIndexList[i]);
  94. }
  95. }
  96. public void RemoveEdge(Edge edge)
  97. {
  98. Debug.Assert(spriteMeshData != null);
  99. spriteMeshData.edges.Remove(edge);
  100. }
  101. public bool FindEdgesContainsIndex(int index, out List<Edge> result)
  102. {
  103. Debug.Assert(spriteMeshData != null);
  104. bool found = false;
  105. result = new List<Edge>();
  106. for (int i = 0; i < spriteMeshData.edges.Count; ++i)
  107. {
  108. Edge edge = spriteMeshData.edges[i];
  109. if (edge.Contains(index))
  110. {
  111. found = true;
  112. result.Add(edge);
  113. }
  114. }
  115. return found;
  116. }
  117. public void Triangulate(ITriangulator triangulator)
  118. {
  119. Debug.Assert(spriteMeshData != null);
  120. Debug.Assert(triangulator != null);
  121. m_VerticesTemp.Clear();
  122. for (int i = 0; i < spriteMeshData.vertexCount; ++i)
  123. m_VerticesTemp.Add(spriteMeshData.GetPosition(i));
  124. triangulator.Triangulate(m_VerticesTemp, spriteMeshData.edges, spriteMeshData.indices);
  125. }
  126. public void Subdivide(ITriangulator triangulator, float largestAreaFactor)
  127. {
  128. Debug.Assert(spriteMeshData != null);
  129. Debug.Assert(triangulator != null);
  130. m_VerticesTemp.Clear();
  131. m_EdgesTemp.Clear();
  132. m_EdgesTemp.AddRange(spriteMeshData.edges);
  133. for (int i = 0; i < spriteMeshData.vertexCount; ++i)
  134. m_VerticesTemp.Add(spriteMeshData.GetPosition(i));
  135. try
  136. {
  137. var indices = new List<int>();
  138. triangulator.Tessellate(0f, 0f, 0f, largestAreaFactor, 100, m_VerticesTemp, m_EdgesTemp, indices);
  139. spriteMeshData.Clear();
  140. for (int i = 0; i < m_VerticesTemp.Count; ++i)
  141. spriteMeshData.AddVertex(m_VerticesTemp[i], default(BoneWeight));
  142. spriteMeshData.edges.AddRange(m_EdgesTemp);
  143. spriteMeshData.indices.AddRange(indices);
  144. }
  145. catch (Exception)
  146. {
  147. }
  148. }
  149. public void ClearWeights(ISelection<int> selection)
  150. {
  151. Debug.Assert(spriteMeshData != null);
  152. for (int i = 0; i < spriteMeshData.vertexCount; ++i)
  153. if (selection == null || (selection.Count == 0 || selection.Contains(i)))
  154. spriteMeshData.GetWeight(i).SetFromBoneWeight(default(BoneWeight));
  155. }
  156. public void OutlineFromAlpha(IOutlineGenerator outlineGenerator, ITextureDataProvider textureDataProvider, float outlineDetail, byte alphaTolerance)
  157. {
  158. Debug.Assert(spriteMeshData != null);
  159. Debug.Assert(textureDataProvider != null);
  160. Debug.Assert(textureDataProvider.texture != null);
  161. int width, height;
  162. textureDataProvider.GetTextureActualWidthAndHeight(out width, out height);
  163. Vector2 scale = new Vector2(textureDataProvider.texture.width / (float)width, textureDataProvider.texture.height / (float)height);
  164. Vector2 scaleInv = new Vector2(1f / scale.x, 1f / scale.y);
  165. Vector2 rectOffset = spriteMeshData.frame.size * 0.5f + spriteMeshData.frame.position;
  166. Rect scaledRect = spriteMeshData.frame;
  167. scaledRect.min = Vector2.Scale(scaledRect.min, scale);
  168. scaledRect.max = Vector2.Scale(scaledRect.max, scale);
  169. spriteMeshData.Clear();
  170. Vector2[][] paths;
  171. outlineGenerator.GenerateOutline(textureDataProvider, scaledRect, outlineDetail, alphaTolerance, false, out paths);
  172. int vertexIndexBase = 0;
  173. for (int i = 0; i < paths.Length; ++i)
  174. {
  175. int numPathVertices = paths[i].Length;
  176. for (int j = 0; j <= numPathVertices; j++)
  177. {
  178. if (j < numPathVertices)
  179. spriteMeshData.AddVertex(Vector2.Scale(paths[i][j], scaleInv) + rectOffset, default(BoneWeight));
  180. if (j > 0)
  181. spriteMeshData.edges.Add(new Edge(vertexIndexBase + j - 1, vertexIndexBase + j % numPathVertices));
  182. }
  183. vertexIndexBase += numPathVertices;
  184. }
  185. }
  186. public void NormalizeWeights(ISelection<int> selection)
  187. {
  188. Debug.Assert(spriteMeshData != null);
  189. for (int i = 0; i < spriteMeshData.vertexCount; ++i)
  190. if (selection == null || (selection.Count == 0 || selection.Contains(i)))
  191. spriteMeshData.GetWeight(i).Normalize();
  192. }
  193. public void CalculateWeights(IWeightsGenerator weightsGenerator, ISelection<int> selection, float filterTolerance)
  194. {
  195. Debug.Assert(spriteMeshData != null);
  196. Vector2[] controlPoints;
  197. Edge[] bones;
  198. int[] pins;
  199. GetControlPoints(out controlPoints, out bones, out pins);
  200. Vector2[] vertices = new Vector2[spriteMeshData.vertexCount];
  201. for (int i = 0; i < spriteMeshData.vertexCount; ++i)
  202. vertices[i] = spriteMeshData.GetPosition(i);
  203. BoneWeight[] boneWeights = weightsGenerator.Calculate(vertices, spriteMeshData.edges.ToArray(), controlPoints, bones, pins);
  204. Debug.Assert(boneWeights.Length == spriteMeshData.vertexCount);
  205. for (int i = 0; i < spriteMeshData.vertexCount; ++i)
  206. {
  207. if (selection == null || (selection.Count == 0 || selection.Contains(i)))
  208. {
  209. EditableBoneWeight editableBoneWeight = EditableBoneWeightUtility.CreateFromBoneWeight(boneWeights[i]);
  210. if (filterTolerance > 0f)
  211. {
  212. editableBoneWeight.FilterChannels(filterTolerance);
  213. editableBoneWeight.Normalize();
  214. }
  215. spriteMeshData.SetWeight(i, editableBoneWeight);
  216. }
  217. }
  218. }
  219. public void CalculateWeightsSafe(IWeightsGenerator weightsGenerator, ISelection<int> selection, float filterTolerance)
  220. {
  221. var tempSelection = new IndexedSelection();
  222. var vertexSelector = new GenericVertexSelector();
  223. vertexSelector.spriteMeshData = spriteMeshData;
  224. vertexSelector.selection = tempSelection;
  225. vertexSelector.SelectionCallback = (int i) => {
  226. return spriteMeshData.GetWeight(i).Sum() == 0f && (selection == null || selection.Count == 0 || selection.Contains(i));
  227. };
  228. vertexSelector.Select();
  229. if (tempSelection.Count > 0)
  230. CalculateWeights(weightsGenerator, tempSelection, filterTolerance);
  231. }
  232. public void SmoothWeights(int iterations, ISelection<int> selection)
  233. {
  234. var boneWeights = new BoneWeight[spriteMeshData.vertexCount];
  235. for (var i = 0; i < spriteMeshData.vertexCount; i++)
  236. boneWeights[i] = spriteMeshData.GetWeight(i).ToBoneWeight(false);
  237. BoneWeight[] smoothedWeights;
  238. SmoothingUtility.SmoothWeights(boneWeights, spriteMeshData.indices, spriteMeshData.boneCount, iterations, out smoothedWeights);
  239. for (var i = 0; i < spriteMeshData.vertexCount; i++)
  240. if (selection == null || (selection.Count == 0 || selection.Contains(i)))
  241. spriteMeshData.GetWeight(i).SetFromBoneWeight(smoothedWeights[i]);
  242. }
  243. public bool FindTriangle(Vector2 point, out Vector3Int indices, out Vector3 barycentricCoords)
  244. {
  245. Debug.Assert(spriteMeshData != null);
  246. indices = Vector3Int.zero;
  247. barycentricCoords = Vector3.zero;
  248. if (spriteMeshData.indices.Count < 3)
  249. return false;
  250. int triangleCount = spriteMeshData.indices.Count / 3;
  251. for (int i = 0; i < triangleCount; ++i)
  252. {
  253. indices.x = spriteMeshData.indices[i * 3];
  254. indices.y = spriteMeshData.indices[i * 3 + 1];
  255. indices.z = spriteMeshData.indices[i * 3 + 2];
  256. MathUtility.Barycentric(
  257. point,
  258. spriteMeshData.GetPosition(indices.x),
  259. spriteMeshData.GetPosition(indices.y),
  260. spriteMeshData.GetPosition(indices.z),
  261. out barycentricCoords);
  262. if (barycentricCoords.x >= 0f && barycentricCoords.y >= 0f && barycentricCoords.z >= 0f)
  263. return true;
  264. }
  265. return false;
  266. }
  267. private List<float> m_VertexOrderList = new List<float>(1000);
  268. private List<WeightedTriangle> m_WeightedTriangles = new List<WeightedTriangle>(1000);
  269. public void SortTrianglesByDepth()
  270. {
  271. Debug.Assert(spriteMeshData != null);
  272. if (spriteMeshData.boneCount == 0)
  273. return;
  274. m_VertexOrderList.Clear();
  275. m_WeightedTriangles.Clear();
  276. for (var i = 0; i < spriteMeshData.vertexCount; i++)
  277. {
  278. var vertexOrder = 0f;
  279. var boneWeight = spriteMeshData.GetWeight(i);
  280. for (var j = 0; j < boneWeight.Count; ++j)
  281. vertexOrder += spriteMeshData.GetBoneDepth(boneWeight[j].boneIndex) * boneWeight[j].weight;
  282. m_VertexOrderList.Add(vertexOrder);
  283. }
  284. for (int i = 0; i < spriteMeshData.indices.Count; i += 3)
  285. {
  286. int p1 = spriteMeshData.indices[i];
  287. int p2 = spriteMeshData.indices[i + 1];
  288. int p3 = spriteMeshData.indices[i + 2];
  289. float weight = (m_VertexOrderList[p1] + m_VertexOrderList[p2] + m_VertexOrderList[p3]) / 3f;
  290. m_WeightedTriangles.Add(new WeightedTriangle() { p1 = p1, p2 = p2, p3 = p3, weight = weight });
  291. }
  292. m_WeightedTriangles.Sort();
  293. spriteMeshData.indices.Clear();
  294. for (var i = 0; i < m_WeightedTriangles.Count; ++i)
  295. {
  296. var triangle = m_WeightedTriangles[i];
  297. spriteMeshData.indices.Add(triangle.p1);
  298. spriteMeshData.indices.Add(triangle.p2);
  299. spriteMeshData.indices.Add(triangle.p3);
  300. }
  301. }
  302. public void GetMultiEditChannelData(ISelection<int> selection, int channel,
  303. out bool enabled, out int boneIndex, out float weight,
  304. out bool isEnabledMixed, out bool isBoneIndexMixed, out bool isWeightMixed)
  305. {
  306. Debug.Assert(spriteMeshData != null);
  307. if (selection == null)
  308. throw new ArgumentNullException("selection is null");
  309. var first = true;
  310. enabled = false;
  311. boneIndex = -1;
  312. weight = 0f;
  313. isEnabledMixed = false;
  314. isBoneIndexMixed = false;
  315. isWeightMixed = false;
  316. var indices = selection.elements;
  317. foreach (int i in indices)
  318. {
  319. var editableBoneWeight = spriteMeshData.GetWeight(i);
  320. if (first)
  321. {
  322. enabled = editableBoneWeight[channel].enabled;
  323. boneIndex = editableBoneWeight[channel].boneIndex;
  324. weight = editableBoneWeight[channel].weight;
  325. first = false;
  326. }
  327. else
  328. {
  329. if (enabled != editableBoneWeight[channel].enabled)
  330. {
  331. isEnabledMixed = true;
  332. enabled = false;
  333. }
  334. if (boneIndex != editableBoneWeight[channel].boneIndex)
  335. {
  336. isBoneIndexMixed = true;
  337. boneIndex = -1;
  338. }
  339. if (weight != editableBoneWeight[channel].weight)
  340. {
  341. isWeightMixed = true;
  342. weight = 0f;
  343. }
  344. }
  345. }
  346. }
  347. public void SetMultiEditChannelData(ISelection<int> selection, int channel,
  348. bool oldEnabled, bool newEnabled, int oldBoneIndex, int newBoneIndex, float oldWeight, float newWeight)
  349. {
  350. Debug.Assert(spriteMeshData != null);
  351. if (selection == null)
  352. throw new ArgumentNullException("selection is null");
  353. bool channelEnabledChanged = oldEnabled != newEnabled;
  354. bool boneIndexChanged = oldBoneIndex != newBoneIndex;
  355. bool weightChanged = oldWeight != newWeight;
  356. var indices = selection.elements;
  357. foreach (int i in indices)
  358. {
  359. var editableBoneWeight = spriteMeshData.GetWeight(i);
  360. if (channelEnabledChanged)
  361. editableBoneWeight[channel].enabled = newEnabled;
  362. if (boneIndexChanged)
  363. editableBoneWeight[channel].boneIndex = newBoneIndex;
  364. if (weightChanged)
  365. editableBoneWeight[channel].weight = newWeight;
  366. if (channelEnabledChanged || weightChanged)
  367. editableBoneWeight.CompensateOtherChannels(channel);
  368. }
  369. }
  370. public void GetControlPoints(out Vector2[] points, out Edge[] edges, out int[] pins)
  371. {
  372. Debug.Assert(spriteMeshData != null);
  373. points = null;
  374. edges = null;
  375. List<Vector2> pointList = new List<Vector2>();
  376. List<Edge> edgeList = new List<Edge>();
  377. List<int> pinList = new List<int>();
  378. List<SpriteBoneData> bones = new List<SpriteBoneData>(spriteMeshData.boneCount);
  379. for (int i = 0; i < spriteMeshData.boneCount; ++i)
  380. bones.Add(spriteMeshData.GetBoneData(i));
  381. foreach (var bone in bones)
  382. {
  383. var length = (bone.endPosition - bone.position).magnitude;
  384. if (length > 0f)
  385. {
  386. int index1 = FindPoint(pointList, bone.position, 0.01f);
  387. int index2 = FindPoint(pointList, bone.endPosition, 0.01f);
  388. if (index1 == -1)
  389. {
  390. pointList.Add(bone.position);
  391. index1 = pointList.Count - 1;
  392. }
  393. if (index2 == -1)
  394. {
  395. pointList.Add(bone.endPosition);
  396. index2 = pointList.Count - 1;
  397. }
  398. edgeList.Add(new Edge(index1, index2));
  399. }
  400. else if (bone.length == 0f)
  401. {
  402. pointList.Add(bone.position);
  403. pinList.Add(pointList.Count - 1);
  404. }
  405. }
  406. points = pointList.ToArray();
  407. edges = edgeList.ToArray();
  408. pins = pinList.ToArray();
  409. }
  410. private int FindPoint(List<Vector2> points, Vector2 point, float distanceTolerance)
  411. {
  412. float sqrTolerance = distanceTolerance * distanceTolerance;
  413. for (int i = 0; i < points.Count; ++i)
  414. {
  415. if ((points[i] - point).sqrMagnitude <= sqrTolerance)
  416. return i;
  417. }
  418. return -1;
  419. }
  420. public void SmoothFill()
  421. {
  422. var tempSelection = new IndexedSelection();
  423. var vertexSelector = new GenericVertexSelector();
  424. var currentWeightSum = 0f;
  425. var prevWeightSum = 0f;
  426. vertexSelector.spriteMeshData = spriteMeshData;
  427. vertexSelector.selection = tempSelection;
  428. vertexSelector.SelectionCallback = (int i) => {
  429. var sum = spriteMeshData.GetWeight(i).Sum();
  430. currentWeightSum += sum;
  431. return sum < 0.99f;
  432. };
  433. do
  434. {
  435. prevWeightSum = currentWeightSum;
  436. currentWeightSum = 0f;
  437. vertexSelector.Select();
  438. if (tempSelection.Count > 0)
  439. SmoothWeights(1, tempSelection);
  440. }
  441. while (currentWeightSum - prevWeightSum > 0.001f);
  442. if (tempSelection.Count > 0)
  443. NormalizeWeights(tempSelection);
  444. }
  445. }
  446. }