I want to calculate the indices necessary to draw the outline of a shape using clockwise winding. The example uses a square but it could be any regular polygon.
Given a square with vertices 0, 1, 2, 3, it can be drawn with indices 0, 1, 2 and 0, 2, 3. The outline vertices are the same 4 vertices as the original square (4, 5, 6, 7) plus 4 more (8, 9, 10, 11) some distance and direction from the original vertices.
The code below calculates the relevant indices for the outline and appends them to the indices for the original shape. For the example square, the outline indices are as follows:
4, 8, 9,
4, 9, 5,
5, 9, 10,
5, 10, 6,
6, 10, 11,
6, 11, 7,
7, 11, 8,
7, 8, 4
fn update_outline_vertices(&mut self) {
let point_count = self.point_count();
let inner_vertex_count = 4;
let inner_index_count = (point_count - 2) * 3;
if self.outline_thickness == 0.0 {
// Resize.
return;
}
let outline_vertex_count = inner_vertex_count * 2;
let vertex_count = inner_vertex_count + outline_vertex_count;
let index_count = inner_index_count + outline_vertex_count * 3;
self.vertices.resize(vertex_count);
self.indices.resize(index_count, 0);
for i in 0..point_count {
// https://stackoverflow.com/questions/68973103/how-to-create-outline?noredirect=1&lq=1
let p = if i == 0 { point_count - 1 } else { i - 1 };
let p1 = self.point(p);
let p2 = self.point(i);
let p3 = self.point(i + 1);
let outline_point = calculate_outline_point(p1, p2, p3, self.outline_thickness);
self.vertices[point_count + i].position = p2;
self.vertices[2 * point_count + i].position = outline_point;
// Build outline indices.
let offset = inner_index_count + i * 6;
self.indices[offset] = (i + point_count) as u32;
self.indices[offset + 1] = ((i + point_count) + point_count) as u32;
self.indices[offset + 2] =
(((i + point_count + 1) % point_count + point_count) + point_count) as u32;
self.indices[offset + 3] = (i + point_count) as u32;
self.indices[offset + 4] =
(((i + point_count + 1) % point_count + point_count) + point_count) as u32;
self.indices[offset + 5] = (((i + 1) % point_count) + point_count) as u32;
}
}
However, there's a lot going on with the modulo and multiple point_count's when calculating each index and it's not exactly obvious what is going on or why. What is a more common algorithm to calculate these outline points?
