# Use Recursion in grasshopper C#

I’m trying to use recursion in grasshopper C#. But I don’t know how to collect data that I need. I just get the last triangle. It should be a lot of triangle.Thank you for your reply!

This is my code:
public Polyline tl(Polyline x, int count)
{
Line[] l = x.GetSegments();
List ptlist = new List();
for(int i = 0;i < l.Length;i++)
{
Point3d pt = l[i].PointAt(0.5);
}
Polyline nl = new Polyline(ptlist);
int co = count - 1;
if(count > 0)
{
return tl(nl, co);
}
else
{
return x;
}
}

I’m trying to make this out.

Hello, here is a method for doing the same thing you want but with mesh, you can copy the logic, it makes a mesh sphere based on dodecaedron :
private void RunScript(int nfaces, ref object A)
{
int n;
n = (int) (Math.Log10((double) nfaces / 20.0) / Math.Log10(4.0));
double t = (1.0 + Math.Sqrt(5.0)) / 2.0;
double c = Math.Sqrt(1 + (1.0 + Math.Sqrt(5.0)) * (1.0 + Math.Sqrt(5.0)) / 4.0);
//Icosaedron
Rhino.Geometry.Mesh mesh = new Rhino.Geometry.Mesh();
mesh.Vertices.Add(-1 / c, t / c, 0);
mesh.Vertices.Add(1 / c, t / c, 0);
mesh.Vertices.Add(-1 / c, -t / c, 0);
mesh.Vertices.Add(1 / c, -t / c, 0);
mesh.Vertices.Add(0, -1 / c, t / c);
mesh.Vertices.Add(0, 1 / c, t / c);
mesh.Vertices.Add(0, -1 / c, -t / c);
mesh.Vertices.Add(0, 1 / c, -t / c);
mesh.Vertices.Add(t / c, 0, -1 / c);
mesh.Vertices.Add(t / c, 0, 1 / c);
mesh.Vertices.Add(-t / c, 0, -1 / c);
mesh.Vertices.Add(-t / c, 0, 1 / c);
// 5 faces around point 3
for (int i = 0; i < n; i++)
{
Rhino.Geometry.Mesh mesh_rec = new Rhino.Geometry.Mesh();
recursiveSubdivision(mesh, ref mesh_rec);
mesh = mesh_rec;
}

mesh.Vertices.CombineIdentical(true, true);
mesh.Normals.ComputeNormals();
mesh.Compact();
A = mesh;
}
//

public void recursiveSubdivision(Mesh mesh, ref Mesh mesh_rec)
{
int ind = 0;
for (int i = 0; i < mesh.Faces.Count; i++)
{
Point3f A = new Point3f(mesh.Vertices[mesh.Faces[i].A].X, mesh.Vertices[mesh.Faces[i].A].Y, mesh.Vertices[mesh.Faces[i].A].Z);
Point3f B = new Point3f(mesh.Vertices[mesh.Faces[i].B].X, mesh.Vertices[mesh.Faces[i].B].Y, mesh.Vertices[mesh.Faces[i].B].Z);
Point3f C = new Point3f(mesh.Vertices[mesh.Faces[i].C].X, mesh.Vertices[mesh.Faces[i].C].Y, mesh.Vertices[mesh.Faces[i].C].Z);
ind = mesh_rec.Vertices.Count;
mesh_rec.Faces.AddFace(ind + 0, ind + 1, ind + 5);
mesh_rec.Faces.AddFace(ind + 1, ind + 3, ind + 5);
mesh_rec.Faces.AddFace(ind + 1, ind + 2, ind + 3);
mesh_rec.Faces.AddFace(ind + 5, ind + 3, ind + 4);
}
}

public Point3f middle(Point3f A, Point3f B)
{
Point3f AB = new Point3f();
float length;
AB.X = (A.X + B.X) / 2;
AB.Y = (A.Y + B.Y) / 2;
AB.Z = (A.Z + B.Z) / 2;
length = (float) Math.Sqrt(AB.X * AB.X + AB.Y * AB.Y + AB.Z * AB.Z);
AB.X = AB.X / length;
AB.Y = AB.Y / length;
AB.Z = AB.Z / length;
return AB;
}

1 Like