Create layers from material names

I have bought an obj model of a car, just to painfully discover that all meshes are on the same layer with about 30 different materials applied to them, hence my question:

Should it be possible by script (I can do some python) to select an object, take its material name, create a layer with that name and move the object to that layer?

This works here on separate meshes with standard rhino materials. No error proofing so could be dangerous. I’d open the obj in separate rhino file, run script, then copy it into your real file. If the entire car mesh is joined then it won’t work as it needs separate doc objects to change layer attribute. Also, if the materials are 3rd party render content, I’m not sure it will work.

import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino

guids = rs.GetObjects('select objects')

for guid in guids:
    obj = rs.coercerhinoobject(guid)
    material_index = obj.Attributes.MaterialIndex
    rhino_material = sc.doc.Materials[material_index]
    material_color = rhino_material.DiffuseColor
    material_name = rhino_material.Name
    print rhino_material.Name
    layer_index = sc.doc.Layers.Find(material_name, True)
    if layer_index >= 0:
        obj.Attributes.LayerIndex = layer_index
        obj.CommitChanges()
    else:
        new_layer_index = sc.doc.Layers.Add(material_name, material_color)
        obj.Attributes.LayerIndex = new_layer_index
        obj.CommitChanges()
2 Likes

10*6 thanks Nathan! Sorry for the late reply, was terribly busy with something els but I’m running now to try it!

Works like a CHARM!
Tried it on vray materials and the onlz concern is that it keeps the “/” that the plugin/rhino adds before the material name, but that’s no worrz. Either I delete it bz hand or even better I trz to tweak your code with my little python skills to have it done automatically.

Thanks again!!

Glad it worked!

1 Like

wow, thanks!
works perfectly

however would it be possible to make couple small adjustments?

  • on scripts run so not request to select objects - just create layers for all objects in the scene
  • skip (trim) “_material” from each layer name created

thank you very much

1 Like

Hi! I have been thinking that it is a really useful script! Also I was thinking if that’s for example possible to do same on Rhino Blocks? To make it open each one and assign the layers to material names accordingly? That would 100% solve most of my issues with models from different workflows.