Add Polygon in Loop

I want to create a polygon mesh with points in an array. I want to go through the array adding the points to the mesh. What I do not know how to do is use “add_polygon” with my mesh. When I put it inside the loop (in the >>x<<) it does not work. But if I take it out of the loop it does not pick up the points. Any advice?

newArr = [[0,0,0],[100, 0, 0],[100, 100, 0],[0, 100, 0],[200, 0, 50],[200, 100, 50]]

      myMesh = Geom::PolygonMesh.new

      newArr.each do |point|
        newPoint = Geom::Point3d.new (point)
        UI.messagebox(newPoint)
        myMesh.add_point(newPoint)
        >>>>>>myMesh.add_polygon newPoint<<<<<<
      end

      >>>>myMesh.add_polygon newPoint<<<<

      group = Sketchup.active_model.entities.add_group
      material = Sketchup.active_model.materials.add('green')
      smooth_flags = Geom::PolygonMesh::NO_SMOOTH_OR_HIDE
      group.entities.add_faces_from_mesh(myMesh, smooth_flags, material)
1 Like

Nevermind. I think I found a solution. If I create a new array to hold the points then use that.

      pointArr = Array.new

      newArr.each do |point|
        newPoint = Geom::Point3d.new (point)
        UI.messagebox(newPoint)
        myMesh.add_point(newPoint)
        pointArr.push(newPoint)
        
      end

      myMesh.add_polygon pointArr

It works. But if anyone knows of a better way of doing this, please let me know.

I’ve had good luck with something like the following. Note that I basically create a 2D array and then use that to populate the mesh with triangular polygons:

  model = Sketchup.active_model
  mesh = Geom::PolygonMesh.new()
  node = []
  for i in 0..10 do
    pts = []
    for j in 0..20 do
      x = i
      y = j
      z = i * j / 20.0
      pts.push(Geom::Point3d.new(x,y,z))
    end
    node.push(pts)
  end
  group = model.active_entities.add_group
  for i in 0...10 do
    for j in 0...20 do
      mesh.add_polygon(node[i][j],node[i+1][j],node[i][j+1])
      mesh.add_polygon(node[i][j+1],node[i+1][j],node[i+1][j+1])
    end
  end
  group.entities.fill_from_mesh(mesh,1,0)
1 Like

Thanks. I’ll take a look at trying it in a similar way.