def generate_part_images(structure): global view_aspect w_l = conf['part_img_width'] h_l = int(w_l / view_aspect) for iSub in xrange(len(structure)): subsystem = structure.keys()[iSub] v = structure[subsystem] utils.show_only(subsystem) utils.hide_children(subsystem) for iStep in xrange(len(v)): step = v.keys()[iStep] vv = v[step] stepnumeral = str(iSub + 1) + '.' + str(iStep + 1) rs.LayerVisible(step, True) for partkind, vvv in vv.items(): rs.HideObjects(vvv) for partkind, vvv in vv.items(): if len(vvv) >= 1: part = vvv[0] rs.ShowObject(part) # create images rs.RestoreNamedView(conf['persp_view']) rs.ZoomExtents() create_view_image( conf['part_img_persp'] % (stepnumeral, partkind), w_l, h_l) rs.RestoreNamedView(conf['top_view']) rs.ZoomExtents() create_view_image( conf['part_img_top'] % (stepnumeral, partkind), w_l, h_l) rs.RestoreNamedView(conf['front_view']) rs.ZoomExtents() create_view_image( conf['part_img_front'] % (stepnumeral, partkind), w_l, h_l) rs.RestoreNamedView(conf['right_view']) rs.ZoomExtents() create_view_image( conf['part_img_right'] % (stepnumeral, partkind), w_l, h_l) # rs.HideObject(part) for partkind, vvv in vv.items(): rs.ShowObject(vvv) rs.LayerVisible(step, False) # utils.show_children(subsystem) utils.show_step_children(subsystem) utils.show_blocks() utils.show_subsystems() rs.ZoomExtents()
def create_image_set(stepnumeral, w, h): rs.RestoreNamedView(conf['persp_view']) rs.ZoomExtents() create_view_image(conf['step_img_persp'] % stepnumeral, w, h) rs.RestoreNamedView(conf['top_view']) rs.ZoomExtents() create_view_image(conf['step_img_top'] % stepnumeral, w, h) rs.RestoreNamedView(conf['front_view']) rs.ZoomExtents() create_view_image(conf['step_img_front'] % stepnumeral, w, h) rs.RestoreNamedView(conf['right_view']) rs.ZoomExtents() create_view_image(conf['step_img_right'] % stepnumeral, w, h)
def viewCapture(fileName, directory, viewNames, image_width, image_height, dispModeStr, keepAspectRatio): for viewName in viewNames: if viewName in rs.ViewNames(): rs.CurrentView(viewName, True) else: # change to RhinoDoc to get access to NamedViews sc.doc = rc.RhinoDoc.ActiveDoc namedViews = rs.NamedViews() if viewName in namedViews: viewName = rs.RestoreNamedView(viewName) else: viewName = None # change back to Grasshopper sc.doc = ghdoc viewName = rs.CurrentView(viewName, True) rs.CurrentView(viewName) sc.doc.Views.Find(viewName, False) viewtoCapture = sc.doc.Views.ActiveView try: dispMode = rc.Display.DisplayModeDescription.FindByName(dispModeStr) sc.doc.Views.ActiveView.ActiveViewport.DisplayMode = dispMode except: pass if image_height == None: image_h = viewtoCapture.ActiveViewport.Size.Height else: image_h = image_height if image_width == None: image_w = viewtoCapture.ActiveViewport.Size.Width else: image_w = image_width # aspectRatio if keepAspectRatio: if image_height == None and image_width != None: image_h = image_h * (image_w/viewtoCapture.ActiveViewport.Size.Width) elif image_height != None and image_width == None: image_w = image_w * (image_h/viewtoCapture.ActiveViewport.Size.Height) viewSize = System.Drawing.Size(int(image_w), int(image_h)) pic = rc.Display.RhinoView.CaptureToBitmap(viewtoCapture , viewSize) fullPath = os.path.join(directory, fileName +'_'+ viewName + '.png') try: System.Drawing.Bitmap.Save(pic , fullPath) except: try: fullPath = os.path.join(directory, fileName +'_'+ viewName + '_1.png') System.Drawing.Bitmap.Save(pic , fullPath) except: print "Failed!" return pass return fullPath
def capture_named_views(view, file): command = '-_ViewCaptureToFile {file} _EnterEnd'.format(file=file) all_views = rs.NamedViews() selected_views = rs.MultiListBox(all_views) for view_name in selected_views: rs.RestoreNamedView(view_name) rs.Command(command)
def viewCaptureToFile(): namedViews = rs.NamedViews() items = [] for view in namedViews: items.append([view, False]) returnedVals = rs.CheckListBox(items, "Select Views to Export", "Extract Views") if returnedVals is None: return chosenViews = [] for val in returnedVals: if val[1]: chosenViews.append(val[0]) if len(chosenViews) < 1: return path = rs.BrowseForFolder(message = "Choose Folder to export to") if path is None: return width = rs.GetInteger("Image Width in Pixels", number = 1920, minimum = 600, maximum = 10000) if width is None: return height = .625 * width rs.AddNamedView("temp") now = datetime.date.today() dateList = [] if len(str(now.month))>1: month = str(now.month) else: month = "0"+str(now.month) if len(str(now.day))>1: day = str(now.day) else: day = "0"+str(now.day) time = str(now.year)+month+day for x in chosenViews: rs.RestoreNamedView(x) fileName = "\\" + str(time) + "_" + x + ".jpg" filePath = path + fileName rs.Command("_-ViewCaptureToFile " + str(filePath) + " w " + str(width) + " h " + str(height) + " _Enter") rs.RestoreNamedView("temp") rs.DeleteNamedView("temp")
def ExportNamedViews(): ''' Extract view coordinates and write to JSON Example: * Open original .3dm file * RunPythonScript `ExportNamedViews()` * Create a New .3dm file * RunPythonScript `ImportNamedViews()` ''' log = open('./views.json', 'a') fname = rs.DocumentPath() + rs.DocumentName() data = {} data[fname] = {} for view in rs.NamedViews(): rs.RestoreNamedView(view) data[fname][view] = (list(rs.ViewCamera()), list(rs.ViewTarget())) log.write(json.dumps(data, indent=2) + '\n') log.close() return data
def viewCapture(fileName, directory, viewNames, image_width, image_height, dispModeStr, keepAspectRatio, transparent): fullPaths = [] for viewName in viewNames: if viewName in rs.ViewNames(): rs.CurrentView(viewName, True) else: # change to RhinoDoc to get access to NamedViews sc.doc = rc.RhinoDoc.ActiveDoc namedViews = rs.NamedViews() if viewName in namedViews: viewName = rs.RestoreNamedView(viewName) else: viewName = None # change back to Grasshopper sc.doc = ghdoc viewName = rs.CurrentView(viewName, True) rs.CurrentView(viewName) sc.doc.Views.Find(viewName, False) viewtoCapture = sc.doc.Views.ActiveView try: dispMode = rc.Display.DisplayModeDescription.FindByName( dispModeStr) sc.doc.Views.ActiveView.ActiveViewport.DisplayMode = dispMode except: pass if image_height == None: image_h = viewtoCapture.ActiveViewport.Size.Height else: image_h = image_height if image_width == None: image_w = viewtoCapture.ActiveViewport.Size.Width else: image_w = image_width # aspectRatio if keepAspectRatio: if image_height == None and image_width != None: image_h = image_h * (image_w / viewtoCapture.ActiveViewport.Size.Width) elif image_height != None and image_width == None: image_w = image_w * (image_h / viewtoCapture.ActiveViewport.Size.Height) viewSize = System.Drawing.Size(int(image_w), int(image_h)) pic = rc.Display.RhinoView.CaptureToBitmap(viewtoCapture, viewSize) if transparent == True: if sc.doc.Views.ActiveView.ActiveViewport.DisplayMode.EnglishName == 'Rendered': rhBackColor = sc.doc.Views.Document.RenderSettings.BackgroundColorTop else: rhBackColor = rc.ApplicationSettings.AppearanceSettings.ViewportBackgroundColor pic.MakeTransparent(rhBackColor) fullPath = os.path.join(directory, fileName + '_' + viewName + '.png') try: System.Drawing.Bitmap.Save(pic, fullPath) except: try: fullPath = os.path.join(directory, fileName + '_' + viewName + '_1.png') System.Drawing.Bitmap.Save(pic, fullPath) except: print "Failed!" return pass fullPaths.append(fullPath) return fullPaths
def viewCapture(fileName, directory, viewNames, image_width, image_height, keepAspectRatio, saveAlpha): fullPathList = [] if saveAlpha == None: saveAlpha = False for viewName in viewNames: if viewName in rs.ViewNames(): rs.CurrentView(viewName, True) else: # change to RhinoDoc to get access to NamedViews sc.doc = rc.RhinoDoc.ActiveDoc namedViews = rs.NamedViews() if viewName in namedViews: viewName = rs.RestoreNamedView(viewName) else: viewName = None # change back to Grasshopper sc.doc = ghdoc viewName = rs.CurrentView(viewName, True) rs.CurrentView(viewName) sc.doc.Views.Find(viewName, False) viewtoCapture = sc.doc.Views.ActiveView try: dispMode = rc.Display.DisplayModeDescription.FindByName( dispModeStr) sc.doc.Views.ActiveView.ActiveViewport.DisplayMode = dispMode except: pass if image_height == None: image_h = viewtoCapture.ActiveViewport.Size.Height else: image_h = image_height if image_width == None: image_w = viewtoCapture.ActiveViewport.Size.Width else: image_w = image_width # aspectRatio if keepAspectRatio: if image_height == None and image_width != None: image_h = image_h * (image_w / viewtoCapture.ActiveViewport.Size.Width) elif image_height != None and image_width == None: image_w = image_w * (image_h / viewtoCapture.ActiveViewport.Size.Height) fullPath = os.path.join(directory, fileName + '_' + viewName + '.png') fullPathList.append(fullPath) # Set the image size rc.RhinoDoc.ActiveDoc.RenderSettings.UseViewportSize = False viewSize = System.Drawing.Size(int(image_w), int(image_h)) rc.RhinoDoc.ActiveDoc.RenderSettings.ImageSize = viewSize try: VRayForRhinoNETInterface.VRayInterface.SetRenderOutputSize( int(image_w), int(image_h)) except: pass print "Image dimensions set to (" + str(int(image_w)) + "x" + str( int(image_h)) + ")" # Render the image and save it. try: # V-Ray is the renderer. VRayForRhinoNETInterface.VRayInterface.HasRenderFinished() rs.Command("!_Render", echo=False) print "Rendering " + viewName + "..." while not VRayForRhinoNETInterface.VRayInterface.HasRenderFinished( ): if sc.escape_test(False): print("Rendering cancelled") rs.Command("_CloseRenderWindow", echo=False) rs.GetPlugInObject("V-Ray for Rhino").SetBatchRenderOn( True) vray.CancelRender() rs.GetPlugInObject("V-Ray for Rhino").SetBatchRenderOn( False) esc = True break rs.Sleep(10) rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName + '_' + viewName + ".png\"") rs.Command( "_-CloseRenderWindow" ) #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. if saveAlpha == False: try: alphaPath = os.path.join( directory, fileName + '_' + viewName + '.Alpha.png') os.remove(alphaPath) except: pass except: if renderTime_ != None: # V-Ray is probably the renderer. start = time.clock() rs.Command("!_Render", echo=False) print "Rendering " + viewName + "..." while float(time.clock() - start) < renderTime_: rs.Sleep(10) rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName + '_' + viewName + ".jpeg\"") rs.Command( "_-CloseRenderWindow" ) #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. if saveAlpha == False: try: alphaPath = os.path.join( directory, fileName + '_' + viewName + '.Alpha.jpeg') os.remove(alphaPath) except: pass else: # Hopefully Rhino is the renderer. print "Rendering " + viewName + "..." rs.Command("!_render") rs.Command("_-SaveRenderWindowAs \"" + directory + "\\" + fileName + '_' + viewName + ".png\"") rs.Command( "_-CloseRenderWindow" ) #close the rendered window when in saving mode to avoid stacking a series of renderWindows when running on Rhino renderer. return fullPathList
def __init__(self, outputUnits, dynamicSHDGroup_1, dynamicSHDGroup_2, RhinoViewsName, adaptiveZone, dgp_imageSize, onlyRunGlareAnalysis): if len(outputUnits) != 0 and outputUnits[0] != None: self.outputUnits = outputUnits else: self.outputUnits = [2] self.onlyAnnualGlare = onlyRunGlareAnalysis self.runAnnualGlare = False validViews = [] if RhinoViewsName != []: for viewName in RhinoViewsName: # check viewes if viewName in rs.ViewNames(): validViews.append(rs.CurrentView(viewName, True)) else: # change to RhinoDoc to get access to NamedViews sc.doc = rc.RhinoDoc.ActiveDoc namedViews = rs.NamedViews() if viewName in namedViews: validViews.append(rs.RestoreNamedView(viewName)) else: warning = viewName + " is not a valid Rhino view name in this document." ghenv.Component.AddRuntimeMessage( gh.GH_RuntimeMessageLevel.Warning, warning) # change back to Grasshopper sc.doc = ghdoc viewName = rs.CurrentView(viewName, True) self.RhinoViewsName = validViews if self.RhinoViewsName != []: self.runAnnualGlare = True if adaptiveZone == None: adaptiveZone = False self.adaptiveZone = adaptiveZone if not dgp_imageSize: dgp_imageSize = 250 self.dgp_imageSize = dgp_imageSize if dynamicSHDGroup_1 == None and dynamicSHDGroup_2 == None: class dynamicSHDRecipe(object): def __init__(self, type=1, name="no_blind"): self.type = type self.name = name self.DShdR = [dynamicSHDRecipe(type=1, name="no_blind")] else: self.DShdR = [] shadingGroupNames = [] if dynamicSHDGroup_1 != None: self.DShdR.append(dynamicSHDGroup_1) shadingGroupNames.append(dynamicSHDGroup_1.name) if dynamicSHDGroup_2 != None: self.DShdR.append(dynamicSHDGroup_2) shadingGroupNames.append(dynamicSHDGroup_2.name) if len(shadingGroupNames ) == 2 and shadingGroupNames[0] == shadingGroupNames[1]: msg = "Shading group names cannot be the same. Change the names and try again." # Number of ill files self.numOfIll = 1 for shadingRecipe in self.DShdR: if shadingRecipe.name == "no_blind": pass elif shadingRecipe.name == "conceptual_dynamic_shading": self.numOfIll += 1 else: # advanced dynamic shading self.numOfIll += len(shadingRecipe.shadingStates) - 1 print "number of ill files = " + str(self.numOfIll)
import rhinoscriptsyntax as rs import os all_views = rs.NamedViews() # a list of names (strings) selected_views = rs.MultiListBox(all_views, message="select views to save", defaults=all_views) filename_base = rs.GetString("base file name", "Rics_file_") savepath = r"C:\Users\Tchunoo\Pictures" # savepath = rs.BrowseForFolder(rs.DocumentPath(), "destination directory") filepath = os.path.join(savepath, filename_base) for view_name in selected_views: rs.RestoreNamedView(view_name) rs.Command('-_ViewCaptureToFile ' + chr(34) + filepath + view_name + '.jpg' + chr(34) + ' _EnterEnd')
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 Make2d(): ''' Rhinoceros Mac v5.4 WIP, 2D output improves when run with a smaller subset of objects. This macro generates 2D curves in three stages: 1. Surface and intersections 2. Surface U IsoCurves 2. Surface V IsoCurves Due to form complexity, rounding issues/floating point mathematics, manual correction may be required. [1](https://gist.github.com/bengolder/3959792) [2](http://archiologics.com/2011-10-20-15-32-52/rhino-scripts/animation-tools/81-rvb-batch-render-make2d) [3](https://github.com/localcode/rhinopythonscripts/blob/master/Make2D.py) [4](http://docs.mcneel.com/rhino/5/help/en-us/commands/make2d.htm) ''' def run(): RunScript( '-Make2D DrawingLayout=CurrentView ' + 'ShowTangentEdges=Yes ' + 'CreateHiddenLines=No ' + 'MaintainSourceLayers=Yes ' + 'Enter ', True) rs.CurrentLayer('Default') baseLayers = [layer('PolySurfaces', 1), layer('Intersect', 'Curves')] # Allow user to select required views views = [(view, True) for i, view in enumerate(rs.NamedViews())] result = rs.CheckListBox(views, 'Select Views', 'Make2D') for view in [item[0] if item[1] else None for item in result]: if view is not None: # and view != 'Base' rs.CurrentLayer('Default') rs.RestoreNamedView(view) # Hide all Layers for l in rs.LayerNames(): if l != 'Default': Visible(l, False) # 1. Generate Outlines # Generate 2D curves with relaxed tolerance(s) (decrease accuracy) # Curves are generated twice, once per tolerance, # to increase coverage and minimise fragmentation. for i, tolerance in enumerate((0.1, 0.001)): rs.UnitAbsoluteTolerance(tolerance, True) rs.UnselectAllObjects() # Select objects for l in baseLayers: if rs.IsLayer(l): Visible(l, True) # rs.LayerVisible(l, True, True) rs.ObjectsByLayer(l, True) run() # Transfer 2D curves to View layer for l in baseLayers: for child in ('lines', 'tangents'): a = layer('Make2D', 'visible', child, l) b = layer(view, 'visible', child, str(i), l) Transfer(a, b) Visible(view, False) PurgeLayer('Make2D') # 2. Generate IsoCurves # Decrease tolerance (increase accuracy) rs.UnitAbsoluteTolerance(0.0000000001, True) # Run Make2D once per curve direction for dimension in 'UV': isoCurves = layer('Curves', 1, 0, dimension) layers = list(baseLayers) # copy layers.append(isoCurves) rs.UnselectAllObjects() # Select objects for l in layers: if rs.IsLayer(l): Visible(l, True) # rs.LayerVisible(l, True, True) rs.ObjectsByLayer(l, True) run() a = layer('Make2D', 'visible', 'lines', isoCurves) b = layer(view, 'visible', 'lines', isoCurves) Transfer(a, b) Visible(view, False) Visible(isoCurves, False) PurgeLayer('Make2D') # 3. Compare and remove overlapping Curves args = {k: [] for k in 'ab'} for l in baseLayers: for child in ('lines', 'tangents'): a = layer(view, 'visible', child, 0, l) b = layer(view, 'visible', child, 1, l) for var in 'ab': l2 = eval(var) if rs.IsLayer(l2): Visible(l2, True) args[var].extend(rs.ObjectsByLayer(l2)) RemoveOverlappingCurves(*args.values())