TriangleSampler.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // -----------------------------------------------------------------------
  2. // <copyright file="TriangleSampler.cs">
  3. // Original Triangle code by Jonathan Richard Shewchuk, http://www.cs.cmu.edu/~quake/triangle.html
  4. // Triangle.NET code by Christian Woltering, http://triangle.codeplex.com/
  5. // </copyright>
  6. // -----------------------------------------------------------------------
  7. namespace UnityEngine.U2D.Animation.TriangleNet
  8. {
  9. using System;
  10. using System.Collections.Generic;
  11. using Animation.TriangleNet.Topology;
  12. /// <summary>
  13. /// Used for triangle sampling in the <see cref="TriangleLocator"/> class.
  14. /// </summary>
  15. class TriangleSampler : IEnumerable<Triangle>
  16. {
  17. private const int RANDOM_SEED = 110503;
  18. // Empirically chosen factor.
  19. private const int samplefactor = 11;
  20. private Random random;
  21. private Mesh mesh;
  22. // Number of random samples for point location (at least 1).
  23. private int samples = 1;
  24. // Number of triangles in mesh.
  25. private int triangleCount = 0;
  26. public TriangleSampler(Mesh mesh)
  27. : this(mesh, new Random(RANDOM_SEED))
  28. {
  29. }
  30. public TriangleSampler(Mesh mesh, Random random)
  31. {
  32. this.mesh = mesh;
  33. this.random = random;
  34. }
  35. /// <summary>
  36. /// Reset the sampler.
  37. /// </summary>
  38. public void Reset()
  39. {
  40. this.samples = 1;
  41. this.triangleCount = 0;
  42. }
  43. /// <summary>
  44. /// Update sampling parameters if mesh changed.
  45. /// </summary>
  46. public void Update()
  47. {
  48. int count = mesh.triangles.Count;
  49. if (triangleCount != count)
  50. {
  51. triangleCount = count;
  52. // The number of random samples taken is proportional to the cube root
  53. // of the number of triangles in the mesh. The next bit of code assumes
  54. // that the number of triangles increases monotonically (or at least
  55. // doesn't decrease enough to matter).
  56. while (samplefactor * samples * samples * samples < count)
  57. {
  58. samples++;
  59. }
  60. }
  61. }
  62. public IEnumerator<Triangle> GetEnumerator()
  63. {
  64. return mesh.triangles.Sample(samples, random).GetEnumerator();
  65. }
  66. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  67. {
  68. return GetEnumerator();
  69. }
  70. }
  71. }