diff --git a/$$/Check if command comes from a plugin - WIP - needs a filter and get all available commands functions.py b/$$/Check if command comes from a plugin - WIP - needs a filter and get all available commands functions.py new file mode 100644 index 0000000..9a5ca96 --- /dev/null +++ b/$$/Check if command comes from a plugin - WIP - needs a filter and get all available commands functions.py @@ -0,0 +1,17 @@ +import Rhino.PlugIns as rp +import rhinoscriptsyntax as rs + +pl_cmd = dict() +query_string = rs.GetString(message="name of the command") + +for plkv in rp.PlugIn.GetInstalledPlugIns(): + guid = plkv.Key + name = plkv.Value + pl_info = rp.PlugIn.GetPlugInInfo(guid) + pl_cmd[name] = [cmd for cmd in pl_info.CommandNames] + +for pl in pl_cmd: + for pl_com + if query_string in pl: + print pl + print "\t" + str(pl_cmd[pl]) diff --git a/$$/DupLayersSublayersAndObjs.py b/$$/DupLayersSublayersAndObjs.py new file mode 100644 index 0000000..2b7aada --- /dev/null +++ b/$$/DupLayersSublayersAndObjs.py @@ -0,0 +1,52 @@ +"""Duplicates a layer and all its sublayers incuding objects +Script by Mitch Heynick 20 April 2014""" + +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def CopyObjectsToLayer(objs,layer): + copies=rs.CopyObjects(objs) + rs.ObjectLayer(copies,layer) + +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] + if top: newName+=" - Copy" + if newName in layers: + i=0 + while True: + i+=1 + testName=newName+"({})".format(i) + if not testName in layers: return testName + return newName + +def DupAllSubLayers(layer,layerCopy): + subs=rs.LayerChildren(layer) + if subs: + for sub in subs: + color=rs.LayerColor(sub) + objs=rs.ObjectsByLayer(sub) + name=UniqueLayerCopyName(sub,False) + addLayer=rs.AddLayer(name,color,parent=layerCopy) + CopyObjectsToLayer(objs,addLayer) + rs.ExpandLayer(addLayer,rs.IsLayerExpanded(sub)) + DupAllSubLayers(sub,addLayer) + +def DupLayersSublayersAndObjs(): + layer=rs.GetLayer() + if layer==None: return + #do initial run with selected layer + color=rs.LayerColor(layer) + objs=rs.ObjectsByLayer(layer) + parentLayer=rs.ParentLayer(layer) + + + copyName=UniqueLayerCopyName(layer,True) + layerCopy=rs.AddLayer(copyName,color,parent=parentLayer) + CopyObjectsToLayer(objs,layerCopy) + rs.ExpandLayer(layerCopy,rs.IsLayerExpanded(layer)) + DupAllSubLayers(layer,layerCopy) + +DupLayersSublayersAndObjs() \ No newline at end of file diff --git a/$$/FlipCamera-NOT-WORKING-DUE-TO-VIEWPORTS-STRETCHING-FRUSTUMS.py b/$$/FlipCamera-NOT-WORKING-DUE-TO-VIEWPORTS-STRETCHING-FRUSTUMS.py new file mode 100644 index 0000000..033346e --- /dev/null +++ b/$$/FlipCamera-NOT-WORKING-DUE-TO-VIEWPORTS-STRETCHING-FRUSTUMS.py @@ -0,0 +1,14 @@ + +import scriptcontext as sc + +vp = sc.doc.Views.ActiveView.ActiveViewport +p1 = vp.CameraLocation +p2 = vp.CameraTarget +vecDir = p2-p1 +p1 = p1 + (vecDir*2) +vecDir.Reverse() + +vp.SetCameraLocations(p2, p1) +sc.doc.Views.Redraw() + + \ No newline at end of file diff --git a/$$/PrintAllAsSeparatePagesMultiprocess-SUPERSEDED.py b/$$/PrintAllAsSeparatePagesMultiprocess-SUPERSEDED.py new file mode 100644 index 0000000..66fe85e --- /dev/null +++ b/$$/PrintAllAsSeparatePagesMultiprocess-SUPERSEDED.py @@ -0,0 +1,8 @@ +import os +import subprocess +import rhinoscriptsyntax as rs + +with open(os.environ['TEMP'] + "\\printing-madness" + ".cmd", "w") as madness: + madness.write('start /min "" "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" /nosplash /runscript="-RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\_PrintAllAsSeparatePages.py) -Exit No" ' + chr(34) + rs.DocumentPath() + "\\" + rs.DocumentName() + chr(34)) + madness.flush() + subprocess.Popen(madness.name, shell=True) \ No newline at end of file diff --git a/$$/RemapCplaneCopyGUI.py b/$$/RemapCplaneCopyGUI.py new file mode 100644 index 0000000..b50329d --- /dev/null +++ b/$$/RemapCplaneCopyGUI.py @@ -0,0 +1,31 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +#doesn't work when this section turned on - try using transforms instead: + +#selected_obj = rs.coercerhinoobject(rs.GetObject(preselect=True)) +#if str(selected_obj.ObjectType) == "InstanceReference": +# selected_obj_name = selected_obj.InstanceDefinition.Name +#else: +# selected_obj_name = "" + +named_cplanes = [i.Name for i in list(sc.doc.NamedConstructionPlanes.GetEnumerator())] +selected_cplane_from = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map from") +selected_cplane_to = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map to") + + +#doesn't work when this section turned on - try using transforms instead: +#message_from = "Name: " + selected_obj_name + "\n" + "Cplane to Map from" +#message_to = "Name: " + selected_obj_name + "\n" + "Cplane to Map to" + +#selected_cplane_from = rs.ComboListBox(sorted(named_cplanes), message=message_from) +#selected_cplane_to = rs.ComboListBox(sorted(named_cplanes), message=message_to) + + +current_cplane = rs.ViewCPlane() +rs.RestoreNamedCPlane(selected_cplane_from) + +rs.Command("RemapCplane Copy=Yes Cplane " + chr(34) + selected_cplane_to + chr(34)) + +#restore previous Cplane +rs.ViewCPlane(plane=current_cplane) \ No newline at end of file diff --git a/$$/RemapCplaneGUI-WIP.py b/$$/RemapCplaneGUI-WIP.py new file mode 100644 index 0000000..5261fc7 --- /dev/null +++ b/$$/RemapCplaneGUI-WIP.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +named_cplanes = [i.Name for i in list(sc.doc.NamedConstructionPlanes.GetEnumerator())] +selected_cplane_to = rs.ComboListBox(named_cplanes, "Cplane to Map to") +selected_cplane_from = rs.ComboListBox(named_cplanes, "Cplane to Map from") + +rs.ViewCPlane(plane=selected_cplane_to) +rs.Command("RemapCplane Cplane " + selected_cplane) \ No newline at end of file diff --git a/$$/RemapCplaneGUI.py b/$$/RemapCplaneGUI.py new file mode 100644 index 0000000..98e8dc0 --- /dev/null +++ b/$$/RemapCplaneGUI.py @@ -0,0 +1,15 @@ +# needs a FROM Cplane - could use NamedCplaneGUI.py + +import rhinoscriptsyntax as rs +import scriptcontext as sc + +#world_top_cplane = rs.PlaneFromPoints("0,0,0", "1,0,0", "0,1,0") + +named_cplanes = [i.Name for i in list(sc.doc.NamedConstructionPlanes.GetEnumerator())] +selected_cplane_to = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map to") + +#rs.coerceplane() + +#rs.ViewCPlane(plane=world_top_cplane) +rs.Command("RemapCplane Cplane " + chr(34) + selected_cplane_to + chr(34)) +#rs.Command("Cplane Undo Enter") \ No newline at end of file diff --git a/$$/ReopenThisFileWithoutSaving-WIP.py b/$$/ReopenThisFileWithoutSaving-WIP.py new file mode 100644 index 0000000..86767c2 --- /dev/null +++ b/$$/ReopenThisFileWithoutSaving-WIP.py @@ -0,0 +1,5 @@ +# can't get it to work when file isn't saved, below commands return None +import rhinoscriptsyntax as rs + +document_location = rs.DocumentPath() + rs.DocumentName() +rs.Command("Open No " + chr(34) + document_location + chr(34)) \ No newline at end of file diff --git a/$$/SelColorOnlyInBlocks.py b/$$/SelColorOnlyInBlocks.py new file mode 100644 index 0000000..e4f98e0 --- /dev/null +++ b/$$/SelColorOnlyInBlocks.py @@ -0,0 +1,38 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +selected_colors = list() + +# get colors of blocks' sub-objects +# looping through all objects due to: https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/12 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + sub_object_ids = object.GetSelectedSubObjects() + if sub_object_ids: + for sub_object_id in sub_object_ids: + sub_object = object.InstanceDefinition.GetObjects()[sub_object_id.Index] + sub_object_color = sub_object.Attributes.DrawColor(sc.doc) + selected_colors.append(sub_object_color) + +# get colors of other objects +for object_id in rs.SelectedObjects(): + object = rs.coercerhinoobject(object_id) + object_color = object.Attributes.DrawColor(sc.doc) + selected_colors.append(object_color) + +def _SelColor(object): + for sub_object_id, sub_object in enumerate(object.InstanceDefinition.GetObjects()): + if type(sub_object) == Rhino.DocObjects.InstanceObject: + _SelColor(sub_object) + if sub_object.Attributes.DrawColor(sc.doc) in selected_colors: + object.SelectSubObject(Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.InstanceDefinitionPart, sub_object_id), True, True, True) + +# select objects by color recursively, even though doesn't work for nested blocks +# https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/13 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + _SelColor(object) + +rs.EnableRedraw() +rs.Redraw() diff --git a/$$/SelLayerByObject-BUMMER-DOESNT-SELECT-MULTIPLE-LAYERS-USE-SELLAYER-INSTEAD.py b/$$/SelLayerByObject-BUMMER-DOESNT-SELECT-MULTIPLE-LAYERS-USE-SELLAYER-INSTEAD.py new file mode 100644 index 0000000..29d70af --- /dev/null +++ b/$$/SelLayerByObject-BUMMER-DOESNT-SELECT-MULTIPLE-LAYERS-USE-SELLAYER-INSTEAD.py @@ -0,0 +1,11 @@ +import scriptcontext as sc +import rhinoscriptsyntax as rs + +object_ids = rs.GetObjects(preselect=True) + +if object_ids: + object_layers = [] + for object_id in object_ids: + object_layers.append(rs.ObjectLayer(object_id)) + + rs.ObjectsByLayer(object_layers) \ No newline at end of file diff --git a/$$/SelLayerByObject-GOT-A-BIT-CONFUSED-HERE.py b/$$/SelLayerByObject-GOT-A-BIT-CONFUSED-HERE.py new file mode 100644 index 0000000..64a4926 --- /dev/null +++ b/$$/SelLayerByObject-GOT-A-BIT-CONFUSED-HERE.py @@ -0,0 +1,15 @@ +import scriptcontext as sc +import rhinoscriptsyntax as rs + +object_id = rs.GetObject(preselect=True) +object_layer = rs.ObjectLayer(object_id) +a=rs.ObjectsByLayer(object_layer) +a + +#this won't work - rs.ObjectsByLayer doesn't accept lists +#if object_ids: +# object_layers = [] +# for object_id in object_ids: +# object_layers.append(rs.ObjectLayer(object_id)) +# +# rs.ObjectsByLayer(object_layers) \ No newline at end of file diff --git a/$$/SelMaterialOnlyInBlocks.py b/$$/SelMaterialOnlyInBlocks.py new file mode 100644 index 0000000..4c8449a --- /dev/null +++ b/$$/SelMaterialOnlyInBlocks.py @@ -0,0 +1,40 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +selected_materials = list() + +# get materials of blocks' sub-objects +# looping through all objects due to: https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/12 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + sub_object_ids = object.GetSelectedSubObjects() + if sub_object_ids: + for sub_object_id in sub_object_ids: + sub_object = object.InstanceDefinition.GetObjects()[sub_object_id.Index] + if sub_object.RenderMaterial: + sub_object_material = sub_object.RenderMaterial.Id + selected_materials.append(sub_object_material) + +# get materials of other objects +for object_id in rs.SelectedObjects(): + object = rs.coercerhinoobject(object_id) + if object.RenderMaterial: + object_material = object.RenderMaterial.Id + selected_materials.append(object_material) + +def _SelMaterial(object): + for sub_object_id, sub_object in enumerate(object.InstanceDefinition.GetObjects()): + if type(sub_object) == Rhino.DocObjects.InstanceObject: + _SelMaterial(sub_object) + if sub_object.RenderMaterial and sub_object.RenderMaterial.Id in selected_materials: + object.SelectSubObject(Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.InstanceDefinitionPart, sub_object_id), True, True, True) + +# select objects by material recursively, even though doesn't work for nested blocks +# https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/13 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + _SelMaterial(object) + +rs.EnableRedraw() +rs.Redraw() diff --git a/$$/SelectAllObjsOnObjLayers.py b/$$/SelectAllObjsOnObjLayers.py new file mode 100644 index 0000000..d269640 --- /dev/null +++ b/$$/SelectAllObjsOnObjLayers.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs + +def SelectAllObjsOnObjLayers(): + objs=rs.GetObjects("Select objects",preselect=True) + if not objs: return + rs.EnableRedraw(False) + layers=[rs.ObjectLayer(obj) for obj in objs] + for layer in layers: rs.ObjectsByLayer(layer,True) +SelectAllObjsOnObjLayers() \ No newline at end of file diff --git a/$$/SetAllLayerPrintWidths-Chetwoods-Standard-ctb-TOO-SLOW.py b/$$/SetAllLayerPrintWidths-Chetwoods-Standard-ctb-TOO-SLOW.py new file mode 100644 index 0000000..688405c --- /dev/null +++ b/$$/SetAllLayerPrintWidths-Chetwoods-Standard-ctb-TOO-SLOW.py @@ -0,0 +1,93 @@ +import rhinoscriptsyntax as rs +import re + +#find layers that have one of the codes in the name +layers = [layer for layer in rs.LayerNames() if ">" not in layer and + re.search("AR[0-9]+", layer)] + +def SetAllLayerPrintWidths(): + for layer in layers: + [rs.LayerPrintWidth(layer, width=v) for k, v in ctb_printwidths.items() + if k in layer] + +#codes extracted from template files +ctb_printwidths={ +"AR000": 0.05, +"AR001": 0.05, +"AR002": 0.05, +"AR003": 0.1, +"AR004": 0.05, +"AR006": 0.05, +"AR007": 0.18, +"AR008": 0.05, +"AR009": 0.05, +"AR031": 0.1, +"AR035": 0.05, +"AR036": 0.05, +"AR042": 0.05, +"AR061": 0.05, +"AR062": 0.05, +"AR063": 0.05, +"AR070": 0.1, +"AR071": 0.05, +"AR075": 0.05, +"AR169": 0.1, +"AR211": 0.18, +"AR214": 0.1, +"AR216": 0.15, +"AR219": 0.1, +"AR221": 0.18, +"AR229": 0.05, +"AR231": 0.05, +"AR232": 0.25, +"AR237": 0.18, +"AR240": 0.15, +"AR241": 0.15, +"AR272": 0.18, +"AR277": 0.15, +"AR281": 0.18, +"AR282": 0.15, +"AR283": 0.15, +"AR310": 0.05, +"AR314": 0.1, +"AR315": 0.15, +"AR318": 0.1, +"AR319": 0.25, +"AR324": 0.15, +"AR325": 0.15, +"AR340": 0.1, +"AR351": 0.15, +"AR371": 0.15, +"AR413": 0.18, +"AR414": 0.1, +"AR420": 0.15, +"AR431": 0.05, +"AR439": 0.15, +"AR471": 0.05, +"AR520": 0.05, +"AR522": 0.05, +"AR525": 0.18, +"AR610": 0.18, +"AR611": 0.1, +"AR630": 0.1, +"AR640": 0.05, +"AR661": 0.15, +"AR664": 0.1, +"AR680": 0.05, +"AR683": 0.1, +"AR711": 0.1, +"AR731": 0.1, +"AR741": 0.05, +"AR783": 0.1, +"AR785": 0.05, +"AR900": 0.25, +"AR901": 0.05, +"AR902": 0.05, +"AR904": 0.05, +"AR905": 0.05, +"AR906": 0.05, +"AR907": 0.1, +"AR908": 0.1, +"AR910": 0.05} + +SetAllLayerPrintWidths() diff --git a/$$/ShowSelectedByMatchingLayer.py b/$$/ShowSelectedByMatchingLayer.py new file mode 100644 index 0000000..daefc92 --- /dev/null +++ b/$$/ShowSelectedByMatchingLayer.py @@ -0,0 +1,37 @@ +import rhinoscriptsyntax as rs +import Rhino +import scriptcontext as sc +import System + +def ShowSelectedByMatchingLayers(): + + hIds = rs.HiddenObjects() + if not hIds: + print "No objects are hidden." + return + + selIds = rs.SelectedObjects() + + if not selIds: + selIds = rs.GetObjects("Select objects on the layers to match.") + if not selIds:return + + allIds = rs.AllObjects() + if not allIds: return + + offLayers = [] + lockedLayers = [] + selLayers = list(set([System.Guid((rs.LayerId(rs.ObjectLayer(id)))) for id in selIds])) + + rs.EnableRedraw(False) + for id in allIds: + obj = sc.doc.Objects.Find(id) + if obj.IsHidden: + idx = obj.Attributes.LayerIndex + layerId = sc.doc.Layers.FindIndex(idx).Id + if layerId in selLayers: + rs.ShowObject(id) + + rs.EnableRedraw(True) + +if __name__ == "__main__": ShowSelectedByMatchingLayers() \ No newline at end of file diff --git a/$$/_PrintAllAsSeparatePages.py b/$$/_PrintAllAsSeparatePages.py new file mode 100644 index 0000000..44a4bbc --- /dev/null +++ b/$$/_PrintAllAsSeparatePages.py @@ -0,0 +1,56 @@ +import Rhino +import scriptcontext as sc +import System.Drawing +import rhinoscriptsyntax as rs +import os + +folder = os.getcwd() +titleblock = dict() + +def createSinglePDF(view, titleblock): + pdf = Rhino.FileIO.FilePdf.Create() + dpi = 300 + settings = Rhino.Display.ViewCaptureSettings(view, dpi) + settings.OutputColor = Rhino.Display.ViewCaptureSettings.ColorMode.DisplayColor + settings.DefaultPrintWidthMillimeters = 0.18 + pdf.AddPage(settings) + filename = folder + os.path.sep + titleblock.get("project_number","0000") + "-" + \ + titleblock.get("originator", "00") + "-" + \ + titleblock.get("zone", "00") + "-" + \ + titleblock.get("level", "00") + "-" + \ + titleblock.get("drawing_type", "00") + "-" + \ + titleblock.get("role", "0") + "-" + \ + titleblock.get("drawing_number", "00000") + "_" + \ + titleblock.get("latest_revision", "00") + " " + \ + titleblock.get("drawing_title_1", "000000000") + " " + \ + titleblock.get("drawing_title_2", "") + " " + \ + titleblock.get("drawing_title_3", "") + ".pdf" + pdf.Write(filename) + +for view in sc.doc.Views.GetPageViews(): + for object in sc.doc.Objects.FindByLayer("titleblock index-AR002"): + if type(object) == Rhino.DocObjects.TextObject and \ + view.ActiveViewportID == object.Attributes.ViewportId: + if object.Name == "Project Number": + titleblock["project_number"] = object.DisplayText + if object.Name == "Originator": + titleblock["originator"] = object.DisplayText + if object.Name == "Zone": + titleblock["zone"] = object.DisplayText + if object.Name == "Level": + titleblock["level"] = object.DisplayText + if object.Name == "Drawing Type": + titleblock["drawing_type"] = object.DisplayText + if object.Name == "Role": + titleblock["role"] = object.DisplayText + if object.Name == "Drawing Number": + titleblock["drawing_number"] = object.DisplayText + if object.Name == "Latest Revision": + titleblock["latest_revision"] = object.DisplayText + if object.Name == "Drawing Title 1": + titleblock["drawing_title_1"] = object.DisplayText + if object.Name == "Drawing Title 2": + titleblock["drawing_title_2"] = object.DisplayText + if object.Name == "Drawing Title 3": + titleblock["drawing_title_3"] = object.DisplayText + createSinglePDF(view, titleblock) \ No newline at end of file diff --git a/$$/pywin32-conenct-to-a-running-Rhino-process.py b/$$/pywin32-conenct-to-a-running-Rhino-process.py new file mode 100644 index 0000000..160481c --- /dev/null +++ b/$$/pywin32-conenct-to-a-running-Rhino-process.py @@ -0,0 +1,6 @@ +import win32com.client as win32 + +a = win32.Dispatch("Rhino.Interface") +b=a.IsInitialized +c=a.BringToTop() +d=a.Visible \ No newline at end of file diff --git a/1Layout1PDF.py b/1Layout1PDF.py new file mode 100644 index 0000000..ff22d5b --- /dev/null +++ b/1Layout1PDF.py @@ -0,0 +1,21 @@ +import Rhino +import scriptcontext as sc +import System.Drawing +import rhinoscriptsyntax as rs + +def createSinglePDF(view): + folder = rs.BrowseForFolder() + prefix = "PREFIX" + folder += "\\" + prefix + pdf = Rhino.FileIO.FilePdf.Create() + dpi = 300 +# size = System.Drawing.Size(8.5*dpi,11*dpi) + settings = Rhino.Display.ViewCaptureSettings(view, dpi) + pdf.AddPage(settings) + filename = folder+view.PageName+'.pdf' + pdf.Write(filename) + + +for i in sc.doc.Views: + if type(i) is Rhino.Display.RhinoPageView: + createSinglePDF(i) diff --git a/AbsoluteTolerance.py b/AbsoluteTolerance.py new file mode 100644 index 0000000..7814fb0 --- /dev/null +++ b/AbsoluteTolerance.py @@ -0,0 +1,11 @@ +from rhinoscriptsyntax import UnitAbsoluteTolerance, ComboListBox + +def AbsoluteTolerance(): + selected_tolerance = ComboListBox([100,10,1,0.1,0.01,0.001,0.0001], + message="Choose Absolute Tolerace", + title="Absolute Tolerace") + if selected_tolerance == None: + return + UnitAbsoluteTolerance(float(selected_tolerance)) + +AbsoluteTolerance() \ No newline at end of file diff --git a/AcadIntegration.py b/AcadIntegration.py new file mode 100644 index 0000000..e3fbad5 --- /dev/null +++ b/AcadIntegration.py @@ -0,0 +1,15 @@ +import rhinoscriptsyntax as rs +from datetime import datetime +import os + +buffer_folder = rs.GetDocumentData("ACAD_Exports", "Folder") +if buffer_folder is None: + buffer_folder = rs.BrowseForFolder() + rs.SetDocumentData("ACAD_Exports", "Folder", buffer_folder) + +file_name = buffer_folder + os.path.sep + \ +datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S-%f')[:-3] + "-" + \ +rs.DocumentName() + ".dwg" + +rs.Command("-_Export " + chr(34) + file_name + chr(34)) + diff --git a/ActivateDetailViewsonLayouts-WORK-IN-PROGRESS.py b/ActivateDetailViewsonLayouts-WORK-IN-PROGRESS.py new file mode 100644 index 0000000..c379200 --- /dev/null +++ b/ActivateDetailViewsonLayouts-WORK-IN-PROGRESS.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +strLayout = rs.CurrentView() +aDetails = sc.doc.Views.GetPageViews()[2].GetDetailViews() + +for i in aDetails: + rs.CurrentDetail("05047", detail=i.Id) + diff --git a/BatchMake2D-NOT-WORKING-FOR-LINKED-BLOCKS-AND-CLIPPING-PLANES.py b/BatchMake2D-NOT-WORKING-FOR-LINKED-BLOCKS-AND-CLIPPING-PLANES.py new file mode 100644 index 0000000..104a11a --- /dev/null +++ b/BatchMake2D-NOT-WORKING-FOR-LINKED-BLOCKS-AND-CLIPPING-PLANES.py @@ -0,0 +1,78 @@ +import Rhino.Geometry +from Rhino.DocObjects import ObjectType +from Rhino.Display import RhinoPageView +import scriptcontext as sc +import rhinoscriptsyntax as rs + +def BatchMake2D(): + selected_page_names = rs.MultiListBox([i.PageName for i in sc.doc.Views.GetPageViews()]) + if selected_page_names == None: + return + selected_pages = [i for i in sc.doc.Views.GetPageViews() if i.PageName in selected_page_names] + + for selected_page in selected_pages: + detail_views = RhinoPageView.GetDetailViews(selected_page) + + cgeo_views = [detail_view for detail_view in detail_views if detail_view.Name and "CGeo" in detail_view.Name] + if len(cgeo_views) == 0: + rs.MessageBox("No '-CGeo' viewports found.\nAdd corresponding named viewports.\nBatch Make2D will exit now.") + return + + for detail_view in detail_views: + if detail_view.Name == None: + continue + if "CGeo" in detail_view.Name: + continue + + first_corner = Rhino.Geometry.Point2d(detail_view.Viewport.Bounds.Left, detail_view.Viewport.Bounds.Bottom) + second_corner = Rhino.Geometry.Point2d(detail_view.Viewport.Bounds.Right, detail_view.Viewport.Bounds.Top) + + detail_view.IsActive = True + + rhino_objects = sc.doc.Objects.FindByCrossingWindowRegion(detail_view.Viewport, + first_corner, second_corner, + True, ObjectType.AnyObject) + + parameters = Rhino.Geometry.HiddenLineDrawingParameters() + parameters.AbsoluteTolerance = sc.doc.ModelAbsoluteTolerance + parameters.Flatten = True + parameters.IncludeHiddenCurves = False + parameters.IncludeTangentEdges = False + parameters.IncludeTangentSeams = False + parameters.SetViewport(detail_view.Viewport) + for obj in rhino_objects: + parameters.AddGeometry(obj.Geometry, obj.Id) + + for vp in detail_views: + if vp.Name and detail_view.Name in vp.Name and "CGeo" in vp.Name: + cgeo_viewport = vp.Viewport + break + else: + cgeo_viewport = None + + if cgeo_viewport == None: + continue + + cgeo_viewport_plane = Rhino.Geometry.Plane(cgeo_viewport.CameraTarget, + cgeo_viewport.CameraX, + cgeo_viewport.CameraY) + xform = Rhino.Geometry.Transform.PlaneToPlane(Rhino.Geometry.Plane.WorldXY, cgeo_viewport_plane) + + hld = Rhino.Geometry.HiddenLineDrawing.Compute(parameters, True) + + for hld_curve in hld.Segments: + if not hld_curve: + continue + if not hld_curve.ParentCurve: + continue + if hld_curve.ParentCurve.SilhouetteType == Rhino.Geometry.SilhouetteType.None: + continue + if hld_curve.SegmentVisibility == Rhino.Geometry.HiddenLineDrawingSegment.Visibility.Visible: + source_obj_attribs = rs.coercerhinoobject(hld_curve.ParentCurve.SourceObject.Tag).Attributes + curve = hld_curve.CurveGeometry.DuplicateCurve() + curve.Transform(xform) + sc.doc.Objects.AddCurve(curve, source_obj_attribs) + + sc.doc.Views.Redraw() + +BatchMake2D() \ No newline at end of file diff --git a/BatchMake2D.py b/BatchMake2D.py new file mode 100644 index 0000000..2b25cff --- /dev/null +++ b/BatchMake2D.py @@ -0,0 +1,70 @@ +import Rhino.Geometry +from Rhino.DocObjects import ObjectType +from Rhino.Display import RhinoPageView +import scriptcontext as sc +import rhinoscriptsyntax as rs + +def BatchMake2D(): + selected_page_names = rs.MultiListBox([i.PageName for i in sc.doc.Views.GetPageViews()]) + if selected_page_names == None: + return + selected_pages = [i for i in sc.doc.Views.GetPageViews() if i.PageName in selected_page_names] + + for selected_page in selected_pages: + all_detail_views = RhinoPageView.GetDetailViews(selected_page) + + #select views by "CGeo" in the name + #in the future autogenerate corresponding views based on geolocation (EarthAnchorPoint) + target_views = [detail_view for detail_view in all_detail_views if detail_view.Name and "CGeo" in detail_view.Name] + if len(target_views) == 0: + rs.MessageBox("No '-CGeo' viewports found.\nAdd corresponding named viewports.\nBatch Make2D will exit now.") + return + + for source_view in all_detail_views: + if source_view.Name == None: + continue + if "CGeo" in source_view.Name: + continue + + first_corner = Rhino.Geometry.Point2d(source_view.Viewport.Bounds.Left, source_view.Viewport.Bounds.Bottom) + second_corner = Rhino.Geometry.Point2d(source_view.Viewport.Bounds.Right, source_view.Viewport.Bounds.Top) + + + for vp in all_detail_views: + if vp.Name and source_view.Name in vp.Name and "CGeo" in vp.Name: + target_viewport = vp.Viewport + break + else: + target_viewport = None + if target_viewport == None: + continue + + source_view.IsActive = True + + sc.doc.Objects.UnselectAll() + #https://discourse.mcneel.com/t/how-to-get-coordinates-of-a-viewport-corners/153493 + rhino_objects = sc.doc.Objects.FindByCrossingWindowRegion(source_view.Viewport, + first_corner, second_corner, + True, ObjectType.AnyObject) + rs.SelectObjects(rhino_objects) + + #transform Make2D results to the correct location (based on chosen real-world "geolocation") + source_viewport_plane = Rhino.Geometry.Plane(source_view.Viewport.CameraTarget, + source_view.Viewport.CameraX, + source_view.Viewport.CameraY) + target_viewport_plane = Rhino.Geometry.Plane(target_viewport.CameraTarget, + target_viewport.CameraX, + target_viewport.CameraY) + + xform = Rhino.Geometry.Transform.PlaneToPlane(source_viewport_plane, target_viewport_plane) + + rs.Command("CPlane View _Enter") + rs.Command("-Make2D Layout=CPlane Properties=MaintainSourceLayers CreateHiddenLines=No ShowTangents=No CreateSceneSilhouette=No CreateClippingPlaneIntersections=No ShowViewRectangle=No GroupOutput=No LayerName " + source_view.Name + " _Enter") + rs.Command("_Enter") + make2d_results = rs.SelectedObjects() + rs.TransformObjects(make2d_results, xform, copy=False) + + sc.doc.Objects.UnselectAll() + source_view.IsActive = False + +BatchMake2D() \ No newline at end of file diff --git a/BlockTools 1.4.rhi b/BlockTools 1.4.rhi new file mode 100644 index 0000000..06172ea Binary files /dev/null and b/BlockTools 1.4.rhi differ diff --git a/BlockUpdate.py b/BlockUpdate.py new file mode 100644 index 0000000..3a6129d --- /dev/null +++ b/BlockUpdate.py @@ -0,0 +1,11 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def BlockUpdate(): + object_ids = rs.GetObjects(preselect=True) + for id in object_ids: + block_instance = sc.doc.Objects.Find(id) + block_definition = block_instance.InstanceDefinition + sc.doc.InstanceDefinitions.RefreshLinkedBlock(block_definition) + +BlockUpdate() \ No newline at end of file diff --git a/BlockUpdateSelected-NOT-WORKING-MISSING-UPDATE-OPTION.py b/BlockUpdateSelected-NOT-WORKING-MISSING-UPDATE-OPTION.py new file mode 100644 index 0000000..ee4d2a2 --- /dev/null +++ b/BlockUpdateSelected-NOT-WORKING-MISSING-UPDATE-OPTION.py @@ -0,0 +1,12 @@ +import rhinoscriptsyntax as rs + +def BlockUpdateSelected(): + insts = rs.GetObjects("Select block instnces to refresh.", 4096, preselect=True) + + if insts: + names = [rs.BlockInstanceName(inst)for inst in insts] + pass + for name in list(set(names)): + if not rs.IsBlockEmbedded(name): + rs.Command("-BlockManager Update " + chr(34) +name+ chr(34) + " Enter") +BlockUpdateSelected() diff --git a/ChangeCameraProjection.py b/ChangeCameraProjection.py new file mode 100644 index 0000000..ce59006 --- /dev/null +++ b/ChangeCameraProjection.py @@ -0,0 +1,24 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def ChangeCameraProjection(): + projection_type = ["Parallel", "Perspective", "Two Point"] + projection_selected = rs.ComboListBox(projection_type) + + if projection_selected == None: + return + + if projection_selected == "Parallel": + sc.doc.Views.ActiveView.ActiveViewport.ChangeToParallelProjection(symmetricFrustum=True) + rs.EnableRedraw(True) + rs.Redraw() + if projection_selected == "Perspective": + sc.doc.Views.ActiveView.ActiveViewport.ChangeToPerspectiveProjection(symmetricFrustum=False, lensLength=60) + rs.EnableRedraw(True) + rs.Redraw() + if projection_selected == "Two Point": + sc.doc.Views.ActiveView.ActiveViewport.ChangeToTwoPointPerspectiveProjection(lensLength=60) + rs.EnableRedraw(True) + rs.Redraw() + +ChangeCameraProjection() \ No newline at end of file diff --git a/ChangeLayerInBlockRecursively.py b/ChangeLayerInBlockRecursively.py new file mode 100644 index 0000000..0575028 --- /dev/null +++ b/ChangeLayerInBlockRecursively.py @@ -0,0 +1,34 @@ +import rhinoscriptsyntax as rs + + +def ChangeLayerInBlockRecursively(): + + ids = rs.GetObjects("Select block instances", 4096, preselect=True) + if not ids:return + + targ = rs.GetLayer() + if not targ:return + + names = list(set([rs.BlockInstanceName(id) for id in ids])) + done = [] + + def BlockDrill(names): + while True: + if len (names) > 0 : + name = names.pop() + else: break + + done.append(name) + temp = rs.BlockObjects(name) + rs.ObjectLayer(temp, targ) + + for tempId in temp: + if rs.IsBlockInstance(tempId): + tempName = rs.BlockInstanceName(tempId) + if tempName not in names and tempName not in done: + names.append(tempName) + BlockDrill(names) + + BlockDrill(names) + +if __name__ == "__main__": ChangeLayerInBlockRecursively() \ No newline at end of file diff --git a/ChangeMaterial.py b/ChangeMaterial.py new file mode 100644 index 0000000..3a7b003 --- /dev/null +++ b/ChangeMaterial.py @@ -0,0 +1,25 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def ChangeMaterial(): + material_names = [i.Name for i in sc.doc.RenderMaterials] + selected_material_name = rs.ComboListBox(sorted(material_names)) + + if selected_material_name == None: + return + + for material in sc.doc.RenderMaterials: + if material.Name == selected_material_name: + selected_material = material + + selected_objects = rs.GetObjects(preselect=True) + + if selected_objects == None: + return + + for selected_object_guid in selected_objects: + selected_object = rs.coercerhinoobject(selected_object_guid) + selected_object.RenderMaterial = selected_material + selected_object.CommitChanges() + +ChangeMaterial() \ No newline at end of file diff --git a/ChangeMaterialForAll.py b/ChangeMaterialForAll.py new file mode 100644 index 0000000..4c8449a --- /dev/null +++ b/ChangeMaterialForAll.py @@ -0,0 +1,40 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +selected_materials = list() + +# get materials of blocks' sub-objects +# looping through all objects due to: https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/12 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + sub_object_ids = object.GetSelectedSubObjects() + if sub_object_ids: + for sub_object_id in sub_object_ids: + sub_object = object.InstanceDefinition.GetObjects()[sub_object_id.Index] + if sub_object.RenderMaterial: + sub_object_material = sub_object.RenderMaterial.Id + selected_materials.append(sub_object_material) + +# get materials of other objects +for object_id in rs.SelectedObjects(): + object = rs.coercerhinoobject(object_id) + if object.RenderMaterial: + object_material = object.RenderMaterial.Id + selected_materials.append(object_material) + +def _SelMaterial(object): + for sub_object_id, sub_object in enumerate(object.InstanceDefinition.GetObjects()): + if type(sub_object) == Rhino.DocObjects.InstanceObject: + _SelMaterial(sub_object) + if sub_object.RenderMaterial and sub_object.RenderMaterial.Id in selected_materials: + object.SelectSubObject(Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.InstanceDefinitionPart, sub_object_id), True, True, True) + +# select objects by material recursively, even though doesn't work for nested blocks +# https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/13 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + _SelMaterial(object) + +rs.EnableRedraw() +rs.Redraw() diff --git a/ClipEnableGUI.py b/ClipEnableGUI.py new file mode 100644 index 0000000..9136a2a --- /dev/null +++ b/ClipEnableGUI.py @@ -0,0 +1,30 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def ClipEnable(): + selection_settings = Rhino.DocObjects.ObjectEnumeratorSettings() + selection_settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.ClipPlane + clip_planes_iterator = sc.doc.Objects.GetObjectList(selection_settings) + + # getobjectlist methods yields an iterator that gets exhausted + # line below converts it into an immutable list + clip_planes = list(clip_planes_iterator) + + clip_plane_names = [clip_plane.Name for clip_plane in clip_planes + if clip_plane.Name is not None] + + selected_clip_planes = rs.MultiListBox(sorted(set(clip_plane_names))) + + if selected_clip_planes == None: + return + + # new gui pop up that selects detail views by name + # which means you'll have to name them + # and addclipview + + selected_clip_planes_guids = [clip_plane.Id for clip_plane in clip_planes + if clip_plane.Name in selected_clip_planes] + + rs.SelectObjects(selected_clip_planes_guids) + +ClipEnable() \ No newline at end of file diff --git a/ClipSelGUI.py b/ClipSelGUI.py new file mode 100644 index 0000000..d4d4f63 --- /dev/null +++ b/ClipSelGUI.py @@ -0,0 +1,29 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def ClipSel(): + selection_settings = Rhino.DocObjects.ObjectEnumeratorSettings() + selection_settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.ClipPlane + clip_planes_iterator = sc.doc.Objects.GetObjectList(selection_settings) + + # getobjectlist methods yields an iterator that gets exhausted + # line below converts it into an immutable list + clip_planes = list(clip_planes_iterator) + + clip_plane_names = [clip_plane.Name for clip_plane in clip_planes + if clip_plane.Name is not None] + + selected_clip_planes = rs.ComboListBox(sorted(set(clip_plane_names))) + + if selected_clip_planes == None: + return + + # may be a problem if there is only one clipping plane with that name? + + selected_clip_planes_guids = [clip_plane.Id for clip_plane in clip_planes + if clip_plane.Name == selected_clip_planes] + + rs.SelectObjects(selected_clip_planes_guids) + +ClipSel() \ No newline at end of file diff --git a/ClipSelGUIMultiple.py b/ClipSelGUIMultiple.py new file mode 100644 index 0000000..3bb9005 --- /dev/null +++ b/ClipSelGUIMultiple.py @@ -0,0 +1,27 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def ClipSel(): + selection_settings = Rhino.DocObjects.ObjectEnumeratorSettings() + selection_settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.ClipPlane + clip_planes_iterator = sc.doc.Objects.GetObjectList(selection_settings) + + # getobjectlist methods yields an iterator that gets exhausted + # line below converts it into an immutable list + clip_planes = list(clip_planes_iterator) + + clip_plane_names = [clip_plane.Name for clip_plane in clip_planes + if clip_plane.Name is not None] + + selected_clip_planes = rs.MultiListBox(sorted(set(clip_plane_names))) + + if selected_clip_planes == None: + return + + selected_clip_planes_guids = [clip_plane.Id for clip_plane in clip_planes + if clip_plane.Name in selected_clip_planes] + + rs.SelectObjects(selected_clip_planes_guids) + +ClipSel() \ No newline at end of file diff --git a/ConsolidateLayers.py b/ConsolidateLayers.py new file mode 100644 index 0000000..3c8210f --- /dev/null +++ b/ConsolidateLayers.py @@ -0,0 +1,54 @@ +import scriptcontext as sc +import rhinoscriptsyntax as rs +import collections + +def ConsolidateLayers(): + + layers = rs.LayerNames() + + stripped = [] + top = [] + crnt = False + for layer in layers: + if not rs.LayerChildren(layer) and not crnt: + rs.CurrentLayer(layer) + crnt=True + idx = layer.find("::",1) + if idx>-1: + stripped.append(layer[idx+1:]) + else: + top.append(layer) + pass + dups = [item for item, count in collections.Counter(stripped).items() if count > 1] + + + + + rs.EnableRedraw(False) + for item in dups: + targLayer = None + for tLayer in top: + tempLayer = tLayer+":"+item + if rs.IsLayer(tempLayer): + if not targLayer: + targLayer = tempLayer + ids = rs.ObjectsByLayer(tempLayer) + rs.ObjectLayer(ids, targLayer) + if tempLayer != targLayer: + rs.DeleteLayer(tempLayer) + + if targLayer:pass + + for layer in layers: + if rs.IsLayer(layer): + if rs.IsLayerEmpty(layer): + rs.DeleteLayer(layer) + + # for layer in top: + # if rs.IsLayer(layer): + # print layer + # print rs.PurgeLayer(layer) + + rs.EnableRedraw(True) + +if __name__== '__main__': ConsolidateLayers() \ No newline at end of file diff --git a/ConvertHatchesToSrfs_cmd.py b/ConvertHatchesToSrfs_cmd.py new file mode 100644 index 0000000..01e0c17 --- /dev/null +++ b/ConvertHatchesToSrfs_cmd.py @@ -0,0 +1,23 @@ +import rhinoscriptsyntax as rs + +def RunCommand( is_interactive ): + + #get current color + hatchId = rs.GetObject( + "Pick one hatch", filter=65536, preselect=True, select=True, + subobjects=False) + color = rs.ObjectColor(hatchId) + + #run macro + macro = """ + selcolor invert hide selprev dupborder invert + delete selall planarsrf delete selall join dupborder + invert delete selall planarsrf delete selall group show + """ + rs.Command(macro, echo=False) + + #set previous color as a new material + new_objects = rs.SelectedObjects() + for i in new_objects: + material_idx = rs.AddMaterialToObject(i) + rs.MaterialColor(material_idx, color) \ No newline at end of file diff --git a/ConvertPlanarSrfsToHatch-v8.py b/ConvertPlanarSrfsToHatch-v8.py new file mode 100644 index 0000000..091364c --- /dev/null +++ b/ConvertPlanarSrfsToHatch-v8.py @@ -0,0 +1,25 @@ +import rhinoscriptsyntax as rs +import Rhino +import scriptcontext as sc + +def HatchPlanarSrfs(): + + srfs = rs.GetObjects("select planar surfaces to hatch", filter=8, preselect=True) + if not srfs: + return + for srf in srfs: + srf = rs.coercebrep(srf) + face = srf.Faces[0] + if not face.IsPlanar(): + continue + edges = srf.Edges + edges = [edge.DuplicateCurve() for edge in edges] + edges = Rhino.Geometry.Curve.JoinCurves(edges) + + hatch_solid_idx = sc.doc.HatchPatterns.Find("Solid", True) + hatch = Rhino.Geometry.Hatch.Create(edges, hatch_solid_idx, 0, 0) + sc.doc.Objects.AddHatch(hatch[0]) + sc.doc.Views.Redraw() + +if __name__ == "__main__": + HatchPlanarSrfs() \ No newline at end of file diff --git a/ConvertPlanarSrfsToHatch.py b/ConvertPlanarSrfsToHatch.py new file mode 100644 index 0000000..d53236f --- /dev/null +++ b/ConvertPlanarSrfsToHatch.py @@ -0,0 +1,25 @@ +import rhinoscriptsyntax as rs +import Rhino +import scriptcontext as sc + +def HatchPlanarSrfs(): + + srfs = rs.GetObjects("select planar surfaces to hatch", filter=8, preselect=True) + if not srfs: + return + for srf in srfs: + srf = rs.coercebrep(srf) + face = srf.Faces[0] + if not face.IsPlanar(): + continue + edges = srf.Edges + edges = [edge.DuplicateCurve() for edge in edges] + edges = Rhino.Geometry.Curve.JoinCurves(edges) + + hatch_solid_idx = sc.doc.HatchPatterns.Find("SOLID", True) + hatch = Rhino.Geometry.Hatch.Create(edges, hatch_solid_idx, 0, 0) + sc.doc.Objects.AddHatch(hatch[0]) + sc.doc.Views.Redraw() + +if __name__ == "__main__": + HatchPlanarSrfs() \ No newline at end of file diff --git a/ConvertProjectV8ToV7.py b/ConvertProjectV8ToV7.py new file mode 100644 index 0000000..3b4d4ab --- /dev/null +++ b/ConvertProjectV8ToV7.py @@ -0,0 +1,34 @@ +import os +import rhinoscriptsyntax as rs +import scriptcontext as sc +import System +import subprocess +import Rhino + +block_defs = list(sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True)) + +for idx, block_def in enumerate(block_defs): + if rs.IsBlockEmbedded(block_def.Name) == False and ".3dm" in block_def.SourceArchive: + with open(os.environ['TEMP'] + "\\converting-madness-" + str(idx) + ".cmd", "w") as madness: + + xref_folder, xref_file_name = os.path.split(block_def.SourceArchive) + if not os.path.exists(xref_folder + "\\RhinoV7"): + os.mkdir(xref_folder + "\\RhinoV7") + + madness.write('start /min "" "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" /nosplash /runscript="-RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\_XrefFilePathSourceV7.py) -saveas version=7 ' + '""' + xref_folder + "\\RhinoV7\\" + xref_file_name + '""' + ' -Exit No" ' + chr(34) + block_def.SourceArchive + chr(34)) + madness.flush() + subprocess.Popen(madness.name, shell=True) + +for idx, block_def in enumerate(block_defs): + if rs.IsBlockEmbedded(block_def.Name) == False and ".3dm" in block_def.SourceArchive: + block_folder, block_file_name = os.path.split(block_def.SourceArchive) + new_block_path = block_folder + "\\RhinoV7\\" + block_file_name + sc.doc.InstanceDefinitions.ModifySourceArchive(block_def.Index, + new_block_path, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + 0) + +document_name, document_ext = os.path.splitext(rs.DocumentName()) +rs.Command("-saveas version=7 " + chr(34) + rs.DocumentPath() + document_name + "-V7" + document_ext + chr(34)) +subprocess.Popen(rs.DocumentPath() + document_name + "-V7" + document_ext) +rs.Command("-Exit No") \ No newline at end of file diff --git a/ConvertV8ToV7ForFiles.py b/ConvertV8ToV7ForFiles.py new file mode 100644 index 0000000..7bef28a --- /dev/null +++ b/ConvertV8ToV7ForFiles.py @@ -0,0 +1,21 @@ +import os +import rhinoscriptsyntax as rs +import System +import subprocess + + +dlg = System.Windows.Forms.OpenFileDialog() +dlg.Multiselect = True +if dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK: + selected_files = dlg.FileNames + +for i, selected_file in enumerate(selected_files): + with open(os.environ['TEMP'] + "\\converting-madness-" + str(i) + ".cmd", "w") as madness: + + selected_file_path, selected_file_name = os.path.split(selected_file) + if not os.path.exists(selected_file_path + "\\v7"): + os.mkdir(selected_file_path + "\\v7") + + madness.write('start /min "" "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" /nosplash /runscript="-saveas version=7 ' + '""' + selected_file_path + "\\v7\\" + selected_file_name + '""' + ' exit" ' + chr(34) + selected_file + chr(34)) + madness.flush() + subprocess.Popen(madness.name, shell=True) \ No newline at end of file diff --git a/DeleteBlock.py b/DeleteBlock.py new file mode 100644 index 0000000..bc969fa --- /dev/null +++ b/DeleteBlock.py @@ -0,0 +1,8 @@ +import rhinoscriptsyntax as rs + +def DeleteBlock(): + block_names_all = rs.BlockNames() + block_name = rs.ComboListBox(sorted(block_names_all)) + rs.DeleteBlock(block_name) + +DeleteBlock() \ No newline at end of file diff --git a/DeleteNamedCplane.py b/DeleteNamedCplane.py new file mode 100644 index 0000000..dcdd063 --- /dev/null +++ b/DeleteNamedCplane.py @@ -0,0 +1,7 @@ +# need to find a way to escape the last command + +import rhinoscriptsyntax as rs + +named_cplanes = rs.NamedCPlanes() +new_name = rs.ComboListBox(sorted(named_cplanes)) +rs.Command("-NamedCplane Delete " + chr(34) + new_name + chr(34) + " Enter") \ No newline at end of file diff --git a/DisableAllClippingPlanes.py b/DisableAllClippingPlanes.py new file mode 100644 index 0000000..383b4be --- /dev/null +++ b/DisableAllClippingPlanes.py @@ -0,0 +1,11 @@ +import scriptcontext as sc +import Rhino + +def DisableAllClippingPlanes(): + + clipping_planes = [i for i in sc.doc.Objects if type(i) == Rhino.DocObjects.ClippingPlaneObject] + + for clipping_plane in clipping_planes: + clipping_plane.RemoveClipViewport(sc.doc.Views.ActiveView.ActiveViewport, True) + +DisableAllClippingPlanes() \ No newline at end of file diff --git a/EtoForm_MultipleListBox_PrintAllBlockDefinitionsInDocument.py b/EtoForm_MultipleListBox_PrintAllBlockDefinitionsInDocument.py new file mode 100644 index 0000000..63dc07d --- /dev/null +++ b/EtoForm_MultipleListBox_PrintAllBlockDefinitionsInDocument.py @@ -0,0 +1,204 @@ +""" + Show a dialog window with all document layers + Allow searching through the list + + print selected layer name(s) + + +""" +import System + +import Rhino +import Rhino.UI +import rhinoscriptsyntax as rs + +import Eto +import Eto.Drawing as drawing +import Eto.Forms as forms + +import scriptcontext as sc + +import os +import fnmatch + +import itertools +flatten = itertools.chain.from_iterable +graft = itertools.combinations + +# make modal dialog +class DocLayerSelectionDialog(Eto.Forms.Dialog[bool]): + # Initializer + def __init__(self): + # Eto initials + self.Title = "All Layers" + self.Padding = Eto.Drawing.Padding(5) + self.Spacing = Eto.Drawing.Size(5, 5) + + + # fields + self.ScriptList = self.InitializeScriptList() + self.SearchedScriptList = self.ScriptList[::] + + + # initialize layout + layout = Eto.Forms.DynamicLayout() + layout.Padding = Eto.Drawing.Padding(5) + layout.Spacing = Eto.Drawing.Size(5, 5) + + + # add search + layout.BeginVertical() + layout.AddRow(*self.CreateSearchBar()) + layout.EndVertical() + + # add listBox + layout.BeginVertical() + layout.AddRow(self.CreateScriptListBox()) + layout.EndVertical() + + # add buttons + layout.BeginVertical() + layout.AddRow(*self.CreateButtons()) + layout.EndVertical() + + # set content + self.Content = layout + + + + # collect data for list + def InitializeScriptList(self): + return allDocLayers + #return sorted(allDocLayers) + + + # create search bar function + def CreateSearchBar(self): + """ + Creates two controls for the search bar + self.lbl_Search as a simple label + self.tB_Search as a textBox to input search strings to + """ + self.lbl_Search = Eto.Forms.Label() + self.lbl_Search.Text = "Search: " + self.lbl_Search.VerticalAlignment = Eto.Forms.VerticalAlignment.Center + + self.tB_Search = Eto.Forms.TextBox() + self.tB_Search.TextChanged += self.tB_Search_TextChanged + + return [self.lbl_Search, self.tB_Search] + + + + def CreateScriptListBox(self): + # Create a multi selection box with grid view - this is similar to Rhino MultipleListBox + self.lb = forms.GridView() + self.lb.ShowHeader = False + self.lb.AllowMultipleSelection = True + self.lb.Height = 200 + self.lb.AllowColumnReordering = True + + self.lb.DataStore = sorted(allDocLayers) + + self.lb.SelectedRowsChanged += self.RowsChanged + + + # Create Gridview Column + column1 = forms.GridColumn() + column1.Editable = False + column1.Width = 350 + column1.DataCell = forms.TextBoxCell(0) + self.lb.Columns.Add(column1) + + self.lb.DataStore = self.SearchedScriptList + + return self.lb + + + + def CreateButtons(self): + """ + Creates buttons for either print the selection result + or exiting the dialog + """ + self.btn_Run = Eto.Forms.Button() + self.btn_Run.Text = "Run" + self.btn_Run.Click += self.btn_Run_Clicked + + self.btn_Cancel = Eto.Forms.Button() + self.btn_Cancel.Text = "Cancel" + self.btn_Cancel.Click += self.btn_Cancel_Clicked + + return [self.btn_Run, None, self.btn_Cancel] + + + + # create a search function + def Search(self, text): + """ + Searches self.ScriptList with a given string + Supports wildCards + """ + if text == "": + self.lb.DataStore = self.ScriptList + else: + self.SearchedScriptList = list(graft(fnmatch.filter(flatten(self.ScriptList), "*" + text + "*"), 1)) + self.lb.DataStore = self.SearchedScriptList + + + # Gridview SelectedRows Changed Event + def RowsChanged (self,sender,e): + return self.lb.SelectedRows + + + + # function to run when call at button click + def RunScript(self): + # return selected layer names + return self.lb.SelectedValue + + + + # event handler handling text input in ther search bar + def tB_Search_TextChanged(self, sender, e): + self.Search(self.tB_Search.Text) + + + + # event handler handling clicking on the 'run' button + def btn_Run_Clicked(self, sender, e): + # close window after double click action. Otherwise, run with error + self.Close(True) + self.RunScript() + + + # event handler handling clicking on the 'cancel' button + def btn_Cancel_Clicked(self, sender, e): + self.Close(False) + + + +def ShowDocLayerSelectionDialog(): + + dlg = DocLayerSelectionDialog() + rc = Rhino.UI.EtoExtensions.ShowSemiModal(dlg, Rhino.RhinoDoc.ActiveDoc, Rhino.UI.RhinoEtoApp.MainWindow) + + if (rc): + pickedLayers = [] + pickedLayers.append(dlg.RunScript()) + + print pickedLayers + + else: + print "Dialog did not run" + + +if __name__ == "__main__": + docBlocks = rs.BlockNames() + + allDocLayers = [] + i = 0 + while i < len(docBlocks): + allDocLayers.append(docBlocks[i:i+1]) + i += 1 + ShowDocLayerSelectionDialog() \ No newline at end of file diff --git a/EtoForm_MultipleListBox_PrintSelectedLayerName.py b/EtoForm_MultipleListBox_PrintSelectedLayerName.py new file mode 100644 index 0000000..a41c546 --- /dev/null +++ b/EtoForm_MultipleListBox_PrintSelectedLayerName.py @@ -0,0 +1,204 @@ +""" + Show a dialog window with all document layers + Allow searching through the list + + print selected layer name(s) + + +""" +import System + +import Rhino +import Rhino.UI +import rhinoscriptsyntax as rs + +import Eto +import Eto.Drawing as drawing +import Eto.Forms as forms + +import scriptcontext as sc + +import os +import fnmatch + +import itertools +flatten = itertools.chain.from_iterable +graft = itertools.combinations + +# make modal dialog +class DocLayerSelectionDialog(Eto.Forms.Dialog[bool]): + # Initializer + def __init__(self): + # Eto initials + self.Title = "All Layers" + self.Padding = Eto.Drawing.Padding(5) + self.Spacing = Eto.Drawing.Size(5, 5) + + + # fields + self.ScriptList = self.InitializeScriptList() + self.SearchedScriptList = self.ScriptList[::] + + + # initialize layout + layout = Eto.Forms.DynamicLayout() + layout.Padding = Eto.Drawing.Padding(5) + layout.Spacing = Eto.Drawing.Size(5, 5) + + + # add search + layout.BeginVertical() + layout.AddRow(*self.CreateSearchBar()) + layout.EndVertical() + + # add listBox + layout.BeginVertical() + layout.AddRow(self.CreateScriptListBox()) + layout.EndVertical() + + # add buttons + layout.BeginVertical() + layout.AddRow(*self.CreateButtons()) + layout.EndVertical() + + # set content + self.Content = layout + + + + # collect data for list + def InitializeScriptList(self): + return allDocLayers + #return sorted(allDocLayers) + + + # create search bar function + def CreateSearchBar(self): + """ + Creates two controls for the search bar + self.lbl_Search as a simple label + self.tB_Search as a textBox to input search strings to + """ + self.lbl_Search = Eto.Forms.Label() + self.lbl_Search.Text = "Search: " + self.lbl_Search.VerticalAlignment = Eto.Forms.VerticalAlignment.Center + + self.tB_Search = Eto.Forms.TextBox() + self.tB_Search.TextChanged += self.tB_Search_TextChanged + + return [self.lbl_Search, self.tB_Search] + + + + def CreateScriptListBox(self): + # Create a multi selection box with grid view - this is similar to Rhino MultipleListBox + self.lb = forms.GridView() + self.lb.ShowHeader = False + self.lb.AllowMultipleSelection = True + self.lb.Height = 200 + self.lb.AllowColumnReordering = True + + self.lb.DataStore = sorted(allDocLayers) + + self.lb.SelectedRowsChanged += self.RowsChanged + + + # Create Gridview Column + column1 = forms.GridColumn() + column1.Editable = False + column1.Width = 350 + column1.DataCell = forms.TextBoxCell(0) + self.lb.Columns.Add(column1) + + self.lb.DataStore = self.SearchedScriptList + + return self.lb + + + + def CreateButtons(self): + """ + Creates buttons for either print the selection result + or exiting the dialog + """ + self.btn_Run = Eto.Forms.Button() + self.btn_Run.Text = "Run" + self.btn_Run.Click += self.btn_Run_Clicked + + self.btn_Cancel = Eto.Forms.Button() + self.btn_Cancel.Text = "Cancel" + self.btn_Cancel.Click += self.btn_Cancel_Clicked + + return [self.btn_Run, None, self.btn_Cancel] + + + + # create a search function + def Search(self, text): + """ + Searches self.ScriptList with a given string + Supports wildCards + """ + if text == "": + self.lb.DataStore = self.ScriptList + else: + self.SearchedScriptList = list(graft(fnmatch.filter(flatten(self.ScriptList), "*" + text + "*"), 1)) + self.lb.DataStore = self.SearchedScriptList + + + # Gridview SelectedRows Changed Event + def RowsChanged (self,sender,e): + return self.lb.SelectedRows + + + + # function to run when call at button click + def RunScript(self): + # return selected layer names + return self.lb.SelectedValue + + + + # event handler handling text input in ther search bar + def tB_Search_TextChanged(self, sender, e): + self.Search(self.tB_Search.Text) + + + + # event handler handling clicking on the 'run' button + def btn_Run_Clicked(self, sender, e): + # close window after double click action. Otherwise, run with error + self.Close(True) + self.RunScript() + + + # event handler handling clicking on the 'cancel' button + def btn_Cancel_Clicked(self, sender, e): + self.Close(False) + + + +def ShowDocLayerSelectionDialog(): + + dlg = DocLayerSelectionDialog() + rc = Rhino.UI.EtoExtensions.ShowSemiModal(dlg, Rhino.RhinoDoc.ActiveDoc, Rhino.UI.RhinoEtoApp.MainWindow) + + if (rc): + pickedLayers = [] + pickedLayers.append(dlg.RunScript()) + + print pickedLayers + + else: + print "Dialog did not run" + + +if __name__ == "__main__": + docLayers = rs.LayerNames() + + allDocLayers = [] + i = 0 + while i < len(docLayers): + allDocLayers.append(docLayers[i:i+1]) + i += 1 + ShowDocLayerSelectionDialog() \ No newline at end of file diff --git a/ExportDwgSchemeRGBColors.py b/ExportDwgSchemeRGBColors.py new file mode 100644 index 0000000..9de27e8 --- /dev/null +++ b/ExportDwgSchemeRGBColors.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs +import os + +file_name = rs.OpenFileName() +# in case user added extension +file_name_without_ext, file_name_with_ext = os.path.splitext(file_name) +file_name = file_name_without_ext + ".dwg" + +rs.Command('-Export "C:\\Users\\user\\Desktop\\test" Scheme "Default-Copy" _Enter') diff --git a/ExportObjectsToSeparateFiles.py b/ExportObjectsToSeparateFiles.py new file mode 100644 index 0000000..17288ed --- /dev/null +++ b/ExportObjectsToSeparateFiles.py @@ -0,0 +1,36 @@ +"""Export folder is same as current folder if file has been saved; +otherwise, choice of location. +Change format on line 18. +Script by Mitch Heynick 08.07.19""" + +import rhinoscriptsyntax as rs +import scriptcontext as sc +import os + +def ExportObjectsToSeparateFiles(): + names = rs.GetObjects(preselect=True) + + #get folder to save file in + folder=rs.WorkingFolder() + doc_path=rs.DocumentPath() + ft="3dm" + msg="Main file name/folder for {} export?".format(ft) + if doc_path: + msg+=" (Enter to save in current folder)".format(ft) + folder=doc_path + save_folder = rs.BrowseForFolder(folder,msg) + if not save_folder: return + + #start the export sequence + rs.EnableRedraw(False) + for name in names: + e_file_name = '{}.{}'.format(name,ft.lower()) + filename=os.path.join(save_folder,str(e_file_name)) + rs.UnselectAllObjects() + rs.SelectObject(name, redraw=False) + #runs the export using the file name/path and your settings + rs.Command('-_Export "{}" _Enter'.format(filename), echo=True) + rs.UnselectAllObjects() + rs.EnableRedraw(True) + +ExportObjectsToSeparateFiles() diff --git a/ExportViewportsToImages.py b/ExportViewportsToImages.py new file mode 100644 index 0000000..767e85f --- /dev/null +++ b/ExportViewportsToImages.py @@ -0,0 +1,41 @@ +import rhinoscriptsyntax as rs +import Rhino +import os +import scriptcontext as sc +import System.Drawing.Size + +def ExportViewportsToImages(): + + details = Rhino.Display.RhinoPageView.GetDetailViews(sc.doc.Views.ActiveView) + names = [detail.Attributes.Name for detail in details if detail.Attributes.Name != None] + + if len(names) == 0: + rs.MessageBox("No named Viewports found on this page.\n\n" + + "Please give viewports a name that will be used to name output images.\n\n" + + "To do this select each viewport on the sheet and in the properties panel fill in the 'Name' field.", title="Error") + return + + folder = rs.BrowseForFolder() + + for detail in details: + if detail.Attributes.Name: + bbox = rs.BoundingBox(detail.Id) + width = abs(bbox[0].X - bbox[1].X) + length = abs(bbox[1].Y - bbox[2].Y) + size = System.Drawing.Size(width*12, length*12) + + viewcap = Rhino.Display.ViewCapture() + viewcap.TransparentBackground = False + + settings = Rhino.Display.ViewCaptureSettings(sc.doc.Views.ActiveView, size, 300) + settings.SetWindowRect(bbox[0], bbox[2]) + settings.RasterMode = True + settings.DrawGrid = False + settings.DrawAxis = False + settings.DrawWallpaper = False + settings.OutputColor = Rhino.Display.ViewCaptureSettings.ColorMode.DisplayColor + + capture = Rhino.Display.ViewCapture.CaptureToBitmap(settings) + capture.Save(folder + os.path.sep + detail.Attributes.Name + ".jpg") + +ExportViewportsToImages() \ No newline at end of file diff --git a/ExtendCameraTarget.py b/ExtendCameraTarget.py new file mode 100644 index 0000000..af9bff9 --- /dev/null +++ b/ExtendCameraTarget.py @@ -0,0 +1,26 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def PushTarget(): + + vp = sc.doc.Views.ActiveView.ActiveViewport + t = vp.CameraTarget + c = vp.CameraLocation + + factor = 1.25 + if sc.sticky.has_key('TARGET_FACTOR'): + factor = sc.sticky['TARGET_FACTOR'] + + factor = rs.GetReal('Factor', factor, minimum= .1, maximum = None) + if not factor: return + + sc.sticky['TARGET_FACTOR']= factor + + vecDir = t-c + vecDir = vecDir * factor + + vp.SetCameraTarget (c+ vecDir, False) + + sc.doc.Views.Redraw() + +if __name__ == '__main__':PushTarget() \ No newline at end of file diff --git a/FormatTextAreaSquareMeters.py b/FormatTextAreaSquareMeters.py new file mode 100644 index 0000000..2979cba --- /dev/null +++ b/FormatTextAreaSquareMeters.py @@ -0,0 +1,10 @@ +import rhinoscriptsyntax as rs + +obj_guid = rs.GetObject("Select Object to Measure its area", preselect=True) +obj = rs.coercerhinoobject(obj_guid) + +text_guid = rs.GetObject("Select Text Object to report the area", preselect=True) + +format_string = '%% sq m' + +rs.TextObjectText(text_guid, format_string) \ No newline at end of file diff --git a/FormatTextAreaSquareMetersWholeNumbers.py b/FormatTextAreaSquareMetersWholeNumbers.py new file mode 100644 index 0000000..9550eee --- /dev/null +++ b/FormatTextAreaSquareMetersWholeNumbers.py @@ -0,0 +1,10 @@ +import rhinoscriptsyntax as rs + +obj_guid = rs.GetObject("Select Object to Measure its area", preselect=True) +obj = rs.coercerhinoobject(obj_guid) + +text_guid = rs.GetObject("Select Text Object to report the area", preselect=True) + +format_string = '%%' + +rs.TextObjectText(text_guid, format_string) \ No newline at end of file diff --git a/GetActiveViewportParameters.py b/GetActiveViewportParameters.py new file mode 100644 index 0000000..335d4d2 --- /dev/null +++ b/GetActiveViewportParameters.py @@ -0,0 +1,19 @@ +import scriptcontext as sc +from Rhino.UI.Dialogs import ShowTextDialog + +active_viewport = sc.doc.Views.ActiveView.ActiveViewport + +string = str(active_viewport.CameraLocation[0]) + ";" + \ + str(active_viewport.CameraLocation[1]) + ";" + \ + str(active_viewport.CameraLocation[2]) + ";" + \ + str(active_viewport.CameraTarget[0]) + ";" + \ + str(active_viewport.CameraTarget[1]) + ";" + \ + str(active_viewport.CameraTarget[2]) + ";" + \ + str(active_viewport.CameraUp[0]) + ";" + \ + str(active_viewport.CameraUp[1]) + ";" + \ + str(active_viewport.CameraUp[2]) + ";" + \ + "0.0" + ";" + \ + "true" + ";" + \ + str(active_viewport.Camera35mmLensLength) + ";" + +ShowTextDialog(string, "Active Viewport Parameters") \ No newline at end of file diff --git a/GetAllBlockDefinitionsInDocument.py b/GetAllBlockDefinitionsInDocument.py new file mode 100644 index 0000000..95eb03b --- /dev/null +++ b/GetAllBlockDefinitionsInDocument.py @@ -0,0 +1,8 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def GetAllBlockDefinitionsInDocument(): + all_block_definitions = rs.BlockNames() + rs.ComboListBox(all_block_definitions) + +GetAllBlockDefinitionsInDocument() \ No newline at end of file diff --git a/GetAllObjectsNames.py b/GetAllObjectsNames.py new file mode 100644 index 0000000..dde20d0 --- /dev/null +++ b/GetAllObjectsNames.py @@ -0,0 +1,10 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def GetNames(): + object_names = [object.Name for object in sc.doc.Objects if object.Name] + format = "\n".join(sorted(set(object_names))) + Rhino.UI.Dialogs.ShowTextDialog(format, "Block Names") + +GetNames() \ No newline at end of file diff --git a/GetBlocksName.py b/GetBlocksName.py new file mode 100644 index 0000000..a070818 --- /dev/null +++ b/GetBlocksName.py @@ -0,0 +1,12 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +block_ids = rs.GetObjects(filter=4096, preselect=True) + +if block_ids: + block_names = list() + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_names.append(block_name) + Rhino.UI.Dialogs.ShowTextDialog("\n".join(sorted(block_names)), "Block Names") \ No newline at end of file diff --git a/GetBlocksNameSet.py b/GetBlocksNameSet.py new file mode 100644 index 0000000..6be1ead --- /dev/null +++ b/GetBlocksNameSet.py @@ -0,0 +1,11 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +block_ids = rs.GetObjects(filter=4096, preselect=True) + +if block_ids: + block_names = list() + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_names.append(block_name) + rs.ComboListBox(sorted(list(set(block_names)))) \ No newline at end of file diff --git a/GetBlocksOnLayers.py b/GetBlocksOnLayers.py new file mode 100644 index 0000000..ca8aae2 --- /dev/null +++ b/GetBlocksOnLayers.py @@ -0,0 +1,28 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def GetBlocksOnLayers(): + layer_names = rs.GetLayers() + blocks_using_layer = set() + for layer_name in layer_names: + layer_idx = sc.doc.Layers.FindByFullPath(layer_name, notFoundReturnValue=False) + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + for block_definition in block_definitions: + block_objects = block_definition.GetObjects() + for block_object in block_objects: + if block_object.Attributes.LayerIndex==layer_idx: + blocks_using_layer.add(block_definition.Name) + selected_blocks = rs.MultiListBox(list(blocks_using_layer)) + return selected_blocks + +def InsertSelectedBlocks(selected_blocks): + for selected_block in selected_blocks: + rs.InsertBlock(selected_block, "0,0,0") + +#def InsertSelectedBlocksManually(selected_blocks): +# for selected_block in selected_blocks: +# rs.Command("-Insert _Enter " + chr(34) + selected_block + chr(34)) + +selected_blocks = GetBlocksOnLayers() +InsertSelectedBlocks(selected_blocks) \ No newline at end of file diff --git a/GetGuid.py b/GetGuid.py new file mode 100644 index 0000000..a01c679 --- /dev/null +++ b/GetGuid.py @@ -0,0 +1,5 @@ +import rhinoscriptsyntax as rs + +obj_guid = rs.GetObject(preselect=True) +obj = rs.coercerhinoobject(obj_guid) +rs.ClipboardText(obj.Id) \ No newline at end of file diff --git a/GetGuidToClipboard.py b/GetGuidToClipboard.py new file mode 100644 index 0000000..a01c679 --- /dev/null +++ b/GetGuidToClipboard.py @@ -0,0 +1,5 @@ +import rhinoscriptsyntax as rs + +obj_guid = rs.GetObject(preselect=True) +obj = rs.coercerhinoobject(obj_guid) +rs.ClipboardText(obj.Id) \ No newline at end of file diff --git a/GetLayers.py b/GetLayers.py new file mode 100644 index 0000000..71a3deb --- /dev/null +++ b/GetLayers.py @@ -0,0 +1,16 @@ +import rhinoscriptsyntax as rs +import Rhino + +def GetLayers(): + object_ids = rs.GetObjects(preselect=True) + + if object_ids: + object_layers = set() + for object_id in object_ids: + object_layer = rs.ObjectLayer(object_id) + object_layers.add(object_layer) + format = "\n".join(sorted(object_layers)) + Rhino.UI.Dialogs.ShowTextDialog(format, "Block Names") +# rs.ComboListBox(sorted(list(object_layers))) + +GetLayers() \ No newline at end of file diff --git a/GetNameBlocks.py b/GetNameBlocks.py new file mode 100644 index 0000000..9717bb1 --- /dev/null +++ b/GetNameBlocks.py @@ -0,0 +1,16 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def GetNameBlocks(): + block_ids = rs.GetObjects(filter=4096, preselect=True) + + if block_ids: + block_names = list() + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_names.append(block_name) + Rhino.UI.Dialogs.ShowTextDialog("\n".join(sorted(block_names)), "Block Names") +# rs.ComboListBox(block_names) + +GetNameBlocks() \ No newline at end of file diff --git a/GetNameSetBlocks.py b/GetNameSetBlocks.py new file mode 100644 index 0000000..5ab3cf6 --- /dev/null +++ b/GetNameSetBlocks.py @@ -0,0 +1,14 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def GetNameSetBlocks(): + block_ids = rs.GetObjects(filter=4096, preselect=True) + + if block_ids: + block_names = list() + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_names.append(block_name) + rs.ComboListBox(sorted(list(set(block_names)))) + +GetNameSetBlocks() \ No newline at end of file diff --git a/GetNames.py b/GetNames.py new file mode 100644 index 0000000..bcc688e --- /dev/null +++ b/GetNames.py @@ -0,0 +1,12 @@ +import rhinoscriptsyntax as rs +import Rhino + +def GetNames(): + selected_object_ids = rs.SelectedObjects() + if selected_object_ids == None: return + + selected_object_names = [rs.coercerhinoobject(id).Name for id in selected_object_ids if rs.coercerhinoobject(id).Name] + format = "\n".join(sorted(set(selected_object_names))) + Rhino.UI.Dialogs.ShowTextDialog(format, "Object Names") + +GetNames() \ No newline at end of file diff --git a/Get_Box_Dims.py b/Get_Box_Dims.py new file mode 100644 index 0000000..a9b3d3e --- /dev/null +++ b/Get_Box_Dims.py @@ -0,0 +1,15 @@ +from __future__ import print_function +import Rhino.Geometry.Box as Box + +x,y,z=[],[],[] + +for i in range(len(breps)): + x1,x2 = Box.X.GetValue(breps[i]) + y1,y2 = Box.Y.GetValue(breps[i]) + z1,z2 = Box.Z.GetValue(breps[i]) + + x.append(round(abs(x1-x2)*2)/2) + y.append(round(abs(y1-y2)*2)/2) + z.append(round(abs(z1-z2)*2)/2) + +[print(i,j,k) for i,j,k in zip(x,y,z)] diff --git a/HatchPlanarSrfs-v8.py b/HatchPlanarSrfs-v8.py new file mode 100644 index 0000000..091364c --- /dev/null +++ b/HatchPlanarSrfs-v8.py @@ -0,0 +1,25 @@ +import rhinoscriptsyntax as rs +import Rhino +import scriptcontext as sc + +def HatchPlanarSrfs(): + + srfs = rs.GetObjects("select planar surfaces to hatch", filter=8, preselect=True) + if not srfs: + return + for srf in srfs: + srf = rs.coercebrep(srf) + face = srf.Faces[0] + if not face.IsPlanar(): + continue + edges = srf.Edges + edges = [edge.DuplicateCurve() for edge in edges] + edges = Rhino.Geometry.Curve.JoinCurves(edges) + + hatch_solid_idx = sc.doc.HatchPatterns.Find("Solid", True) + hatch = Rhino.Geometry.Hatch.Create(edges, hatch_solid_idx, 0, 0) + sc.doc.Objects.AddHatch(hatch[0]) + sc.doc.Views.Redraw() + +if __name__ == "__main__": + HatchPlanarSrfs() \ No newline at end of file diff --git a/HatchPlanarSrfs.py b/HatchPlanarSrfs.py new file mode 100644 index 0000000..d53236f --- /dev/null +++ b/HatchPlanarSrfs.py @@ -0,0 +1,25 @@ +import rhinoscriptsyntax as rs +import Rhino +import scriptcontext as sc + +def HatchPlanarSrfs(): + + srfs = rs.GetObjects("select planar surfaces to hatch", filter=8, preselect=True) + if not srfs: + return + for srf in srfs: + srf = rs.coercebrep(srf) + face = srf.Faces[0] + if not face.IsPlanar(): + continue + edges = srf.Edges + edges = [edge.DuplicateCurve() for edge in edges] + edges = Rhino.Geometry.Curve.JoinCurves(edges) + + hatch_solid_idx = sc.doc.HatchPatterns.Find("SOLID", True) + hatch = Rhino.Geometry.Hatch.Create(edges, hatch_solid_idx, 0, 0) + sc.doc.Objects.AddHatch(hatch[0]) + sc.doc.Views.Redraw() + +if __name__ == "__main__": + HatchPlanarSrfs() \ No newline at end of file diff --git a/HideLayerInLayoutDetails.py b/HideLayerInLayoutDetails.py new file mode 100644 index 0000000..576a22c --- /dev/null +++ b/HideLayerInLayoutDetails.py @@ -0,0 +1,40 @@ +__author__ = "Alasdair Mott" +__version__ = "2018.03.15" +# modified 24.11.22 to replace CheckListBox with MultiListBox + +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def hideLayerInLayouts(page): + details = Rhino.Display.RhinoPageView.GetDetailViews(page) + + for i, detail in enumerate(details): + + #rs.CurrentDetail(pageName, detail) + detailId = detail.Id + + for layerString in layers: + + layer_idx = sc.doc.Layers.FindByFullPath(layerString, True) + layer = sc.doc.Layers.FindIndex(layer_idx) + Rhino.DocObjects.Layer.SetPerViewportVisible(layer, detailId, False) + +pageName = rs.CurrentView() +pageNames = rs.ViewNames(True, 1) +pages = sc.doc.Views.GetPageViews() + +""" User Input """ +layers = rs.GetLayers() + +if pageNames and layers: + pageNamesHide = rs.MultiListBox(pageNames, "Layouts to turn off Layer In", "Hide Layer In Layout") + +""" Iterate Pages """ +rs.EnableRedraw(False) +if layers: + if pageNamesHide: + for page in pages: + hideLayerInLayouts(page) +rs.EnableRedraw(True) +rs.Redraw() diff --git a/HideLayers.py b/HideLayers.py new file mode 100644 index 0000000..36b736a --- /dev/null +++ b/HideLayers.py @@ -0,0 +1,15 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def HideLayers(): + layers=rs.GetLayers() + for layer in layers: + rs.LayerVisible(layer, visible=False) + +# couldn't figure out a faster way to do this :( +def HideLayers2(): + selected_layer = rs.GetLayer() + layer_object = sc.doc.Layers.Find() + layer_object.IsVisible = False + +HideLayers() \ No newline at end of file diff --git a/HideObjectInLayoutDetails-WORK-IN-PROGRESS.py b/HideObjectInLayoutDetails-WORK-IN-PROGRESS.py new file mode 100644 index 0000000..e36ea8e --- /dev/null +++ b/HideObjectInLayoutDetails-WORK-IN-PROGRESS.py @@ -0,0 +1,41 @@ +__author__ = "Alasdair Mott" +__version__ = "2018.03.15" + +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def hideLayerInLayouts(page): + details = Rhino.Display.RhinoPageView.GetDetailViews(page) + + for i, detail in enumerate(details): + + #rs.CurrentDetail(pageName, detail) + detailId = detail.Id + + for layerString in layers: + + layer_idx = sc.doc.Layers.FindByFullPath(layerString, True) + layer = sc.doc.Layers.FindIndex(layer_idx) + Rhino.DocObjects.Layer.SetPerViewportVisible(layer, detailId, False) + +pageName = rs.CurrentView() +pageNames = rs.ViewNames(True, 1) +pages = sc.doc.Views.GetPageViews() + +""" User Input """ +layers = rs.GetLayers() + +if pageNames and layers: + items = [(layout, True) for layout in pageNames] + pageNamesHide = rs.CheckListBox(items, "Layouts to turn off Layer In", "Hide Layer In Layout") + +""" Iterate Pages """ +rs.EnableRedraw(False) +if layers: + if pageNamesHide: + for i, page in enumerate(pages): + if pageNamesHide[i][1] == True: + hideLayerInLayouts(page) +rs.EnableRedraw(True) +rs.Redraw() diff --git a/ImportLayers-WIP.py b/ImportLayers-WIP.py new file mode 100644 index 0000000..74d315f --- /dev/null +++ b/ImportLayers-WIP.py @@ -0,0 +1,12 @@ +import rhinoscriptsyntax as rs +import Rhino +import scriptcontext as sc + +rhino_file = rs.OpenFileName() +rhino_file_layers = Rhino.FileIO.File3dm.Read(rhino_file).Layers +selected_layers = rs.ComboListBox(sorted(list(rhino_file_layers))) +a + +for rhino_file_layer in rhino_file_layers: + print(rhino_file_layer) +# sc.doc.Layers.Add() \ No newline at end of file diff --git a/JJ-LayMCur-Make-Object-Layer-Current.py b/JJ-LayMCur-Make-Object-Layer-Current.py new file mode 100644 index 0000000..5cc8a79 --- /dev/null +++ b/JJ-LayMCur-Make-Object-Layer-Current.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs + +object_guids = rs.GetObjects(preselect=True) +if len(object_guids) > 1: + object_layers = list(set([rs.ObjectLayer(i) for i in object_guids])) + selected_layer = rs.ComboListBox(object_layers) + rs.CurrentLayer(selected_layer) +else: + rs.CurrentLayer(rs.ObjectLayer(object_guids[0])) \ No newline at end of file diff --git a/LayoutAddFromClipboard.py b/LayoutAddFromClipboard.py new file mode 100644 index 0000000..e1acc7e --- /dev/null +++ b/LayoutAddFromClipboard.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs + +message = rs.ClipboardText().split("-_-_-") + +page_name = message[0] +page_width = message[1] +page_height = message[2] + +rs.AddLayout(page_name, [float(page_width), float(page_height)]) \ No newline at end of file diff --git a/LayoutCopyToClipboard-WIP.py b/LayoutCopyToClipboard-WIP.py new file mode 100644 index 0000000..e700981 --- /dev/null +++ b/LayoutCopyToClipboard-WIP.py @@ -0,0 +1,17 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import pickle + +#page_width = sc.doc.Views.ActiveView.PageWidth +#page_height = sc.doc.Views.ActiveView.PageHeight +#page_name = sc.doc.Views.ActiveView.PageName +# +#rs.ClipboardText("-_-_-".join([page_name, str(page_width), str(page_height)])) + +page_obj_ids = list() +for obj in sc.doc.Objects: + if obj.Attributes.ViewportId == sc.doc.Views.ActiveView.ActiveViewportID: + page_obj_ids.append(obj.Id) + +#rs.SelectObjects(page_obj_ids) + diff --git a/LayoutCopyToClipboard.py b/LayoutCopyToClipboard.py new file mode 100644 index 0000000..89902e0 --- /dev/null +++ b/LayoutCopyToClipboard.py @@ -0,0 +1,8 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +page_width = sc.doc.Views.ActiveView.PageWidth +page_height = sc.doc.Views.ActiveView.PageHeight +page_name = sc.doc.Views.ActiveView.PageName + +rs.ClipboardText("-_-_-".join([page_name, str(page_width), str(page_height)])) diff --git a/ListAllChangedBlocks.py b/ListAllChangedBlocks.py new file mode 100644 index 0000000..559d9e2 --- /dev/null +++ b/ListAllChangedBlocks.py @@ -0,0 +1,18 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) +block_definitions_list = list(block_definitions) +linked_blocks=[i for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False and + ">" not in i.Name] + +changed_blocks = list() +for linked_block in linked_blocks: + if rs.BlockStatus(linked_block.Name) == 1: + changed_blocks.append((linked_block.Name, linked_block.SourceArchive)) + +# might use better string formatting, but will do for now +Rhino.UI.Dialogs.ShowTextDialog("\n".join(sorted([i for sub in changed_blocks for i in sub])), + "Changed Blocks") \ No newline at end of file diff --git a/Make2D.py b/Make2D.py new file mode 100644 index 0000000..9690bb3 --- /dev/null +++ b/Make2D.py @@ -0,0 +1,40 @@ +import Rhino +import rhinoscriptsyntax as rs +import scriptcontext as sc + +a = [view.GetDetailViews() for view in sc.doc.Views.GetPageViews()] +b = [view.PageName for view in sc.doc.Views.GetPageViews()] +c + +if rs.GetDocumentUserText("Child") is None: +# dwg_folder_path = rs.BrowseForFolder("Choose folder to save DWGs into") + a = [view for view in sc.doc.Views.GetPageViews()] + + selected_views = rs.MultiListBox(sorted()) + files = rs.OpenFileNames("Choose files to save as DWG") + for file in files: + subprocess.Popen('start "" /min "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" ' + \ + '/nosplash /runscript="-SetDocumentUserText Child Child ' + \ + '-SetDocumentUserText Export_DWG_folder_path ' + \ + chr(34) + chr(34) + dwg_folder_path + chr(34) + chr(34) + ' ' + \ + '-RunPythonScript (' + __file__ + ') -Exit No" ' + \ + chr(34) + file + chr(34), shell=True) +else: + dwg_folder_path_child = rs.GetDocumentUserText("Export_DWG_folder_path") + rs.Command("-SaveAs " + chr(34) + dwg_folder_path_child + "\\" + \ + os.path.splitext(rs.DocumentName())[0] + ".dwg" + chr(34)) + rs.Command("-Exit No") + + +rs.Command("-Make2D Layout=CPlane Properties=MaintainSourceLayers " + +"CreateHiddenLines=No ShowTangents=No CreateSceneSilhouette=Yes " + +"CreateClippingPlaneIntersections=Yes ShowViewRectangle=Yes " + +"GroupOutput=No " + +"LayerName test2 " + +"_Enter", + echo=True) + +#for reference - methods in RhinoCommon: +#https://developer.rhino3d.com/api/RhinoCommon/html/T_Rhino_Geometry_HiddenLineDrawingParameters.htm +#make2d_options = Rhino.Geometry.HiddenLineDrawingParameters() +#Rhino.Geometry.HiddenLineDrawing.Compute() \ No newline at end of file diff --git a/Make2DBatch-WIP.py b/Make2DBatch-WIP.py new file mode 100644 index 0000000..fd63cf6 --- /dev/null +++ b/Make2DBatch-WIP.py @@ -0,0 +1,3 @@ +import rhinoscriptsyntax as rs + +a = rs.VisibleObjects(select=True) \ No newline at end of file diff --git a/MergeLayerTrees-2-WORK-IN-PROGRESS.py b/MergeLayerTrees-2-WORK-IN-PROGRESS.py new file mode 100644 index 0000000..d59e931 --- /dev/null +++ b/MergeLayerTrees-2-WORK-IN-PROGRESS.py @@ -0,0 +1,11 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +a=rs.GetLayer("Get First Layer to Merge") +b=rs.GetLayer("Get Second Layer to Merge") + +c = rs.LayerNames() + +sc.doc.Objects.FindByLayer + +a \ No newline at end of file diff --git a/MergeLayerTrees-WORK-IN-PROGRESS.py b/MergeLayerTrees-WORK-IN-PROGRESS.py new file mode 100644 index 0000000..d1fdfd4 --- /dev/null +++ b/MergeLayerTrees-WORK-IN-PROGRESS.py @@ -0,0 +1,4 @@ +import rhinoscriptsyntax as rs + +layer_tree_from=rs.GetLayers(title="Select Parent Layer to Merge From") +layer_tree_to=rs.GetLayers(title="Select Parent Layer to Merge To") \ No newline at end of file diff --git a/NamedCplaneGUI.py b/NamedCplaneGUI.py new file mode 100644 index 0000000..f754059 --- /dev/null +++ b/NamedCplaneGUI.py @@ -0,0 +1,10 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +named_cplanes = rs.NamedCPlanes() +if not named_cplanes: + raise Exception("No Named CPlanes") +else: + selected_cplane = rs.ComboListBox(sorted(named_cplanes), "Named CPlanes") + +rs.RestoreNamedCPlane(selected_cplane) \ No newline at end of file diff --git a/NamedLayerFilter.py b/NamedLayerFilter.py new file mode 100644 index 0000000..320d35e --- /dev/null +++ b/NamedLayerFilter.py @@ -0,0 +1,22 @@ +import rhinoscriptsyntax as rs +# add globbing +#import glob + +named_layer_filters_str = rs.GetDocumentUserText("Named-Layer-Filters") + +if named_layer_filters_str is None: + selected_filter = rs.ComboListBox(["None"], message="Create a Named Layer Filter") + rs.SetDocumentUserText("Named-Layer-Filters", selected_filter) +else: + named_layer_filters_list = named_layer_filters_str.split(",") + selected_filter = rs.ComboListBox(named_layer_filters_list) + named_layer_filters_list.append(selected_filter) + named_layer_filters_list_new = list(set(named_layer_filters_list)) + named_layer_filters_list_new_str = ",".join(named_layer_filters_list_new) + rs.SetDocumentUserText("Named-Layer-Filters", named_layer_filters_list_new_str) + +visible = rs.ComboListBox(["Show", "Hide"]) +if visible == "Show": + [rs.LayerVisible(layer, visible=True) for layer in rs.LayerNames() if selected_filter in layer] +if visible == "Hide": + [rs.LayerVisible(layer, visible=False) for layer in rs.LayerNames() if selected_filter in layer] \ No newline at end of file diff --git a/NamedViewGUI.py b/NamedViewGUI.py new file mode 100644 index 0000000..5a729dd --- /dev/null +++ b/NamedViewGUI.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +named_views = rs.NamedViews() +if not named_views: + raise Exception("No Named Views") +else: + selected_view = rs.ComboListBox(sorted(named_views), "Named Views") + rs.RestoreNamedView(selected_view) \ No newline at end of file diff --git a/NewNamedCplane.py b/NewNamedCplane.py new file mode 100644 index 0000000..27ea3b4 --- /dev/null +++ b/NewNamedCplane.py @@ -0,0 +1,9 @@ +# need to find a way to escape the last command + +import rhinoscriptsyntax as rs + +named_cplanes = rs.NamedCPlanes() +if not named_cplanes: + named_cplanes = [" "] +new_name = rs.ComboListBox(sorted(named_cplanes), message="Name for the new Named Cplane") +rs.Command("-NamedCplane Save " + chr(34) + new_name + chr(34) + " Enter") \ No newline at end of file diff --git a/ObjectsGroupsToLayers.rvb b/ObjectsGroupsToLayers.rvb new file mode 100644 index 0000000..8d68006 --- /dev/null +++ b/ObjectsGroupsToLayers.rvb @@ -0,0 +1,120 @@ +Option Explicit +'Script written by willemderks.com +'Script version Tuesday, April 12, 2014 + +Call AllGroupsObjectsToIndividualLayers() +Sub AllGroupsObjectsToIndividualLayers() + + Dim arrObj : arrObj = Rhino.GetObjects("Get Objects to distribute to layers") + If isNull(arrObj) Then Exit Sub + + Dim i + Dim digits :digits = Int(len(Cstr(Ubound(arrObj)))) + 1 + Dim tmp + Dim arrGroups + ReDim arrGroups(Ubound(arrObj)) + For i=0 To Ubound(arrObj) + arrGroups(i) = Rhino.ObjectGroups(arrObj(i)) + If Not isNull(arrGroups(i)) Then + tmp = arrGroups(i)(0) + arrGroups(i) = tmp + Else + arrGroups(i) = Null + End If + Next + + Call ArrayCullNull(arrGroups) + + Dim arrObjGrouped : arrObjGrouped = array() + + Dim g,arrG + If Ubound(arrGroups) > -1 Then + arrGroups = Rhino.CullDuplicateStrings(arrGroups) + + + arrObjGrouped = Rhino.MakeArray(Ubound(arrGroups), array()) + + For g=0 To Ubound(arrGroups) + For i=0 To Ubound(arrObj) + If Not isNull(arrObj(i)) Then + arrG = Rhino.ObjectGroups(arrObj(i)) + If Not isNull(arrG) Then + If arrGroups(g) = arrG(0) Then + arrObjGrouped(g) = Rhino.JoinArrays(arrObjGrouped(g), array(arrObj(i))) + arrObj(i) = Null + End If + End If + End If + Next + Next + End If + + + Call ArrayCullNull(arrObj) + If Ubound(arrObj) > -1 Then + For i=0 To Ubound(arrObj) + tmp = array(arrObj(i)) + arrObj(i) = tmp + Next + End If + + Dim arrToDistribute + arrToDistribute = Rhino.JoinArrays(arrObjGrouped, arrObj) + + + If Rhino.MessageBox("Distributing " & Ubound(arrToDistribute) + 1 & " Objects and/or Groups To New layers." & Chr(13) & "Do you want to proceed?", 4 + 48, "Objects and Groups to Layers") = 6 Then + + Dim N,str + N = 1 + For i=0 To Ubound(arrToDistribute) + + + + + Do + str = "OBJ_" & PadDigits(N, digits) + If Not Rhino.IsLayer(str) Then Exit Do + N = N + 1 + + Loop + + + Call Rhino.AddLayer(str, RGB(Rnd * 255, Rnd * 255, Rnd * 255), True, False) + Call Rhino.ObjectLayer(arrToDistribute(i), str) + + Next + + + + + + + End If + + + + +End Sub + +Function ArrayCullNull(ByRef arr) + 'Purges all array items that are Null + 'Returns a newly dimensioned array + 'when all items are purges the array returned is an emoty array with Ubound = -1 + Dim i, j + If IsArray(arr) Then + i = 0 : j = -1 + For i = 0 To UBound(arr) + If Not isNull(arr(i))Then + j = j + 1 + arr(j) = arr(i) + End If + Next + ReDim Preserve arr(j) + End If +End Function + + +Function PadDigits(val, digits) + 'thanks to Dale Fugier + PadDigits = Right(String(digits, "0") & val, digits) +End Function \ No newline at end of file diff --git a/ObjectsToLayerByName.py b/ObjectsToLayerByName.py new file mode 100644 index 0000000..485f62f --- /dev/null +++ b/ObjectsToLayerByName.py @@ -0,0 +1,16 @@ +import rhinoscriptsyntax as rs + + +def ObjectsToLayerByName(): + + ids = rs.NormalObjects() + if not ids: return + + for id in ids: + name = rs.ObjectName(id) + if name is not None: + if not rs.IsLayer(name): + rs.AddLayer(name) + rs.ObjectLayer(id, name) + +if __name__ == '__main__': ObjectsToLayerByName() \ No newline at end of file diff --git a/ObjectsToLayers.rvb b/ObjectsToLayers.rvb new file mode 100644 index 0000000..4e2ea48 --- /dev/null +++ b/ObjectsToLayers.rvb @@ -0,0 +1,53 @@ +Option Explicit +'Script written by willemderks.com +'Script version Tuesday, April 1, 2014 09:47:27 + +Call AllObjectsToIndividualLayers() +Sub AllObjectsToIndividualLayers() + + Dim arrObj : arrObj = Rhino.NormalObjects() + If isNull(arrObj) Then Exit Sub + + Dim digits :digits = Int(len(Cstr(Ubound(arrObj)))) + 1 + + + If Rhino.MessageBox("Distributing " & Ubound(arrObj) + 1 & " Objects To New layers." & Chr(13) & "Do you want to proceed?", 4 + 48, "Objects to Layers") = 6 Then + + Dim i,N,str + N = 1 + For i=0 To Ubound(arrObj) + + + + + Do + str = "OBJ_" & PadDigits(N, digits) + If Not Rhino.IsLayer(str) Then Exit Do + N = N + 1 + + Loop + + + Call Rhino.AddLayer(str, RGB(Rnd * 255, Rnd * 255, Rnd * 255), True, False) + Call Rhino.ObjectLayer(arrObj(i), str) + + Next + + + + + + + End If + + + + +End Sub + + + +Function PadDigits(val, digits) + 'thanks to Dale Fugier + PadDigits = Right(String(digits, "0") & val, digits) +End Function \ No newline at end of file diff --git a/OpenBlockWithDefaultApplication.py b/OpenBlockWithDefaultApplication.py new file mode 100644 index 0000000..8954d34 --- /dev/null +++ b/OpenBlockWithDefaultApplication.py @@ -0,0 +1,13 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import os + +def OpenBlockWithDefaultApplication(): + block_ids = rs.GetObjects(filter=4096, preselect=True) + if block_ids: + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_path = rs.BlockPath(block_name) + os.startfile(block_path) + +OpenBlockWithDefaultApplication() \ No newline at end of file diff --git a/OpenBlockWithRhino8WIP.py b/OpenBlockWithRhino8WIP.py new file mode 100644 index 0000000..b6f49af --- /dev/null +++ b/OpenBlockWithRhino8WIP.py @@ -0,0 +1,14 @@ +import rhinoscriptsyntax as rs +#import os +import subprocess + +def OpenBlockWithRhino8WIP(): + block_ids = rs.GetObjects(filter=4096, preselect=True) + if block_ids: + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_path = rs.BlockPath(block_name) +# os.system("C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" + " " + block_path) + subprocess.Popen(["C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe", block_path], close_fds=True) + +OpenBlockWithRhino8WIP() \ No newline at end of file diff --git a/ParentLayer.py b/ParentLayer.py new file mode 100644 index 0000000..f8bdd95 --- /dev/null +++ b/ParentLayer.py @@ -0,0 +1,7 @@ +import rhinoscriptsyntax as rs + +layers = rs.GetLayers(title="Select Layers to move") +layer_parent = rs.GetLayer(title="Select Parent") + +for layer in layers: + rs.ParentLayer(layer, layer_parent) diff --git a/PrintAllAsSeparatePages.py b/PrintAllAsSeparatePages.py new file mode 100644 index 0000000..c5716dc --- /dev/null +++ b/PrintAllAsSeparatePages.py @@ -0,0 +1,56 @@ +import Rhino +import scriptcontext as sc +import System.Drawing +import rhinoscriptsyntax as rs +import os + +folder = rs.BrowseForFolder() +titleblock = dict() + +def createSinglePDF(view, titleblock): + pdf = Rhino.FileIO.FilePdf.Create() + dpi = 300 + settings = Rhino.Display.ViewCaptureSettings(view, dpi) + settings.OutputColor = Rhino.Display.ViewCaptureSettings.ColorMode.DisplayColor + settings.DefaultPrintWidthMillimeters = 0.18 + pdf.AddPage(settings) + filename = folder + "\\" + titleblock.get("project_number","0000") + "-" + \ + titleblock.get("originator", "00") + "-" + \ + titleblock.get("zone", "00") + "-" + \ + titleblock.get("level", "00") + "-" + \ + titleblock.get("drawing_type", "00") + "-" + \ + titleblock.get("role", "0") + "-" + \ + titleblock.get("drawing_number", "00000") + "_" + \ + titleblock.get("latest_revision", "00") + " " + \ + titleblock.get("drawing_title_1", "000000000") + " " + \ + titleblock.get("drawing_title_2", "") + " " + \ + titleblock.get("drawing_title_3", "") + ".pdf" + pdf.Write(filename) + +for view in sc.doc.Views.GetPageViews(): + for object in sc.doc.Objects.FindByLayer("titleblock index-AR002"): + if type(object) == Rhino.DocObjects.TextObject and \ + view.ActiveViewportID == object.Attributes.ViewportId: + if object.Name == "Project Number": + titleblock["project_number"] = object.DisplayText + if object.Name == "Originator": + titleblock["originator"] = object.DisplayText + if object.Name == "Zone": + titleblock["zone"] = object.DisplayText + if object.Name == "Level": + titleblock["level"] = object.DisplayText + if object.Name == "Drawing Type": + titleblock["drawing_type"] = object.DisplayText + if object.Name == "Role": + titleblock["role"] = object.DisplayText + if object.Name == "Drawing Number": + titleblock["drawing_number"] = object.DisplayText + if object.Name == "Latest Revision": + titleblock["latest_revision"] = object.DisplayText + if object.Name == "Drawing Title 1": + titleblock["drawing_title_1"] = object.DisplayText + if object.Name == "Drawing Title 2": + titleblock["drawing_title_2"] = object.DisplayText + if object.Name == "Drawing Title 3": + titleblock["drawing_title_3"] = object.DisplayText + createSinglePDF(view, titleblock) \ No newline at end of file diff --git a/PrintAllAsSeparatePagesMultiprocess.py b/PrintAllAsSeparatePagesMultiprocess.py new file mode 100644 index 0000000..897867d --- /dev/null +++ b/PrintAllAsSeparatePagesMultiprocess.py @@ -0,0 +1,90 @@ +import Rhino +import scriptcontext as sc +import rhinoscriptsyntax as rs +import os +import subprocess +import System.Drawing + +def createSinglePDF(view, titleblock): + pdf = Rhino.FileIO.FilePdf.Create() + dpi = 300 + settings = Rhino.Display.ViewCaptureSettings(view, dpi) + settings.OutputColor = Rhino.Display.ViewCaptureSettings.ColorMode.DisplayColor + settings.DefaultPrintWidthMillimeters = 0.18 + pdf.AddPage(settings) + filename = folder + os.path.sep + titleblock.get("project_number","0000") + "-" + \ + titleblock.get("originator", "00") + "-" + \ + titleblock.get("zone", "00") + "-" + \ + titleblock.get("level", "00") + "-" + \ + titleblock.get("drawing_type", "00") + "-" + \ + titleblock.get("role", "0") + "-" + \ + titleblock.get("drawing_number", "00000") + "_" + \ + titleblock.get("latest_revision", "00") + " " + \ + titleblock.get("drawing_title_1", "000000000") + " " + \ + titleblock.get("drawing_title_2", "") + " " + \ + titleblock.get("drawing_title_3", "") + ".pdf" + # FIX ME - special formatting variables aka <%%> don't seem to work + # https://discourse.mcneel.com/t/displaytext-property-of-text-objects-returns-text-field-aka/150514 + pdf.Write(filename) + +def print_views(): + print_chunk_pages_str = rs.GetDocumentUserText("Print_Chunk_Pages").split("--||--") + # cast to integer in case 'if in' below didn't work for strings + print_chunk_pages = [int(i) for i in print_chunk_pages_str] + for view in sc.doc.Views.GetPageViews(): + if int(view.PageNumber) in print_chunk_pages: + for object in sc.doc.Objects.FindByLayer("titleblock index-AR002"): + if type(object) == Rhino.DocObjects.TextObject and \ + view.ActiveViewportID == object.Attributes.ViewportId: + if object.Name == "Project Number": + titleblock["project_number"] = object.DisplayText + if object.Name == "Originator": + titleblock["originator"] = object.DisplayText + if object.Name == "Zone": + titleblock["zone"] = object.DisplayText + if object.Name == "Level": + titleblock["level"] = object.DisplayText + if object.Name == "Drawing Type": + titleblock["drawing_type"] = object.DisplayText + if object.Name == "Role": + titleblock["role"] = object.DisplayText + if object.Name == "Drawing Number": + titleblock["drawing_number"] = "{0}".format(object.DisplayText) + if object.Name == "Latest Revision": + titleblock["latest_revision"] = object.DisplayText + if object.Name == "Drawing Title 1": + titleblock["drawing_title_1"] = object.DisplayText + if object.Name == "Drawing Title 2": + titleblock["drawing_title_2"] = object.DisplayText + if object.Name == "Drawing Title 3": + titleblock["drawing_title_3"] = object.DisplayText + createSinglePDF(view, titleblock) + +# get folder +folder = rs.GetDocumentData("Print", "Folder") +if folder is None: + folder = rs.BrowseForFolder(message="choose location for PDFs - " + \ + "once chosen won't prompt for it again, " + \ + "can be changed in Rhino - Options " + \ + "- Document User Text") + rs.SetDocumentData("Print", "Folder", folder) + + # prompt to save the file with the above variable in DocumentUserData + # so subprocesses can use it + answer = rs.ComboListBox(["yes", "no"], message="Need to save the file first, proceed?") + if answer == "yes": + rs.Command("-Save _Enter") + else: + raise Exception('User chose not to save the file - exiting...') + +if rs.GetDocumentUserText("Child") is None: + # number of child processes + n = 3 + for i in xrange(n): + print_chunk_pages = [view.PageNumber for view in sc.doc.Views.GetPageViews()[i::n]] + print_chunk_pages_str = [str(i) for i in print_chunk_pages] + print_chunk_pages_str_joined = "--||--".join(print_chunk_pages_str) + subprocess.Popen('start "" /min "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" /nosplash /runscript="-SetDocumentUserText Child Child -SetDocumentUserText Print_Chunk_Pages ' + print_chunk_pages_str_joined + ' -RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\PrintAllAsSeparatePagesMultiprocess.py) -Exit No" ' + chr(34) + rs.DocumentPath() + "\\" + rs.DocumentName() + chr(34), shell=True) +else: + titleblock = dict() + print_views() \ No newline at end of file diff --git a/PrintForFiles-WIP.py b/PrintForFiles-WIP.py new file mode 100644 index 0000000..33eed3f --- /dev/null +++ b/PrintForFiles-WIP.py @@ -0,0 +1,16 @@ +import rhinoscriptsyntax as rs +import subprocess +import os + +if rs.GetDocumentUserText("Child") is None: + files = rs.OpenFileNames("choose files to convert curves to lines") + for file in files: + subprocess.Popen('start "" /min "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" ' + \ + '/nosplash /runscript="-SetDocumentUserText Child Child ' + \ + '-RunPythonScript (' + __file__ + ')" ' + \ + chr(34) + file + chr(34), shell=True) +else: + rs.Command("_SelLine") + rs.Command("_Convert Output=Lines SimplifyInput=No DeleteInput=Yes OutputLayer=Input _Enter") + rs.Command("Save") + rs.Command("Exit") \ No newline at end of file diff --git a/ProximityNetworkCurves-GhPlayer.gh b/ProximityNetworkCurves-GhPlayer.gh new file mode 100644 index 0000000..df9900f Binary files /dev/null and b/ProximityNetworkCurves-GhPlayer.gh differ diff --git a/PullBlocksDown.py b/PullBlocksDown.py new file mode 100644 index 0000000..5ebc15f --- /dev/null +++ b/PullBlocksDown.py @@ -0,0 +1,34 @@ +# should check first which object is higher - at the moment meshes are always first then srfs then polysrfs + +import rhinoscriptsyntax as rs +import Rhino + +blocks = [rs.coercerhinoobject(block) for block in rs.GetObjects(message="Select blocks", preselect=True)] +targets = rs.GetObjects(message="Select Meshes, Surfaces or Polysurfaces", filter=56) + +mesh_ids = [target for target in targets if rs.IsMesh(target)] +surface_ids = [target for target in targets if rs.IsSurface(target)] +poly_surface_ids = [target for target in targets if rs.IsPolysurface(target)] + +def move_object(projected_point): + pull_vector = projected_point[0] - block.InsertionPoint + rs.MoveObject(block, pull_vector) + +for block in blocks: + if mesh_ids: + projected_point = rs.ProjectPointToMesh(block.InsertionPoint, mesh_ids, (0,0,-1)) + if projected_point: + move_object(projected_point) + if surface_ids: + projected_point = rs.ProjectPointToSurface(block.InsertionPoint, surface_ids, (0,0,-1)) + if projected_point: + move_object(projected_point) + if poly_surface_ids: + poly_surfaces = [rs.coercebrep(poly_surface_id) for poly_surface_id in poly_surface_ids] + + vector = Rhino.Geometry.Vector3d.ZAxis * -1 + ray = Rhino.Geometry.Ray3d(block.InsertionPoint, vector) + + projected_point = Rhino.Geometry.Intersect.Intersection.RayShoot(ray, poly_surfaces, 1) + if projected_point: + move_object(projected_point) \ No newline at end of file diff --git a/PullBlocksToMeshesDown.py b/PullBlocksToMeshesDown.py new file mode 100644 index 0000000..0a837f7 --- /dev/null +++ b/PullBlocksToMeshesDown.py @@ -0,0 +1,10 @@ +import rhinoscriptsyntax as rs + +blocks = [rs.coercerhinoobject(block) for block in rs.GetObjects(message="Select blocks", preselect=True)] +meshes = rs.GetObjects(message="Select Meshes", filter=32) + +for block in blocks: + projected_point = rs.ProjectPointToMesh(block.InsertionPoint, meshes, (0,0,-1)) + if projected_point: + pull_vector = projected_point[0] - block.InsertionPoint + rs.MoveObject(block, pull_vector) \ No newline at end of file diff --git a/PullBlocksToSurfacesDown.py b/PullBlocksToSurfacesDown.py new file mode 100644 index 0000000..6efbc76 --- /dev/null +++ b/PullBlocksToSurfacesDown.py @@ -0,0 +1,10 @@ +import rhinoscriptsyntax as rs + +blocks = [rs.coercerhinoobject(block) for block in rs.GetObjects(message="Select blocks", preselect=True)] +surfaces = rs.GetObjects(message="Select Surfaces", filter=8) + +for block in blocks: + projected_point = rs.ProjectPointToSurface(block.InsertionPoint, surfaces, (0,0,-1)) + if projected_point: + pull_vector = projected_point[0] - block.InsertionPoint + rs.MoveObject(block, pull_vector) \ No newline at end of file diff --git a/QuickExportToDWG-NewScheme.py b/QuickExportToDWG-NewScheme.py new file mode 100644 index 0000000..fe77119 --- /dev/null +++ b/QuickExportToDWG-NewScheme.py @@ -0,0 +1,6 @@ +import rhinoscriptsyntax as rs + +current_cplane = rs.ViewCPlane() +rs.Command("Cplane World Top") +rs.Command('Export') +rs.ViewCPlane(plane=current_cplane) \ No newline at end of file diff --git a/QuickExportToDWG.py b/QuickExportToDWG.py new file mode 100644 index 0000000..1dca3c4 --- /dev/null +++ b/QuickExportToDWG.py @@ -0,0 +1,20 @@ +import rhinoscriptsyntax as rs +from datetime import datetime +import os + +stash = rs.GetDocumentData("ACAD_Exports", "Folder") +if stash is None: + stash = rs.BrowseForFolder(message="choose location to stash temporary exports - required only once per Rhino Document") + rs.SetDocumentData("ACAD_Exports", "Folder", stash) + +if rs.DocumentName(): + document_name, document_extension = os.path.splitext(rs.DocumentName()) +else: + document_name = "Untitled" + +file_name = stash + os.path.sep + \ +datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S-%f')[:-3] + "-" + \ +document_name + ".dwg" + +rs.Command("-_Export " + chr(34) + file_name + chr(34)) + diff --git a/QuickSaveAsToDWG.py b/QuickSaveAsToDWG.py new file mode 100644 index 0000000..5a1d570 --- /dev/null +++ b/QuickSaveAsToDWG.py @@ -0,0 +1,19 @@ +import rhinoscriptsyntax as rs +from datetime import datetime +import os + +stash = rs.GetDocumentData("ACAD_SaveAs", "Folder") +if stash is None: + stash = rs.BrowseForFolder(message="choose location to stash temporary exports - required only once per Rhino Document") + rs.SetDocumentData("ACAD_SaveAs", "Folder", stash) + +document_name = "Untitled" +if rs.DocumentName(): + document_name = rs.DocumentName() + +file_name = stash + os.path.sep + \ +datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S-%f')[:-3] + "-" + \ +document_name + ".dwg" + +rs.Command("-_SaveAs " + chr(34) + file_name + chr(34)) + diff --git a/ReMapCamera.py b/ReMapCamera.py new file mode 100644 index 0000000..8ff1fd6 --- /dev/null +++ b/ReMapCamera.py @@ -0,0 +1,35 @@ +import rhinoscriptsyntax as rs +import Rhino +import scriptcontext as sc + + +def RemapView(): + + vp = sc.doc.Views.ActiveView.ActiveViewport + + plane1 = vp.ConstructionPlane() + + rc, view = Rhino.Input.RhinoGet.GetView("Select the view with the target CPlane") + + if view.ActiveViewport.Name == vp.Name: + return + + x = view.ActiveViewport + if rc!=Rhino.Commands.Result.Success: + return + + plane2 = view.ActiveViewport.ConstructionPlane() + + xform = Rhino.Geometry.Transform.PlaneToPlane(plane1, plane2) + info = Rhino.DocObjects.ViewportInfo(vp) + + info.TransformCamera(xform) + + vp.SetCameraLocation(info.CameraLocation, False) + vp.SetCameraTarget(info.TargetPoint, False) + vp.SetCameraDirection (info.CameraDirection, True) + vp.CameraUp = (info.CameraUp) + sc.doc.Views.Redraw() + +if __name__ == '__main__': + RemapView() \ No newline at end of file diff --git a/ReOpenThisFileWithoutSaving.py b/ReOpenThisFileWithoutSaving.py new file mode 100644 index 0000000..8fbdbf3 --- /dev/null +++ b/ReOpenThisFileWithoutSaving.py @@ -0,0 +1,10 @@ +import rhinoscriptsyntax as rs +import os +import scriptcontext as sc + +this_location = rs.DocumentPath() + os.path.sep + rs.DocumentName() + +if sc.doc.Modified: + rs.Command("-Open No " + chr(34) + this_location + chr(34) + " _Enter _Enter _Enter") +else: + rs.Command("-Open " + chr(34) + this_location + chr(34) + " _Enter _Enter _Enter") \ No newline at end of file diff --git a/RebuildSurfaceBorder-GhPlayer.gh b/RebuildSurfaceBorder-GhPlayer.gh new file mode 100644 index 0000000..0f22425 Binary files /dev/null and b/RebuildSurfaceBorder-GhPlayer.gh differ diff --git a/RemapCplaneCopyGUI.py b/RemapCplaneCopyGUI.py new file mode 100644 index 0000000..df05625 --- /dev/null +++ b/RemapCplaneCopyGUI.py @@ -0,0 +1,14 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +named_cplanes = [i.Name for i in list(sc.doc.NamedConstructionPlanes.GetEnumerator())] +selected_cplanes_from = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map from") +selected_cplane_to = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map to") + +current_cplane = rs.ViewCPlane() +rs.RestoreNamedCPlane(selected_cplanes_from) + +rs.Command("RemapCplane Copy=Yes Cplane " + chr(34) + selected_cplane_to + chr(34)) + +#restore previous Cplane +rs.ViewCPlane(plane=current_cplane) \ No newline at end of file diff --git a/RemapCplaneCopyMultipleGUI.py b/RemapCplaneCopyMultipleGUI.py new file mode 100644 index 0000000..dbb309e --- /dev/null +++ b/RemapCplaneCopyMultipleGUI.py @@ -0,0 +1,15 @@ +import rhinoscriptsyntax as rs + +named_cplanes = rs.NamedCPlanes() +selected_cplanes_from = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map from") +selected_cplanes_to = rs.MultiListBox(sorted(named_cplanes), "Cplane to Map to") + +current_cplane = rs.ViewCPlane() + +rs.RestoreNamedCPlane(selected_cplanes_from) + +for selected_cplane_to in selected_cplanes_to: + rs.Command("RemapCplane Copy=Yes Cplane " + chr(34) + selected_cplane_to + chr(34)) + +#restore previous Cplane +rs.ViewCPlane(plane=current_cplane) \ No newline at end of file diff --git a/RemapCplaneGUI-WIP.py b/RemapCplaneGUI-WIP.py new file mode 100644 index 0000000..5261fc7 --- /dev/null +++ b/RemapCplaneGUI-WIP.py @@ -0,0 +1,9 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +named_cplanes = [i.Name for i in list(sc.doc.NamedConstructionPlanes.GetEnumerator())] +selected_cplane_to = rs.ComboListBox(named_cplanes, "Cplane to Map to") +selected_cplane_from = rs.ComboListBox(named_cplanes, "Cplane to Map from") + +rs.ViewCPlane(plane=selected_cplane_to) +rs.Command("RemapCplane Cplane " + selected_cplane) \ No newline at end of file diff --git a/RemapCplaneGUI.py b/RemapCplaneGUI.py new file mode 100644 index 0000000..b50329d --- /dev/null +++ b/RemapCplaneGUI.py @@ -0,0 +1,31 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +#doesn't work when this section turned on - try using transforms instead: + +#selected_obj = rs.coercerhinoobject(rs.GetObject(preselect=True)) +#if str(selected_obj.ObjectType) == "InstanceReference": +# selected_obj_name = selected_obj.InstanceDefinition.Name +#else: +# selected_obj_name = "" + +named_cplanes = [i.Name for i in list(sc.doc.NamedConstructionPlanes.GetEnumerator())] +selected_cplane_from = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map from") +selected_cplane_to = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map to") + + +#doesn't work when this section turned on - try using transforms instead: +#message_from = "Name: " + selected_obj_name + "\n" + "Cplane to Map from" +#message_to = "Name: " + selected_obj_name + "\n" + "Cplane to Map to" + +#selected_cplane_from = rs.ComboListBox(sorted(named_cplanes), message=message_from) +#selected_cplane_to = rs.ComboListBox(sorted(named_cplanes), message=message_to) + + +current_cplane = rs.ViewCPlane() +rs.RestoreNamedCPlane(selected_cplane_from) + +rs.Command("RemapCplane Copy=Yes Cplane " + chr(34) + selected_cplane_to + chr(34)) + +#restore previous Cplane +rs.ViewCPlane(plane=current_cplane) \ No newline at end of file diff --git a/RemapCplaneMultipleGUI.py b/RemapCplaneMultipleGUI.py new file mode 100644 index 0000000..76f1c64 --- /dev/null +++ b/RemapCplaneMultipleGUI.py @@ -0,0 +1,32 @@ +# something's not workign - check remapcplanecopygui + +import rhinoscriptsyntax as rs + +def RemapCplaneCopyMultipleGUI(): + # if it's a block show it's name in the message title + # should be developed to take other objects' names + selected_obj = rs.coercerhinoobject(rs.GetObject(preselect=True)) + if str(selected_obj.ObjectType) == "InstanceReference": + selected_obj_name = selected_obj.InstanceDefinition.Name + else: + selected_obj_name = "" + + named_cplanes = rs.NamedCPlanes() + + selected_cplane_from = rs.ComboListBox(sorted(named_cplanes), "Name: " + selected_obj_name + "\n" + "Cplane to Map from") + selected_cplane_to = rs.ComboListBox(sorted(named_cplanes), "Name: " + selected_obj_name + "\n" + "Cplane to Map to") + + current_cplane = rs.ViewCPlane() + rs.RestoreNamedCPlane(selected_cplane_from) + + if selected_cplane_from == None or selected_cplane_to == None: + return + + # needs to find a way to take a list from a combolistbox +# for selected_cplane_to in list(selected_cplanes_to): + rs.Command("RemapCplane Copy=Yes Cplane " + chr(34) + selected_cplane_to + chr(34)) + + #restore previous Cplane + rs.ViewCPlane(plane=current_cplane) + +RemapCplaneCopyMultipleGUI() \ No newline at end of file diff --git a/RemapView.py b/RemapView.py new file mode 100644 index 0000000..0b5fd69 --- /dev/null +++ b/RemapView.py @@ -0,0 +1,26 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +vp = sc.doc.Views.ActiveView.ActiveViewport + +named_cplanes = [i.Name for i in sc.doc.NamedConstructionPlanes] +selected_cplane_name_from = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map from") +selected_cplane_name_to = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map to") + +for i in sc.doc.NamedConstructionPlanes: + if i.Name == selected_cplane_name_from: + plane1 = i.Plane + if i.Name == selected_cplane_name_to: + plane2 = i.Plane + +xform = Rhino.Geometry.Transform.PlaneToPlane(plane1, plane2) +info = Rhino.DocObjects.ViewportInfo(vp) + +info.TransformCamera(xform) + +vp.SetCameraLocation(info.CameraLocation, False) +vp.SetCameraTarget(info.TargetPoint, False) +vp.SetCameraDirection (info.CameraDirection, True) +vp.CameraUp = (info.CameraUp) +sc.doc.Views.Redraw() \ No newline at end of file diff --git a/RemapViewGUI.py b/RemapViewGUI.py new file mode 100644 index 0000000..0b5fd69 --- /dev/null +++ b/RemapViewGUI.py @@ -0,0 +1,26 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +vp = sc.doc.Views.ActiveView.ActiveViewport + +named_cplanes = [i.Name for i in sc.doc.NamedConstructionPlanes] +selected_cplane_name_from = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map from") +selected_cplane_name_to = rs.ComboListBox(sorted(named_cplanes), "Cplane to Map to") + +for i in sc.doc.NamedConstructionPlanes: + if i.Name == selected_cplane_name_from: + plane1 = i.Plane + if i.Name == selected_cplane_name_to: + plane2 = i.Plane + +xform = Rhino.Geometry.Transform.PlaneToPlane(plane1, plane2) +info = Rhino.DocObjects.ViewportInfo(vp) + +info.TransformCamera(xform) + +vp.SetCameraLocation(info.CameraLocation, False) +vp.SetCameraTarget(info.TargetPoint, False) +vp.SetCameraDirection (info.CameraDirection, True) +vp.CameraUp = (info.CameraUp) +sc.doc.Views.Redraw() \ No newline at end of file diff --git a/ReopenThisFileWithoutSaving-WIP.py b/ReopenThisFileWithoutSaving-WIP.py new file mode 100644 index 0000000..86767c2 --- /dev/null +++ b/ReopenThisFileWithoutSaving-WIP.py @@ -0,0 +1,5 @@ +# can't get it to work when file isn't saved, below commands return None +import rhinoscriptsyntax as rs + +document_location = rs.DocumentPath() + rs.DocumentName() +rs.Command("Open No " + chr(34) + document_location + chr(34)) \ No newline at end of file diff --git a/ReplaceBlockFromFile.py b/ReplaceBlockFromFile.py new file mode 100644 index 0000000..0bfe05a --- /dev/null +++ b/ReplaceBlockFromFile.py @@ -0,0 +1,19 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def ReplaceBlockFromFile(): + new_block_file_path = rs.OpenFileName() + + sc.doc.ActiveDoc.InstanceDefinitions.ModifySourceArchive( + + block_ids = rs.GetObjects(filter=4096, preselect=True) + + if block_ids: + block_paths = list() + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_path = rs.BlockPath(block_name) + block_paths.append(block_path) + rs.ComboListBox(block_paths) + +ReplaceBlockFromFile() \ No newline at end of file diff --git a/ResetTransformation.py b/ResetTransformation.py new file mode 100644 index 0000000..0952a0c --- /dev/null +++ b/ResetTransformation.py @@ -0,0 +1,20 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +def RunCommand( is_interactive ): + if sc.escape_test(False): + print "script cancelled" #do something + print "Resetting..." + objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) + if not objectIds: + print "No objects" + return False + rs.EnableRedraw(False) + for id in objectIds: + blockXForm = rs.BlockInstanceXform(id) + inverseBlockXForm = blockXForm.TryGetInverse()[1] + rs.TransformObject(id, inverseBlockXForm) + rs.SelectObjects(objectIds) + rs.EnableRedraw(True) + print "...aaand its done." + return 0 +RunCommand(True) \ No newline at end of file diff --git a/Rhino-Aliases.txt b/Rhino-Aliases.txt new file mode 100644 index 0000000..50541bf --- /dev/null +++ b/Rhino-Aliases.txt @@ -0,0 +1,162 @@ +Z '_Zoom +ZE '_Zoom _Extents +ZEA '_Zoom _All _Extents +ZS '_Zoom _Selected +ZSA '_Zoom _All _Selected +S '_Snap +O '_Ortho +P '_Planar +M ! _Move +U _Undo +POn ! _PointsOn +POff ! _PointsOff +C '_SelCrossing +W '_SelWindow +COn '_CurvatureGraph +COff '_CurvatureGraphOff +PlugInManager ! _OptionsPage _PlugIns +AdvancedDisplay ! _OptionsPage _DisplayModes +DisplayAttrsMgr ! _OptionsPage _DisplayModes +Break ! _DeleteSubCrv +SelPolysurface '_SelPolysrf +seoltSelEntireObjLayerTree -RunPythonScript "Z:\scripts\rhino\SelEntireObjLayerTree.py" +solSelObjectsLayer -RunPythonScript "Z:\scripts\rhino\SelObjectsLayer-1.py" +ConvertPlanarSrfsToHatch -RunPythonScript "Z:\scripts\rhino\ConvertPlanarSrfsToHatch-v8.py" +ChangeLayerInBlockRecursively -RunPythonScript "Z:\scripts\rhino\ChangeLayerInBlockRecursively.py" +ShowLayerInLayoutDetails -RunPythonScript "Z:\scripts\rhino\ShowLayerInLayoutDetails.py" +HideLayerInLayoutDetails -RunPythonScript "Z:\scripts\rhino\HideLayerInLayoutDetails.py" +nvstNamedViewSaveTemp -NamedView Save temp _Enter +nvrtNamedViewRestoreTemp -NamedView Restore temp _Enter LockViewport +SelLayerTree -RunPythonScript "Z:\scripts\rhino\SelLayerTree.py" +GetLayers -RunPythonScript "Z:\scripts\rhino\GetLayers.py" +xfpXrefFilePaths -RunPythonScript "Z:\scripts\rhino\XrefFilePaths.py" +xfpsXrefFilePathsSet -RunPythonScript "Z:\scripts\rhino\XrefFilePathsSet.py" +buBlockUpdate -RunPythonScript "Z:\scripts\rhino\BlockUpdate.py" _Pause _Enter _Enter _Enter _Enter _Enter _Enter _Enter _Enter +ExportObjectsToSeparateFiles -RunPythonScript "Z:\scripts\rhino\ExportObjectsToSeparateFiles.py" +OpenBlockWithDefaultApplication -RunPythonScript "Z:\scripts\rhino\OpenBlockWithDefaultApplication.py" +SearchBlockDefinitions -RunPythonScript "Z:\scripts\rhino\EtoForm_MultipleListBox_PrintAllBlockDefinitionsInDocument.py" +SearchLayers -RunPythonScript "Z:\scripts\rhino\EtoForm_MultipleListBox_PrintSelectedLayerName.py" +ResetTransformation -RunPythonScript "Z:\scripts\rhino\ResetTransformation.py" +NewNoTemplate -New None +OpenBlockWithRhino8WIP -RunPythonScript "Z:\scripts\rhino\OpenBlockWithRhino8WIP.py" +GetBlocksOnLayers -RunPythonScript "Z:\scripts\rhino\GetBlocksOnLayers.py" +ParentLayer -RunPythonScript "Z:\scripts\rhino\ParentLayer.py" +solt1SelObjLayerTree1 -RunPythonScript "Z:\scripts\rhino\SelObjLayerTree1.py" +solt2SelObjLayerTree2 -RunPythonScript "Z:\scripts\rhino\SelObjLayerTree2.py" +RebuildSurfaceBorder -GrasshopperPlayer "Z:\scripts\rhino\RebuildSurfaceBorder-GhPlayer.gh" +ProximityNetworkCurves -GrasshopperPlayer "Z:\scripts\rhino\ProximityNetworkCurves-GhPlayer.gh" +svctSetViewCplaneTop -SetView Cplane Top +xsXrefShow -RunPythonScript "Z:\scripts\rhino\XrefShow.py" +xhXrefHide -RunPythonScript "Z:\scripts\rhino\XrefHide.py" +slShowLayers -RunPythonScript "Z:\scripts\rhino\ShowLayers.py" +hlHideLayers -RunPythonScript "Z:\scripts\rhino\HideLayers.py" +XrefHideBlocks -RunPythonScript "Z:\scripts\rhino\XrefHideBlocks.py" +XrefShowBlocks -RunPythonScript "Z:\scripts\rhino\XrefShowBlocks.py" +XrefShowLayersAndBlocks -RunPythonScript "Z:\scripts\rhino\XrefShowLayersAndBlocks.py" +UpdateAllChangedBlocks -RunPythonScript "Z:\scripts\rhino\UpdateAllChangedBlocks.py" _Pause _Enter _Enter _Enter _Enter _Enter _Enter _Enter _Enter _Enter _Enter _Enter _Enter _Enter +XrefSel -RunPythonScript "Z:\scripts\rhino\XrefSel.py" +XrefShowAll -RunPythonScript "Z:\scripts\rhino\XrefShowAll.py" +PrintAllAsSeparatePages -RunPythonScript "Z:\scripts\rhino\PrintAllAsSeparatePages.py" +DeleteBlock -RunPythonScript "Z:\scripts\rhino\DeleteBlock.py" +SelBlockNames -RunPythonScript "Z:\scripts\rhino\SelBlockNames.py" +SetLayerPrintWidthsToMatchCTB -RunPythonScript "Z:\scripts\rhino\SetLayerPrintWidthsToMatchCTB.py" +SetLayerPrintWidthsToMatchCTBForFiles -RunPythonScript "Z:\scripts\rhino\SetLayerPrintWidthsToMatchCTBForFiles.py" +PrintAllAsSeparatePagesMultiprocess -RunPythonScript "Z:\scripts\rhino\PrintAllAsSeparatePagesMultiprocess.py" +ConvertV8ToV7ForFiles -RunPythonScript "Z:\scripts\rhino\ConvertV8ToV7ForFiles.py" +xtXrefToggleVisibility -RunPythonScript "Z:\scripts\rhino\XrefToggleVisibility.py" +ConvertProjectV8ToV7 -RunPythonScript "Z:\scripts\rhino\ConvertProjectV8ToV7.py" +xmpXrefModifyPath -RunPythonScript "Z:\scripts\rhino\XrefModifyPath.py" +SelObjectsLayer -RunPythonScript "Z:\scripts\rhino\SelObjectsLayer-1-mine.py" +ListAllChangedBlocks -RunPythonScript "Z:\scripts\rhino\ListAllChangedBlocks.py" +XrefChangePathWithoutRenaming -RunPythonScript "Z:\scripts\rhino\XrefChangePathWithoutRenaming.py" +GetGuidToClipboard -RunPythonScript "Z:\scripts\rhino\GetGuidToClipboard.py" +FormatTextAreaSquareMeters -RunPythonScript "Z:\scripts\rhino\FormatTextAreaSquareMeters.py" +lctcLayoutCopyToClipboard -RunPythonScript "Z:\scripts\rhino\LayoutCopyToClipboard.py" +lafcLayoutAddFromClipboard -RunPythonScript "Z:\scripts\rhino\LayoutAddFromClipboard.py" +ncgNamedCplaneGUI -RunPythonScript "Z:\scripts\rhino\NamedCplaneGUI.py" +rcgRemapCplaneGUI -RunPythonScript "Z:\scripts\rhino\RemapCplaneGUI.py" +ilIsolateLock IsolateLock +ssShowSelected ShowSelected +qetsQuickExportToDWG -RunPythonScript "Z:\scripts\rhino\QuickExportToDWG-NewScheme.py" +nncNewNamedCplane -RunPythonScript "Z:\scripts\rhino\NewNamedCplane.py" +dncDeleteNamedCplane -RunPythonScript "Z:\scripts\rhino\DeleteNamedCplane.py" +zzsSetViewCplaneZoomSelected -SetView Cplane Top '_Zoom _Selected +xiitspXrefInsertInTheSamePlace -RunPythonScript "Z:\scripts\rhino\XrefInsertInTheSamePlace.py" +xewmbpXrefExportWithModelBasePoint -RunPythonScript "Z:\scripts\rhino\XrefExportWithModelBasePoint.py" +gbnGetBlocksName -RunPythonScript "Z:\scripts\rhino\GetBlocksName.py" +gbnsGetBlocksNameSet -RunPythonScript "Z:\scripts\rhino\GetBlocksNameSet.py" +ndtNewDefaultTemplate -New Default +ndatNewDefaultA1Template -New Default-A1 +xmutXrefModifyUpdateType -RunPythonScript "Z:\scripts\rhino\XrefModifyUpdateType.py" +xcctlffXrefConvertCurvesToLinesForFiles -RunPythonScript "Z:\scripts\rhino\XrefConvertCurvesToLinesForFiles.py" +SaveAsDWGForFiles -RunPythonScript "Z:\scripts\rhino\SaveAsDWGForFiles.py" +rvRemapView -RunPythonScript "Z:\scripts\rhino\RemapView.py" +iiIsolate _Isolate +qsatsQuickSaveAsToDWG -RunPythonScript "Z:\scripts\rhino\QuickSaveAsToDWG.py" +SetLayerColorsToMatchCTBForFiles -RunPythonScript "Z:\scripts\rhino\SetLayerColorsToMatchCTBForFiles.py" +XrefExportSeparateAsDWG -RunPythonScript "Z:\scripts\rhino\XrefExportSeparateAsDWG.py" +jjLayMCur_MakeObjectLayerCurrent -RunPythonScript "Z:\scripts\rhino\jjLayMCur_MakeObjectLayerCurrent.py" +cbCurveBoolean CurveBoolean +FormatTextAreaSquareMetersWholeNumbers -RunPythonScript "Z:\scripts\rhino\FormatTextAreaSquareMetersWholeNumbers.py" +ExportDwgSchemeRGBColors _Export +ExportDwgSchemeIndexColors -Export Browse Scheme "Default-Copy" _Enter +beBlockEdit BlockEdit +ClipSelGUI -RunPythonScript "Z:\scripts\rhino\ClipSelGUI.py" +ccpChangeCameraProjection -RunPythonScript "Z:\scripts\rhino\ChangeCameraProjection.py" +ww what +pococPropertiesObjectColorObjectColorPicker -Properties Object Color Object ColorPicker _Enter _Enter +pdstPrintDisplayStateToggle -PrintDisplay State Toggle _Enter +mmMatchMaterial -MatchProperties _Pause _Pause Name=No Layer=No DisplayColor=No DisplayMode=No Linetype=No LinetypeScale=No PrintColor=No PrintWidth=No Clip=No SectionStyle=No Hyperlink=No CustomMesh=No CastsShadows=No ReceivesShadows=No IsocurveDensity=No Material=Yes CurvePiping=No Displacement=No EdgeSoftening=No ShutLining=No Thickening=No TextureMapping=No AttributeUserText=No _Enter +mpaMatchPropertiesAll -MatchProperties _Pause _Pause MatchAll _Enter +rcmgRemapCplaneMultipleGUI -RunPythonScript "Z:\scripts\rhino\RemapCplaneMultipleGUI.py" +esExtractSrf ExtractSrf +ppPlanarSrf PlanarSrf +boolDiffBooleanDifference BooleanDifference +bdBoolenDifference BooleanDifference +bumacfBooleanUnionMergeAllCoplanarFaces BooleanUnion MergeAllCoplanarFaces +hhHide Hide +jmacfJoinMergeAllCoplanarFaces Join MergeAllCoplanarFaces +poclPropertiesObjectColorLayer -Properties Object Color Layer _Enter _Enter +xselXrefSel -RunPythonScript "Z:\scripts\rhino\XrefSel.py" +mv0MoveVertical000 move vertical _Pause 0,0,0 +cisCopyInplaceSellast Copy InPlace SelLast +r3Rotate3D Rotate3D +ChangeMaterial -RunPythonScript "Z:\scripts\rhino\ChangeMaterial.py" +cmChangeMaterial -RunPythonScript "Z:\scripts\rhino\ChangeMaterial.py" +nvgNamedViewGUI -RunPythonScript "Z:\scripts\rhino\NamedViewGUI.py" +scibSelColorInBlocks -RunPythonScript "Z:\scripts\rhino\SelColorInBlocks.py" +smibSelMaterialInBlocks -RunPythonScript "Z:\scripts\rhino\SelMaterialInBlocks.py" +bsBooleanSplit BooleanSplit +CurrentLayer -Layer Current List _Enter +vvLineVertical Line Vertical +eiExtractIsocurve ExtractIsocurve +evtiExportViewportsToImages -RunPythonScript "Z:\scripts\rhino\ExportViewportsToImages.py" +scpivSelClippingPlaneInViewport SelClippingPlaneInViewport +sltSelLayerTree SelLayerTree +bcBlendCrv BlendCrv _Pause _Pause _Enter +vfbVrayShowVFB VrayShowVFB +vsaeVrayShowAssetEditor vrayShowAssetEditor +bboxBoundingBox BoundingBox +ReOpenThisFileWithoutSaving -RunPythonScript "Z:\scripts\rhino\ReOpenThisFileWithoutSaving.py" +macsMergeAllCoplanarSurfaces MergeAllCoplanarSurfaces +mlMatchLayer MatchLayer +ectExtendCameraTarget -RunPythonScript "Z:\scripts\rhino\ExtendCameraTarget.py" +pbdPullBlocksDown -RunPythonScript "Z:\scripts\rhino\PullBlocksDown.py" +XrefRemoveDWG -RunPythonScript "Z:\scripts\rhino\XrefRemoveDWG.py" +sonSetObjectsName -RunPythonScript "Z:\scripts\rhino\SetObjectsName.py" +scpnSetClippingPlanesName -RunPythonScript "Z:\scripts\rhino\SetClippingPlanesName.py" +gnGetNames -RunPythonScript "Z:\scripts\rhino\GetNames.py" +gaonGetAllObjectsNames -RunPythonScript "Z:\scripts\rhino\GetAllObjectsNames.py" +usUnlockSelected UnlockSelected +dacpDisableAllClippingPlanes -RunPythonScript "Z:\scripts\rhino\DisableAllClippingPlanes.py" +pocPropertiesObjectColor -Properties Object Color Object ColorPicker _Enter _Enter +XrefChangePath -RunPythonScript "Z:\scripts\rhino\XrefChangePath.py" +mmMaxViewport MaxViewport +rccgRemapCplaneCopyGUI -RunPythonScript "Z:\scripts\rhino\RemapCplaneCopyGUI.py" +rvgRemapViewGUI -RunPythonScript "Z:\scripts\rhino\RemapViewGUI.py" +bbeBlockEdit BlockEdit +rccgRemapCplaneCopyMultipleGUI -RunPythonScript "Z:\scripts\rhino\RemapCplaneCopyMultipleGUI.py" +BatchMake2D -RunPythonScript "Z:\scripts\rhino\BatchMake2D.py" +sovnSetObjectViewportsName -RunPythonScript "Z:\scripts\rhino\SetObjectViewportsName.py" +atAbsoluteTolerance -RunPythonScript "Z:\scripts\rhino\AbsoluteTolerance.py" +gavpGetActiveViewportParameters -RunPythonScript "Z:\scripts\rhino\GetActiveViewportParameters.py" diff --git a/SafeLayout.rhp b/SafeLayout.rhp new file mode 100644 index 0000000..ee349d3 Binary files /dev/null and b/SafeLayout.rhp differ diff --git a/SaveAsDWGForFiles.py b/SaveAsDWGForFiles.py new file mode 100644 index 0000000..8433c35 --- /dev/null +++ b/SaveAsDWGForFiles.py @@ -0,0 +1,19 @@ +import rhinoscriptsyntax as rs +import subprocess +import os + +if rs.GetDocumentUserText("Child") is None: + dwg_folder_path = rs.BrowseForFolder("Choose folder to save DWGs into") + files = rs.OpenFileNames("Choose files to save as DWG") + for file in files: + subprocess.Popen('start "" /min "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" ' + \ + '/nosplash /runscript="-SetDocumentUserText Child Child ' + \ + '-SetDocumentUserText Export_DWG_folder_path ' + \ + chr(34) + chr(34) + dwg_folder_path + chr(34) + chr(34) + ' ' + \ + '-RunPythonScript (' + __file__ + ') -Exit No" ' + \ + chr(34) + file + chr(34), shell=True) +else: + dwg_folder_path_child = rs.GetDocumentUserText("Export_DWG_folder_path") + rs.Command("-SaveAs " + chr(34) + dwg_folder_path_child + "\\" + \ + os.path.splitext(rs.DocumentName())[0] + ".dwg" + chr(34)) + rs.Command("-Exit No") \ No newline at end of file diff --git a/SelBlockLinked-CANT-FIND-A-WAY-TO-FILTER-OUT.py b/SelBlockLinked-CANT-FIND-A-WAY-TO-FILTER-OUT.py new file mode 100644 index 0000000..1b2954f --- /dev/null +++ b/SelBlockLinked-CANT-FIND-A-WAY-TO-FILTER-OUT.py @@ -0,0 +1,12 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + + +a=sc.doc.Objects.GetObjectList(Rhino.DocObjects.ObjectType.InstanceReference) + +a[0].SourceArchive + +#temp= [] +#for i in a: +# if i.SourceArchive \ No newline at end of file diff --git a/SelBlockNames.py b/SelBlockNames.py new file mode 100644 index 0000000..e301778 --- /dev/null +++ b/SelBlockNames.py @@ -0,0 +1,17 @@ +import rhinoscriptsyntax as rs +import itertools + +block_names = rs.BlockNames() + +# rs.BlockContainerCount excludes nested blocks, but doesn't work +# in externally linked blocks - WARNING! ">" character can be used +# on filenames in Linux +block_names_not_nested = [block_name for block_name in block_names + if rs.BlockContainerCount(block_name) == 0 + and ">" not in block_name] + +selected_blocks = rs.MultiListBox(sorted(block_names_not_nested)) +block_instances = [rs.BlockInstances(selected_block) for selected_block in selected_blocks] +# https://stackoverflow.com/a/953097 - unpacking lists in python +block_instances_unpacked = list(itertools.chain(*block_instances)) +rs.SelectObjects(block_instances_unpacked) \ No newline at end of file diff --git a/SelClipEnabled.py b/SelClipEnabled.py new file mode 100644 index 0000000..d38d394 --- /dev/null +++ b/SelClipEnabled.py @@ -0,0 +1,26 @@ +# not finished - can't seem to find a way to get ViewIds +# on the clipping planes +# https://developer.rhino3d.com/api/RhinoCommon/html/P_Rhino_Render_ChangeQueue_ClippingPlane_ViewIds.htm + +import Rhino +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def SelClipEnabled(): + selection_settings = Rhino.DocObjects.ObjectEnumeratorSettings() + selection_settings.ObjectTypeFilter = Rhino.DocObjects.ObjectType.ClipPlane + clip_planes_iterator = sc.doc.Objects.GetObjectList(selection_settings) + + # getobjectlist methods yields an iterator that gets exhausted + # line below converts it into an immutable list + clip_planes = list(clip_planes_iterator) + + clip_planes_enabled = [clip_plane.Name for clip_plane in clip_planes + if clip_plane.Name is not None] + + selected_clip_planes_guids = [clip_plane.Id for clip_plane in clip_planes + if clip_plane.Name in selected_clip_planes] + + rs.SelectObjects(selected_clip_planes_guids) + +SelClipEnabled() \ No newline at end of file diff --git a/SelColorInBlocks.py b/SelColorInBlocks.py new file mode 100644 index 0000000..9cb2c8b --- /dev/null +++ b/SelColorInBlocks.py @@ -0,0 +1,40 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +selected_colors = list() + +# get colors of blocks' sub-objects +# looping through all objects due to: https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/12 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + sub_object_ids = object.GetSelectedSubObjects() + if sub_object_ids: + for sub_object_id in sub_object_ids: + sub_object = object.InstanceDefinition.GetObjects()[sub_object_id.Index] + sub_object_color = sub_object.Attributes.DrawColor(sc.doc) + selected_colors.append(sub_object_color) + +# get colors of other objects +for object_id in rs.SelectedObjects(): + object = rs.coercerhinoobject(object_id) + object_color = object.Attributes.DrawColor(sc.doc) + selected_colors.append(object_color) + +def _SelColor(object): + for sub_object_id, sub_object in enumerate(object.InstanceDefinition.GetObjects()): + if type(sub_object) == Rhino.DocObjects.InstanceObject: + _SelColor(sub_object) + if sub_object.Attributes.DrawColor(sc.doc) in selected_colors: + object.SelectSubObject(Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.InstanceDefinitionPart, sub_object_id), True, True, True) + +# select objects by color recursively, even though doesn't work for nested blocks +# https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/13 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + _SelColor(object) + if object.Attributes.DrawColor(sc.doc) in selected_colors: + object.Select(on=True) + +rs.EnableRedraw() +rs.Redraw() diff --git a/SelEntireObjLayerTree.py b/SelEntireObjLayerTree.py new file mode 100644 index 0000000..915a8a7 --- /dev/null +++ b/SelEntireObjLayerTree.py @@ -0,0 +1,32 @@ +import rhinoscriptsyntax as rs +import Rhino +""" +Gets selected objects' layers,then selects all objects on those layers plus all +other layers in the layer tree recursively - i.e. selects objects on layers both +"up" and "down" the tree. Script by Mitch Heynick 17.12.18""" + +def GetTopLevelLayer(layer): + parent=rs.ParentLayer(layer) + if parent: layer=GetTopLevelLayer(parent) + return layer + +def SelObjsLayerAndSubs(layer): + rs.ObjectsByLayer(layer, True) + subLayers = rs.LayerChildren(layer) + if(subLayers): + #layer has one or more sublayers + for sLayer in subLayers: + #recurse + SelObjsLayerAndSubs(sLayer) + +def SelEntireObjLayerTree(): + objs=rs.GetObjects("Select objects",preselect=True,select=True) + if not objs: return + layers=set() + for obj in objs: + layers.add(GetTopLevelLayer(rs.ObjectLayer(obj))) + rs.EnableRedraw(False) + for layer in layers: + SelObjsLayerAndSubs(layer) + +SelEntireObjLayerTree() \ No newline at end of file diff --git a/SelHatchPattern-TRY-ME.py b/SelHatchPattern-TRY-ME.py new file mode 100644 index 0000000..c2048fc --- /dev/null +++ b/SelHatchPattern-TRY-ME.py @@ -0,0 +1,55 @@ +import Rhino +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def SelHatchPattern(): + ids = rs.ObjectsByType(65536, state=1) + if not ids: + print "No hatches found" + return + + h = sc.doc.HatchPatterns + selIdx = None + names = [item.Name for item in h] + + go = Rhino.Input.Custom.GetObject() + go.GeometryFilter = Rhino.DocObjects.ObjectType.Hatch + go.SetCommandPrompt("Select hatch objects or type a hatch pattern name inside double quotes.") + go.AddOption("ListPatterns") + + go.AcceptString(True) + + rc = go.GetMultiple(1,0) + + if go.CommandResult() != Rhino.Commands.Result.Success: + return + if rc == Rhino.Input.GetResult.Option: + selNames = rs.CheckListBox([(name,False) for name in names]) + if not selNames: return + selNames = [item[0].lower() for item in selNames if item[1]] + + elif rc == Rhino.Input.GetResult.String: + nameString = go.StringResult() + if not nameString: return + nameList= nameString.Split(",") + selNames= [name.lower() for name in nameList] + + elif rc == Rhino.Input.GetResult.Object: + selIdx = [go.Object(n).Object().HatchGeometry.PatternIndex for n in range (go.ObjectCount)] + + if selIdx is None: + selIdx = [] + for n in range(h.Count): + if h[n].Name.lower() in selNames: + selIdx.append(h[n].Index) + + indices = [rs.coercerhinoobject(id).HatchGeometry.PatternIndex for id in ids] + + rs.EnableRedraw(False) + for n in range(len(indices)): + if indices[n] in selIdx: + rs.SelectObject(ids[n]) + rs.EnableRedraw(True) + + +if __name__ == '__main__':SelHatchPattern() \ No newline at end of file diff --git a/SelLastN-FINISH-ME.py b/SelLastN-FINISH-ME.py new file mode 100644 index 0000000..d2850c2 --- /dev/null +++ b/SelLastN-FINISH-ME.py @@ -0,0 +1,13 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + + +aa=rs.LastObject() +#a=rs.GetObject(preselect=True) +b=rs.coercerhinoobject(aa) + +c=sc.doc.Objects.AllObjectsSince(b.RuntimeSerialNumber) + +print(type(c)) + +#[i.Select(True) for i in c[:2]] diff --git a/SelLayerTree.py b/SelLayerTree.py new file mode 100644 index 0000000..4d44582 --- /dev/null +++ b/SelLayerTree.py @@ -0,0 +1,32 @@ +import rhinoscriptsyntax as rs +import Rhino +"""Script written by Mitch Heynick version 02.07.15 +Selects objects on chosen layers plus all nested sublayers +GetLayers() method is not yet implemented for Mac Rhino - +so choice is limited to a single layer with GetLayer() for the moment""" +def OnMac(): + return Rhino.Runtime.HostUtils.RunningOnOSX + +def SelObjsLayerAndSubs(layer): + rs.ObjectsByLayer(layer, True) + subLayers = rs.LayerChildren(layer) + if(subLayers): + #layer has one or more sublayers + for sLayer in subLayers: + #recurse + SelObjsLayerAndSubs(sLayer) + +def SelLayerTree(): + if OnMac(): + layer=rs.GetLayer("Select layer for objects") + if not layer: return + layers=[layer] + else: + layers = rs.GetLayers("Select layers for objects") + if not(layers): return + rs.EnableRedraw(False) + rs.UnselectAllObjects() + for pLayer in layers: + SelObjsLayerAndSubs(pLayer) + +SelLayerTree() \ No newline at end of file diff --git a/SelMaterialInBlocks.py b/SelMaterialInBlocks.py new file mode 100644 index 0000000..9d80009 --- /dev/null +++ b/SelMaterialInBlocks.py @@ -0,0 +1,42 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +selected_materials = list() + +# get materials of blocks' sub-objects +# looping through all objects due to: https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/12 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + sub_object_ids = object.GetSelectedSubObjects() + if sub_object_ids: + for sub_object_id in sub_object_ids: + sub_object = object.InstanceDefinition.GetObjects()[sub_object_id.Index] + if sub_object.RenderMaterial: + sub_object_material = sub_object.RenderMaterial.Id + selected_materials.append(sub_object_material) + +# get materials of other objects +for object_id in rs.SelectedObjects(): + object = rs.coercerhinoobject(object_id) + if object.RenderMaterial: + object_material = object.RenderMaterial.Id + selected_materials.append(object_material) + +def _SelMaterial(object): + for sub_object_id, sub_object in enumerate(object.InstanceDefinition.GetObjects()): + if type(sub_object) == Rhino.DocObjects.InstanceObject: + _SelMaterial(sub_object) + if sub_object.RenderMaterial and sub_object.RenderMaterial.Id in selected_materials: + object.SelectSubObject(Rhino.Geometry.ComponentIndex(Rhino.Geometry.ComponentIndexType.InstanceDefinitionPart, sub_object_id), True, True, True) + +# select objects by material recursively, even though doesn't work for nested blocks +# https://discourse.mcneel.com/t/let-selcolor-command-select-objects-inside-blocks/151883/13 +for object in sc.doc.Objects: + if type(object) == Rhino.DocObjects.InstanceObject: + _SelMaterial(object) + if object.RenderMaterial and object.RenderMaterial.Id in selected_materials: + object.Select(on=True) + +rs.EnableRedraw() +rs.Redraw() \ No newline at end of file diff --git a/SelObjLayerTree1.py b/SelObjLayerTree1.py new file mode 100644 index 0000000..9f892a3 --- /dev/null +++ b/SelObjLayerTree1.py @@ -0,0 +1,31 @@ +import rhinoscriptsyntax as rs +import Rhino +""" +Gets selected objects' layers,then selects all objects on those layers plus all +other layers in the layer tree recursively - i.e. selects objects on layers both +"up" and "down" the tree. Script by Mitch Heynick 17.12.18""" + +def GetTopLevelLayer(layer): + parent=rs.ParentLayer(layer) + return parent + +def SelObjsLayerAndSubs(layer): + rs.ObjectsByLayer(layer, True) + subLayers = rs.LayerChildren(layer) + if(subLayers): + #layer has one or more sublayers + for sLayer in subLayers: + #recurse + SelObjsLayerAndSubs(sLayer) + +def SelEntireObjLayerTree(): + objs=rs.GetObjects("Select objects",preselect=True,select=True) + if not objs: return + layers=set() + for obj in objs: + layers.add(GetTopLevelLayer(rs.ObjectLayer(obj))) + rs.EnableRedraw(False) + for layer in layers: + SelObjsLayerAndSubs(layer) + +SelEntireObjLayerTree() \ No newline at end of file diff --git a/SelObjLayerTree2.py b/SelObjLayerTree2.py new file mode 100644 index 0000000..55a0c89 --- /dev/null +++ b/SelObjLayerTree2.py @@ -0,0 +1,32 @@ +import rhinoscriptsyntax as rs +import Rhino +""" +Gets selected objects' layers,then selects all objects on those layers plus all +other layers in the layer tree recursively - i.e. selects objects on layers both +"up" and "down" the tree. Script by Mitch Heynick 17.12.18""" + +def GetTopLevelLayer(layer): + parent=rs.ParentLayer(layer) + parent2=rs.ParentLayer(parent) + return parent2 + +def SelObjsLayerAndSubs(layer): + rs.ObjectsByLayer(layer, True) + subLayers = rs.LayerChildren(layer) + if(subLayers): + #layer has one or more sublayers + for sLayer in subLayers: + #recurse + SelObjsLayerAndSubs(sLayer) + +def SelEntireObjLayerTree(): + objs=rs.GetObjects("Select objects",preselect=True,select=True) + if not objs: return + layers=set() + for obj in objs: + layers.add(GetTopLevelLayer(rs.ObjectLayer(obj))) + rs.EnableRedraw(False) + for layer in layers: + SelObjsLayerAndSubs(layer) + +SelEntireObjLayerTree() \ No newline at end of file diff --git a/SelObjectsLayer-1-mine.py b/SelObjectsLayer-1-mine.py new file mode 100644 index 0000000..3725964 --- /dev/null +++ b/SelObjectsLayer-1-mine.py @@ -0,0 +1,16 @@ +import scriptcontext as sc +import rhinoscriptsyntax as rs + +ids = rs.SelectedObjects() + +layers = [rs.ObjectLayer(id) for id in ids] +layers = list(set(layers)) + +for layer in layers: + parent = rs.ParentLayer(layer) + while parent is not None: + rs.ExpandLayer(parent, True) + parent = rs.ParentLayer(parent) + +layers = [sc.doc.Layers.FindByFullPath(layer, -1) for layer in layers] +sc.doc.Layers.Select(layers, True) diff --git a/SelObjectsLayer-2-clement.py b/SelObjectsLayer-2-clement.py new file mode 100644 index 0000000..2254e7f --- /dev/null +++ b/SelObjectsLayer-2-clement.py @@ -0,0 +1,15 @@ +import Rhino +import scriptcontext +import rhinoscriptsyntax as rs + +def SelectObjectLayer(): + + obj_id = rs.GetObject("Select Object", False, False) + if not obj_id: return + + rh_obj = rs.coercerhinoobject(obj_id, True, True) + layer_index = rh_obj.Attributes.LayerIndex + + scriptcontext.doc.Layers.Select([layer_index], True) + +SelectObjectLayer() diff --git a/SelParallelPlanes-TEST-ME.py b/SelParallelPlanes-TEST-ME.py new file mode 100644 index 0000000..21188e3 --- /dev/null +++ b/SelParallelPlanes-TEST-ME.py @@ -0,0 +1,37 @@ +import Rhino +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def SelParallelPlanes(): + def filter_planar( rhino_object, geometry, component_index): + + if geometry.Faces[0].UnderlyingSurface().TryGetPlane()[0]: + return True + return False + + id = rs.GetObject('Select a planar surface', filter =8, preselect=True, custom_filter=filter_planar) + if not id: return + + geo = rs.coercegeometry(id) + rc, plane = geo.Faces[0].UnderlyingSurface().TryGetPlane() + vecDir = plane.ZAxis + + ids = rs.ObjectsByType(8,state=1) + if not ids or len(ids) == 1: + print('No more planar surfaces found') + return + + rs.EnableRedraw(False) + count = 0 + for id in ids: + geo = rs.coercegeometry(id) + rc, plane = geo.Faces[0].UnderlyingSurface().TryGetPlane() + + if rc: + if plane.ZAxis.IsParallelTo(vecDir) != 0: + rs.SelectObject(id) + count += 1 + print(str(count-1) + ' parallel planes selected.') + rs.EnableRedraw(True) + +if __name__ == '__main__':SelParallelPlanes() \ No newline at end of file diff --git a/SelectByCentralNormal.rvb b/SelectByCentralNormal.rvb new file mode 100644 index 0000000..a68bea1 --- /dev/null +++ b/SelectByCentralNormal.rvb @@ -0,0 +1,29 @@ +-runscript ( +sub SelectByCentralNormal + +Dim arrObjects, strObject +objs = Rhino.AllObjects +If IsArray(objs) Then +Rhino.UnselectAllObjects() +For Each obj In objs + + +' SURFACE CASE +if Rhino.IsSurface(obj) then +surf = obj +UV = Rhino.SurfaceParameter (surf , Array(0.5,0.5)) +normal = Rhino.SurfaceNormal (surf , UV) +cameraLocs = Rhino.ViewCameraTarget() +vector = Rhino.VectorCreate(cameraLocs(1),cameraLocs(0)) +angle = Rhino.VectorAngle(vector,normal) +if angle>90 then +Rhino.SelectObject(surf) +End If +End If + + +Next +Rhino.ZoomSelected() +End If +End sub +SelectByCentralNormal diff --git a/SelectObjectLayer.py b/SelectObjectLayer.py new file mode 100644 index 0000000..3c1c4f4 --- /dev/null +++ b/SelectObjectLayer.py @@ -0,0 +1,15 @@ +import Rhino +import scriptcontext +import rhinoscriptsyntax as rs + +def SelectObjectLayer(): + + obj_id = rs.GetObjects(preselect=True) + if not obj_id: return + + rh_obj = rs.coercerhinoobject(obj_id, True, True) + layer_index = rh_obj.Attributes.LayerIndex + + scriptcontext.doc.Layers.Select([layer_index], True) + +SelectObjectLayer() \ No newline at end of file diff --git a/SetClippingPlanesName.py b/SetClippingPlanesName.py new file mode 100644 index 0000000..c1ce322 --- /dev/null +++ b/SetClippingPlanesName.py @@ -0,0 +1,21 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def SetClippingPlanesName(): + selected_objects = rs.SelectedObjects() + if selected_objects == None: return + + objects = {i.Name for i in sc.doc.Objects if type(i) == Rhino.DocObjects.ClippingPlaneObject} + + if len(selected_objects) == 1: + message = rs.coercerhinoobject(selected_objects[0]).Name + else: + message="Set Objects Name" + + name = rs.ComboListBox(list(objects), message=message, title="All Named Objects") + if name == None: return + + rs.ObjectName(selected_objects, name) + +SetClippingPlanesName() \ No newline at end of file diff --git a/SetLayerColorsToMatchCTB.py b/SetLayerColorsToMatchCTB.py new file mode 100644 index 0000000..53abca2 --- /dev/null +++ b/SetLayerColorsToMatchCTB.py @@ -0,0 +1,98 @@ +import rhinoscriptsyntax as rs +import re +import System.Drawing.Color + +def SetAllLayerColors(): + for layer in rs.LayerNames(): + layer_name_re = re.search("AR[0-9]+", layer) + if layer_name_re: + ctb_layer_code = layer_name_re.group() + + layer_color_str = ctb_colors[ctb_layer_code] + layer_color = System.Drawing.Color.FromArgb(int(layer_color_str.split(",")[0]), + int(layer_color_str.split(",")[1]), + int(layer_color_str.split(",")[2])) + rs.LayerColor(layer, color=layer_color) + +#codes extracted from template files +ctb_colors={ +"0": "255,255,255", +"AR000": "128,128,128", +"AR001": "192,192,192", +"AR002": "255,255,255", +"AR003": "0,255,255", +"AR004": "192,192,192", +"AR006": "255,127,0", +"AR007": "255,0,0", +"AR008": "255,0,0", +"AR009": "255,127,0", +"AR031": "128,128,128", +"AR035": "128,128,128", +"AR036": "255,0,63", +"AR042": "0,0,0", +"AR061": "255,255,255", +"AR062": "255,0,0", +"AR063": "255,255,255", +"AR070": "0,255,255", +"AR071": "128,128,128", +"AR075": "128,128,128", +"AR169": "0,255,255", +"AR211": "255,0,0", +"AR214": "0,255,255", +"AR216": "0,255,0", +"AR219": "0,255,255", +"AR221": "255,0,0", +"AR229": "128,128,128", +"AR231": "128,128,128", +"AR232": "255,255,0", +"AR237": "255,0,0", +"AR240": "0,255,0", +"AR241": "0,255,0", +"AR272": "255,0,0", +"AR277": "0,255,0", +"AR281": "255,0,0", +"AR282": "0,255,0", +"AR283": "0,255,0", +"AR310": "128,128,128", +"AR314": "0,255,255", +"AR315": "0,255,0", +"AR318": "0,255,255", +"AR319": "255,255,0", +"AR324": "0,255,0", +"AR325": "0,255,0", +"AR340": "0,255,255", +"AR351": "0,255,0", +"AR371": "0,255,0", +"AR413": "255,0,0", +"AR414": "0,255,255", +"AR420": "0,255,0", +"AR431": "192,192,192", +"AR439": "0,255,0", +"AR471": "128,128,128", +"AR520": "128,128,128", +"AR522": "128,128,128", +"AR525": "255,0,0", +"AR610": "255,0,0", +"AR611": "0,255,255", +"AR630": "0,255,255", +"AR640": "128,128,128", +"AR661": "0,255,0", +"AR664": "0,255,255", +"AR680": "128,128,128", +"AR683": "0,255,255", +"AR711": "0,255,255", +"AR731": "0,255,255", +"AR741": "128,128,128", +"AR783": "0,255,255", +"AR785": "128,128,128", +"AR900": "255,255,0", +"AR901": "255,0,0", +"AR902": "255,255,255", +"AR904": "128,128,128", +"AR905": "128,128,128", +"AR906": "128,128,128", +"AR907": "0,255,255", +"AR908": "0,255,255", +"AR910": "128,128,128"} + +SetAllLayerColors() diff --git a/SetLayerColorsToMatchCTBForFiles.py b/SetLayerColorsToMatchCTBForFiles.py new file mode 100644 index 0000000..fbfb44b --- /dev/null +++ b/SetLayerColorsToMatchCTBForFiles.py @@ -0,0 +1,20 @@ +import rhinoscriptsyntax as rs +import os +import subprocess +import System + +dlg = System.Windows.Forms.OpenFileDialog() +dlg.Multiselect = True +if dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK: + selected_files = dlg.FileNames + +#for selected_file in selected_files: +# subprocess.Popen(["C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe", "/nosplash", +# '/runscript="-RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\SetLayerColorsToMatchCTB.py) save exit"', +# selected_file], close_fds=True, shell=True) + +for i, selected_file in enumerate(selected_files): + with open(os.environ['TEMP'] + "\\madness" + str(i) + ".cmd", "w") as madness: + madness.write('start "" /min "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" /nosplash /runscript="-RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\SetLayerColorsToMatchCTB.py) save exit" ' + chr(34) + selected_file + chr(34)) + madness.flush() + subprocess.Popen(madness.name, shell=True) diff --git a/SetLayerPrintWidthsToMatchCTB.py b/SetLayerPrintWidthsToMatchCTB.py new file mode 100644 index 0000000..a584711 --- /dev/null +++ b/SetLayerPrintWidthsToMatchCTB.py @@ -0,0 +1,94 @@ +import rhinoscriptsyntax as rs +import re + + +def SetAllLayerPrintWidths(): + for layer in rs.LayerNames(): + layer_name_re = re.search("AR[0-9]+", layer) + if layer_name_re: + ctb_layer_code = layer_name_re.group() + rs.LayerPrintWidth(layer, width=ctb_printwidths[ctb_layer_code]) + + +# codes extracted from template files +ctb_printwidths = { + "AR000": 0.05, + "AR001": 0.05, + "AR002": 0.05, + "AR003": 0.1, + "AR004": 0.05, + "AR006": 0.05, + "AR007": 0.18, + "AR008": 0.05, + "AR009": 0.05, + "AR031": 0.1, + "AR035": 0.05, + "AR036": 0.05, + "AR042": 0.05, + "AR061": 0.05, + "AR062": 0.05, + "AR063": 0.05, + "AR070": 0.1, + "AR071": 0.05, + "AR075": 0.05, + "AR169": 0.1, + "AR211": 0.18, + "AR214": 0.1, + "AR216": 0.15, + "AR219": 0.1, + "AR221": 0.18, + "AR229": 0.05, + "AR231": 0.05, + "AR232": 0.25, + "AR237": 0.18, + "AR240": 0.15, + "AR241": 0.15, + "AR272": 0.18, + "AR277": 0.15, + "AR281": 0.18, + "AR282": 0.15, + "AR283": 0.15, + "AR310": 0.05, + "AR314": 0.1, + "AR315": 0.15, + "AR318": 0.1, + "AR319": 0.25, + "AR324": 0.15, + "AR325": 0.15, + "AR340": 0.1, + "AR351": 0.15, + "AR371": 0.15, + "AR413": 0.18, + "AR414": 0.1, + "AR420": 0.15, + "AR431": 0.05, + "AR439": 0.15, + "AR471": 0.05, + "AR520": 0.05, + "AR522": 0.05, + "AR525": 0.18, + "AR610": 0.18, + "AR611": 0.1, + "AR630": 0.1, + "AR640": 0.05, + "AR661": 0.15, + "AR664": 0.1, + "AR680": 0.05, + "AR683": 0.1, + "AR711": 0.1, + "AR731": 0.1, + "AR741": 0.05, + "AR783": 0.1, + "AR785": 0.05, + "AR900": 0.25, + "AR901": 2.00, + "AR902": 0.05, + "AR904": 0.05, + "AR905": 0.05, + "AR906": 0.05, + "AR907": 0.1, + "AR908": 0.1, + "AR910": 0.05, +} + +SetAllLayerPrintWidths() diff --git a/SetLayerPrintWidthsToMatchCTBForFiles.py b/SetLayerPrintWidthsToMatchCTBForFiles.py new file mode 100644 index 0000000..a087ead --- /dev/null +++ b/SetLayerPrintWidthsToMatchCTBForFiles.py @@ -0,0 +1,20 @@ +import rhinoscriptsyntax as rs +import os +import subprocess +import System + +dlg = System.Windows.Forms.OpenFileDialog() +dlg.Multiselect = True +if dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK: + selected_files = dlg.FileNames + +#for selected_file in selected_files: +# subprocess.Popen(["C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe", "/nosplash", +# '/runscript="-RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\SetLayerPrintWidthsToMatchCTB.py) save exit"', +# selected_file], close_fds=True, shell=True) + +for i, selected_file in enumerate(selected_files): + with open(os.environ['TEMP'] + "\\madness" + str(i) + ".cmd", "w") as madness: + madness.write('start /min "" "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" /nosplash /runscript="-RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\SetLayerPrintWidthsToMatchCTB.py) save exit" ' + chr(34) + selected_file + chr(34)) + madness.flush() + subprocess.Popen(madness.name, shell=True) diff --git a/SetObjectViewportsName.py b/SetObjectViewportsName.py new file mode 100644 index 0000000..f5da2e2 --- /dev/null +++ b/SetObjectViewportsName.py @@ -0,0 +1,21 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +from Rhino.DocObjects import DetailViewObject + +def SetObjectsName(): + selected_objects = rs.SelectedObjects() + if selected_objects == None: return + + objects_viewports = {i.Name for i in sc.doc.Objects if type(i) == DetailViewObject} + + if len(selected_objects) == 1: + message = rs.coercerhinoobject(selected_objects[0]).Name + else: + message="Set Objects (Viewports) Name" + + name = rs.ComboListBox(sorted(list(objects_viewports)), message=message, title="All Named Objects") + if name == None: return + + rs.ObjectName(selected_objects, name) + +SetObjectsName() \ No newline at end of file diff --git a/SetObjectsName.py b/SetObjectsName.py new file mode 100644 index 0000000..5523191 --- /dev/null +++ b/SetObjectsName.py @@ -0,0 +1,22 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +#import Rhino + +def SetObjectsName(): + selected_objects = rs.SelectedObjects() + if selected_objects == None: return + + objects = {i.Name for i in sc.doc.Objects} + #b = [i for i in sc.doc.Objects if type(i) == Rhino.DocObjects.ClippingPlaneObject] + + if len(selected_objects) == 1: + message = rs.coercerhinoobject(selected_objects[0]).Name + else: + message="Set Objects Name" + + name = rs.ComboListBox(sorted(list(objects)), message=message, title="All Named Objects") + if name == None: return + + rs.ObjectName(selected_objects, name) + +SetObjectsName() \ No newline at end of file diff --git a/ShowLayerInLayoutDetails.py b/ShowLayerInLayoutDetails.py new file mode 100644 index 0000000..d1c7796 --- /dev/null +++ b/ShowLayerInLayoutDetails.py @@ -0,0 +1,41 @@ +__author__ = "Alasdair Mott" +__version__ = "2018.03.15" +# modified 24.11.22 to replace CheckListBox with MultiListBox + +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def hideLayerInLayouts(page): + details = Rhino.Display.RhinoPageView.GetDetailViews(page) + + for i, detail in enumerate(details): + + #rs.CurrentDetail(pageName, detail) + detailId = detail.Id + + for layerString in layers: + + layer_idx = sc.doc.Layers.FindByFullPath(layerString, True) + layer = sc.doc.Layers.FindIndex(layer_idx) + Rhino.DocObjects.Layer.SetPerViewportVisible(layer, detailId, True) + +pageName = rs.CurrentView() +pageNames = rs.ViewNames(True, 1) +pages = sc.doc.Views.GetPageViews() + +""" User Input """ +layers = rs.GetLayers() + +if pageNames and layers: + pageNamesHide = rs.MultiListBox(pageNames, "Layouts to turn off Layer In", "Hide Layer In Layout") + +""" Iterate Pages """ +rs.EnableRedraw(False) +if layers: + if pageNamesHide: + for page in pages: + hideLayerInLayouts(page) +rs.EnableRedraw(True) +rs.Redraw() + diff --git a/ShowLayers.py b/ShowLayers.py new file mode 100644 index 0000000..0154612 --- /dev/null +++ b/ShowLayers.py @@ -0,0 +1,8 @@ +import rhinoscriptsyntax as rs + +def ShowLayers(): + layers=rs.GetLayers() + for layer in layers: + rs.LayerVisible(layer, visible=True) + +ShowLayers() \ No newline at end of file diff --git a/SwitchView.py b/SwitchView.py new file mode 100644 index 0000000..5638a8d --- /dev/null +++ b/SwitchView.py @@ -0,0 +1,6 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +scriptcontext.doc.Views.ActiveView +rs.CurrentView() +a \ No newline at end of file diff --git a/Tags-ClearTagObjects.py b/Tags-ClearTagObjects.py new file mode 100644 index 0000000..f7d74b2 --- /dev/null +++ b/Tags-ClearTagObjects.py @@ -0,0 +1,12 @@ +import rhinoscriptsyntax as rs + +def ClearTagObjects(): + + ids = rs.AllObjects() + + if not ids: return + + for id in ids: + rs.SetUserText(id, 'FileTag', "") + +ClearTagObjects() \ No newline at end of file diff --git a/Tags-SelTagObjects.py b/Tags-SelTagObjects.py new file mode 100644 index 0000000..1cea5a8 --- /dev/null +++ b/Tags-SelTagObjects.py @@ -0,0 +1,22 @@ +import rhinoscriptsyntax as rs + +def SelTagObjects(): + + file = rs.DocumentName() + + if not file:return + + tagString = file.split(".")[0] + + ids = rs.NormalObjects() + + if not ids: return + rs.UnselectAllObjects() + rs.EnableRedraw(False) + + for id in ids: + if rs.SetUserText(id, 'FileTag', tagString): + rs.SelectObject(id) + rs.EnableRedraw(True) + +SelTagObjects() \ No newline at end of file diff --git a/Tags-TagObjects.py b/Tags-TagObjects.py new file mode 100644 index 0000000..dfc9143 --- /dev/null +++ b/Tags-TagObjects.py @@ -0,0 +1,18 @@ +import rhinoscriptsyntax as rs + +def TagObjects(): + + file = rs.DocumentName() + + if not file:return + + tagString = file.split(".")[0] + + ids = rs.AllObjects() + + if not ids: return + + for id in ids: + rs.SetUserText(id, 'FileTag', tagString) + +TagObjects() \ No newline at end of file diff --git a/TestMake2D.py b/TestMake2D.py new file mode 100644 index 0000000..5833184 --- /dev/null +++ b/TestMake2D.py @@ -0,0 +1,68 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def TestMake2D(): + msg="Select objects to draw" + #check object collections + objIDs=rs.GetObjects(msg,8+16,preselect=True) + if not objIDs: return + + objs=[sc.doc.Objects.Find(objID).Geometry for objID in objIDs] + +# #Artificially set a top view projection (no viewport needed) +# bb=rs.BoundingBox(objIDs) +# rot_pt=(bb[0]+bb[6])/2 +# ht=bb[4].Z-bb[0].Z +# z_vec=Rhino.Geometry.Vector3d.ZAxis +# vp=Rhino.Display.RhinoViewport() +# vp.ChangeToParallelProjection(True) +# vp.SetCameraTarget(rot_pt-(z_vec*ht),False) +# vp.SetCameraLocation(rot_pt+z_vec*ht,False) + + #get Top viewport from standard Rhino views + for view in sc.doc.Views.GetStandardRhinoViews(): + if view.MainViewport.Name=="Top": + vp=view.MainViewport + break + + #Create the Make2D drawing + hdp=Rhino.Geometry.HiddenLineDrawingParameters() + [hdp.AddGeometry(obj,"") for obj in objs] + hdp.SetViewport(vp) + hld=Rhino.Geometry.HiddenLineDrawing.Compute(hdp,True) + if hld: + crvs=[] + vis=Rhino.Geometry.HiddenLineDrawingSegment.Visibility.Visible + hid=Rhino.Geometry.HiddenLineDrawingSegment.Visibility.Hidden + proj=Rhino.Geometry.HiddenLineDrawingSegment.Visibility.Projecting + dup=Rhino.Geometry.HiddenLineDrawingSegment.Visibility.Duplicate + clip=Rhino.Geometry.HiddenLineDrawingSegment.Visibility.Clipped + uns=Rhino.Geometry.HiddenLineDrawingSegment.Visibility.Unset + + rs.EnableRedraw(False) + for i,seg in enumerate(hld.Segments): + print "Segment {} Type:{}".format(i,seg.SegmentVisibility) + if not seg.SegmentVisibility == vis: + crvID=sc.doc.Objects.AddCurve(seg.CurveGeometry) + rs.ObjectLayer(crvID,"Visible") + elif seg.SegmentVisibility == hid: + crvID=sc.doc.Objects.AddCurve(seg.CurveGeometry) + rs.ObjectLayer(crvID,"Hidden") + elif seg.SegmentVisibility == proj: + crvID=sc.doc.Objects.AddCurve(seg.CurveGeometry) + rs.ObjectLayer(crvID,"Projecting") + elif seg.SegmentVisibility == dup: + crvID=sc.doc.Objects.AddCurve(seg.CurveGeometry) + rs.ObjectLayer(crvID,"Duplicate") + elif seg.SegmentVisibility == clip: + crvID=sc.doc.Objects.AddCurve(seg.CurveGeometry) + rs.ObjectLayer(crvID,"Clipped") + elif seg.SegmentVisibility == uns: + crvID=sc.doc.Objects.AddCurve(seg.CurveGeometry) + rs.ObjectLayer(crvID,"Unset") + else: + crvID=sc.doc.Objects.AddCurve(seg.CurveGeometry) + rs.ObjectLayer(crvID,"Unknown") + sc.doc.Views.Redraw() +TestMake2D() diff --git a/UpdateAllChangedBlocks.py b/UpdateAllChangedBlocks.py new file mode 100644 index 0000000..4e52dd7 --- /dev/null +++ b/UpdateAllChangedBlocks.py @@ -0,0 +1,14 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def UpdateAllChangedBlocks(): + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + block_definitions_list = list(block_definitions) + linked_blocks=[i for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False and + ">" not in i.Name] + for linked_block in linked_blocks: + if rs.BlockStatus(linked_block.Name) == 1: + sc.doc.InstanceDefinitions.RefreshLinkedBlock(linked_block) + +UpdateAllChangedBlocks() \ No newline at end of file diff --git a/XrefChangePath.py b/XrefChangePath.py new file mode 100644 index 0000000..25b6138 --- /dev/null +++ b/XrefChangePath.py @@ -0,0 +1,27 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import System +import Rhino +import os + +block_guids = rs.GetObjects(preselect=True) + +block_names = list() +for block_guid in block_guids: + block_names.append(rs.BlockInstanceName(block_guid)) + +dlg = System.Windows.Forms.OpenFileDialog() +dlg.Title = " and ".join(block_names) +if dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK: + file_location = dlg.FileName + +for block_guid in block_guids: + block_obj = rs.coercerhinoobject(block_guid) + block_idx = block_obj.InstanceDefinition.Index + + sc.doc.InstanceDefinitions.ModifySourceArchive(block_idx, + file_location, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + 1) + block_file_name = os.path.basename(os.path.splitext(block_obj.InstanceDefinition.SourceArchive)[0]) + rs.RenameBlock(block_obj.InstanceDefinition.Name, block_file_name) \ No newline at end of file diff --git a/XrefChangePathList-WIP.py b/XrefChangePathList-WIP.py new file mode 100644 index 0000000..e42b13d --- /dev/null +++ b/XrefChangePathList-WIP.py @@ -0,0 +1,15 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def XrefChangePath(): + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + block_definitions_list = list(block_definitions) + linked_blocks=[i.Name for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False and + ">" not in i.Name] + selected_blocks = rs.MultiListBox(linked_blocks) + for linked_block in selected_blocks: + test=rs.OpenFileName("test") +# sc.doc.InstanceDefinitions.ModifySourceArchive( + +XrefChangePath() \ No newline at end of file diff --git a/XrefChangePathWithoutRenaming.py b/XrefChangePathWithoutRenaming.py new file mode 100644 index 0000000..9ab6a0f --- /dev/null +++ b/XrefChangePathWithoutRenaming.py @@ -0,0 +1,25 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import System +import Rhino +import os + +block_guids = rs.GetObjects(preselect=True) + +block_names = list() +for block_guid in block_guids: + block_names.append(rs.BlockInstanceName(block_guid)) + +dlg = System.Windows.Forms.OpenFileDialog() +dlg.Title = " and ".join(block_names) +if dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK: + file_location = dlg.FileName + +for block_guid in block_guids: + block_obj = rs.coercerhinoobject(block_guid) + block_idx = block_obj.InstanceDefinition.Index + + sc.doc.InstanceDefinitions.ModifySourceArchive(block_idx, + file_location, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + 1) \ No newline at end of file diff --git a/XrefConvertCurvesToLinesForFiles.py b/XrefConvertCurvesToLinesForFiles.py new file mode 100644 index 0000000..33eed3f --- /dev/null +++ b/XrefConvertCurvesToLinesForFiles.py @@ -0,0 +1,16 @@ +import rhinoscriptsyntax as rs +import subprocess +import os + +if rs.GetDocumentUserText("Child") is None: + files = rs.OpenFileNames("choose files to convert curves to lines") + for file in files: + subprocess.Popen('start "" /min "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" ' + \ + '/nosplash /runscript="-SetDocumentUserText Child Child ' + \ + '-RunPythonScript (' + __file__ + ')" ' + \ + chr(34) + file + chr(34), shell=True) +else: + rs.Command("_SelLine") + rs.Command("_Convert Output=Lines SimplifyInput=No DeleteInput=Yes OutputLayer=Input _Enter") + rs.Command("Save") + rs.Command("Exit") \ No newline at end of file diff --git a/XrefCreateProxies.py b/XrefCreateProxies.py new file mode 100644 index 0000000..a40e6dd --- /dev/null +++ b/XrefCreateProxies.py @@ -0,0 +1,15 @@ +import rhinoscriptsyntax as rs +import subprocess +import os + +if rs.GetDocumentUserText("Child") is None: + files = rs.OpenFileNames("choose files to create proxies") + for file in files: + subprocess.Popen('start "" /min "C:\\Program Files\\Rhino 8 WIP\\System\\Rhino.exe" /nosplash /runscript="-SetDocumentUserText Child Child -RunPythonScript (G:\\0000 CAD LIBRARY\\Scripts\\rhino\\CreateProxies.py) -Exit No" ' + chr(34) + file + chr(34), shell=True) +else: + rs.Command("SelSmall 4000") + rs.Command("SelBlockInstance") + rs.Command("Delete") + rs.Command("-Purge _Enter") + rs.Command("-SaveAs " + chr(34) + rs.DocumentPath() + "\\proxy\\" + os.path.splitext(rs.DocumentName())[0] + "-proxy" + chr(34)) + rs.Command("Exit") \ No newline at end of file diff --git a/XrefExportSeparateAsDWG.py b/XrefExportSeparateAsDWG.py new file mode 100644 index 0000000..33ed77b --- /dev/null +++ b/XrefExportSeparateAsDWG.py @@ -0,0 +1,45 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import itertools +import os + +folder = rs.BrowseForFolder("Select Folder to export xref instances") + +# allow for custom prefix in file name +# if doesn't exist in the list append it and save it in the Document's User Text +file_name_prefix_list_str = rs.GetDocumentUserText("File-Name-Prefix-List") +if file_name_prefix_list_str is None: + file_name_prefix_list_str = rs.ComboListBox(["None"], message="Add File Name Prefix") + rs.SetDocumentUserText("File-Name-Prefix-List", file_name_prefix_list_str) + selected_prefix = "" +else: + file_name_prefix_list = file_name_prefix_list_str.split(",") + selected_prefix = rs.ComboListBox(file_name_prefix_list) + file_name_prefix_list_new = list(set(file_name_prefix_list.append(selected_prefix))) + file_name_prefix_list_new_str = ",".join(file_name_prefix_list_new) + rs.SetDocumentUserText("File-Name-Prefix-List", file_name_prefix_list_str) + +block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) +block_definitions_list = list(block_definitions) + +# rs.BlockContainerCount excludes nested blocks, but doesn't work +# in externally linked blocks - WARNING! ">" character can be used +# on filenames in Linux +xrefs = [i.Name for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False + and rs.BlockContainerCount(i.Name) == 0 + and ">" not in i.Name] + +selected_xrefs = rs.MultiListBox(sorted(xrefs)) +xref_instances = [rs.BlockInstances(selected_xref) for selected_xref in selected_xrefs] +# https://stackoverflow.com/a/953097 - unpacking lists in python +xref_instances_unpacked = list(itertools.chain(*xref_instances)) +for xref_instance in xref_instances_unpacked: + rs.Command("SelNone") + rs.SelectObject(xref_instance) + block_name = rs.coercerhinoobject(xref_instance).InstanceDefinition.Name +# document_name = "Untitled" +# if rs.DocumentName(): +# document_name, document_ext = os.path.splitext(rs.DocumentName()) + rs.Command("-Export " + chr(34) + folder + os.path.sep + selected_prefix + block_name + ".dwg" + chr(34)) + rs.Command("SelNone") \ No newline at end of file diff --git a/XrefExportWithModelBasePoint.py b/XrefExportWithModelBasePoint.py new file mode 100644 index 0000000..1954b64 --- /dev/null +++ b/XrefExportWithModelBasePoint.py @@ -0,0 +1,42 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino +import os + +# get folder +xref_export_stash = rs.GetDocumentData("Xrefs", "Folder") +if xref_export_stash is None: + xref_export_stash = rs.BrowseForFolder(message="choose location to stash xrefs - once chosen won't prompt for it again") + rs.SetDocumentData("Xrefs", "Folder", xref_export_stash) + +# get doc name but check if it's an "Untitled" aka not yet saved document +rhino_doc_name = rs.DocumentName() +if rhino_doc_name: + rhino_doc_name = os.path.splitext(rhino_doc_name)[0] + +# get prefix +xref_prefix_set_str = rs.GetDocumentData("Xrefs", "Prefix") + +if xref_prefix_set_str: + xref_prefix_set = set(xref_prefix_set_str.split("--||--")) +else: + xref_prefix_set = set() + xref_prefix_set.add("0") + +selected_xref_prefix = rs.ComboListBox(sorted(xref_prefix_set), message="Choose Xref Prefix") +xref_prefix_set.add(selected_xref_prefix) +rs.SetDocumentData("Xrefs", "Prefix", "--||--".join(xref_prefix_set)) + +# get Cplane +named_cplanes = sc.doc.NamedConstructionPlanes +selected_cplane = rs.ComboListBox([i.Name for i in named_cplanes], "Named CPlanes") + +xref_file_name = xref_export_stash + os.path.sep + rhino_doc_name + " - " + selected_xref_prefix + " - " + selected_cplane + +for named_cplane in named_cplanes: + if named_cplane.Name == selected_cplane: + sc.doc.ModelBasepoint = named_cplane.Plane.Origin + +rs.Command("-Export " + chr(34) + xref_file_name + chr(34)) + +sc.doc.ModelBasepoint = Rhino.Geometry.Point3d(0,0,0) \ No newline at end of file diff --git a/XrefFilePaths.py b/XrefFilePaths.py new file mode 100644 index 0000000..e94de48 --- /dev/null +++ b/XrefFilePaths.py @@ -0,0 +1,14 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +block_ids = rs.GetObjects(filter=4096, preselect=True) + +if block_ids: + block_paths = list() + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_path = rs.BlockPath(block_name) + block_paths.append(block_path) + Rhino.UI.Dialogs.ShowTextDialog("\n".join(block_paths), "Selected Block Paths") +# rs.ComboListBox(block_paths) \ No newline at end of file diff --git a/XrefFilePathsSet.py b/XrefFilePathsSet.py new file mode 100644 index 0000000..c8cc4dd --- /dev/null +++ b/XrefFilePathsSet.py @@ -0,0 +1,17 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +def GetPathSetBlocks(): + block_ids = rs.GetObjects(filter=4096, preselect=True) + + if block_ids: + block_paths = list() + for block_id in block_ids: + block_name = rs.BlockInstanceName(block_id) + block_path = rs.BlockPath(block_name) + block_paths.append(block_path) + Rhino.UI.Dialogs.ShowTextDialog("\n".join(sorted(set(list(block_paths)))), "Selected Block Paths") +# rs.ComboListBox(sorted(set(list(block_paths)))) + +GetPathSetBlocks() \ No newline at end of file diff --git a/XrefHide.py b/XrefHide.py new file mode 100644 index 0000000..48c89a5 --- /dev/null +++ b/XrefHide.py @@ -0,0 +1,12 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +layer_names = rs.LayerNames() +xref_layers = [i.replace('xref-AR000::', '') for i in layer_names if "xref-AR000::" in i] +selected_layers = rs.MultiListBox(xref_layers) + +for layer_short_name in selected_layers: + layer_index = sc.doc.Layers.FindByFullPath('xref-AR000::' + layer_short_name, + notFoundReturnValue=False) + layer_object = sc.doc.Layers.FindIndex(layer_index) + layer_object.IsVisible = False \ No newline at end of file diff --git a/XrefHideBlocks.py b/XrefHideBlocks.py new file mode 100644 index 0000000..f666ea6 --- /dev/null +++ b/XrefHideBlocks.py @@ -0,0 +1,16 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def XrefHideBlocks(): + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + block_definitions_list = list(block_definitions) + linked_blocks=[i.Name for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False and + ">" not in i.Name] + selection_names = rs.MultiListBox(sorted(linked_blocks)) + selection_instances = list() + for selection_name in selection_names: + selection_instances.append(rs.BlockInstances(selection_name)) + rs.HideObjects(selection_instances) + +XrefHideBlocks() \ No newline at end of file diff --git a/XrefInsertInTheSamePlace.py b/XrefInsertInTheSamePlace.py new file mode 100644 index 0000000..e4c0a6b --- /dev/null +++ b/XrefInsertInTheSamePlace.py @@ -0,0 +1,21 @@ +# takes into account blocks that have ModelBasePoint other than 0,0,0 +# 22.11.22 updated to insert other formats than 3dm +# you forgot to restore the previous CPlane +import Rhino +import rhinoscriptsyntax as rs +import os + +xref_file_names = rs.OpenFileNames() +for xref_file_name in xref_file_names: + xref_file_basename, xref_file_ext = os.path.splitext(xref_file_name) + if xref_file_ext == ".3dm": + model_base_point = Rhino.FileIO.File3dm.Read(xref_file_name).Settings.ModelBasepoint + rs.Command('-Cplane World Top -Insert LinkMode=Link LinkStyle=Reference "{}" Block {} 1 0'.format(xref_file_name, str(model_base_point))) + rs.Command('SelLast') + if xref_file_ext == ".dwg": + rs.Command('-Cplane World Top -Insert LinkMode=Link LinkStyle=Reference "{}" Block _Enter 0,0,0 1 0'.format(xref_file_name)) + rs.Command('SelLast') + # not tested yet - use with caution + else: + rs.Command('-Cplane World Top -Insert LinkMode=Link LinkStyle=Reference "{}" Block 0,0,0 1 0'.format(xref_file_name)) + rs.Command('SelLast') \ No newline at end of file diff --git a/XrefLayersHideAndBlocks.py b/XrefLayersHideAndBlocks.py new file mode 100644 index 0000000..87b82f6 --- /dev/null +++ b/XrefLayersHideAndBlocks.py @@ -0,0 +1,17 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def GetXrefLayers(): + a=rs.LayerNames() + b=[i.replace('xref-AR000::', '') for i in a if "xref-AR000::" in i] + c=rs.MultiListBox(b) + return c + +def XrefLayersHideAndBlocks(): + layers = GetXrefLayers() + for layer in layers: + objects = sc.doc.Objects.FindByLayer(layer) + rs.HideObjects(objects) + rs.LayerVisible(layer, visible=False) + +XrefLayersHideAndBlocks() \ No newline at end of file diff --git a/XrefModifyPath.py b/XrefModifyPath.py new file mode 100644 index 0000000..25b6138 --- /dev/null +++ b/XrefModifyPath.py @@ -0,0 +1,27 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import System +import Rhino +import os + +block_guids = rs.GetObjects(preselect=True) + +block_names = list() +for block_guid in block_guids: + block_names.append(rs.BlockInstanceName(block_guid)) + +dlg = System.Windows.Forms.OpenFileDialog() +dlg.Title = " and ".join(block_names) +if dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK: + file_location = dlg.FileName + +for block_guid in block_guids: + block_obj = rs.coercerhinoobject(block_guid) + block_idx = block_obj.InstanceDefinition.Index + + sc.doc.InstanceDefinitions.ModifySourceArchive(block_idx, + file_location, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + 1) + block_file_name = os.path.basename(os.path.splitext(block_obj.InstanceDefinition.SourceArchive)[0]) + rs.RenameBlock(block_obj.InstanceDefinition.Name, block_file_name) \ No newline at end of file diff --git a/XrefModifyPathList-WIP.py b/XrefModifyPathList-WIP.py new file mode 100644 index 0000000..e42b13d --- /dev/null +++ b/XrefModifyPathList-WIP.py @@ -0,0 +1,15 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def XrefChangePath(): + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + block_definitions_list = list(block_definitions) + linked_blocks=[i.Name for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False and + ">" not in i.Name] + selected_blocks = rs.MultiListBox(linked_blocks) + for linked_block in selected_blocks: + test=rs.OpenFileName("test") +# sc.doc.InstanceDefinitions.ModifySourceArchive( + +XrefChangePath() \ No newline at end of file diff --git a/XrefModifyPathWithoutRenaming.py b/XrefModifyPathWithoutRenaming.py new file mode 100644 index 0000000..9ab6a0f --- /dev/null +++ b/XrefModifyPathWithoutRenaming.py @@ -0,0 +1,25 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import System +import Rhino +import os + +block_guids = rs.GetObjects(preselect=True) + +block_names = list() +for block_guid in block_guids: + block_names.append(rs.BlockInstanceName(block_guid)) + +dlg = System.Windows.Forms.OpenFileDialog() +dlg.Title = " and ".join(block_names) +if dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK: + file_location = dlg.FileName + +for block_guid in block_guids: + block_obj = rs.coercerhinoobject(block_guid) + block_idx = block_obj.InstanceDefinition.Index + + sc.doc.InstanceDefinitions.ModifySourceArchive(block_idx, + file_location, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + 1) \ No newline at end of file diff --git a/XrefModifyUpdateType-without-editing.py b/XrefModifyUpdateType-without-editing.py new file mode 100644 index 0000000..0bbffb7 --- /dev/null +++ b/XrefModifyUpdateType-without-editing.py @@ -0,0 +1,54 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino +import time + +block_id = rs.GetObject(filter=4096, preselect=True) +block_definition = rs.coercerhinoobject(block_id).InstanceDefinition + +update_type = rs.ComboListBox(["Embedded", "Linked"], "Change Block Update Type to:") +if update_type == "Embedded" and \ +block_definition.UpdateType == Rhino.DocObjects.InstanceDefinitionUpdateType.Linked: + if rs.SetUserText(block_id, key="SourceArchive", + value=block_definition.SourceArchive): + sc.doc.InstanceDefinitions.ModifySourceArchive(block_definition.Index, + block_definition.SourceArchive, + Rhino.DocObjects.InstanceDefinitionUpdateType.Static, + quiet=1) + rs.SelectObject(block_id) + rs.Command("BlockEdit") + +# use Static instead of Embedded +# Rhino will default to Static even if Embedded was set in ModifySourceArchive function +# https://github.com/mcneel/rhinocommon/blob/master/dotnet/rhino/rhinosdkinstance.cs#L23 +if update_type == "Linked" and \ +block_definition.UpdateType == Rhino.DocObjects.InstanceDefinitionUpdateType.Static: + # you can't store user text on block definition + # and I'd rather not use the description field + # so store it on the first block instance user clicked and + # iterate through all of them (hoping that wasn't deleted) + # don't want to store it in document, because the block may be renamed/reinserted + # https://discourse.mcneel.com/t/can-you-add-user-text-to-block-definition/150530 + for block_instance_id in rs.BlockInstances(block_definition.Name): + block_instance_source_archive = rs.GetUserText(block_instance_id, key="SourceArchive") + if block_instance_source_archive: + model_base_point = Rhino.FileIO.File3dm.Read(block_instance_source_archive).Settings.ModelBasepoint + sc.doc.ModelBasepoint = model_base_point + rs.Command("-Cplane World Top") + rs.Command("-Insert File=No " + chr(34) + block_definition.Name + chr(34) + " Block " + str(model_base_point) + " 1 0") + rs.Command("SelLast") + rs.Command("Explode") + rs.Command("-Export " + chr(34) + block_instance_source_archive + chr(34)) + rs.Command("Delete") + sc.doc.ModelBasepoint = Rhino.Geometry.Point3d(0,0,0) + + sc.doc.InstanceDefinitions.ModifySourceArchive(block_definition.Index, + block_instance_source_archive, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + quiet=1) + + rs.SelectObject(block_id) + + # use the first one found - problably should + # add extra checks in case there are multiple paths + break \ No newline at end of file diff --git a/XrefModifyUpdateType.py b/XrefModifyUpdateType.py new file mode 100644 index 0000000..0bbffb7 --- /dev/null +++ b/XrefModifyUpdateType.py @@ -0,0 +1,54 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino +import time + +block_id = rs.GetObject(filter=4096, preselect=True) +block_definition = rs.coercerhinoobject(block_id).InstanceDefinition + +update_type = rs.ComboListBox(["Embedded", "Linked"], "Change Block Update Type to:") +if update_type == "Embedded" and \ +block_definition.UpdateType == Rhino.DocObjects.InstanceDefinitionUpdateType.Linked: + if rs.SetUserText(block_id, key="SourceArchive", + value=block_definition.SourceArchive): + sc.doc.InstanceDefinitions.ModifySourceArchive(block_definition.Index, + block_definition.SourceArchive, + Rhino.DocObjects.InstanceDefinitionUpdateType.Static, + quiet=1) + rs.SelectObject(block_id) + rs.Command("BlockEdit") + +# use Static instead of Embedded +# Rhino will default to Static even if Embedded was set in ModifySourceArchive function +# https://github.com/mcneel/rhinocommon/blob/master/dotnet/rhino/rhinosdkinstance.cs#L23 +if update_type == "Linked" and \ +block_definition.UpdateType == Rhino.DocObjects.InstanceDefinitionUpdateType.Static: + # you can't store user text on block definition + # and I'd rather not use the description field + # so store it on the first block instance user clicked and + # iterate through all of them (hoping that wasn't deleted) + # don't want to store it in document, because the block may be renamed/reinserted + # https://discourse.mcneel.com/t/can-you-add-user-text-to-block-definition/150530 + for block_instance_id in rs.BlockInstances(block_definition.Name): + block_instance_source_archive = rs.GetUserText(block_instance_id, key="SourceArchive") + if block_instance_source_archive: + model_base_point = Rhino.FileIO.File3dm.Read(block_instance_source_archive).Settings.ModelBasepoint + sc.doc.ModelBasepoint = model_base_point + rs.Command("-Cplane World Top") + rs.Command("-Insert File=No " + chr(34) + block_definition.Name + chr(34) + " Block " + str(model_base_point) + " 1 0") + rs.Command("SelLast") + rs.Command("Explode") + rs.Command("-Export " + chr(34) + block_instance_source_archive + chr(34)) + rs.Command("Delete") + sc.doc.ModelBasepoint = Rhino.Geometry.Point3d(0,0,0) + + sc.doc.InstanceDefinitions.ModifySourceArchive(block_definition.Index, + block_instance_source_archive, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + quiet=1) + + rs.SelectObject(block_id) + + # use the first one found - problably should + # add extra checks in case there are multiple paths + break \ No newline at end of file diff --git a/XrefRemoveDWG.py b/XrefRemoveDWG.py new file mode 100644 index 0000000..11cab77 --- /dev/null +++ b/XrefRemoveDWG.py @@ -0,0 +1,5 @@ +import scriptcontext as sc + +for i in sc.doc.InstanceDefinitions: + if i.SourceArchive and ".dwg" in i.SourceArchive: + sc.doc.InstanceDefinitions.Purge(i.Index) \ No newline at end of file diff --git a/XrefSel.py b/XrefSel.py new file mode 100644 index 0000000..0e6a69b --- /dev/null +++ b/XrefSel.py @@ -0,0 +1,21 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import itertools + +def XrefSel(): + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + block_definitions_list = list(block_definitions) + + # rs.BlockContainerCount excludes nested blocks, but doesn't work + # in externally linked blocks - WARNING! ">" character can be used + # on filenames in Linux + xrefs = [i.Name for i in block_definitions_list + if i.SourceArchive and + rs.BlockContainerCount(i.Name) == 0 + and ">" not in i.Name] + + selected_xref = rs.ComboListBox(sorted(xrefs)) + xref_instances = rs.BlockInstances(selected_xref) + rs.SelectObjects(xref_instances) + +XrefSel() \ No newline at end of file diff --git a/XrefSelMultiple.py b/XrefSelMultiple.py new file mode 100644 index 0000000..8f35db7 --- /dev/null +++ b/XrefSelMultiple.py @@ -0,0 +1,23 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc +import itertools + +def XrefSel(): + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + block_definitions_list = list(block_definitions) + + # rs.BlockContainerCount excludes nested blocks, but doesn't work + # in externally linked blocks - WARNING! ">" character can be used + # on filenames in Linux + xrefs = [i.Name for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False + and rs.BlockContainerCount(i.Name) == 0 + and ">" not in i.Name] + + selected_xrefs = rs.MultiListBox(sorted(xrefs)) + xref_instances = [rs.BlockInstances(selected_xref) for selected_xref in selected_xrefs] + # https://stackoverflow.com/a/953097 - unpacking lists in python + xref_instances_unpacked = list(itertools.chain(*xref_instances)) + rs.SelectObjects(xref_instances_unpacked) + +XrefSel() \ No newline at end of file diff --git a/XrefShow.py b/XrefShow.py new file mode 100644 index 0000000..779bfbd --- /dev/null +++ b/XrefShow.py @@ -0,0 +1,11 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +layer_names = rs.LayerNames() +xref_layers = [i.replace('xref-AR000::', '') for i in layer_names if "xref-AR000::" in i] +selected_layers = rs.MultiListBox(xref_layers) + +for layer in selected_layers: + layer_index = sc.doc.Layers.FindByFullPath('xref-AR000::' + layer, notFoundReturnValue=False) + layer_object = sc.doc.Layers.FindIndex(layer_index) + layer_object.IsVisible = True \ No newline at end of file diff --git a/XrefShowAll.py b/XrefShowAll.py new file mode 100644 index 0000000..d1aff4f --- /dev/null +++ b/XrefShowAll.py @@ -0,0 +1,13 @@ +#check if rewriting in RhinoCommon would be faster +#seems now that toggling layers' visibility is much faster + +import rhinoscriptsyntax as rs + +def XrefShowAll(): + all_layers = rs.LayerNames() + xref_layers = [layer.replace('xref-AR000::', '') for layer in all_layers + if "xref-AR000::" in layer] + for xref_layer in xref_layers: + rs.LayerVisible(xref_layer, visible=True) + +XrefShowAll() \ No newline at end of file diff --git a/XrefShowBlocks.py b/XrefShowBlocks.py new file mode 100644 index 0000000..0285484 --- /dev/null +++ b/XrefShowBlocks.py @@ -0,0 +1,16 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def XrefShowBlocks(): + block_definitions = sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True) + block_definitions_list = list(block_definitions) + linked_blocks=[i.Name for i in block_definitions_list + if rs.IsBlockEmbedded(i.Name)==False and + ">" not in i.Name] + selection_names = rs.MultiListBox(sorted(linked_blocks)) + selection_instances = list() + for selection_name in selection_names: + selection_instances.append(rs.BlockInstances(selection_name)) + rs.ShowObjects(selection_instances) + +XrefShowBlocks() \ No newline at end of file diff --git a/XrefShowLayersAndBlocks.py b/XrefShowLayersAndBlocks.py new file mode 100644 index 0000000..5368b17 --- /dev/null +++ b/XrefShowLayersAndBlocks.py @@ -0,0 +1,17 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +def GetXrefLayers(): + a=rs.LayerNames() + b=[i.replace('xref-AR000::', '') for i in a if "xref-AR000::" in i] + c=rs.MultiListBox(b) + return c + +def XrefShowLayersAndBlocks(): + layers = GetXrefLayers() + for layer in layers: + objects = sc.doc.Objects.FindByLayer(layer) + rs.LayerVisible(layer, visible=True) + rs.ShowObjects(objects) + +XrefShowLayersAndBlocks() \ No newline at end of file diff --git a/XrefToggleVisibility.py b/XrefToggleVisibility.py new file mode 100644 index 0000000..32ea21e --- /dev/null +++ b/XrefToggleVisibility.py @@ -0,0 +1,13 @@ +import rhinoscriptsyntax as rs +import scriptcontext as sc + +layer_names = rs.LayerNames() +xref_layers = [i.replace('xref-AR000::', '') for i in layer_names if "xref-AR000::" in i] +selected_layers = rs.MultiListBox(xref_layers) + +for layer_short_name in selected_layers: + layer_index = sc.doc.Layers.FindByFullPath('xref-AR000::' + layer_short_name, + notFoundReturnValue=False) + layer_object = sc.doc.Layers.FindIndex(layer_index) + # ^= XOR toggling value on and off + layer_object.IsVisible ^= True \ No newline at end of file diff --git a/_PrintAllAsSeparatePages.py b/_PrintAllAsSeparatePages.py new file mode 100644 index 0000000..44a4bbc --- /dev/null +++ b/_PrintAllAsSeparatePages.py @@ -0,0 +1,56 @@ +import Rhino +import scriptcontext as sc +import System.Drawing +import rhinoscriptsyntax as rs +import os + +folder = os.getcwd() +titleblock = dict() + +def createSinglePDF(view, titleblock): + pdf = Rhino.FileIO.FilePdf.Create() + dpi = 300 + settings = Rhino.Display.ViewCaptureSettings(view, dpi) + settings.OutputColor = Rhino.Display.ViewCaptureSettings.ColorMode.DisplayColor + settings.DefaultPrintWidthMillimeters = 0.18 + pdf.AddPage(settings) + filename = folder + os.path.sep + titleblock.get("project_number","0000") + "-" + \ + titleblock.get("originator", "00") + "-" + \ + titleblock.get("zone", "00") + "-" + \ + titleblock.get("level", "00") + "-" + \ + titleblock.get("drawing_type", "00") + "-" + \ + titleblock.get("role", "0") + "-" + \ + titleblock.get("drawing_number", "00000") + "_" + \ + titleblock.get("latest_revision", "00") + " " + \ + titleblock.get("drawing_title_1", "000000000") + " " + \ + titleblock.get("drawing_title_2", "") + " " + \ + titleblock.get("drawing_title_3", "") + ".pdf" + pdf.Write(filename) + +for view in sc.doc.Views.GetPageViews(): + for object in sc.doc.Objects.FindByLayer("titleblock index-AR002"): + if type(object) == Rhino.DocObjects.TextObject and \ + view.ActiveViewportID == object.Attributes.ViewportId: + if object.Name == "Project Number": + titleblock["project_number"] = object.DisplayText + if object.Name == "Originator": + titleblock["originator"] = object.DisplayText + if object.Name == "Zone": + titleblock["zone"] = object.DisplayText + if object.Name == "Level": + titleblock["level"] = object.DisplayText + if object.Name == "Drawing Type": + titleblock["drawing_type"] = object.DisplayText + if object.Name == "Role": + titleblock["role"] = object.DisplayText + if object.Name == "Drawing Number": + titleblock["drawing_number"] = object.DisplayText + if object.Name == "Latest Revision": + titleblock["latest_revision"] = object.DisplayText + if object.Name == "Drawing Title 1": + titleblock["drawing_title_1"] = object.DisplayText + if object.Name == "Drawing Title 2": + titleblock["drawing_title_2"] = object.DisplayText + if object.Name == "Drawing Title 3": + titleblock["drawing_title_3"] = object.DisplayText + createSinglePDF(view, titleblock) \ No newline at end of file diff --git a/_QuickInsertToAutoCAD.py b/_QuickInsertToAutoCAD.py new file mode 100644 index 0000000..8d1c8b6 --- /dev/null +++ b/_QuickInsertToAutoCAD.py @@ -0,0 +1 @@ + diff --git a/_XrefFilePathSourceV7.py b/_XrefFilePathSourceV7.py new file mode 100644 index 0000000..dd94d3d --- /dev/null +++ b/_XrefFilePathSourceV7.py @@ -0,0 +1,15 @@ +import os +import rhinoscriptsyntax as rs +import scriptcontext as sc +import Rhino + +block_defs = list(sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True)) + +for idx, block_def in enumerate(block_defs): + if rs.IsBlockEmbedded(block_def.Name) == False and ".3dm" in block_def.SourceArchive: + block_folder, block_file_name = os.path.split(block_def.SourceArchive) + new_block_path = block_folder + "\\RhinoV7\\" + block_file_name + sc.doc.InstanceDefinitions.ModifySourceArchive(block_def.Index, + new_block_path, + Rhino.DocObjects.InstanceDefinitionUpdateType.Linked, + 0) \ No newline at end of file diff --git a/cplane harvester.gh b/cplane harvester.gh new file mode 100644 index 0000000..eee1571 Binary files /dev/null and b/cplane harvester.gh differ diff --git a/diff.gh b/diff.gh new file mode 100644 index 0000000..b411287 Binary files /dev/null and b/diff.gh differ diff --git a/for-all-3dm-rhino-runpythonscript-save-exit.cmd b/for-all-3dm-rhino-runpythonscript-save-exit.cmd new file mode 100644 index 0000000..8d11668 --- /dev/null +++ b/for-all-3dm-rhino-runpythonscript-save-exit.cmd @@ -0,0 +1 @@ +for %i in (*.3dm) do "C:\Program Files\Rhino 8 WIP\System\Rhino.exe" /nosplash /runscript="-RunPythonScript (.\TagObjects.py) save exit" "%i" \ No newline at end of file diff --git a/jjLayMCur_MakeObjectLayerCurrent.py b/jjLayMCur_MakeObjectLayerCurrent.py new file mode 100644 index 0000000..bf7b988 --- /dev/null +++ b/jjLayMCur_MakeObjectLayerCurrent.py @@ -0,0 +1,3 @@ +import rhinoscriptsyntax as rs + +rs.CurrentLayer(rs.ObjectLayer(rs.GetObject(preselect=True))) \ No newline at end of file