Search code examples
rubyplotsketchup

"add_cpoint" not working in a method in SketchUp's Ruby


I have a piece of code below which plots two points at [2,3,4] and [5,6,7] when the code is run in SketchUp's Ruby console. The end goal is to be able to allow the user to select a line and create points at both ends of the line, but I am taking it step by step at a time.

sel = Sketchup.active_model.selection

fp = [2,3,4]
sp = [5,6,7]

fp = fp.map {|a| 39.3701 *a}
sp = sp.map {|a| 39.3701 *a}

p1 = Geom::Point3d.new(fp)
p2 = Geom::Point3d.new(sp)

addpoint1 = entities.add_cpoint p1
addpoint2 = entities.add_cpoint p2

I am slowly trying to make this code more user friendly. I tried to upgrade it by making it so you need to select a line to create two points at [2,3,4] and [5,6,7].

Also, the number 39.3701 is to convert the units into the units I want (meters), SketchUp has it's own weird units which I've sorta solved with a 'band aid solution'.

([2,3,4] [5,6,7] are hard-coded arrays which I am using just to see if I've scripted things correctly).

Here is my attempt at the next bit of code.

def pointplot
    sel = Sketchup.active_model.selection

    fp = [2,3,4]
    sp = [5,6,7]
    
    fp = fp.map {|a| 39.3701 *a}
    sp = sp.map {|a| 39.3701 *a}

    p1 = Geom::Point3d.new(fp)
    p2 = Geom::Point3d.new(sp)

    addpoint1 = entities.add_cpoint p1
    addpoint2 = entities.add_cpoint p2
end

def check_line
    sel = Sketchup.active_model.selection
    ok = sel.find { |e| e.typename == "Edge" }
    ok ? MF_ENABLED : MF_GRAYED
end

UI.add_context_menu_handler do |menu|

menu.add_separator
item = menu.add_item("Point Plot") { pointplot }

menu.set_validation_proc(item) {check_line}
end

What this bigger piece of code will do is add an option to the menu when the user right clicks on a line. The additional function is called "Point Plot."

However when you click on the 'Point Plot' function, it does not create the two points at [2,3,4] and [5,6,7].

There seems to be an issue around these lines. If I were to put a UI.messagebox() before those two lines the messagebox will appear. But if I put the UI.messagebox() after those two lines, it will not appear.

addpoint1 = entities.add_cpoint p1
addpoint2 = entities.add_cpoint p1

Could anyone please clarify the problem I am running into?

Thanks!


Solution

  • Here is an example for creating a 'construction point' at each vertex of selected edges...

    model = Sketchup.active_model
    entities = model.active_entities
    selection = model.selection
    edges = selection.grep(Sketchup::Edge)
    
    if edges.empty?
      msg = 'Select one or more edges before using this tool.'
      UI.messagebox(msg)
      return
    end
    
    vertices = []
    edges.each { |edge| vertices << edge.vertices }
    vertices.flatten!
    vertices.uniq!
    vertices.each { |vertex| entities.add_cpoint vertex.position }