def AddCoordinateTag_Button(): objs = rs.GetObjects("Select objects to add coordinates to", 1073741853 ,preselect = True) if objs is None: return dotGroup = rs.AddGroup('DotGroup') rs.EnableRedraw(False) for obj in objs: try: rs.AddObjectsToGroup(AddCoordinateTag(obj), dotGroup) utils.SaveFunctionData('Drawing-Add Coordinate Tag', [len(objs), True]) except: utils.SaveFunctionData('Drawing-Add Coordinate Tag', [len(objs), False]) rs.EnableRedraw(True)
def CreateDesignOption(): objs = rs.GetObjects("Select objects to create design option with", preselect=True) if objs is None: return None try: date = utils.GetDatePrefix() origName = date + '_OPTION_00' defaultName = origName for i in range(100): defaultName = utils.UpdateString(defaultName) if origName == defaultName: break if rs.IsBlock(defaultName) == False: break looping = True while looping: designOptionName = rs.StringBox("Design Option Name", defaultName, "Create Design Option") if designOptionName is None: return None if rs.IsBlock(designOptionName): print "Block name already exists" elif len(designOptionName) == 0: print "Must specify a name" else: looping = False block = rs.AddBlock(objs, (0, 0, 0), designOptionName, True) blockInstance = rs.InsertBlock(designOptionName, (0, 0, 0)) #Add user text rs.SetUserText(blockInstance, 'Design Option History', designOptionName) #Ensure 3_DESIGN OPTIONS already exists layers.AddLayerByNumber(3000, False) #Create new layer parentLayer = layers.GetLayerNameByNumber(3000) designOptionLayer = rs.AddLayer(parentLayer + "::" + designOptionName, color=utils.GetRandomColor()) rs.ObjectLayer(blockInstance, designOptionLayer) utils.SaveFunctionData('Blocks-Create Design Option', [__version__, designOptionName]) return True except: print "Failed to create design option" utils.SaveFunctionData('Blocks-Create Design Option', [__version__, '', 'Failed']) return None
def AddAreaTag(): objs = rs.GetObjects("Select curves, hatches, or surfaces to add area tag", 65548, preselect = True) if objs is None: return decPlaces = rs.GetInteger("Number of decimal places", 0, maximum = 8) if decPlaces is None: return #Load Anno style if it doesnt exist already if sc.doc.DimStyles.FindName('PCPA_12') is None: standards.LoadStyles() rs.EnableRedraw(False) total = 0 for obj in objs: try: currentArea,result, tag = AreaTag(obj, decPlaces) utils.SaveFunctionData('Drawing-Add Area Tag', [rs.DocumentName(), rs.ObjectLayer(obj), rs.ObjectDescription(obj), rs.CurrentDimStyle(), currentArea, decPlaces, result]) total += currentArea rs.SetUserText(tag, 'hostGUID', str(obj)) except: pass print 'Cumulative Area = ' + str(total) rs.EnableRedraw(True)
def LoadPCPAMaterials(filepath): try: rs.EnableRedraw(False) rs.Command("-_Import " + '"' + filepath + '" Enter', echo=False) rs.EnableRedraw(True) result = True utils.SaveToAnalytics('standards-Load Materials') except: print "Failed to load PCPA Materials" result = False utils.SaveFunctionData('Standards-Load Materials', [result])
def main(): path = rs.GetObject("Select Ramp Path", rs.filter.curve, True) if path is None: return if 'ramp-widthDefault' in sc.sticky: widthDefault = sc.sticky['ramp-widthDefault'] else: widthDefault = 36 if 'ramp-slopeDefault' in sc.sticky: slopeDefault = sc.sticky['ramp-slopeDefault'] else: slopeDefault = 8.333 width = rs.GetReal("Ramp Clear Width", widthDefault, minimum=36) if width is None: return slope = rs.GetReal("Ramp slope (e.g. 8.33%(1:12) is 8.33)", slopeDefault) if slope is None: return sc.sticky['ramp-widthDefault'] = width sc.sticky['ramp-slopeDefault'] = slope rs.EnableRedraw(False) rampGeoList = Ramp_HeightSlope(path, width, slope / 100) try: layers.AddLayerByNumber(402, False) layerName = layers.GetLayerNameByNumber(402) rs.ObjectLayer(rampGeoList[0], layerName) try: if rampGeoList[2] is not None: layers.AddLayerByNumber(106, False) layerName = layers.GetLayerNameByNumber(106) rs.ObjectLayer(rampGeoList[2], layerName) except: pass result = True except: result = False utils.SaveFunctionData('Architecture-ramp', [ width, slope, str([(pt.X, pt.Y, pt.Z) for pt in rs.CurveEditPoints(path)]), result ]) rs.EnableRedraw(True) print rampGeoList[1] utils.SaveToAnalytics('architecture-ramp')
def CutModel_Button(): objs = rs.GetObjects("Select objects to cut", preselect=True) if objs is None: return srf = rs.GetObject("Select cutting surface", rs.filter.surface) if srf is None: return if rs.IsSurfacePlanar(srf) == False: print "Cutting surface must be planar" return None rs.EnableRedraw(False) result = CutModel(objs, srf) if result: utils.SaveToAnalytics('Drawing-cut Model') utils.SaveFunctionData('Drawing-Cut Model', [__version__, len(objs), result]) rs.EnableRedraw(True)
def Iterate(): block = rs.GetObject("Select Design Option Block to iterate", rs.filter.instance, True) if block is None: return try: prevBlockName = rs.BlockInstanceName(block) prevBlockLayer = rs.ObjectLayer(block) prevBlockLayerColor = rs.LayerColor(prevBlockLayer) newBlock = ReplicateBlock(block) newBlockName = rs.BlockInstanceName(newBlock) #Ensure 3_DESIGN OPTIONS already exists parentLayer = layers.AddLayerByNumber(3000, False)[0] rs.LayerVisible(parentLayer, True) #Create new design option layer #newBlockLayer = rs.AddLayer(parentLayer + "::" + newBlockName, color = utils.StepColor(prevBlockLayerColor)) newBlockLayer = rs.AddLayer(parentLayer + "::" + newBlockName, color=utils.GetRandomColor()) rs.LayerPrintColor(newBlockLayer, (0, 0, 0)) rs.ObjectLayer(newBlock, newBlockLayer) #Save user text try: parentsUserTest = rs.GetUserText(block, 'Design Option History') + "<--" except: parentsUserTest = '' rs.SetUserText(newBlock, 'Design Option History', parentsUserTest + newBlockName) #Turn off prev blocks layer if rs.CurrentLayer() != prevBlockLayer: rs.LayerVisible(prevBlockLayer, False) result = True except: result = False newBlockName = '' utils.SaveFunctionData( 'Blocks-Iterate', [__version__, rs.BlockInstanceName(block), newBlockName, result]) return result
def UpdateAreaTag(): objs = rs.GetObjects('Select area tags to update', preselect = True) if objs is None: return successfulObjsRun = 0 failedObjsRun = 0 for obj in objs: try: host = rs.GetUserText(obj, 'hostGUID') if host is None: print "Could not find associated geometry" return None #Get number of dec places text = rs.TextObjectText(obj) splitText = text.Split(" ") numberString = splitText[0] units = splitText[-1] try: decPlaces = len(numberString.Split(".")[1]) except: decPlaces = 0 #Get area if rs.UnitSystem() == 8: area = rs.Area(rs.coerceguid(host))*0.0069444444444444 areaText = utils.RoundNumber(area, decPlaces) + " " + units else: print "WARNING: Your units are not in inches" area = rs.Area(rs.coerceguid(host)) areaText = area + ' ' + rs.UnitSystemName(False, True, True) rs.TextObjectText(obj, areaText) successfulObjsRun += 1 except: failedObjsRun += 1 print "Tag failed" utils.SaveFunctionData('Drawing-Update Area Tag', [__version__, successfulObjsRun, failedObjsRun]) return successfulObjsRun
def importCAD_Button(): try: #Import CAD filePath = rs.OpenFileName("Select CAD to Import", "Autocad (*.dwg)|*.dwg||") if filePath is None: return None rs.EnableRedraw(False) group = rs.AddGroup('Import CAD Group') allImportedObjects = importCAD(filePath) rs.AddObjectsToGroup(allImportedObjects, group) rs.EnableRedraw(True) result = True except: print "Import Failed" result = False try: utils.SaveFunctionData('IO-Import CAD',[result]) except: print "Failed to save function data" return result
def ColorObjsWithGradient2Pt(): result = True try: objs = rs.GetObjects("Select objects to color", 1073750077, preselect=True) if objs is None: return pt1 = rs.GetPoint("Select first color point") if pt1 is None: return firstColor = rs.GetColor() if firstColor is None: return pt2 = rs.GetPoint("Select second color point") if pt2 is None: return secondColor = rs.GetColor(firstColor) if secondColor is None: return rs.EnableRedraw(False) origLine = rs.AddLine(pt1, pt2) colorLine = rs.AddLine(firstColor, secondColor) try: for obj in objs: bboxpts = rs.BoundingBox(obj) ctrPt = (bboxpts[0] + bboxpts[6]) / 2 param = rs.CurveClosestPoint(origLine, ctrPt) normParam = rs.CurveNormalizedParameter(origLine, param) colorParam = rs.CurveParameter(colorLine, normParam) finalPt = rs.EvaluateCurve(colorLine, colorParam) color = (finalPt.X, finalPt.Y, finalPt.Z) rs.ObjectColor(obj, color) except: result = False rs.DeleteObject(colorLine) rs.DeleteObject(origLine) rs.EnableRedraw(True) except: result = False utils.SaveFunctionData( 'colors-Gradient', [firstColor, secondColor, len(objs), result]) return result
def IntersectGeoAtPt(): try: objs = rs.GetObjects("Select objects to contour", 1073745980, preselect=True) if objs is None: return geos = [] while True: pt = rs.GetPoint("Select point to contour at") if pt is None: break rs.EnableRedraw(False) for obj in objs: if rs.IsBlockInstance(obj): blocksObjects = utils.GetAllBlockObjectsInPosition(obj) for eachBlocksObject in blocksObjects: result = IntersectGeo(eachBlocksObject, pt.Z) if result is None: rs.DeleteObject(eachBlocksObject) continue for each in result: if each is not None: geos.append(each) rs.DeleteObject(eachBlocksObject) else: result = IntersectGeo(obj, pt.Z) if result is None: continue for each in result: if each is not None: geos.append(each) rs.EnableRedraw(True) rs.SelectObjects(geos) result = True except: result = False utils.SaveFunctionData('Geometry-Contour At Pt', [__version__, len(objs), result]) return result
def LoadPCPAComponents(sourceFolder): """ copies PCPA GH Toolbar from source folder to the grasshopper UserObject folder """ if os.path.isdir(sourceFolder) is False: print "FAIL-----PCPA Components folder not found" result = False try: appData = os.getenv('APPDATA') targetFolder = appData + r"\Grasshopper\UserObjects" except: print "FAIL-----UserObjects folder not found" result = False numberOfObjects = 0 try: numberOfObjects = UpdateFolders(sourceFolder, targetFolder) result = True except: print "FAIL-----Could not copy files. Ensure that folder is not open" result = False utils.SaveFunctionData('Standards-PCPA GH Components', [numberOfObjects, result])
def LoadGHDependencies(fileLocations): """ copies GH Dependencies from source folder to the grasshopper library folder """ sourceFolderLibraries = fileLocations['GH Dependencies_Libraries'] sourceFolderUserObjects = fileLocations['GH Dependencies_User Objects'] if os.path.isdir(sourceFolderLibraries) is False: print "FAIL-----'GH Dependecies Libraries' folder not found" result = False if os.path.isdir(sourceFolderUserObjects) is False: print "FAIL-----'GH Dependecies UserObjects' folder not found" result = False try: appData = os.getenv('APPDATA') targetFolderLibraries = appData + r"\Grasshopper\Libraries" targetFolderUserObjects = appData + r"\Grasshopper\UserObjects" result = True except: print "FAIL-----GH Library or User Object folder not found" result = False numberOfLibraryObjects = 0 numberOfUserObjects = 0 try: numberOfLibraryObjects = UpdateFolders(sourceFolderLibraries, targetFolderLibraries) numberOfUserObjects = UpdateFolders(sourceFolderUserObjects, targetFolderUserObjects) result = True except: print "FAIL-----Could not copy dependencies. You must have Grasshopper open. Close and reopen Rhino, then run this again." result = False utils.SaveFunctionData( 'Standards-PCPA GH Dependencies', [numberOfLibraryObjects, numberOfUserObjects, result])
def dimensionPline_Button(): objects = rs.GetObjects("Select Curves to Dimension", filter = 4, preselect = True) if objects is None:return if 'dimPline-dist' in sc.sticky: distDefault = sc.sticky['dimPline-dist'] else: distDefault = 60 offsetDist = rs.GetInteger('Dimension offset distance (in.)', distDefault) if offsetDist is None: return sc.sticky['dimPline-dist'] = offsetDist #Load Anno style if it doesnt exist already if sc.doc.DimStyles.FindName('PCPA_12') is None: standards.LoadStyles() try: layers.AddLayerByNumber(8101) layerName = layers.GetLayerNameByNumber(8101) rs.CurrentLayer(layerName) except: pass rs.EnableRedraw(False) for obj in objects: if rs.IsCurve(obj): try: group, rc = dimensionPline(obj, offsetDist) utils.SaveFunctionData('Drawing-Dim Pline', [rs.DocumentPath(), rs.DocumentName(), rs.ObjectLayer(obj), rs.CurrentDimStyle(), offsetDist, rc]) except: print "Unknown Error" else: print "Not a polyline" rs.EnableRedraw(True)
def Rectify_AngleFirst_Button(): objs = rs.GetObjects("Select polylines to rectify", rs.filter.curve, preselect = True) if objs is None: return if 'geometry-angleMultiple' in sc.sticky: angleDefault = sc.sticky['geometry-angleMultiple'] else: angleDefault = 45 if 'geometry-lengthMultiple' in sc.sticky: lengthDefault = sc.sticky['geometry-lengthMultiple'] else: lengthDefault = 1 angleMultiple = rs.GetReal("Round angle to multiples of", angleDefault) if angleMultiple is None: return sc.sticky['geometry-angleMultiple'] = angleMultiple lengthMultiple = rs.GetReal("Round length to multiples of", lengthDefault) if lengthMultiple is None: return sc.sticky['geometry-lengthMultiple'] = lengthMultiple for obj in objs: try: rs.SimplifyCurve(obj) newLine = Rectify_AngleFirst(obj, angleMultiple, lengthMultiple) rs.MatchObjectAttributes(newLine, obj) utils.SaveToAnalytics('Geometry-Rectify') result = True except: result = False print "Rectify failed" utils.SaveFunctionData('Geometry-Rectify', [angleMultiple, lengthMultiple, str([(pt.X, pt.Y, pt.Z) for pt in rs.CurveEditPoints(obj)]), result]) if result: rs.DeleteObject(obj)
def Unfillet_Button(): objs = [] successList = [] try: #Will remove entire pline when angle > 180 degrees objs = rs.GetObjects("Select curves to unfillet", rs.filter.curve, True, True) if objs is None: return successList = [] for obj in objs: unfilletResult = unfilletObj(obj) if unfilletResult is None: successList.append(False) else: successList.append(True) result = True except: result = False utils.SaveFunctionData( 'Geometry-Unfillet', [__version__, len(objs), str(successList), result]) return result
def PopulatePath(): numObjects = 0 type = None try: crvs = rs.GetObjects("Select curves to populate", rs.filter.curve, True) if crvs is None: return None crvObjs = [] for crv in crvs: crvObjs.append(rs.coercecurve(crv)) #GET POPULATION TYPE type = GetPopulationType() if type is None: return None #GET BLOCK NAMES if type == 'Custom Block': blockNames, instances = GetCustomBlockNames() else: blockNames = GetBlockNames(type) if blockNames is None: return #GET NUMBER OF OBJECTS numObjects = GetNumObjects() if numObjects is None: return None rs.EnableRedraw(False) if type == '2D People' or type == '3D People': spacing = 42 elif type == '2D Trees': spacing = 100 elif type == '3D Trees': spacing = 200 elif type == '3D Vehicles': spacing = 240 else: spacing = GetCustomSpacing( blockNames[0]) #currently just selects the first block #GET PTS upVec = rc.Geometry.Vector3d(0, 0, 1) plane0 = rc.Geometry.Plane(rc.Geometry.Point3d(0, 0, 0), upVec) plane0.Rotate(math.pi / 2, upVec) crvData = [] for i, crvObj in enumerate(crvObjs): lengths = [] frames = [] curveLength = crvObj.GetLength() counter = 0 while len(frames) < numObjects: t = utils.Remap(random.uniform(0, 1), 0, 1, 0, curveLength) posOkay = True if len(lengths) > 0: counter += 1 for eachPrevPos in lengths: if abs(eachPrevPos - t) < spacing: posOkay = False if posOkay: lengths.append(t) pt = crvObj.PointAtLength(t) param = crvObj.LengthParameter(t)[1] tan = crvObj.TangentAt(param) xAxis = rc.Geometry.Vector3d.CrossProduct(tan, upVec) xAxis.Reverse() frames.append(rc.Geometry.Plane(pt, tan, xAxis)) if counter > int(curveLength / numObjects): print "Curve {}: Could only fit {} of the requested {} objects".format( i, len(frames), numObjects) break crvData.append(frames) scaleVariation = .1 #PLACE THE BLOCKS for i, crvObj in enumerate(crvObjs): for i, frame in enumerate(crvData[i]): blockName = blockNames[random.randint(0, len(blockNames) - 1)] if TryLoadBlock(type, blockName): xform = rc.Geometry.Transform.PlaneToPlane(plane0, frame) eachBlock = rs.InsertBlock2(blockName, xform) try: if type == '2D People' or type == '3D People': layerName = layers.GetLayerNameByNumber(2200) elif type == '2D Trees' or type == '3D Trees': layerName = layers.GetLayerNameByNumber(2300) elif type == '3D Vehicles': layerName = layers.GetLayerNameByNumber(2400) elif type == 'Custom Block': layerName = rs.ObjectLayer(instances[0]) else: layers.AddLayerByNumber(2000) layerName = layers.GetLayerNameByNumber(2000) rs.ObjectLayer(eachBlock, layerName) if type != '3D Vehicles': xyScale = random.uniform(1 - scaleVariation, 1 + scaleVariation) zScale = random.uniform(1 - scaleVariation, 1 + scaleVariation) else: xyScale = 1 zScale = 1 rs.ScaleObject(eachBlock, frame, (xyScale, xyScale, zScale)) except: pass rs.EnableRedraw(True) result = True except: result = False utils.SaveFunctionData('Blocks-Populate Path', [__version__, numObjects, type, result])
def ApplyPCPAAliases(scriptFolder): try: ############################################################################ #ARCHITECTURE #STAIR str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\stair.py) ' rs.AddAlias('pcpStair', str) #RAMP str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\ramp.py) ' rs.AddAlias('pcpRamp', str) ############################################################################ #BLOCKS #ITERATE DESIGN OPTION str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\blocks.py) 0 ' rs.AddAlias('pcpIterDesignOpt', str) #MAKE BLOCK UNIQUE str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\blocks.py) 1 ' rs.AddAlias('pcpMakeUnique', str) #SUPER EXPLODE str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\blocks.py) 2 ' rs.AddAlias('pcpSuperExplode', str) #POPULATE str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\populate.py) ' rs.AddAlias('pcpPopulate', str) #RESET BLOCK SCALE str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\blocks.py) 4 ' rs.AddAlias('pcpResetBlockScale', str) #EXPORT AND LINK str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\blocks.py) 5 ' rs.AddAlias('pcpExportAndLink', str) ############################################################################ #DRAWINGS #AREA TAG str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\drawing.py) 0 ' rs.AddAlias('pcpAreaTag', str) #DIM PLINE str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\drawing.py) 1 ' rs.AddAlias('pcpDimPline', str) #ADD LAYOUT str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\layout.py) 0 ' rs.AddAlias('pcpLayout', str) #CUT MODEL str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\cut_model.py) ' rs.AddAlias('pcpCutModel', str) ############################################################################ #GEOMETRY #CONTOUR AT POINT str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\geometry.py) 0 ) ' rs.AddAlias('pcpContourPt', str) #UNFILLET str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\geometry.py) 1 ' rs.AddAlias('pcpUnfillet', str) #RECTIFY str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\rectify.py) ' rs.AddAlias('pcpRectify', str) ############################################################################ #COLOR #COLOR RANDOM RANGE str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\colors.py) 1 ' rs.AddAlias('pcpColorRandRange', str) #COLOR GRADIENT str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\colors.py) 0 ' rs.AddAlias('pcpColorGradient', str) #COLOR BY SIZE str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\colors.py) 3 ' rs.AddAlias('pcpColorBySize', str) #COLOR TO MATERIAL str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\colors.py) 2 ' rs.AddAlias('pcpColorToMaterial', str) ############################################################################ #I/O #CAPTURE DISPLAY MODES str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\file_IO.py) 3 ' rs.AddAlias('pcpCaptureDisplayModes', str) #EXPORT TO RENDER DWG str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\file_IO.py) 1 ' rs.AddAlias('pcpExportToRenderDWG', str) #EXPORT TO RENDER SKP str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\file_IO.py) 2 ' rs.AddAlias('pcpExportToRenderSKP', str) #IMPORT CAD str = r'_NoEcho -_RunPythonScript (' + scriptFolder + '\\file_IO.py) 0 ' rs.AddAlias('pcpImportCAD', str) print "\tLoaded PCPA Aliases" result = True except: print "Failed to load PCPA Aliases" result = False utils.SaveFunctionData('Standards-Load PCPA Aliases', [__version__, result]) return result
def main(): if (rs.UnitSystem() == 2): widthDefault = 1800 widthMin = 900 widthMax = 100000 heightDefault = 5000 heightMin = 300 elif (rs.UnitSystem() == 4): widthDefault = 1.8 widthMin = .9 widthMax = 100.0 heightDefault = 5.0 heightMin = .30 elif (rs.UnitSystem() == 8): widthDefault = 42 widthMin = 36 widthMax = 1000.0 heightDefault = 120 heightMin = 12 else: print "Change your units to inches" return route = rs.GetObject("Select Stair Guide Curve", rs.filter.curve, True) if route is None: return if 'stair-widthDefault' in sc.sticky: widthDefault = sc.sticky['stair-widthDefault'] if 'stair-heightDefault' in sc.sticky: heightDefault = sc.sticky['stair-heightDefault'] width = rs.GetReal("Stair Width", number=widthDefault, minimum=widthMin, maximum=widthMax) if width is None: return height = rs.GetReal("Stair Height", number=heightDefault, minimum=heightMin) if height is None: return sc.sticky['stair-widthDefault'] = width sc.sticky['stair-heightDefault'] = height try: stairGeo = stairHeight(route, width, height) result = True except: result = False try: layers.AddLayerByNumber(401, False) layerName = layers.GetLayerNameByNumber(401) rs.ObjectLayer(stairGeo, layerName) except: pass utils.SaveFunctionData('Architecture-Stair', [ width, height, str([(pt.X, pt.Y, pt.Z) for pt in rs.CurveEditPoints(route)]), result ]) utils.SaveToAnalytics('Architecture-Stair')
def BatchCapture(): try: namedViews = rs.NamedViews() if len(namedViews) < 1: print "There are no Named Views in this file." return None #Prepare checklis items = [] for view in namedViews: items.append([view, False]) #Checklist returnedVals = rs.CheckListBox(items, "Select Views to Export", "Batch Capture") if returnedVals is None: return chosenViews = [] for val in returnedVals: if val[1]: chosenViews.append(val[0]) if len(chosenViews) < 1: return defaultFilename = utils.GetDatePrefix() + '_FILENAME' #path = rs.SaveFileName('Batch Capture', "PNG (*.png)|*.png||", filename = date+'_FILENAME') path = rs.SaveFileName('Save view location', "PNG (*.png)|*.png|JPEG (*.jpeg)|*.jpeg||", filename = defaultFilename, extension = ".png") if path is None: return #Check if in stick if 'batchCapture-width' in sc.sticky: defaultWidth = sc.sticky['batchCapture-width'] else: defaultWidth = 5100 if 'batchCapture-height' in sc.sticky: defaultHeight = sc.sticky['batchCapture-height'] else: defaultHeight = 3300 #Get output width width = rs.GetInteger('Width', defaultWidth, 200, 10000 ) if width is None: return sc.sticky['batchCapture-width'] = width #Get output height height = rs.GetInteger('Height', defaultHeight, 200, 10000 ) if height is None: return sc.sticky['batchCapture-height'] = height rs.AddNamedView("temp") baseName = os.path.splitext(path)[0] for eachView in chosenViews: rs.RestoreNamedView(eachView) splitPath = path.Split(".") if splitPath[-1] == "png": filePath = baseName + "_" + eachView + ".png" result = SafeCapture_PNG(filePath, width, height) else: filePath = baseName + "_" + eachView + ".jpg" result = SafeCapture_JPG(filePath, width, height) #return to original view rs.RestoreNamedView("temp") rs.DeleteNamedView("temp") result = True except: result = False utils.SaveFunctionData('IO-BatchCapture', [__version__] + chosenViews) return result
def CaptureDisplayModesToFile(): try: displayModeNames = [] displayModeBool = [] displayModesChecked = [] ######## #Get current display mode originalDisplayMode = rc.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.DisplayMode.LocalName ######## #Get default display mode selection if 'CaptureDisplayModes-DisplayModes' in sc.sticky: dict = sc.sticky['CaptureDisplayModes-DisplayModes'] for each in rc.Display.DisplayModeDescription.GetDisplayModes(): displayModeNames.append(each.EnglishName) if each.EnglishName in dict: displayModeBool.append(dict[each.EnglishName]) else: displayModeBool.append(False) else: for each in rc.Display.DisplayModeDescription.GetDisplayModes(): displayModeNames.append(each.EnglishName) displayModeBool.append(False) results = rs.CheckListBox(zip(displayModeNames, displayModeBool), 'Select Display Modes', 'Capture Display Modes To File') if results is None: return ######## #Save display modes to sticky resultDict = {} for each in results: resultDict[each[0]] = each[1] sc.sticky['CaptureDisplayModes-DisplayModes'] = resultDict for each in results: if each[1]: displayModesChecked.append(each[0]) ######## #Get default filename date = utils.GetDatePrefix() activeView = sc.doc.Views.ActiveView.ActiveViewport.Name if activeView is None: activeView = 'VIEW' path = rs.SaveFileName('Export All Display Modes', "PNG (*.png)|*.png||", filename = date+'_'+activeView) if path is None: return ######## #Get sizes from sticky if 'catpureDisplays-width' in sc.sticky: widthDefault = sc.sticky['catpureDisplays-width'] else: widthDefault = 5100 if 'catpureDisplays-height' in sc.sticky: heightDefault = sc.sticky['catpureDisplays-height'] else: heightDefault = 3300 width = rs.GetInteger('Image Width', number = widthDefault, minimum = 200, maximum = 20000) height = rs.GetInteger('Image Height', number = heightDefault, minimum = 200, maximum = 20000) ######## #Save sizes to sticky sc.sticky['catpureDisplays-width'] = width sc.sticky['catpureDisplays-height'] = height ####################################################################### #Export the images count = 0 for name in displayModesChecked: try: rs.ViewDisplayMode(mode = name) exportImage(path, name, width, height) count += 1 except: pass print "{} Images saved to {}".format(count , os.path.abspath(os.path.join(path, os.pardir))) result = True except: result = False ######## #Restore original display mode if originalDisplayMode is not None: rs.ViewDisplayMode(mode = originalDisplayMode) ######## #Save analytics try: utils.SaveFunctionData('IO-Capture Display Modes', [__version__, str(displayModesChecked), width, height, result]) except: print "Failed to save function data" return result