Centrepoints of mesh faces on a mesh in Grasshopper and Rhino

C# code for getting the centrepoint of a mesh face in Grasshopper

A method I quickly wrote to get the centrepoint of a mesh face using the C# component in Grasshopper. More information about the mesh data structure used to generate this code is in this post.

The method essentially calculates the ‘average’ location of each of the 3 or 4 nodes on the mesh. (Formally, this is a simplification of the first moment of area.)

  Point3d CentrePoint(int meshfaceindex, Mesh m)
  {
    var temppt = new Point3d(0, 0, 0);

    temppt.X += m.Vertices[m.Faces[meshfaceindex].A].X;
    temppt.Y += m.Vertices[m.Faces[meshfaceindex].A].Y;
    temppt.Z += m.Vertices[m.Faces[meshfaceindex].A].Z;

    temppt.X += m.Vertices[m.Faces[meshfaceindex].B].X;
    temppt.Y += m.Vertices[m.Faces[meshfaceindex].B].Y;
    temppt.Z += m.Vertices[m.Faces[meshfaceindex].B].Z;

    temppt.X += m.Vertices[m.Faces[meshfaceindex].C].X;
    temppt.Y += m.Vertices[m.Faces[meshfaceindex].C].Y;
    temppt.Z += m.Vertices[m.Faces[meshfaceindex].C].Z;

    if(m.Faces[meshfaceindex].IsQuad)
    {
      temppt.X += m.Vertices[m.Faces[meshfaceindex].D].X;
      temppt.Y += m.Vertices[m.Faces[meshfaceindex].D].Y;
      temppt.Z += m.Vertices[m.Faces[meshfaceindex].D].Z;

      temppt.X /= 4;
      temppt.Y /= 4;
      temppt.Z /= 4;
    }
    else
    {
      temppt.X /= 3;
      temppt.Y /= 3;
      temppt.Z /= 3;
    }

    return temppt;
  }

It’s sloppy to have the code so repetitive, but the .A and the .X notation don’t make for good code efficiency. It’s sometimes possible to use temppt[d] where d = 0, 1 or 2 for X, Y and Z correspondingly (which would allow the use of a ‘for’ loop), but the mesh Vertices property returns Point3f instead of Point3d, which doesn’t allow this.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.