MCPcopy Create free account
hub / github.com/admtrv/objcurses / triangularize

Function triangularize

utils/algorithms.cpp:63–121  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

61}
62
63std::optional<std::vector<size_t>> triangularize(const std::vector<Vec3> &points)
64{
65 const size_t n = points.size();
66 if (n < 3)
67 {
68 return std::nullopt; // insufficient points
69 }
70
71 const Vec3 normal = Vec3::normal(points);
72
73 if (normal.magnitude() < 1e-12f)
74 {
75 return std::nullopt; // degenerate polygon
76 }
77
78 // list of vertex indexes
79 std::vector<size_t> indices(n);
80 std::iota(indices.begin(), indices.end(), 0);
81
82 std::vector<size_t> result;
83
84 // ears search
85 while (indices.size() > 3)
86 {
87 bool ear_found = false;
88
89 for (std::size_t i = 0; i < indices.size(); i++)
90 {
91 if (is_ear(i, points, indices, normal))
92 {
93 // adding triangle
94 size_t prev = indices[(i + indices.size() - 1) % indices.size()];
95 size_t curr = indices[i];
96 size_t next = indices[(i + 1) % indices.size()];
97
98 result.push_back(prev);
99 result.push_back(curr);
100 result.push_back(next);
101
102 // removing current ear
103 indices.erase(std::next(indices.begin(), static_cast<std::ptrdiff_t>(i)));
104 ear_found = true;
105 break;
106 }
107 }
108
109 if (!ear_found)
110 {
111 return std::nullopt; // no valid ear
112 }
113 }
114
115 // adding last triangle
116 result.push_back(indices[0]);
117 result.push_back(indices[1]);
118 result.push_back(indices[2]);
119
120 return result;

Callers 1

parse_faceMethod · 0.85

Calls 2

is_earFunction · 0.85
magnitudeMethod · 0.80

Tested by

no test coverage detected