Skip to content

Instantly share code, notes, and snippets.

@andybak
Last active August 16, 2020 14:26
Show Gist options
  • Save andybak/d645d3d5abe4993556a6a2132722919a to your computer and use it in GitHub Desktop.
Save andybak/d645d3d5abe4993556a6a2132722919a to your computer and use it in GitHub Desktop.
public ConwayPoly Subdivide(float offset)
{
var faceIndices = new List<int[]>();
var vertexPoints = new List<Vector3>();
// Add existing vertices
for (int vertexIndex = 0; vertexIndex < Vertices.Count; vertexIndex++)
{
var x = Vertices[vertexIndex];
vertexPoints.Add(x.Position + x.Normal * offset);
}
// Create new vertices, one at the midpoint of each edge
var newVertices = new Dictionary<(Guid, Guid)?, int>();
int currentVertexIndex = vertexPoints.Count;
foreach (var edge in Halfedges)
{
vertexPoints.Add(edge.Midpoint);
newVertices[edge.PairedName] = currentVertexIndex++;
}
for (var faceIndex = 0; faceIndex < Faces.Count; faceIndex++)
{
var face = Faces[faceIndex];
// Create a new face for each existing face
var newFace = new int[face.Sides];
var edge = face.Halfedge;
for (int i = 0; i < face.Sides; i++)
{
newFace[i] = newVertices[edge.PairedName];
edge = edge.Next;
}
faceIndices.Add(newFace);
}
// Create new faces for each vertex
for (int idx = 0; idx < Vertices.Count; idx++)
{
var vertex = Vertices[idx];
var adjacentFaces = vertex.GetVertexFaces();
for (var faceIndex = 0; faceIndex < adjacentFaces.Count; faceIndex++)
{
Face face = adjacentFaces[faceIndex];
var edge = face.GetHalfedges().Find(x => x.Vertex == vertex);
int currVertex = newVertices[edge.PairedName];
int prevVertex = newVertices[edge.Next.PairedName];
var triangle = new[] {idx, prevVertex, currVertex};
faceIndices.Add(triangle);
var vertexFaceIndices = vertex.GetVertexFaces().Select(f => Faces.IndexOf(f));
}
}
var poly = new ConwayPoly(vertexPoints, faceIndices);
return poly;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment