Adding different types of entities to different layers

Building upon our previous example where we counted number of different types of entities in Sketchup file, we will take a look at how we can create new layers in Sketchup with Ruby API and assign different entity types to their appropriate layer.

We will create 3 layers of most basic types of entities in Sketchup, and those are Edge, Face and ComponentInstance.

Let’s open up a new file in text editor and define a function assign_layer_for_elements. First we will create 3 layers: edges, faces, componentInstances.

  model = Sketchup.active_model
  ent = model.entities
  #create layers for each type of entity
  edge_layer = model.layers.add("edges")
  face_layer = model.layers.add("faces")
  componentInstance_layer = model.layers.add("componentInstances")

As you can see from the code above, we can create layers current active model by model.layer.add(“name of layer”). We did this 3 times for 3 types of entities.

Next we will once again use each method on ent variable (which holds all entities in our Sketchup model) and based upon their type assign them to appropriate layer.

ent.each{|x|
   x.layer = edge_layer if x.is_a? Sketchup::Edge
   x.layer = face_layer if x.is_a? Sketchup::Face
   x.layer = componentInstance_layer if x.is_a? Sketchup::ComponentInstance
  }

If current entity (x) is of type Sketchup:Edge, we assign it to edge_layer, the same goes for Sketchup::Face and Sketchup::ComponentInstance.

Run this code in Web Console and you will see that 3 new layers appeared (if you don’t have layers view active, go to Window->Layers). In my model, if I turn off all layers except edges layer I get the following result (as compared to view if I have all layers turned ON):

Final sourcecode of assign_layer_for_elements function

def assign_layer_for_elements
  model = Sketchup.active_model
  ent = model.entities
  #create layers for each type of element
  edge_layer = model.layers.add("edges")
  face_layer = model.layers.add("faces")
  componentInstance_layer = model.layers.add("componentInstances")
  
  ent.each{|x|
   x.layer = edge_layer if x.is_a? Sketchup::Edge
   x.layer = face_layer if x.is_a? Sketchup::Face
   x.layer = componentInstance_layer if x.is_a? Sketchup::ComponentInstance
  }

end
Advertisements

, ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: