def cutAtPlan(level): planPlane = rs.AddPlaneSurface([-1000,-1000,level], 3000, 3000) baseLayer = rs.AddLayer("60_PLANS") newParent = rs.AddLayer("PLAN_"+str(level), parent = baseLayer) origLayer = rs.CurrentLayer() shortName = rs.LayerName(origLayer, fullpath = False) #newChildsParent = rs.AddLayer( , parent = newParent) newChild = rs.AddLayer(shortName, parent = newParent, color = rs.LayerColor(origLayer)) rs.CurrentLayer(newChild) objs = rs.ObjectsByLayer(origLayer) #if len(objs)<1: # skip = True intersectCrvs = [] tempCrv = None for obj in objs: if rs.IsBrep(obj): tempCrv = rs.IntersectBreps(obj, planPlane) if tempCrv != None: intersectCrvs.append(tempCrv) for crv in intersectCrvs: if not None: rs.ObjectLayer(crv, newChild) rs.DeleteObject(planPlane) rs.CurrentLayer(origLayer)
def makePlan(): """ make2d from above. input: list of layers to make2d returns: None """ objs = rs.ObjectsByGroup("Below") #Make2d rs.SelectObjects(objs) rs.Command("-_make2d _D _U _Enter") projLines = rs.GetObjects("", preselect = True) #Get make2d root layer make2dRootRaw = rs.ObjectLayer(projLines[0]) make2dRoot = make2dRootRaw.split("::")[0] #Rename make2d layers root = rs.AddLayer("60_PLANS") roofLay = rs.AddLayer("Roof", parent = root) for projLine in projLines: linesLayer = rs.ObjectLayer(projLine) linesColor = rs.ObjectColor(projLine) linesLayerName = rs.LayerName(linesLayer, fullpath = False) newLayers = rs.AddLayer(linesLayerName, parent = roofLay, color = linesColor) rs.ObjectLayer(projLine,newLayers) rs.ObjectColor(projLine, (200,200,200)) #Delete make2d Layers rs.DeleteLayer(make2dRoot) return
def unIsolateLayers(): """Unisolate layers by unhiding layers.""" file_name = rs.DocumentName() file_path = rs.DocumentPath() if file_name is None: temp_file_name = "IsolateLayers_temp.json" else: temp_file_name = file_path + 'IsolateLayers_temp_' + file_name.strip( '.3dm') + '.json' if not os.path.isfile(temp_file_name): print("Temp File does not exist!") return with open(temp_file_name, "r") as f: layers_data = json.load(f) layers_data = {rs.LayerName(k): v for k, v in layers_data.items()} sorted_layers_data = sorted(layers_data.iteritems()) for layer_name, layer_visibility in sorted_layers_data: rs.LayerVisible(layer_name, layer_visibility) # remove TEMP FILE os.remove(temp_file_name)
def exportAllPlansToCAD(): if rs.IsLayer("6_DRAWINGS"): children = rs.LayerChildren("6_DRAWINGS") items = [] for child in children: items.append(rs.LayerName(child, False)) #level = rs.ComboListBox(items) print rs.DocumentPath() pathParts = rs.DocumentPath().split("\\") if pathParts[0] == "P:": defaultPath = pathParts[0] + "\\" + pathParts[ 1] + "\\" + pathParts[2] + "\\" + pathParts[3] folder = rs.BrowseForFolder( folder=defaultPath, message="Select Folder to export plans.", title="Export Plans") else: folder = rs.BrowseForFolder() RhinoFile = rs.DocumentName() rhinoName = RhinoFile.split(".")[0] + "_P_" for item in items: levelNum = item.split("_")[-1] fileName = "\\" + rhinoName + levelNum + ".dwg" savePath = folder + fileName #savePath = rs.SaveFileName("Save", "Autocad (*.dwg)|*.dwg||") if savePath is not None: exportPlanToCAD(item, savePath) else: print "No plans currently cut. Use CutPlans." return
def joinLayCrvs(): origLayer = rs.CurrentLayer() #shortName = rs.LayerName(origLayer, fullpath = False) fullname = rs.LayerName(origLayer) objs = rs.ObjectsByLayer(fullname) curves = [] for obj in objs: if (rs.IsCurve(obj)): curves.append(obj) if (len(curves) > 1): rs.JoinCurves(curves, True)
def ExportLayersStructure(): """Save layers settings to a json file.""" file_name = rs.SaveFileName( "Save", "Text Files (*.json)|*.json|All Files (*.*)|*.*||") if not file_name: return layers_properties = { rs.LayerName(l): get_layer_properties(l) for l in rs.LayerNames() } with open(file_name, "w+") as f: f.write(json.dumps(layers_properties, sort_keys=True, indent=4))
def mergeLayers(layA, layB): """ layA is kept, layB is deleted input: (layA, layB) each is a layer, the top parent in a tree to merge with another. returns: None """ rs.EnableRedraw(False) Alayers = rs.LayerChildren(layA) Blayers = rs.LayerChildren(layB) AlayersShort = [] BlayersShort = [] for Alayer in Alayers: AlayersShort.append(rs.LayerName(Alayer, False)) for Blayer in Blayers: BlayersShort.append(rs.LayerName(Blayer, False)) uniqueLayers = list(set(BlayersShort) - set(AlayersShort)) #move unique layers for uniqueLayer in uniqueLayers: rs.ParentLayer(uniqueLayer, layA) #get duplicate name layers duppedLayers = list(set(BlayersShort) - set(uniqueLayers)) #move objects to layA twin for duppedLayer in duppedLayers: newParent = layA + "::" + duppedLayer duppedObjs = rs.ObjectsByLayer(layB + "::" + duppedLayer) for duppedObj in duppedObjs: rs.ObjectLayer(duppedObj, newParent) #if it has children, recursively move them if rs.LayerChildCount(layB + "::" + duppedLayer) > 0: mergeLayers(layA + "::" + duppedLayer, layB + "::" + duppedLayer) else: rs.DeleteLayer(layB + "::" + duppedLayer) rs.DeleteLayer(layB) rs.EnableRedraw(True) return None
def getLayerIdsFromNames(sLayerNames): """ Parameter: List of layer names Returns: List of layer GUID's """ # Get all layer GUID's in document. idx_Layers = rs.LayerIds() if idx_Layers is None: return idx_Layers_Target = [ idx_Layer for idx_Layer in idx_Layers if rs.LayerName(idx_Layer) in sLayerNames ] return idx_Layers_Target
def setup_layer(name, options): parent = options.get('parent', None) locked = options.get('locked', False) if not rs.IsLayer(name): layer = rs.AddLayer(name=name, parent=parent, locked=locked) else: rs.ParentLayer(name, parent) layer = rs.LayerName(name) color = options.get('color', (0, 0, 0)) print_width = options.get('lineWeight', 0) linetype = options.get('lineType', 'Continuous') rs.LayerColor(name, color) rs.LayerPrintWidth(name, print_width) rs.LayerLinetype(name, linetype) return layer
def RunCommand(is_interactive): # this script can turn off layers of your selected object rs.AddLayer("_t") rs.CurrentLayer("_t") layers = rs.LayerNames() CurObjLayNames = [] CurObjs = rs.GetObjects("select objects to turn layers off") for CurObj in CurObjs: CurObjLayId = rs.ObjectLayer(CurObj) CurObjLayName = rs.LayerName(CurObjLayId, fullpath=True) CurObjLayNames.extend([CurObjLayName]) for layer in layers: if layer in CurObjLayNames and layer != "_t": rs.LayerVisible(layer, False) return 0
def RunCommand(is_interactive): # this script can turn off layers of your selected object rs.AddLayer("_t") rs.CurrentLayer("_t") Layers = [] CurObjLayNames = [] CurObjLayParentNames = [] for layer in rs.LayerNames(): if rs.IsLayerVisible(layer): Layers.extend([layer]) Layers = list(dict.fromkeys(Layers)) CurObjs = rs.GetObjects("select object to keep layers on") for CurObj in CurObjs: CurObjLayId = rs.ObjectLayer(CurObj) CurObjLayName = rs.LayerName(CurObjLayId, fullpath=True) CurObjLayNames.extend([CurObjLayName]) CurObjLayNames = list(dict.fromkeys(CurObjLayNames)) for name in CurObjLayNames: for layer in Layers: if rs.IsLayerParentOf(name, layer): CurObjLayParentNames.extend([layer]) CurObjLayParentNames = list(dict.fromkeys(CurObjLayParentNames)) layList = CurObjLayNames + CurObjLayParentNames i = 0 for layer in Layers: if layer not in layList and layer != "_t": rs.LayerVisible(layer, False) i += 1 rs.MessageBox(str(i) + " layers closed", 0, title="GBQT_Sandelions") return 0
def ExportAsSKP(objs, newFolder, newFolderName): tempLayers = [] copiedObjs = [] rs.StatusBarProgressMeterShow('Exporting to SKP', 0, len(objs)) for i, obj in enumerate(objs): tempCopy = rs.CopyObject(obj) rs.ObjectLayer(tempCopy, rs.ObjectLayer(obj)) copiedObjs.append(tempCopy) rs.StatusBarProgressMeterUpdate(i) for obj in copiedObjs: shortName = rs.LayerName(rs.ObjectLayer(obj), False) layerName = newFolderName + '_' + shortName if rs.IsLayer(layerName): rs.ObjectLayer(obj, layerName) else: matIndex = rs.LayerMaterialIndex(rs.ObjectLayer(obj)) newLayer = rs.AddLayer(layerName, rs.LayerColor(rs.ObjectLayer(obj))) rs.LayerMaterialIndex(newLayer, matIndex) tempLayers.append(newLayer) rs.ObjectLayer(obj, newLayer) rs.StatusBarProgressMeterHide() try: filepath = os.path.join(newFolder,newFolderName + '.skp') rs.SelectObjects(copiedObjs) rs.Command('-_Export ' + '"' + filepath + '"' + ' s SketchUp2015 Enter ', False) #CLEANUP rs.UnselectAllObjects() try: rs.DeleteObjects(copiedObjs) except: rs.DeleteObject(copiedObjs) for layer in tempLayers: rs.DeleteLayer(layer) except: print "export failed"
def ExportEachLayerAsOBJ(objs, newFolder, newFolderName): try: allLayers = [] for obj in objs: layer = rs.ObjectLayer(obj) if layer not in allLayers: allLayers.append(layer) for eachLayer in allLayers: try: #FindByLayer doesnt work with full layer names id = rs.LayerId(eachLayer) shortName = rs.LayerName(id, False) filepath = os.path.join(newFolder,newFolderName+ '_' + shortName + '.obj') rhobjs = sc.doc.Objects.FindByLayer(shortName) rs.SelectObjects(rhobjs) rs.Command('-_Export ' + '"' + filepath + '"' + ' Enter Enter ') rs.UnselectAllObjects() except: pass except: print 'ExportEachLayerAsSat failed'
def makeRoofPlan(layers): """ make2d from above. input: list of layers to make2d returns: None """ rs.EnableRedraw(False) #Get the objects objsRaw = [] for layer in layers: objsRaw.append(rs.ObjectsByLayer(layer)) objs = [item for sublist in objsRaw for item in sublist] #Make2d rs.SelectObjects(objs) rs.Command("-_make2d _D _U _Enter") projLines = rs.GetObjects("", preselect=True) #Get make2d root layer make2dRootRaw = rs.ObjectLayer(projLines[0]) make2dRoot = make2dRootRaw.split("::")[0] #Rename make2d layers root = rs.AddLayer("60_PLANS") roofLay = rs.AddLayer("Roof", parent=root) for projLine in projLines: linesLayer = rs.ObjectLayer(projLine) linesColor = rs.ObjectColor(projLine) linesLayerName = rs.LayerName(linesLayer, fullpath=False) newLayers = rs.AddLayer(linesLayerName, parent=roofLay, color=linesColor) rs.ObjectLayer(projLine, newLayers) #Delete make2d Layers rs.DeleteLayer(make2dRoot) rs.EnableRedraw(True) return
def RunCommand( is_interactive ): # this script can turn off layers of your selected object import rhinoscriptsyntax as rs rs.AddLayer("_t") rs.CurrentLayer("_t") layers = rs.LayerNames() CurObjLayNames=[] CurObjs = rs.GetObjects("select object to keep layers on") for CurObj in CurObjs: CurObjLayId = rs.ObjectLayer(CurObj) CurObjLayName = rs.LayerName(CurObjLayId, fullpath=True) CurObjLayNames.extend([CurObjLayName]) for layer in layers: if layer in CurObjLayNames and layer != "_t": rs.LayerLocked(layer,True) return 0
def UniqueLayerCopyName(layer, top): #Extract main level name; add - Copy to top level layer name only layers = rs.LayerNames() nameList = layer.split("::") newName = nameList[-1] rawName = rs.LayerName(layer, False) try: newNum = int(rawName.split("_")[-1]) + 1 except: newNum = rawName if newNum < 10: newNum = "0" + str(newNum) layerName = rawName.split("_")[0] + "_" + str(newNum) if top: newName = layerName if newName in layers: i = 0 while True: i += 1 testName = newName + "({})".format(i) if not testName in layers: return testName return newName
def ImportLayersStructure(): """Import layers settings into the current document from a json file.""" file_name = rs.OpenFileName( "Open", "Text Files (*.json)|*.json|All Files (*.*)|*.*||") if not file_name: return with open(file_name, "r") as f: layers_properties = json.load(f) actual_layers_properties = [rs.LayerName(l) for l in rs.LayerNames()] for l, i in zip(layers_properties.keys(), layers_properties.values()): override = True if l in actual_layers_properties: override = rs.MessageBox(l, buttons=1, title="Override existing properties:") if override == 2: override = False else: rs.AddLayer(l) if override: set_layer_properties(l, i)
def layerTag(obj): roomName = rs.LayerName(rs.ObjectLayer(obj), False) #add text tag try: text = str(roomName) pt0 = rs.BoundingBox(obj)[0] pt2 = rs.BoundingBox(obj)[2] pt = rs.AddPoint(rs.PointDivide(rs.PointAdd(pt0, pt2), 2)) rs.MoveObject(pt, [0, 1.5, 0]) areaTag = rs.AddText(text, pt, 1, justification=131074) except: print "Object has no name" return rs.DeleteObject(pt) parentLayer = rs.ParentLayer(rs.ObjectLayer(obj)) hostLayer = rs.AddLayer("ANNO_LAYER", (128, 128, 128), parent=parentLayer) rs.ObjectLayer(areaTag, hostLayer) #te = rs.coercerhinoobject(id, True, True) #te.Geometry.TextFormula = text #te.CommitChanges() #sc.doc.Views.Redraw() return None
def addLayerFromCSV(layNumList): """ Adds a layer from a CSV file Input: int - list of Layer numbers, associated with CSV layer number Returns: None """ rhinoLayerFilePath = "Q:\\Staff Postbox\\Tim Williams\\10 DESIGN LAYERS\\dev\\LAYERS\\RhinoLayersV3.csv" #Read the CSV file = open(rhinoLayerFilePath, "r") contents = file.readlines() file.close() #Variables RhinoLayerCol = 1 ColorCol = 3 MaterialCol = 4 LinetypeCol = 5 PrintColorCol = 6 PrintWidthCol = 7 found = False allLayerInfo = [] #Find layer info for row in contents: rowParts = row.split(",") for item in layNumList: #if layNum matches the CSV: if row.split(",")[0] == str(item): thisLayInfo = [] nameCol = row.split(",")[RhinoLayerCol] if len(nameCol) < 1: break thisLayInfo.append(row.split(",")[RhinoLayerCol]) #Linetype LinetypeRaw = row.split(",")[LinetypeCol] if len(LinetypeRaw) > 1: Linetype = LinetypeRaw else: Linetype = "Continuous" #Layer Color LayColorRaw = row.split(",")[ColorCol] if len(LayColorRaw) > 1: LayColor = (int(LayColorRaw.split("-")[0]), int(LayColorRaw.split("-")[1]), int(LayColorRaw.split("-")[2])) else: LayColor = (0, 0, 0) #Print Color PrintColorRaw = row.split(",")[PrintColorCol] if len(PrintColorRaw) > 1: PrintColor = (int(PrintColorRaw.split("-")[0]), int(PrintColorRaw.split("-")[1]), int(PrintColorRaw.split("-")[2])) else: PrintColor = (0, 0, 0) #Print Width PrintWidthRaw = row.split(",")[PrintWidthCol] if len(PrintWidthRaw) > 1: PrintWidth = float(PrintWidthRaw) else: PrintWidth = float(0) thisLayInfo.append(LayColor) thisLayInfo.append(PrintColor) thisLayInfo.append(Linetype) thisLayInfo.append(PrintWidth) allLayerInfo.append(thisLayInfo) found = True break if not found: return None #Find root layer root = rs.LayerName(rs.CurrentLayer()).split("::")[0] #print root #Add Layer parent = None for eachItem in allLayerInfo: parent = rs.AddLayer(eachItem[0], color=eachItem[1], parent=parent) rs.LayerPrintColor(parent, eachItem[2]) rs.LayerLinetype(parent, eachItem[3]) rs.LayerPrintWidth(parent, eachItem[4]) return parent
""" For use with the Feasibility Study Workflow. See "F:\Resource\Strategic Initiatives\0702013.20 Research Initiative\Rhino Workflow" For use with Feasibility Study Assistant Grasshopper Script. See "F:\Resource\Strategic Initiatives\0702013.20 Research Initiative\Grasshopper\Grasshopper Toolset\Feasibility Drafting and modeling Assistant" This script is to create a subfolder to a hatch layer that specifies it as an open area, as you might label as "OPEN TO BELOW" in floor plans. Make sure the layer you want to add an OPEN layer to is the currently selected layer before running. """ import rhinoscriptsyntax as rs currentLayer = rs.CurrentLayer() layerName = rs.LayerName(currentLayer, fullpath=False) newLayer = rs.AddLayer(name=layerName+"_OPEN") rs.ParentLayer(newLayer, currentLayer) layer_c = rs.LayerColor(currentLayer) layer_m = rs.LayerMaterialIndex(currentLayer) if layer_m == -1: layer_m = rs.AddMaterialToLayer(newLayer) rs.MaterialColor(layer_m, layer_c) rs.LayerPrintColor(newLayer, layer_c) rs.LayerColor(newLayer, layer_c)
if __name__ == "__main__": type = rs.GetInteger("", number=0) if (type == 0): exportTEN_CAD() elif (type == 1): #Import CAD importTEN_CAD() elif (type == 2): #Export All plans if rs.IsLayer("6_DRAWINGS"): children = rs.LayerChildren("6_DRAWINGS") items = [] for child in children: items.append(rs.LayerName(child, False)) level = rs.ComboListBox(items) print rs.DocumentPath() pathParts = rs.DocumentPath().split("\\") if pathParts[0] == "P:": defaultPath = pathParts[0] + "\\" + pathParts[ 1] + "\\" + pathParts[2] + "\\" + pathParts[3] folder = rs.BrowseForFolder( folder=defaultPath, message="Select Folder to export plan.", title="Export Plan") else: folder = rs.BrowseForFolder() RhinoFile = rs.DocumentName() rhinoName = RhinoFile.split(".")[0] + "_P_" levelNum = level.split("_")[-1]
def importTEN_CAD(): savePath0 = rs.OpenFileName("Open", "Autocad (*.dwg)|*.dwg||") items = [["Units", "Meters", "Millimeters"]] defaults = [False] CADinMilli = rs.GetBoolean("Is that CAD file in meters or mm?", items, defaults)[0] explodeBlockBoo = True if savePath0 is None: return rs.EnableRedraw(False) #setup the layers rs.AddLayer("7_REF") rs.AddLayer("CAD", parent="7_REF") fileNameExt = savePath0.split('\\')[-1] fileName = fileNameExt.split('.')[0] savePath1 = '"' + savePath0 + '"' #create layer name now = datetime.date.today() dateList = [] if len(str(now.month)) > 1: month = str(now.month) else: month = "0" + str(now.month) if len(str(now.day)) > 1: day = str(now.day) else: day = "0" + str(now.day) time = str(now.year) + month + day layerName = time + "_" + fileName + "_01" children = rs.LayerChildren("7_REF::CAD") finalNums = [] for child in children: num = rs.LayerName(child, fullpath=False).split("_")[-1] try: finalNums.append(int(num)) except: finalNums.append(0) finalNums.sort() if rs.IsLayer("7_REF::CAD::" + layerName): num = int(finalNums[-1]) + 1 if len(str(num)) < 2: finalNum = "0" + str(num) else: finalNum = str(num) layerName = time + "_" + fileName + "_" + finalNum par = rs.AddLayer("7_REF") cat = rs.AddLayer("CAD", parent=par) element = rs.AddLayer(layerName, parent=cat) rs.CurrentLayer(element) #get intial list of all layers in the file currentLayers = rs.LayerNames() rs.Command('_-Import ' + savePath1 + ' _Enter') #get new layers added endLayersNames = rs.LayerNames() #newLayers = [item for item in currentLayers if item not in endLayersNames] newLayers = diff(endLayersNames, currentLayers) print newLayers for layer in newLayers: rs.ParentLayer(layer, element) objects = rs.ObjectsByLayer(layer) if rs.IsLayerEmpty(layer): rs.DeleteLayer(layer) else: for obj in objects: if rs.IsDimension(obj): rs.DeleteObject(obj) elif rs.IsHatch(obj): rs.DeleteObject(obj) #Get all the imported geometry allObjects = [] finalLayers = rs.LayerChildren(rs.CurrentLayer()) for finalLayer in finalLayers: allObjects.append(rs.ObjectsByLayer(finalLayer)) finalAllObjects = [item for sublist in allObjects for item in sublist] #Format Coordinate try: rawCoordinate = rs.GetDocumentData("Project Info", "CAD coordinate (X,Y,Z)") except: print "No CAD Coordinate specified in the Project Info" rawCoordinate = (0, 0, 0) coordinate = rawCoordinate.split(",") print "Aa" try: for i in range(0, 3): coordinate[i] = float(coordinate[i]) except: coordinate = None if coordinate is None: print "CAD coordinate has an error" else: #move all objects negVec = rs.VectorReverse(coordinate) rs.MoveObjects(finalAllObjects, negVec) if CADinMilli: rs.ScaleObjects(finalAllObjects, [0, 0, 0], [.001, .001, .001]) importGroup = rs.AddGroup(str(layerName)) rs.AddObjectsToGroup(finalAllObjects, importGroup) rs.ZoomSelected() print "Import EXECUTED" rs.EnableRedraw(True) return None
Layers = [] CurObjLayNames = [] CurObjLayParentNames = [] for layer in rs.LayerNames(): if not rs.IsLayerLocked(layer): Layers.extend([layer]) Layers = list(dict.fromkeys(Layers)) CurObjs = rs.GetObjects("select object to keep layers on") for CurObj in CurObjs: CurObjLayId = rs.ObjectLayer(CurObj) CurObjLayName = rs.LayerName(CurObjLayId, fullpath=True) CurObjLayNames.extend([CurObjLayName]) CurObjLayNames = list(dict.fromkeys(CurObjLayNames)) for name in CurObjLayNames: for layer in Layers: if rs.IsLayerParentOf(name, layer): CurObjLayParentNames.extend([layer]) CurObjLayParentNames = list(dict.fromkeys(CurObjLayParentNames)) layList = CurObjLayNames + CurObjLayParentNames i = 0 for layer in Layers: if layer not in layList and layer != "_t":
def translateLayer(layer): """ translates from Rhino Name to CAD Name input: one layer returns: new layer name """ rhinoLayerFilePath = "C:\\Users\\Tim\\Desktop\\temp\\RhinoLayersV2.csv" #Read the CSV file = open(rhinoLayerFilePath, "r") contents = file.readlines() file.close() #Variables CategoryCol = 1 RhinoLayerCol = 2 CADNameCol = 9 CADColorCol = 10 CADLineweightCol = 11 found = False layerShort = rs.LayerName(layer, False) newLayerName = "" #Check the CSV for row in contents: rowParts = row.split(",") if row.split(",")[RhinoLayerCol] == str( layerShort): #if layer name exists in CSV CADName = row.split(",")[CADNameCol] CADColor = translateColor(layer, row.split(",")[CADColorCol]) CADLineweight = row.split(",")[CADLineweightCol] #if Rhino name found but no CAD name associated with it if not CADName: CADName = "A-RHINO-" + layerShort newLayerName = CADName if len(CADLineweight) < 2: CADLineweight = 0 #Check if layer already exists. parent = rs.ParentLayer(layer) existLayers = rs.LayerChildren(parent) isExisting = False for existLayer in existLayers: #if new name already exists as a layer if rs.LayerName(existLayer, False) == CADName: layersObjs = rs.ObjectsByLayer(layer) for layersObj in layersObjs: rs.ObjectLayer(layersObj, existLayer) rs.DeleteLayer(layer) newLayerName = rs.LayerName(existLayer, False) print "Layer {} merged with existing layer {}.".format( layerShort, rs.LayerName(layer, False)) isExisting = True break #if layer does not already exist if isExisting == False: rs.LayerColor(layer, CADColor) rs.LayerPrintWidth(layer, float(CADLineweight)) newLayerName = CADName rs.RenameLayer(layer, CADName) print "Layer {} changed to layer {}.".format( layerShort, CADName) found = True break if not found: layerShort = rs.LayerName(layer, False) CADName = "A-RHINO-" + layerShort newLayerName = CADName rs.RenameLayer(layer, CADName) print "Layer {} has no matching CAD layer.".format(layerShort) return newLayerName return newLayerName
import rhinoscriptsyntax as rs import Rhino import scriptcontext as sc import math import re import time import os #add to rhino as an alias if not rs.IsAlias("TNM_renameLayers"): rs.AddAlias("TNM_renameLayers", "'_-runPythonScript \"%s\"" % __file__) print 'addAlias' else: print 'alias could not be added' layers = rs.LayerIds() for layer_id in layers: if rs.IsLayer(layer_id): old_name = rs.LayerName(layer_id, False) if (re.search('0.0.0', old_name)): new_name = old_name.replace('0.0.0', '0.0.160.0') rs.RenameLayer(old_name, new_name) else: print layer_id
def lb_generate_analysis(self): try: if self.m_test_points == None: print "missing grid objects" return #prepare paramters window_groups = [] #not included yet in eto interface name = 'default_name'#not included yet in eto interface sun_path_panel = list(self.Parents)[-1].get_sun_path_panel() sun_vectors = sun_path_panel.m_vectors hoys = sun_path_panel.m_hoys timestep = sun_path_panel.m_timestep #hb objects data hb_object_ids = self.m_hb_object_ids hb_object_types, hb_object_mats = self.lb_get_hb_objects_data() #project data folder = self.m_project_path_picker.FilePath filename = self.m_project_name_text_box.Text save_file_only = self.m_save_file_check_box.Checked #turn off last results layers if 'Eto_DisplayLayerIndex' in sc.sticky and sc.sticky['Eto_DisplayLayerIndex']: last_layer_index = sc.sticky['Eto_DisplayLayerIndex'] last_layer = Rhino.RhinoDoc.ActiveDoc.Layers.FindIndex(last_layer_index) last_layer_name = rs.LayerName(last_layer.Id, True) last_parentLayer = rs.LayerName(last_layer.ParentLayerId, True) rs.LayerVisible(last_parentLayer, False) results_layer = None # generate one analysis merging points/vector and meshes points_item = [] vectors_item = [] for index in range(len(self.m_test_points)): points_item += self.m_test_points[index] vectors_item += self.m_pts_vectors[index] mesh_item = self.m_output_mesh.pop(0) if len(self.m_output_mesh): mesh_item.Append(self.m_output_mesh) rs.EnableRedraw(False) LadybugEto.generateAnalysis(points_item, vectors_item, name, window_groups, sun_vectors, hoys, timestep, hb_object_ids, hb_object_types, hb_object_mats, folder, filename, save_file_only, [mesh_item]) #consolidate multiple result objects into one layer (workaround to #solve current ladybug_ResultVisualization.bakeObjects behaviour) layer_index = sc.sticky['Eto_DisplayLayerIndex'] last_layer = Rhino.RhinoDoc.ActiveDoc.Layers.FindIndex(layer_index) last_layer_name = rs.LayerName(last_layer.Id, True) p_layer_name = rs.LayerName(last_layer.ParentLayerId, True) #use first analysis layers if index == 0: results_layer_index = layer_index results_layer = last_layer_name results_p_layer = p_layer_name #delte all subsequent analysis layers elif last_layer_name <> results_layer: #Move all objects to analysis layer and delete layers objects_id = rs.ObjectsByLayer(last_layer_name) res = list(rs.ObjectLayer(obj_id, results_layer) for obj_id in objects_id) rs.DeleteLayer(last_layer_name) rs.DeleteLayer(p_layer_name) rs.EnableRedraw(True) #replace the sticky to results layer used sc.sticky['Eto_DisplayLayerIndex'] = results_layer_index #copy original analysis surfaces hb objects to analisys layer created rs.EnableRedraw(False) #copy analysis grid new_layer_name = rs.AddLayer(results_p_layer+"::Analysis_grid_objects", color=Color.Red) gridsurfs_ids = list(item.Tag for item in self.m_gridsurfs_list_box.Items) new_grid_objects = rs.CopyObjects(gridsurfs_ids) res = list(rs.ObjectLayer(obj_id, new_layer_name) for obj_id in new_grid_objects) #copy hb objects new_layer_name = rs.AddLayer(results_p_layer+"::HB_objects", color=Color.LightGreen) new_grid_objects = rs.CopyObjects(self.m_hb_object_ids) res = list(rs.ObjectLayer(obj_id, new_layer_name) for obj_id in new_grid_objects) rs.EnableRedraw(True) except Exception as e: print e