def select_polyline(message='Select one polyline (curve with degree = 1, and multiple segments).'): """Select one polyline in the Rhino view. Parameters ---------- message : str, optional Instruction for the user. Returns ------- System.Guid The identifer of the selected polyline. """ guid = rs.GetObject(message, preselect=True, select=True, filter=rs.filter.curve) if is_curve_polyline(guid): return guid return None
def fitcurvetolength(): curve_id = rs.GetObject("Select a curve to fit to length", 4, True, True) if curve_id is None: return length = rs.CurveLength(curve_id) length_limit = rs.GetReal("Length limit", 0.5 * length, 0.01 * length, length) if length_limit is None: return while True: if rs.CurveLength(curve_id) <= length_limit: break curve_id = rs.ScaleObject(curve_id, (0, 0, 0), (0.95, 0.95, 0.95)) if curve_id is None: print "Something went wrong..." return print "New curve length: ", rs.CurveLength(curve_id)
def select_polygon( message='Select one polygon (closed curve with degree = 1)'): """Select one polygon in the Rhino view. Parameters ---------- message : str, optional Default is "Select an polygon.". Returns ------- GUID The identifer of the selected polygon. """ guid = rs.GetObject(message, filter=rs.filter.curve) if is_curve_polygon(guid): return guid return None
def select_curve(message='Select one curve.'): """Select one curve in the Rhino view. Parameters ---------- message : str, optional Default is "Select an line.". Returns ------- GUID The identifer of the selected curve. """ return rs.GetObject(message, preselect=True, select=True, group=False, filter=rs.filter.curve)
def select_mesh(message='Select one mesh.'): """Select one mesh in the Rhino view. Parameters ---------- message : str, optional Instruction for the user. Returns ------- System.Guid The identifer of the selected mesh. """ return rs.GetObject( message, preselect=True, select=True, filter=rs.filter.mesh )
def select_polygon(message='Select one polygon (closed curve with degree = 1)'): """Select one polygon in the Rhino view. Parameters ---------- message : str, optional Instruction for the user. Returns ------- System.Guid The identifer of the selected polygon. """ guid = rs.GetObject(message, preselect=True, select=True, filter=rs.filter.curve) if is_curve_polygon(guid): return guid return None
def select_line(message='Select line.'): """Select one line in the Rhino view. Parameters ---------- message : str, optional Instruction for the user. Returns ------- System.Guid The identifer of the selected line. """ guid = rs.GetObject(message, preselect=True, select=True, filter=rs.filter.curve) if is_curve_line(guid): return guid return None
def __init__(self): self.midpoints = [] self.partsHash = {} self.curve_object = rs.GetObject("Pick a backbone curve", 4, True, False) self.outFile = rs.GetString('Input a name for the length file') self.create_cross_sections() self.brep = rs.AddLoftSrf(self.cross_sections) self.points_from_cross() # self.add_text() self.points_for_lines() self.create_lines() self.label_and_len_lines() rs.DeleteObjects(self.brep) self.draw_points() f = open('{0}.json'.format(self.outFile), 'w') f.write(json.dumps(self.partsHash)) f.close()
def AnnotateCurveEndPoints(): """Annotates the endpoints of curve objects. If the curve is closed then only the starting point is annotated. """ # get the curve object objectId = rs.GetObject("Select curve", rs.filter.curve) if objectId is None: return # Add the first annotation point = rs.CurveStartPoint(objectId) rs.AddPoint(point) rs.AddTextDot(point, point) # Add the second annotation if not rs.IsCurveClosed(objectId): point = rs.CurveEndPoint(objectId) rs.AddPoint(point) rs.AddTextDot(point, point)
def select_polyline( message='Select one polyline (curve with degree = 1, and multiple segments).' ): """Select one polyline in the Rhino view. Parameters ---------- message : str, optional Default is "Select an polyline.". Returns ------- GUID The identifer of the selected polyline. """ guid = rs.GetObject(message, filter=rs.filter.curve) if is_curve_polyline(guid): return guid return None
def ptsOnSrf (): surfaceId = rs.GetObject("pick surface", 8, True, True) uVal = rs.GetInteger("pick u/row count",4, 1, 20) vVal = rs.GetInteger("pick v/col count",4, 1, 20) uDomain = rs.SurfaceDomain(surfaceId, 0) vDomain = rs.SurfaceDomain(surfaceId, 1) uStep = (uDomain[1] - uDomain[0])/ uVal vStep = (vDomain[1] - vDomain[0])/ vVal count = 0 allPts = [] for i in rs.frange(uDomain[0], uDomain[1], uStep): for j in rs.frange(vDomain[0], vDomain[1], vStep): point = rs.EvaluateSurface(surfaceId, i, j) newPt = rs.AddPoint(point) allPts.append(newPt) rs.AddInterpCrvOnSrf(surfaceId, allPts) rs.DeleteObjects(allPts)
def Sweep1(): rail = rs.GetObject("Select rail curve", rs.filter.curve) rail_crv = rs.coercecurve(rail) if not rail_crv: return cross_sections = rs.GetObjects("Select cross section curves", rs.filter.curve) if not cross_sections: return cross_sections = [rs.coercecurve(crv) for crv in cross_sections] sweep = Rhino.Geometry.SweepOneRail() sweep.AngleToleranceRadians = scriptcontext.doc.ModelAngleToleranceRadians sweep.ClosedSweep = False sweep.SweepTolerance = scriptcontext.doc.ModelAbsoluteTolerance sweep.SetToRoadlikeTop() breps = sweep.PerformSweep(rail_crv, cross_sections) for brep in breps: scriptcontext.doc.Objects.AddBrep(brep) scriptcontext.doc.Views.Redraw()
def flatWorm(): curveObject = rs.GetObject("pick a backbone curve", 4, True, False) samples = rs.GetInteger("# of crosssections", 100, 5) bend_radius = rs.GetReal("bend radius", 0.5, 0.001) # r1 perp_radius = rs.GetReal("ribbon plan radius", 2.0, 0.001) #r2 crvDom = rs.CurveDomain( curveObject ) # domain != length // why do we use domains? == "The domain is the set of all possible input values to the function that defines the curve or surface." crossSections = [] # empty array to store sections t_step = (crvDom[1] - crvDom[0]) / samples # this is starting to be a pattern! t = crvDom[0] # start pt for loop at the start of the line for t in rs.frange(crvDom[0], crvDom[1], t_step): # loop thru entire domain w/ floats crvCurvature = rs.CurveCurvature( curveObject, t ) # evaluate curve with a circle - gives 3d normals & gives radius info crossSecPlane = None if not crvCurvature: crvPoint = rs.EvaluateCurve(curveObject, t) crvTan = rs.CurveTangent(curveObject, t) # get tangent vector crvPerp = (0, 0, 1) crvNorm = rs.VectorCrossProduct(crvTan, crvPerp) # = product of 2 vectors crossSecPlane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNorm) else: crvPoint = crvCurvature[0] crvTan = crvCurvature[1] crvPerp = rs.VectorUnitize(crvCurvature[4]) crvNorm = rs.VectorCrossProduct(crvTan, crvPerp) # look up crossSecPlane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNorm) if crossSecPlane: csec = rs.AddEllipse( crossSecPlane, bend_radius, perp_radius ) # draw ellipse at tan/normal to point along curve with radii crossSections.append(csec) # add ellipses to an array t += t_step # step through domain rs.AddLoftSrf(crossSections) # loft list of curves rs.DeleteObjects( crossSections) # delete original list of curves as cleanup
def scalecurve(): curve_id = rs.GetObject("pick curve", 4) # provide breakout bc idk if curve_id is None: return length = rs.CurveLength(curve_id) print "current length: %g " % length length_max = rs.GetReal("max length? ", .5 * length, .1 * length, 10 * length) # you can set ranges! if length_max is None: return while length < length_max: curve_id = rs.ScaleObject(curve_id, (0, 0, 0), (1.5, 1.5, 1.5), True) length = rs.CurveLength(curve_id) print "new curve length: %g" % rs.CurveLength(curve_id)
def array_between(): rs.SelectObject(u) m=rs.GetObject('select the curve for path') amount = rs.GetInteger('How many objects in array') if not amount: return p=rs.DivideCurveEquidistant(m,amount,True) for i in p: point1 = i for x in p: point2 = x vector = rs.VectorCreate(point2, point1) copyvec = rs.VectorDivide(vector, amount - 1) for v in range(1, amount): copy = rs.CopyObject(u, copyvec * v) rs.UnselectObject(u)
def FlatWorm(): curve_object = rs.GetObject("Pick a backbone curve", 4, True, False) if not curve_object: return samples = rs.GetInteger("Number of cross sections", 100, 5) if not samples: return bend_radius = rs.GetReal("Bend plane radius", 0.5, 0.001) if not bend_radius: return perp_radius = rs.GetReal("Ribbon plane radius", 2.0, 0.001) if not perp_radius: return crvdomain = rs.CurveDomain(curve_object) crosssections = [] t_step = (crvdomain[1]-crvdomain[0])/samples t = crvdomain[0] while t<=crvdomain[1]: crvcurvature = rs.CurveCurvature(curve_object, t) crosssectionplane = None if not crvcurvature: crvPoint = rs.EvaluateCurve(curve_object, t) crvTangent = rs.CurveTangent(curve_object, t) crvPerp = (0,0,1) crvNormal = rs.VectorCrossProduct(crvTangent, crvPerp) crosssectionplane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNormal) else: crvPoint = crvcurvature[0] crvTangent = crvcurvature[1] crvPerp = rs.VectorUnitize(crvcurvature[4]) crvNormal = rs.VectorCrossProduct(crvTangent, crvPerp) crosssectionplane = rs.PlaneFromFrame(crvPoint, crvPerp, crvNormal) if crosssectionplane: csec = rs.AddEllipse(crosssectionplane, bend_radius, perp_radius) crosssections.append(csec) t += t_step if not crosssections: return rs.AddLoftSrf(crosssections) rs.DeleteObjects(crosssections)
def deletecurvesontuesdays(): object_id = rs.GetObject("Select an object to delete on tuesdays", 0, True, True) if object_id is None: return if rs.IsCurve(object_id): if rs.CurveLength(object_id) < 1.0: if rs.IsCurveClosed(object_id): now = datetime.datetime.now() if now.weekday() == 1: rs.DeleteObject(object_id) else: print "This software is a tryout version and runs only on Tuesdays." print "Please purchase the full product." else: print "Curve was not closed" else: print "Curve was too long" else: print "Object was not a curve"
def select_line(message='Select line.'): """Select one line in the Rhino view. Parameters ---------- message : str, optional Default is "Select an line.". Returns ------- GUID The identifer of the selected line. """ guid = rs.GetObject(message, preselect=True, select=True, filter=rs.filter.curve) if is_curve_line(guid): return guid return None
def moveLight(): """ Use this script to move a light in the direction it is aimed. Positive values are in the direction it aimed at. Typically use this in a toolbar, where you can pass the distance directly. script by Gijs de Zwart www.studiogijs.nl """ distance = rs.GetInteger(number=10) object = rs.GetObject("select light to move in normal direction", preselect=True, filter=256) if not object: return light = rs.coercerhinoobject(object) dir = light.LightGeometry.Direction dir.Unitize() trans = dir * distance rs.MoveObject(object, trans) rs.SelectObject(object)
def AddToBlock(): objects = rs.GetObjects("Choose Objects to Add to Block", preselect=True) if not objects: return block = rs.GetObject("Choose Block to Add Object to", rs.filter.instance) if not block: return rs.EnableRedraw(False) blockName = rs.BlockInstanceName(block) objref = rs.coercerhinoobject(block) idef = objref.InstanceDefinition idefIndex = idef.Index if rs.IsBlockReference(blockName): print "Block is referenced from file; unable to add object(s)" return blnCopy = False XformBlock = rs.BlockInstanceXform(block) rs.TransformObjects(objects, rs.XformInverse(XformBlock), blnCopy) objects.extend(rs.BlockObjects(blockName)) newGeometry = [] newAttributes = [] for object in objects: newGeometry.append(rs.coercegeometry(object)) ref = Rhino.DocObjects.ObjRef(object) attr = ref.Object().Attributes newAttributes.append(attr) InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry, newAttributes) rs.DeleteObjects(objects) rs.EnableRedraw(True)
def duplicateN(): obj = rs.GetObject("Select object to duplicate", 16, True) if obj is None: return box = rs.BoundingBox(obj) if not isinstance(box, list): return origin = rs.PointDivide(rs.PointAdd(box[0], box[6]), 2) endpt = rs.GetPoint("To point") ndups = rs.GetInteger("Number of duplications") maxd = rs.GetReal("Max Distance") translation = rs.VectorCreate(endpt, origin) for i in range(0, ndups, 1): xr = random() if random() < 0.5 else -1*random() yr = random() if random() < 0.5 else -1*random() zr = random() if random() < 0.5 else -1*random() newpt = [xr*maxd, yr*maxd, zr*maxd] translation1 = rs.VectorCreate(endpt, newpt) translation2 = rs.VectorCreate(translation1, origin) rs.CopyObject(obj, translation2)
def setAdditiveObj(self): ''' set object that is added when pick object, it must be mesh or polysurface if picked object is mesh, it will be converted to polysurface ''' tmp = rs.GetObject("Pick a additive obj", rs.filter.polysurface | rs.filter.mesh) if rs.IsMesh(tmp): self.additiveObj = rs.MeshToNurb(tmp) elif rs.IsPolysurface(tmp): self.additiveObj = tmp else: print("Please select \"mesh\" or \"polysurface\"") return False return True
def _prompt_for_expected_labeled_shape_elements_dict(): """Prompts the user to select frame instances and their elements to construct an expected labeled shape elements dictionary. Returns: expected_labeled_shape_elements_dict {str: [guid]}. A non-empty dictionary of labeled shape names and element lists """ (message_intro) = "%s %s" % ( "Select the frame instance of a non-empty initial shape ('i'),", "or the left ('l') or right ('r') shape of a non-empty rule") print(message_intro) (message_type) = "Enter the type of frame: 'i', 'l', or 'r'" (labeled_shape_elements_dict) = {} (message_frame) = "Select a frame" (block_instance_filter) = s.Settings.block_instance_filter (message_elements) = "Select the elements in the frame" (curve_filter) = s.Settings.curve_filter (text_dot_filter) = s.Settings.text_dot_filter (element_filter) = curve_filter + text_dot_filter while True: labeled_shape_type = rs.GetString(message_type) if not labeled_shape_type: break else: frame_instance = rs.GetObject(message_frame, block_instance_filter) layer = rs.ObjectLayer(frame_instance) if labeled_shape_type == 'i': labeled_shape = layer elif labeled_shape_type == 'l': labeled_shape = '%s_L' % layer elif labeled_shape_type == 'r': labeled_shape = '%s_R' % layer else: labeled_shape = 'bad_labeled_shape' element_list = [frame_instance] elements = rs.GetObjects(message_elements, element_filter) if elements: element_list.extend(elements) labeled_shape_elements_dict[labeled_shape] = element_list return labeled_shape_elements_dict
def curveDivByDiameter(): curve = rs.GetObject("sel curve") point = rs.GetPoint("sel point") num = rs.GetReal("radius") cBool = True # ptDir = rs.GetPoint("set Direction:") numA= num if(cBool): numA = num/2 else: numA = num circle = rs.AddCircle(point,numA) ix = rs.CurveCurveIntersection(curve,circle) rs.AddPoint(ix[0][1]) # or alternatively: # rs.AddPoint(ix[0][1]) # this should get the first intersection curve # rs.AddPoint(ix[1][1]) # this should get the second intersection curve arrPt = [] count = 20 countConst = count #create a check for point by point(x,y,z) value while(True != (ix[0][1] in arrPt) and count > 0): circle = rs.AddCircle(ix[0][1],num) ix = rs.CurveCurveIntersection(curve,circle) arrPt.append(rs.AddPoint(ix[0][1])) count -= 1 rs.Prompt(str(countConst-count)); count = 20 circle = rs.AddCircle(point,numA) ix = rs.CurveCurveIntersection(curve,circle) while(True != (ix[1][1] in arrPt) and count > 0): circle = rs.AddCircle(ix[1][1],num) ix = rs.CurveCurveIntersection(curve,circle) arrPt.append(rs.AddPoint(ix[1][1])) count -= 1 rs.Prompt(str(countConst-count));
def geodesicCurve(): #get a surface surface = rs.GetObject("Select Surface to Fit Curve", 8, True, True) if not surface: return #get the vertices for the shortest r2 path with 10 sample points vertices = getr2PathOnSurface(surface, 10, "Start Point for Curve", "End Point for Curve") if not vertices: return #set the tolerence for 1/10 of the tolerence of the model space tolerence = rs.UnitAbsoluteTolerance() * 0.1 #set a big and small starting value for our length tests length = 1e300 newLength = 0.0 #do this recursivly while True: print("Solving for %d samples" % len(vertices)) #run the vertices into the fitting subroutine vertices = geodesicFit(vertices, surface, tolerence) #check our length here, if we are with acceptable tolerence we should go newLength = polylineLength(vertices) if abs(newLength - length) < tolerence: break #if for some reason we still haven't found a solution and have over 1000 #vertices we should also go if len(vertices) > 1000: break #subdivide the polyline to double the number of samples and get ready to #start the fitting again vertices = subdivPolyline(vertices) length = newLength #once we are fit within tolerence, add the line to the document and prompt user rs.AddPolyline(vertices) print("added line")
def ExportControlPoints(): "Export curve's control points to a text file" #pick a curve object curve = rs.GetObject("Select curve", rs.filter.curve) #get the curve's control points points = rs.CurvePoints(curve) if not points: return #prompt the user to specify a file name filter = "Text file (*.txt)|*.txt|All files (*.*)|*.*||" filename = rs.SaveFileName("Save Control Points As", filter) if not filename: return file = open( filename, "w" ) for point in points: x_str = str(point.X) y_str = str(point.Y) z_str = str(point.Z) coord_string = x_str + ', ' + y_str + ', ' + z_str + '\n' file.write(coord_string) file.close()
def play_text(): draw_lpoint.draw_lpoint() annotation = rs.GetObject('Select object', rs.filter.annotation) point = rs.TextObjectPoint(annotation) label = rs.TextObjectText(annotation) print('object type: %s' % type(point)) point_type = type(point) if point_type == list: print('point type is list') elif point_type == tuple: print('point type is tuple') elif point_type == array.array: print('point type is array') # elif point_type == Point: # print('point type is Point') else: print('point type is something else') print('len(point): %i' % len(point)) x, y, z = point[0], point[1], point[2] print('coords: (%s, %s, %s)' % (x, y, z)) print('point: %s' % point) print('label: %s' % label)
def Section2D(): #"Create cross-section and rotate to 2D plane" # Select objects to draw section from objects = rs.GetObjects("Select objects to rotate", rs.filter.curve) # Select cross section plane sectionplane = rs.GetObject("Select cross-section line", rs.filter.curve) # Calculate orientation of cross-section plane startpt = rs.CurveStartPoint(sectionplane) midpt = rs.CurveMidPoint(sectionplane) endpt = rs.CurveEndPoint(sectionplane) x1, y1 = startpt[0], startpt[1] x2, y2 = endpt[0], endpt[1] rad2deg = 180 / math.pi angle = math.atan((y2 - y1) / (x2 - x1)) * rad2deg # rotate cross-section objects to 2D plane rs.RotateObjects(objects, midpt, -angle) rs.RotateObjects(objects, midpt, -90, [1, 0, 0])
def alloyWeight(): #alloy density density = { "Sterling Silver": 0.0105, "18K White": 0.0176, "18K Yellow": 0.0155, "9K White": 0.014, "9K Yellow": 0.012, "Platinum": 0.0215 } #create option list alloy = [] for y in density: alloy.append(y) try: #select object objs = rs.GetObject("Select PolySurfaces", rs.filter.polysurface) if objs is None: print "Aborted" return #check for naked edges if not rs.IsObjectSolid(objs): rs.ClearCommandHistory() print("\nPolySurface not solid") return #check for valid selection if objs: choice = rd.ListBox(alloy, "Select Alloy", "Alloys") wgt = round(rs.SurfaceVolume(objs)[0] * density.get(choice), 2) rs.ClearCommandHistory() print("\nVolume: " + str(round(rs.SurfaceVolume(objs)[0], 2)) + " amounts to " + str(wgt) + "g of " + choice) else: rs.ClearCommandHistory() print("\nNo valid PolySurface Selected!") except: print "Operation Aborted" Rhino.Commands.Result.Cancel
def RunSearch(): id = rs.GetObject("select mesh", rs.filter.mesh) mesh = rs.coercemesh(id) if mesh: rs.UnselectObject(id) tree = Rhino.Geometry.RTree() # I can add a RhinoCommon function that just builds an rtree from the # vertices in one quick shot, but for now... for i, vertex in enumerate(mesh.Vertices): tree.Insert(vertex, i) while (True): point = rs.GetPoint("test point") if not point: break data = SearchData(mesh, point) # Use the first vertex in the mesh to define a start sphere distance = point.DistanceTo(mesh.Vertices[0]) sphere = Rhino.Geometry.Sphere(point, distance * 1.1) if tree.Search(sphere, SearchCallback, data): rs.AddPoint(mesh.Vertices[data.Index]) print "Found point in {0} tests".format(data.HitCount)