def rename(): layerName = rs.GetString("Name of layer to rename") matchingLayers = [layer for layer in doc.Layers if layer.Name == layerName] layerToRename = None if len(matchingLayers) == 0: print "Layer \"{0}\" does not exist.".format(layerName) return if len(matchingLayers) == 1: layerToRename = matchingLayers[0] elif len(matchingLayers) > 1: i = 0 for layer in matchingLayers: print "({0}) {1}".format( i + 1, matchingLayers[i].FullPath.replace("::", "->")) i += 1 selectedLayer = rs.GetInteger("which layer?", -1, 1, len(matchingLayers)) if selectedLayer == None: return layerToRename = matchingLayers[selectedLayer - 1] layerName = rs.GetString("New layer name") layerToRename.Name = layerName layerToRename.CommitChanges() return
def __init__(self): FileName = "type_data.csv" FilePath = rs.GetString( "Enter the working directory for the program : ") try: os.stat(FilePath) except: os.mkdir(FilePath) os.chdir(FilePath) site_bool = rs.GetString( 'Use default site Profile- (Y)? Or select - (N) ', 'Y').lower() n = rs.GetInteger('Enter number of variations required') if (n == 0 or n == None): n = 1 for i in range(0, 2000 * n, 2000): site = None site_crv = None if (site_bool == 'y' or site_bool == 'Y'): site = genSite(i, 0) site_crv = site.getSite() else: site_crv = rs.GetObject('pick site boundary') site_crv = rs.CopyObject(site_crv, [i, 0, 0]) m = main(FileName, site_crv) m.getInpObj() m.genFuncObj_Site() m.writeToCsv()
def OffsetMulticrvs2SidesWEnds(): #user input section msg = "Select planar curve(s) to offset both sides" crvs = rs.GetObjects(msg, 4, preselect=True, custom_filter=plcrv_filt) if not crvs: return tol = sc.doc.ModelAbsoluteTolerance t_choice = ["Sharp", "Round", "Smooth", "Chamfer"] e_choice = ["None", "Straight", "Arc", "OffsetStraight"] #Get previous settings if "OffsetCrvs_Dist" in sc.sticky: old_dist = sc.sticky["OffsetCrvs_Dist"] else: old_dist = 1.0 if "OffsetCrvs_TChoice" in sc.sticky: old_trans = sc.sticky["OffsetCrvs_TChoice"] else: old_trans = "Sharp" if "OffsetCrvs_EChoice" in sc.sticky: old_ends = sc.sticky["OffsetCrvs_EChoice"] else: old_ends = "None" off_dist = rs.GetReal("Distance to offset", old_dist, tol) if not off_dist: return trans_type = rs.GetString("Offset transition?", old_trans, t_choice) if not trans_type: return if trans_type == "Sharp": tt = 1 elif trans_type == "Round": tt = 2 elif trans_type == "Smooth": tt = 3 elif trans_type == "Chamfer": tt = 4 else: return end_type = rs.GetString("End connection type?", old_ends, e_choice) if not end_type: return if end_type == "None": conn = -1 elif end_type == "Straight": conn = 0 elif end_type == "Arc": conn = 1 elif end_type == "OffsetStraight": conn = 2 else: return rs.EnableRedraw(False) rs.UnselectAllObjects count = 0 for crv in crvs: success = OffsetCurve2Sides(crv, off_dist, tt, conn, tol) if success: count += 1 if count < len(crvs): err_msg = " Unable to offset {} curves".format(len(crvs) - count) else: err_msg = "" print "Successfully offset {} curves.".format(count) + err_msg #Set preferences sc.sticky["OffsetCrvs_Dist"] = off_dist sc.sticky["OffsetCrvs_TChoice"] = trans_type sc.sticky["OffsetCrvs_EChoice"] = end_type
def RunCommand(is_interactive): if "FOFIN" not in sc.sticky: print("Initialise the plugin first!") return FOFIN = sc.sticky["FOFIN"] options = ["save", "save_as"] option = rs.GetString("Save the FOFIN session.", options[0], options) if not option: return data = {"settings": FOFIN["settings"], "cablenet": None} if FOFIN["cablenet"]: data["cablenet"] = FOFIN["cablenet"].to_data() file_dir = FOFIN["settings"]["file.dir"] file_name = FOFIN["settings"]["file.name"] if option == "save": if not file_dir: file_dir = compas_rhino.select_folder(default=HERE) if not file_dir: print("No directory selected.") return if not file_name: file_name = rs.GetString("File name") elif option == "save_as": FOLDER = file_dir or HERE file_dir = compas_rhino.select_folder(default=FOLDER) if not file_dir: print("No directory selected.") return file_name = rs.GetString("File name") FOFIN["settings"]["file.dir"] = file_dir FOFIN["settings"]["file.name"] = file_name if not os.path.isdir(file_dir): print("The selected directory is invalid: {}".format(file_dir)) return if not file_name: print("No filename provided.") return if not file_name.endswith(".fofin"): print("The filename is invalid: {}".format(file_name)) return filepath = os.path.join(file_dir, file_name) with open(filepath, "w") as f: json.dump(data, f)
def customized_smoothing_constraints(mesh, constraints): """Add custom point, curve and surface constraints to the vertices of a mesh to smooth. Parameters ---------- mesh : Mesh The mesh to apply the constraints to for smoothing. constraints : dict A dictionary of mesh constraints for smoothing as vertex keys pointing to point, curve or surface objects. Returns ------- constraints : dict The updated dictionary of mesh constraints for smoothing as vertex keys pointing to point, curve or surface objects. """ while True: guids = display_smoothing_constraints(mesh, constraints) vkeys = mesh_select_vertices(mesh) if len(vkeys) == 2 and rs.GetString( 'get all polyedge?', strings=['True', 'False']) == 'True': u, v = vkeys vkeys = mesh.polyedge(u, v) if vkeys is None: break constraint = rs.GetString( 'edit smoothing constraints?', strings=['point', 'curve', 'surface', 'exit']) rs.DeleteObjects(guids) if constraint is None or constraint == 'exit': break elif constraint == 'point': point = RhinoPoint.from_selection() constraints.update({vkey: point.guid for vkey in vkeys}) elif constraint == 'curve': curve = RhinoCurve.from_selection() constraints.update({vkey: curve.guid for vkey in vkeys}) elif constraint == 'surface': surface = RhinoSurface.from_selection() constraints.update({vkey: surface.guid for vkey in vkeys}) return constraints
def Rename(): blockName = rs.GetString("block to rename") instanceDefinition = doc.InstanceDefinitions.Find(blockName, True) if not instanceDefinition: print "{0} block does not exist".format(blockName) return newName = rs.GetString("new name") instanceDefinition = doc.InstanceDefinitions.Find(newName, True) if instanceDefinition: print "the name '{0}' is already taken by another block".format(newName) return rs.RenameBlock(blockName, newName)
def _get_rule(self, left_shape, right_shape): """Receives the left and right shapes: Shape Shape Prompts for a name. Returns the new rule: Rule """ prompt_for_name = 'Enter the name of the rule' name = rs.GetString(prompt_for_name) while not self._is_well_formed(name): prompt_for_name = ('The name may not contain a space or a #. ' + 'Enter the name of the rule') name = rs.GetString(prompt_for_name) new_rule = rule.Rule(name, left_shape, right_shape) return new_rule
def density_menu(pattern): """Modify density. Parameters ---------- pattern : Pattern The pattern instance. Returns ------- string Which modification to do. """ functions = { 'densify_equal': densification_equal_density_parameters, 'densify_target': densification_target_based_density_parameters, 'densify_edit': set_strip_density_parameter } func = rs.GetString('density', strings=list(functions)) if func in functions: functions[func](pattern) pattern.draw_density() pattern.draw_topology() pattern.draw_geometry()
def process(): objs = rs.GetObjects('select objs', preselect=True) grade = rs.GetString("toggle grade") rs.EnableRedraw(False) isUG = trp.boolToggle(grade) groups = trp.groupByElevation(objs, isUG) trp.setLevel(groups, isUG, trp.setLevelforObj)
def prompt(): objs = rs.GetObjects("select Objects to set to new layer:", 0, True, True, False) if objs: layerName = rs.GetString("layer name:") if layerName: setObjectToLayer(objs, layerName)
def RunCommand(): gs = Rhino.Input.Custom.GetObject() gs.SetCommandPrompt("select sphere") gs.GeometryFilter = Rhino.DocObjects.ObjectType.Surface gs.DisablePreSelect() gs.SubObjectSelect = False gs.Get() if gs.CommandResult() != Rhino.Commands.Result.Success: return gs.CommandResult() b, sphere = gs.Object(0).Surface().TryGetSphere() if sphere.IsValid: mesh = Rhino.Geometry.Mesh.CreateFromSphere(sphere, 10, 10) if mesh == None: return Rhino.Commands.Result.Failure conduit = DrawBlueMeshConduit(mesh) conduit.Enabled = True doc.Views.Redraw() inStr = rs.GetString("press <Enter> to continue") conduit.Enabled = False doc.Views.Redraw() return Rhino.Commands.Result.Success else: return Rhino.Commands.Result.Failure
def RunCommand(is_interactive): try: if 'compas_assembly' not in sc.sticky: raise Exception('Initialise the Assembly plugin first!') assembly = sc.sticky['compas_assembly']['assembly'] settings = sc.sticky['compas_assembly']['settings'] session_dir = compas_rhino.select_folder('Save where?', SESSIONS) if not session_dir: return session_name = rs.GetString('Session name', 'session.compas_assembly') if not session_name: return session_path = os.path.join(session_dir, session_name) Blocks = { key: assembly.blocks[key].to_data() for key in assembly.vertices() } data = { 'settings': settings, 'assembly': assembly.to_data(), 'blocks': Blocks, } with open(session_path, 'w+') as fo: json.dump(data, fo) except Exception as error: print(error) print(traceback.format_exc())
def GetOptions(): restore = rs.GetBoolean("Rhino Appearance Settings", [("Option", "Save", "Restore")], [False]) if restore is None: return restore = restore[0] name = rs.GetString("Scheme Name") if name: return name, restore
def singularity_menu(pattern): """Modify singularites. Parameters ---------- pattern : Pattern The pattern instance. Returns ------- string Which modification to do. """ functions = { 'new_from_medial_axis': medial_axis_singularity_mesh, 'edit_existing': edit_singularity_mesh } func = rs.GetString('singularity', strings=list(functions)) if func in functions: functions[func](pattern) pattern.draw_singularity() pattern.draw_density() pattern.draw_topology() pattern.draw_geometry()
def topology_menu(pattern): """Display topology menu to select what to modify. Parameters ---------- pattern : Pattern The pattern instance. Returns ------- string Which modification to do. """ functions = { 'reset': reset_topology_mesh, 'global': global_topology, 'local': local_topology } func = rs.GetString('topology', strings=list(functions)) if func in functions: functions[func](pattern) pattern.draw_topology() pattern.draw_geometry()
def get_next_action(): actions = ["e","a","m","r","s","n"] actions.extend(config.exit_commands) next_action = "" while next_action not in actions: next_action = rs.GetString('Enter (e) for new emotion, (a) to add emotion, (m) to modify, (r) to render animation, (s) to save, or (n) for new object:') return next_action
def save_design(coarse_pseudo_quad_mesh, layer): """Save one of the meshes based on the coarse quad mesh. Parameters ---------- mesh : CoarsePseudoQuadMesh The coarse quad mesh from which to save data. """ mesh_to_save = rs.GetString('mesh to save?', strings=[ 'coarse_pseudo_quad_mesh', 'pseudo_quad_mesh', 'polygonal_mesh' ]) guid = None if mesh_to_save == 'coarse_pseudo_quad_mesh': artist = rhino_artist.MeshArtist(coarse_pseudo_quad_mesh) guid = artist.draw_mesh(coarse_pseudo_quad_mesh) elif mesh_to_save == 'pseudo_quad_mesh': artist = rhino_artist.MeshArtist( coarse_pseudo_quad_mesh.get_quad_mesh()) guid = artist.draw_mesh() elif mesh_to_save == 'polygonal_mesh': artist = rhino_artist.MeshArtist( coarse_pseudo_quad_mesh.get_polygonal_mesh()) guid = artist.draw_mesh() if guid is not None: layer = rs.GetLayer(layer=layer) rs.ObjectLayer(guid, layer)
def RunCommand(is_interactive): try: if 'compas_assembly' not in sc.sticky: raise Exception('Initialise the Assembly plugin first!') assembly = sc.sticky['compas_assembly']['assembly'] folder = compas_rhino.select_folder(default=compas_rbe.DATA) print(folder) if not folder: return filename = rs.GetString('Name of the json file?') print(filename) if not filename: return name, ext = os.path.splitext(filename) if ext != '.json': filename = name + ext + '.json' assembly.to_json(os.path.join(folder, filename)) except Exception as error: print(error) print(traceback.format_exc())
def meshfunction_xy(): zfunc, domain, resolution = loadfunctiondata() zfunc = rs.StringBox( zfunc, "Specify a function f(x,y[,D,A])", "Mesh function") if not zfunc: return while True: prompt = "Function domain x{%f,%f} y{%f,%f} @%d" % (domain[0], domain[1], domain[2], domain[3], resolution) result = rs.GetString(prompt, "Insert", ("xMin","xMax","yMin","yMax","Resolution","Insert")) if not result: return result = result.upper() if result=="XMIN": f = rs.GetReal("X-Domain start", domain[0]) if f is not None: domain[0]=f elif result=="XMAX": f = rs.GetReal("X-Domain end", domain[1]) if f is not None: domain[1]=f elif result=="YMIN": f = rs.GetReal("Y-Domain start", domain[2]) if f is not None: domain[2]=f elif result=="YMAX": f = rs.GetReal("Y-Domain end", domain[3]) if f is not None: domain[3]=f elif result=="RESOLUTION": f = rs.GetInteger("Resolution of the graph", resolution) if f is not None: resolution=f elif result=="INSERT": break verts = createmeshvertices(zfunc, domain, resolution) faces = createmeshfaces(resolution) rs.AddMesh(verts, faces)
def _get_shape(self, side): """Receives 'left' or 'right': str Prompts for elements (lines and textdots) and a name. Returns the new shape: Shape """ # left shape must not be empty prompt_for_elements = ( 'Select the lines and textdots in the %s shape' % side) guids = rs.GetObjects(prompt_for_elements, rs.filter.curve + rs.filter.textdot) if side == 'left': while guids == None: prompt_for_elements = ( 'The left shape may not be empty. ' + 'Select the lines and textdots in the left shape') guids = rs.GetObjects(prompt_for_elements, rs.filter.curve + rs.filter.textdot) elif side == 'right': if guids == None: guids = [] else: pass line_specs, lpoint_specs = ( self._get_line_specs_and_lpoint_specs(guids)) prompt_for_name = ('Enter the name of the %s shape' % side) name = rs.GetString(prompt_for_name) new_shape = shape.Shape(name, line_specs, lpoint_specs) return new_shape
def createcurvaturegraph(): curve_ids = rs.GetObjects("Curves for curvature graph", 4, False, True, True) if not curve_ids: return samples = 10 scale = 1.0 preview = [] while True: rs.EnableRedraw(False) for p in preview: rs.DeleteObjects(p) preview = [] for id in curve_ids: cg = addcurvaturegraph(id, samples, scale) preview.append(cg) rs.EnableRedraw(True) result = rs.GetString("Curvature settings", "Accept", ("Samples", "Scale", "Accept")) if not result: for p in preview: rs.DeleteObjects(p) break result = result.upper() if result == "ACCEPT": break elif result == "SAMPLES": numsamples = rs.GetInteger("Number of samples per knot-span", samples, 3, 100) if numsamples: samples = numsamples elif result == "SCALE": sc = rs.GetReal("Scale of the graph", scale, 0.01, 1000.0) if sc: scale = sc
def RunCommand(is_interactive): if "FOFIN" not in sc.sticky: print("Initialise the plugin first!") return FOFIN = sc.sticky["FOFIN"] if not FOFIN["cablenet"]: print("No cablenet to serialise.") return file_dir = FOFIN["settings"]["file.dir"] FOLDER = file_dir or HERE file_dir = compas_rhino.select_folder(default=FOLDER) if not file_dir: print("No directory selected.") return if not os.path.isdir(file_dir): print("The selected directory is invalid: {}".format(file_dir)) return file_name = rs.GetString("File name") if not file_name: print("No filename provided.") return if not file_name.endswith(".json"): print("The filename is invalid: {}".format(file_name)) return filepath = os.path.join(file_dir, file_name) FOFIN["cablenet"].to_json(filepath)
def global_topology(pattern): """Global topological editing of the density mesh. Parameters ---------- pattern : Pattern The pattern instance. Returns ------- """ conway_operators = { 'conway_dual': conway_dual, 'conway_join': conway_join, 'conway_ambo': conway_ambo, 'conway_kis': conway_kis, 'conway_needle': conway_needle, 'conway_zip': conway_zip, 'conway_truncate': conway_truncate, 'conway_ortho': conway_ortho, 'conway_expand': conway_expand, 'conway_gyro': conway_gyro, 'conway_snub': conway_snub, 'conway_meta': conway_meta, 'conway_bevel': conway_bevel } op = rs.GetString('topology', strings=list(conway_operators)) if op in conway_operators: pattern.topology_mesh = conway_operators[op](pattern.topology_mesh)
def apply_conway_operator(singularity_mesh): conway_operators = { 'back_to_seed', 'conway_dual', 'conway_join', 'conway_ambo', 'conway_kis', 'conway_needle', 'conway_zip', 'conway_truncate', 'conway_ortho', 'conway_expand', 'conway_gyro', 'conway_snub', 'conway_meta', 'conway_bevel' } conway = {operator[7:]: operator for operator in conway_operators} operator = rs.GetString('select Conway operator', strings=conway.keys() + ['exit']) if operator == 'back_to_seed': singularity_mesh.polygonal_mesh = singularity_mesh.quad_mesh.copy() elif operator in conway and conway[operator] in globals() and str(conway[operator])[: 6] == 'conway': singularity_mesh.polygonal_mesh = globals()[conway[operator]](singularity_mesh.polygonal_mesh) return singularity_mesh
def lock(): layerName = rs.GetString("Name of layer to lock") matchingLayers = [layer for layer in doc.Layers if layer.Name == layerName] layerToLock = None if len(matchingLayers) == 0: print "Layer \"{0}\" does not exist.".format(layerName) elif len(matchingLayers) == 1: layerToLock = matchingLayers[0] elif len(matchingLayers) > 1: i = 0 for layer in matchingLayers: print "({0}) {1}".format( i + 1, matchingLayers[i].FullPath.replace("::", "->")) i += 1 selectedLayer = rs.GetInteger("which layer?", -1, 1, len(matchingLayers)) if selectedLayer == None: return layerToLock = matchingLayers[selectedLayer - 1] if layerToLock.IsLocked: print "layer {0} is already locked.".format(layerToLock.FullPath) else: layerToLock.IsLocked = True layerToLock.CommitChanges()
def GetMap(): socket.setdefaulttimeout(10) filename = 'c:\\map.jpg' # you migth hve to change this path street = rs.GetString('Street') city = rs.GetString('City') country = rs.GetString('Country') zoom = rs.GetInteger('Zoom', 17, 1, 19) rs.UnitSystem(4, True) url = 'http://nominatim.openstreetmap.org/search?q=' + street + ',' + city + ',' + country + '&format=xml' rs.CurrentView('Top') try: xml = urllib.urlopen(url).read() except: print 'http://nominatim.openstreetmap.org produced an error' return temp = xml[xml.find("lat=") + 5:-1] lat = temp[0:temp.find("'")] temp = xml[xml.find("lon=") + 5:-1] lng = temp[0:temp.find("'")] print 'Latitude, Longitude: ' + lat + ", " + lng picture_page = 'http://osm-tah-cache.firefishy.com/MapOf/?lat=' + lat + '&long=' + lng + '&z=' + str( zoom) + '&w=1000&h=1000&format=jpeg' opener1 = urllib2.build_opener() try: page1 = opener1.open(picture_page) my_picture = page1.read() except: print 'http://osm-tah-cache.firefishy.com produced an error' return try: fout = open(filename, 'wb') fout.write(my_picture) fout.close() except: print 'writing of ' + path + ' produced an error' return res = 40075017 * math.cos( float(lat) / 180 * math.pi) / (256 * 2**zoom) * 1000 rs.Command('_-BackgroundBitmap Remove _Enter', False) rs.Command( '_-BackgroundBitmap ' + filename + ' ' + str(-res / 2) + ',' + str(-res / 2) + ',0 ' + str(res / 2) + ',' + str(res / 2) + ',0 _Enter', True) rs.Command('_-BackgroundBitmap Grayscale=No _Enter', False) rs.Command( '_-EarthAnchorPoint Latitude ' + lat + ' Longitude ' + lng + ' _Enter _Enter _Enter _Enter _Enter', False)
def Delete(): blockName = rs.GetString("block to delete") instanceDefinition = doc.InstanceDefinitions.Find(blockName, True) if not instanceDefinition: print "{0} block does not exist".format(blockName) return rs.DeleteBlock(blockName)
def get_obj_type(): object_id = "" while object_id not in config.object_types and object_id not in config.exit_commands: object_id = rs.GetString('Enter object type (B=Bottle)') if object_id in config.exit_commands: return None else: return config.object_types[object_id]
def editing_topology(coarse_pseudo_quad_mesh): """Edit the topology of a pattern, i.e. its singularities, via its strips. Parameters ---------- coarse_pseudo_quad_mesh : CoarsePseudoQuadMesh The pattern to edit. """ while True: # update drawing rs.EnableRedraw(False) artist = rhino_artist.MeshArtist(coarse_pseudo_quad_mesh) guid = artist.draw_mesh() rs.EnableRedraw(True) # choose operation operation = rs.GetString('edit strip topology?', strings=['add', 'delete', 'split', 'exit']) # stop if asked if operation is None or operation == 'exit': rs.DeleteObject(guid) break # apply operation if operation == 'add': skey = add_strip(coarse_pseudo_quad_mesh, select_mesh_polyedge(coarse_pseudo_quad_mesh))[0] coarse_pseudo_quad_mesh.set_strip_density(skey, 1) elif operation == 'delete': skeys = set(select_quad_mesh_strips(coarse_pseudo_quad_mesh)) skey_to_skeys = delete_strips(coarse_pseudo_quad_mesh, skeys) if skey_to_skeys is not None: for skey_0, skeys in skey_to_skeys.items(): d = int( ceil( float( coarse_pseudo_quad_mesh.get_strip_density( skey_0)) / 2.)) coarse_pseudo_quad_mesh.set_strips_density(d, skeys) elif operation == 'split': skey = select_quad_mesh_strip(coarse_pseudo_quad_mesh) n = rs.GetInteger('number of splits', number=2, minimum=2) skeys = split_strip(coarse_pseudo_quad_mesh, skey, n=n) # update data d = int( ceil( float(coarse_pseudo_quad_mesh.get_strip_density(skey)) / float(n))) coarse_pseudo_quad_mesh.set_strips_density(d, skeys) # delete drawing rs.DeleteObject(guid)
def get_modified_emotion_breakdown_directly(emotion_object): emotion_breakdown = emotion_object.get_breakdown() for primary_emotion in emotion_breakdown: new_value = int(rs.GetString("'"+str(primary_emotion)+"' is currently set to "+str(emotion_breakdown[primary_emotion])+". Enter (0) or (int) to reset it to that value.")) # prevent negatives if new_value < 0: new_value = 0 emotion_breakdown[primary_emotion] = new_value return emotion_breakdown