Add Materials to DWG imported layers (groups and instances)

Lisp is a functional language also better known as “stupid parenthesis land”.
It is vastly different than dynamic OOP multi-paradigm languages like Python and Ruby (which are quite similar except for some syntax differences. Ie, it’s relatively easy to translate one into the other.)

In order to use any API extension to the Ruby language, an author needs to learn core Ruby.
To that end I’ve created a pinned set of resource lists in this category …

All file imports do this (regardless of source format.) You usually need to explode this imported object if you want it’s entities at the top level.

Secondly, in the UI, “Layers” have been renamed “Tags” (but the old class name persists in the APIs.)
SketchUp tags (layers) are not geometric collections. They are display behaviors that multiple entities can be “tagged” with to tell the display pipeline how to show them.

These are Material names, and it’s actually "0128_White" (not "123_White".)

The main issue you will have is that the Sketchup::Layer#color= setter method only takes a Sketchup::Color instance object or a predefined color name (listed in the class Overview.)

So if you do …

model = Sketchup.active_model
layers = model.layers
layers["Generic"].color= "0128_White"

… you get this exception raised:

Error: #<ArgumentError: Cannot find color named 0128_White>

Instead you need to steal the RGBA properties from the Sketchup::Material objects, but you need to temporarily load them into the model’s Sketchup::Materials collection.
Ex:

model = Sketchup.active_model
materials = model.materials

# Get white color:
filename = 'Materials/Colors-Named/0128_White.skm'
path = Sketchup.find_support_file(filename)
material = materials.load(path)
white_color = material.color
#=> Color(255, 255, 255, 255)
layers.each do |layer|
  layer.color= white_color unless layer.name == '0_EX_Glazing'
end
materials.remove(material)

# Get gray glass color:
filename = 'Materials/Glass and Mirrors/Translucent Glass Gray.skm'
path = Sketchup.find_support_file(filename)
material = materials.load(path)
glass_color = material.color
#=> Color(128, 128, 128, 255)
# Notice how the result did not return the correct alpha ?
# So we have to specifically get that property thus:
glass_color.alpha= material.alpha
#=> 0.5
layers["0_EX_Glazing"].color= glass_color
#=> Color(128, 128, 128, 127)
# See how the alpha was correctly set ?
materials.remove(material)

# Set the style to use Color By Tag (Layer):
model.rendering_options["DisplayColorByLayer"]= true

scroll to see all example code.

1 Like