View draw texture working example

The code example shown in the API docs for the Sketchup::View#load_texture and Sketchup::View#release_texture methods is not a working example and is fragile (will fail with raised exception just after a new model is loaded.)

Here is an working example …

module Example
  class MyTool

    def activate
      view = Sketchup.active_model.active_view
      @points = [ [0, 0, 0], [9, 0, 0], [9, 9, 0], [0, 9, 0] ]
      @uvs = [ [0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0] ]
      @extents = Sketchup.active_model.bounds.add(@points)
      @color = Sketchup::Color.new(0, 0, 255)
      matl = view.model.materials.current
      # The current material might be nil just after model load.
      # Also the current selected material may not have a texture:
      if matl && matl.texture
        image_rep = matl.texture.image_rep
        @texture_id = view.load_texture(image_rep)
      else
        @texture_id = nil
      end
    rescue => err
      puts err.inspect
    ensure
      view.invalidate # redraw the view immediately
    end

    def deactivate(view)
      view.release_texture(@texture_id) if @texture_id
      view.invalidate # redraw the view when done
    end

    def draw(view)
      view.line_stipple = '' # Solid line
      view.drawing_color = @color
      if @texture_id
        view.draw(GL_QUADS, @points, texture: @texture_id, uvs: @uvs)
      else
        view.draw(GL_QUADS, @points)
      end
    end

    def getExtents
      @extents
    end

    def onMouseMove(flags, x, y, view)
      view.invalidate # redraw the view on mousemove
    end

  end
end

Sketchup.active_model.select_tool(Example::MyTool.new)
2 Likes