Turning On and Off layers with Python Grasshopper Laggy

I am trying to control Layer Visibility from Human UI though Python in grasshopper, I have been able to create a python code that works but is very laggy (2 Seconds+) in a larger file with lots of layers. So tried to rewrite it so it did not search all layers, but just the ones that where children of the parent layer but this option is still laggy and breaks if the Layer to turn on is none.

Working but Laggy

import Rhino.RhinoDoc as rhDoc
import rhinoscriptsyntax as rs
import scriptcontext as sc

# Turn select layers on and off with Switch
sc.doc = rhDoc.ActiveDoc

for l in rhDoc.ActiveDoc.Layers:
    if LayerOn is not None and l.Name == LayerOn:
        pLayer = rs.ParentLayer(LayerOn)
        rs.LayerVisible(pLayer,True)
        rs.LayerVisible(LayerOn,True)
    elif l.Name == LayerOff:
        rs.LayerVisible(LayerOff,False)

sc.doc = ghdoc

Broken and Also Laggy
As wants a string for pLayer = rs.ParentLayer(LayerOn) even if LayerOn is none.

# Turn Selected layers on and off with Grasshoper
import Rhino.RhinoDoc as rhDoc
import rhinoscriptsyntax as rs
import scriptcontext as sc

sc.doc = rhDoc.ActiveDoc

if LayerOn is not None:
    pLayer = rs.ParentLayer(LayerOn)
    rs.LayerVisible(pLayer,True)
    rs.LayerVisible(LayerOn,True)
else:
    rs.LayerVisible(LayerOff,False)

sc.doc = ghdoc

Demo Files
Layer Control GH.3dm (271.9 KB)
Control Layer Visabilty with GH.gh (9.4 KB)

I’m not sure I understood you correctly, Do you have subLayers with similar names but different parents in your file? If so, Do you know which one you want to change?

import Rhino
currentLayer = Rhino.RhinoDoc.ActiveDoc.Layers.CurrentLayer
parentLayer = Rhino.RhinoDoc.ActiveDoc.Layers.FindName(ParentLayerName)
for subLayer in parentLayer.GetChildren():
    if subLayer.Name in LayerNames:
        parentLayer.IsVisible = True
        subLayer.IsVisible = True
    elif subLayer != currentLaye:
        subLayer.IsVisible = False
        subLayer.SetPersistentVisibility(False)

LayerVisibility.gh (13.7 KB)

A hacky idea :wink: (untested)

What if you run rs.Command() that invokes RunPythonScript command?

changing the layers from Rhino instead of GH?

Interesting revised workflow. Works well just need to add a extra boolean so i could bring the name in but only turn the layer on if a switch was on.

    if subLayer.Name in LayerNames and Preview != False:

LayerVisibility PreviewSwitch.gh (17.6 KB)

If you’re doing this for a lot of layers, it might help to call rs.EnableRedraw(False) before fiddling with the Rhino document/layers, and rs.EnableRedraw(True) afterwards.

2 Likes