def automated_smoothing_surface_constraints(mesh, surface): """Apply automatically surface-related constraints to the vertices of a mesh to smooth: kinks, boundaries and surface. Parameters ---------- mesh : Mesh The mesh to apply the constraints to for smoothing. surface : RhinoSurface A RhinoSurface object on which to constrain mesh vertices. Returns ------- constraints : dict A dictionary of mesh constraints for smoothing as vertex keys pointing to point, curve or surface objects. """ constraints = {} points = [rs.AddPoint(point) for point in surface.kinks()] curves = surface.borders(type=0) constraints.update({vkey: surface.guid for vkey in mesh.vertices()}) for vkey in mesh.vertices_on_boundary(): xyz = mesh.vertex_coordinates(vkey) projections = { curve: distance_point_point( xyz, RhinoCurve.from_guid(curve).closest_point(xyz)) for curve in curves } constraints.update({vkey: min(projections, key=projections.get)}) key_to_index = { i: vkey for i, vkey in enumerate(mesh.vertices_on_boundary()) } vertex_coordinates = tuple( mesh.vertex_coordinates(vkey) for vkey in mesh.vertices_on_boundary()) constraints.update({ key_to_index[closest_point_in_cloud(rs.PointCoordinates(point), vertex_coordinates)[2]]: point for point in points }) return constraints
def jump(self, force, dis): #make three points that together they can make an Arc, the first point would be heading position) distance = rs.VectorScale(self.direction, dis) startPoint = rs.PointCoordinates(self.point) endpoint = [ startPoint[0] + distance.X, startPoint[1] + distance.Y, startPoint[2] + distance.Z ] midpoint = [ startPoint[0] + distance.X / 2, startPoint[1] + distance.Y / 2, startPoint[2] + distance.Z / 2 ] rotatevec = rs.VectorRotate(self.direction, 90, [0, 0, 1]) heightvec = rs.VectorScale(rotatevec, force) midpoint1 = rs.AddPoint(midpoint) forcepoint = rs.MoveObject(midpoint1, heightvec) jumppath2 = rs.AddCurve([startPoint, forcepoint, endpoint]) jumppath3 = rs.AddInterpCurve([startPoint, forcepoint, endpoint])
def get_singularity_mesh(): guid = rs.GetObject('get singularity mesh', filter=32) vertices, faces = RhinoMesh.from_guid(guid).get_vertices_and_faces() clean_faces(faces) poles = [] for face in faces: if len(face) != 4: poles = [ rs.PointCoordinates(point) for point in rs.GetObjects('get pole points', filter=1) ] break singularity_mesh = CoarsePseudoQuadMesh.from_vertices_and_faces_with_poles( vertices, faces, poles) singularity_mesh.init_strip_density() singularity_mesh.quad_mesh = singularity_mesh.copy() singularity_mesh.polygonal_mesh = singularity_mesh.copy() return singularity_mesh
def closest_points(self,rh_objects): closest_list = [] test_object = rh_objects[0] closest_list.append(test_object) while True: if len(rh_objects) == 0: break rh_objects.pop(rh_objects.index(test_object)) if len(rh_objects) == 0: break closest_point_index = rs.PointArrayClosestPoint([rs.PointCoordinates(i.start_point) for i in rh_objects],test_object.point) closest_object = rh_objects[closest_point_index] closest_list.append(closest_object) test_object = closest_object #rs.DeleteObjects([point for point in point_cloud]) return closest_list
def get_point_coordinates(guids): """Get the coordintes of the locations of point objects. Parameters ---------- guids : list of GUID Returns ------- list of point The location coordinates of the points. """ points = [] for guid in guids: point = rs.PointCoordinates(guid) if point: points.append(map(float, point)) return points
def RestoreWorldCoordinate(): try: rs.EnableRedraw(False) # retreive northing and easting from text object obj = rs.ObjectsByName("_ORIGIN_TEXT_") if obj: text = rs.TextObjectText(obj) textList = text.split() easting = float(textList[1]) northing = float(textList[3]) # create reference coordinates to make vector orPoint = (easting, northing, 0) point = rs.PointCoordinates(rs.ObjectsByName("_ORIGIN_POINT_")) vector = rs.VectorCreate(orPoint, point) # move all objects back to original origin point allObj = rs.AllObjects() rs.MoveObjects(allObj, vector) # delete coordinate geometry isCurrent = rs.IsLayerCurrent("_ORIGIN_") if isCurrent == False: rs.PurgeLayer("_ORIGIN_") if isCurrent == True: defaultCheck = rs.IsLayer("Default") if defaultCheck == True: rs.CurrentLayer("Default") rs.PurgeLayer("_ORIGIN_") if defaultCheck == False: rs.AddLayer("Default") rs.CurrentLayer("Default") rs.PurgeLayer("_ORIGIN_") rs.EnableRedraw(True) except: print("Failed to execute") rs.EnableRedraw(True) return
def Main(): pts = rs.GetObjects("please select points", rs.filter.point) crvs = rs.GetObjects("please select crvs", rs.filter.curve) lines = [] for i in range(len(crvs)): lines.append( lineEq(rs.CurveStartPoint(crvs[i]), rs.CurveEndPoint(crvs[i]))) for i in range(len(pts)): pts[i] = rs.PointCoordinates(pts[i]) minDist = 10000000000000000000000 closest = lines[0].st for j in range(len(lines)): close = lines[j].closePt(pts[i]) dist = vecMag(vecDiff(close, pts[i])) if dist < minDist: minDist = dist closest = close rs.AddCurve([pts[i], closest]) #Main()
def ExportPoints(objectIds, filename): if (objectIds == None): return if (filename == None): return """ Using a 'with' loop to open the file, we do not need to clean up or close the file when we are done, Python takes care of it. Here, we'll write the points with a line break, otherwise all the points will end up on one line. """ with open(filename, "w") as file: for id in objectIds: #process point clouds if (rs.IsPointCloud(id)): points = rs.PointCloudPoints(id) for pt in points: # convert the point list to a string, # add a new line character, and write to the file file.write(str(pt) + "\n") elif (rs.IsPoint(id)): point = rs.PointCoordinates(id) file.write(str(point) + "\n")
def ExportPoints(): #Get the points to export objectIds = rs.GetObjects("Select Points", rs.filter.point | rs.filter.pointcloud, True, True) if (objectIds == None): return #Get the filename to create filter = "Text File (*.txt)|*.txt|All Files (*.*)|*.*||" filename = rs.SaveFileName("Save point coordinates as", filter) if (filename == None): return file = open(filename, "w") for id in objectIds: #process point clouds if (rs.IsPointCloud(id)): points = rs.PointCloudPoints(id) for pt in points: file.writeline(str(pt)) elif (rs.IsPoint(id)): point = rs.PointCoordinates(id) file.writeline(str(point)) file.close()
def __init__(self, curve, input_data, general_input, compensation, pocketing): self.log = [] self.input_data = input_data self.general_input = general_input self.compensation = compensation self.pocketing = pocketing self.asignedcluster = -1 self.iscluster = False self.nurbs_curve = curve self.curve = curve #Curva original2 self.type = "point" if rs.IsPoint( self.nurbs_curve) else "curve" if rs.IsCurveClosed( self.nurbs_curve) else "open_curve" self.point = self.curve if rs.IsPoint( self.nurbs_curve) else rs.CurveAreaCentroid( self.nurbs_curve)[0] if rs.IsCurveClosed( self.nurbs_curve) else rs.CurveStartPoint( self.nurbs_curve) # Centroide curva original self.start_point = rs.PointCoordinates( self.nurbs_curve, False) if rs.IsPoint( self.nurbs_curve) else rs.CurveStartPoint(self.nurbs_curve) self.cut_curve = self.get_cut_curve() self.time = 10
def add_node_set(structure, guids, name): """ Adds node set information from Rhino point guids. Parameters ---------- structure : obj Structure object to update. guids : list Rhino point guids. name : str Name of the new node set. Returns ------- None """ nodes = [] for guid in guids: node = structure.check_node_exists(rs.PointCoordinates(guid)) if node is not None: nodes.append(node) structure.add_set(name=name, type='node', selection=nodes)
def getX(point): pCood = rs.PointCoordinates(point) return pCood[0]
def __init__(self, pos=[0, 0, 0], heading=[1, 0, 0]): self.heading = heading self.point = rs.AddPoint(pos) pointPos = rs.PointCoordinates(self.point) self.direction = rs.VectorCreate(heading, pointPos) self.lines = []
def goto(self, x, y, z): prevPos = rs.PointCoordinates(self.point) movement = rs.VectorCreate([x, y, z], prevPos) rs.MoveObject(self.point, movement) currentPos = rs.PointCoordinates(self.point)
import rhinoscriptsyntax as rs from compas_rhino.geometry import RhinoMesh from compas_pattern.datastructures.mesh_quad_pseudo.mesh_quad_pseudo import PseudoQuadMesh from compas_pattern.cad.rhino.draw import draw_graph guids = rs.GetObjects('get quad meshes', filter=32) poles = rs.GetObjects('get pole points', filter=1) if poles is None: poles = [] else: poles = [rs.PointCoordinates(pole) for pole in poles] rs.EnableRedraw(False) for guid in guids: vertices, faces = RhinoMesh.from_guid(guid).get_vertices_and_faces() mesh = PseudoQuadMesh.from_vertices_and_faces_with_poles( vertices, faces, poles) #mesh = QuadMesh.from_vertices_and_faces(*RhinoMesh.from_guid(guid).get_vertices_and_faces()) #print('euler', mesh.euler()) #print('nb_boundaries', len(mesh.boundaries())) #mesh.collect_strips() #mesh.collect_polyedges() #polylines = [rs.AddPolyline(mesh.strip_edge_midpoint_polyline(skey)) for skey in mesh.strips()] #for i, polyline in enumerate(polylines): # #polylines = [rs.AddPolyline(polyline) for polyline in mesh.singularity_polylines()] #polylines = [rs.AddPolyline(polyline) for polyline in mesh.polylines()] #for polyline in polylines: # rs.CurveArrows(polyline, 3) #for i, vkey in enumerate(mesh.vertices()): # rs.AddCircle(mesh.vertex_coordinates(vkey), 2) # rs.AddText(str(i), mesh.vertex_coordinates(vkey), 2)
return y def randZ(z_range): z = random.uniform(0,z_range) return z #setting range for random numbers defined above xnum = randX(10) ynum = randY(10) znum = randZ(10) """ #og_source_pts = rs.ObjectsByLayer("Source Points", True) og_source_pts = rs.GetObjects("Select Source Points", rs.filter.point) for pt in og_source_pts: ptCoord = rs.PointCoordinates(pt) source_pts.append(ptCoord) def obj_layer(layer_name): '''trying to be able to call obj_layer on clos_pt with a particular layer name to give the corresponding cloud points a different parameter to move by ''' layer = rs.ObjectsByLayer(layer_name) return layer #initializing cloud of points, vectorize between cloud and original points, move pt by sub_vect amount\ #draw line between pt and original points for i in range(0, 5):
def place_pts(x_range, y_range, z_range): x = random.uniform(-25, x_range) y = random.uniform(-.2, y_range) z = random.uniform(-.2, z_range) pt = [x, y, z] return pt #put source point coordinates in source_pts list #og_source_pts = rs.ObjectsByLayer("Source Points", True) og_source_pts = rs.getobjects("Select Source Points", rs.filter.point) for pt in og_source_pts: ptCoord = rs.PointCoordinates(pt) source_pts.append(ptCoord) #find layer of each point, put in pt_layer_id = rs.ObjectLayer(pt) #initializing cloud of points for i in range(0, 3000): pt = rs.AddPoint(place_pts(25, .2, .2)) cloud_pts.append(pt) #find closest points from cloud to source points index = rs.PointArrayClosestPoint(source_pts, pt) clos_pt = source_pts[index] vect = rs.VectorCreate(clos_pt, pt) unit_vect = rs.VectorUnitize(vect) sub_vect = vect - unit_vect
boxes.append(array) #initializing line start = rs.AddPoint(0, 0, 0) end = rs.AddPoint(100, 0, 0) line = rs.AddLine(start, end) #Points = rs.DivideCurveLength(line,1,True,True) #pts.append(Points) for i in range(100): newPt = rs.AddPoint(i, 0, 0) xnum = randX(10) ynum = randY(10) znum = randZ(10) #find newPt coordinates to feed into the 8 needed box corners newPtCoord = rs.PointCoordinates(newPt) #newPtCoord = rs.PointCoordinates(pt) #add random xnum,ynum, or znum to respective index newboxArray = rs.AddBox([(newPtCoord),(newPtCoord[0]+xnum,newPtCoord[1],newPtCoord[2]),\ (newPtCoord[0]+xnum,newPtCoord[1]+ynum,newPtCoord[2]),(newPtCoord[0],newPtCoord[1]+ynum,newPtCoord[2]),\ (newPtCoord[0],newPtCoord[1],newPtCoord[2]+znum),(newPtCoord[0]+xnum,newPtCoord[1],\ newPtCoord[2]+znum),(newPtCoord[0]+xnum,newPtCoord[1]+ynum,newPtCoord[2]+znum),\ (newPtCoord[0],newPtCoord[1]+ynum,newPtCoord[2]+znum)]) pts.append(newPt) boxes.append(newboxArray)
def DeconstructPoint(pCords): point = rs.PointCoordinates(pCords) xval = point.X yval = point.Y pos = (xval, yval) return pos
def GetPoint(): pl = rs.ObjectsByType(1, False, 1) for p in pl: print rs.PointCoordinates(p)
def surface_discrete_mapping(srf_guid, discretisation, minimum_discretisation=5, crv_guids=[], pt_guids=[]): """Map the boundaries of a Rhino NURBS surface to planar poylines dicretised within some discretisation using the surface UV parameterisation. Curve and point feautres on the surface can be included. Parameters ---------- srf_guid : guid A surface guid. crv_guids : list List of guids of curves on the surface. pt_guids : list List of guids of points on the surface. discretisation : float The discretisation of the surface boundaries. minimum_discretisation : int The minimum discretisation of the surface boundaries. Returns ------- tuple Tuple of the mapped objects: outer boundary, inner boundaries, polyline_features, point_features. """ srf = RhinoSurface(srf_guid) # a boundary may be made of multiple boundary components and therefore checking for closeness and joining are necessary mapped_borders = [] for i in [1, 2]: mapped_border = [] for border in srf.borders(type=i): border = RhinoCurve(border) points = [ list(srf.point_xyz_to_uv(pt)) + [0.0] for pt in border.divide( max( int(border.length() / discretisation) + 1, minimum_discretisation)) ] if border.is_closed(): points.append(points[0]) mapped_border.append(points) rs.DeleteObject(border.guid) mapped_borders.append(mapped_border) outer_boundaries, inner_boundaries = [ network_polylines( Network.from_lines([(u, v) for border in mapped_borders[i] for u, v in pairwise(border)])) for i in [0, 1] ] # mapping of the curve features on the surface mapped_curves = [] for crv_guid in crv_guids: curve = RhinoCurve(crv_guid) points = [ list(srf.point_xyz_to_uv(pt)) + [0.0] for pt in curve.divide( max( int(curve.length() / discretisation) + 1, minimum_discretisation)) ] if curve.is_closed(): points.append(points[0]) mapped_curves.append(points) polyline_features = network_polylines( Network.from_lines([(u, v) for curve in mapped_curves for u, v in pairwise(curve)])) # mapping of the point features onthe surface point_features = [ list(srf.point_xyz_to_uv(rs.PointCoordinates(pt_guid))) + [0.0] for pt_guid in pt_guids ] return outer_boundaries[ 0], inner_boundaries, polyline_features, point_features
import rhinoscriptsyntax as rs import math as ma id = rs.GetObject("Select a point", 1) point0 = rs.PointCoordinates(id) for z in rs.frange(0, 100, 1): for theta in rs.frange(0, ma.pi * 2, ma.pi / 120): vec = [z * ma.cos(theta), z * ma.sin(theta), 5 * theta] point = rs.PointAdd(point0, vec) rs.AddPoint(point)
Properties(name='ep_plinth', material='mat_concrete', section='sec_plinth', elsets='elset_plinth', reinforcement=reb_plinth), Properties(name='ep_wall', material='mat_concrete', section='sec_wall', elsets='elset_wall', reinforcement=reb_wall)]) # Displacements mdl.add_displacement(FixedDisplacement(name='disp_fixed', nodes='nset_fixed')) # Loads mdl.add_load(GravityLoad(name='load_gravity', elements=['elset_wall', 'elset_plinth'])) components = {} for guid in rs.ObjectsByLayer('nset_loads'): px, py, pz = rs.ObjectName(guid).split(' ') components[mdl.check_node_exists(rs.PointCoordinates(guid))] = {'z': float(pz)*100} mdl.add_load(PointLoads(name='load_points', components=components)) loads = ['load_gravity', 'load_points'] # Steps mdl.add_steps([ GeneralStep(name='step_bc', nlgeom=False, displacements=['disp_fixed']), GeneralStep(name='step_loads', nlgeom=False, loads=loads)]) mdl.steps_order = ['step_bc', 'step_loads'] # Summary mdl.summary() # Run (Abaqus)
guids = rs.ObjectsByLayer('Lines') lines = [[rs.CurveStartPoint(i), rs.CurveEndPoint(i)] for i in guids if rs.IsCurve(i)] network = Network.from_lines(lines) # Attributes network.update_default_edge_attributes({'E': E, 'A': A, 's0': s0}) # Pins gkey_key = network.gkey_key() pins = [] for i in rs.ObjectsByLayer('Pins'): gkey = geometric_key(rs.PointCoordinates(i)) key = gkey_key[gkey] network.set_vertex_attributes(key, 'B', [[0, 0, 0]]) pins.append(key) # Run XFunc X, f, l, network = XFunc('compas.numerical.drx.drx_numpy.drx_numpy')( structure=network, factor=factor, tol=tol, steps=steps, refresh=10, update=True) # Draw Network
def main(): global g_instances global g_parts global g_indent global g_materials #print(sys.version_info) # (2, 7, 0, 'beta', 0) dlg = rc.UI.SaveFileDialog() dlg.DefaultExt = "model" dlg.Filter = "RocketScience 3D Model (*.model)" dlg.InitialDirectory = os.path.dirname(sc.doc.Path) if not dlg.ShowSaveDialog(): return None selectedObjects = rs.SelectedObjects() objects = [] origin = [0, 0, 0] for object in selectedObjects: name = rs.ObjectName(object) type = rs.ObjectType(object) if type == rs.filter.point: if name.startswith("Origin"): origin = rs.PointCoordinates(object) else: objects.append(object) print("Processing " + str(len(objects)) + " object(s)") print("Origin is [%.2f,%.2f,%.2f]" % (origin[0], origin[1], origin[2])) rootInstance = \ { "name" : "*", "fullName" : "*", "type" : "*", "xform" : None, "parents" : [], "parts" : [], "touched" : False, } g_instances.append(rootInstance) objectsCopied = rs.CopyObjects(objects, rs.VectorScale(origin, -1)) for object in objectsCopied: processObject(object, [rootInstance]) output = open(dlg.FileName, "w") #output.write("# i <instance-type> <instance-name> " # "<parent-instance-name>\n") #output.write("# x <x-axis-x> <y-axis-x> <z-axis-x> <translation-x>\n") #output.write("# x <x-axis-y> <y-axis-y> <z-axis-y> <translation-y>\n") #output.write("# x <x-axis-z> <y-axis-z> <z-axis-z> <translation-z>\n") #output.write("# m <material-name> <ambient> <diffuse> <emission>\n") #output.write("# p <part-name> <instance-name> <material-name> " # "<vertices> <triangles>\n") #output.write("# v <pos-x> <pos-y> <pox-z> <norm-x> <norm-y> <norm-z>\n") #output.write("# t <vertex-1> <vertex-2> <vertex-3>\n") #output.write("\n") g_instances.sort(key=instanceSortKey) for instance in g_instances: parentCount = len(instance["parents"]) indent = g_indent * (parentCount - 1) parentName = "*" if instance["parents"]: parentName = instance["parents"][-1]["name"] line = format( "i%s %s %s %s" % (indent, instance["type"], instance["fullName"], parentName)) print(line) output.write(line + "\n") if parentCount < 1: xform = rc.Geometry.Transform(1.0) else: xform = instance["xform"] indent += " " output.write("x " + indent + formatHexFloats( [xform.M00, xform.M01, xform.M02, xform.M03], True) + "\n") output.write("x " + indent + formatHexFloats( [xform.M10, xform.M11, xform.M12, xform.M13], True) + "\n") output.write("x " + indent + formatHexFloats( [xform.M20, xform.M21, xform.M22, xform.M23], True) + "\n") for materialName, materialIdx in g_materials.iteritems(): material = sc.doc.Materials[materialIdx] ambient = material.AmbientColor diffuse = material.DiffuseColor emission = material.EmissionColor line = format( "m %s %s" % (materialName, formatColors([ambient, diffuse, emission]))) print(line) output.write(line + "\n") g_parts.sort(key=partSortKey) for part in g_parts: mesh = part["mesh"] line = format( "p %s %s %s %d %d" % (part["name"], part["instance"]["fullName"], part["material"], mesh.Vertices.Count, mesh.Faces.Count)) print(line) output.write(line + "\n") indent = " " for vertexIdx in range(0, mesh.Vertices.Count): vertex = mesh.Vertices[vertexIdx] normal = mesh.Normals[vertexIdx] output.write("v " + indent + formatHexFloats( [vertex.X, vertex.Y, vertex.Z, normal.X, normal.Y, normal.Z]) + "\n") line = lineInit = "t" + indent for faceIdx in range(0, mesh.Faces.Count): face = mesh.Faces[faceIdx] if not face.IsTriangle: print("WARNING: Non-triangle face %d" % (faceIdx)) part = format(" %d %d %d" % (face.A, face.B, face.C)) if len(line) + len(part) > 100: output.write(line + "\n") line = lineInit line += part if len(line) > 0: output.write(line + "\n") output.close()
section='sec_tie', elset='elset_tie'), ]) # Displacements mdl.add([ PinnedDisplacement(name='disp_pin', nodes='nset_pin'), RollerDisplacementX(name='disp_roller', nodes='nset_roller'), ]) # Loads loads = {} for i in rs.ObjectsByLayer('loads'): loads[mdl.check_node_exists(rs.PointCoordinates(i))] = { 'y': float(rs.ObjectName(i)) } mdl.add([ PointLoads(name='load_points', components=loads), PrestressLoad(name='load_prestress', elements='elset_tie', sxx=50 * 10**6), ]) # Steps mdl.add([ GeneralStep(name='step_bc', displacements=['disp_pin', 'disp_roller']), GeneralStep(name='step_prestress', loads=['load_prestress']), GeneralStep(name='step_load', loads=['load_points']), ])
import rhinoscriptsyntax as rs from compas.utilities import XFunc points = rs.GetObjects('pts', filter=1) points = [rs.PointCoordinates(pt) for pt in points] points = [[xyz[0], xyz[1], xyz[2]] for xyz in points] #from compas_pattern.algorithms.spatial_skeletonisation import spatial_skeleton_xfunc simplices, neighbors = XFunc( 'compas_pattern.algorithms.spatial_skeletonisation.spatial_skeleton_xfunc' )(points) #rs.EnableRedraw(False) #for a, b, c, d in simplices: # a, b, c, d = points[a], points[b], points[c], points[d] # group = rs.AddGroup() # lines = [rs.AddLine(a, b), rs.AddLine(a, c), rs.AddLine(a, d), rs.AddLine(b, c), rs.AddLine(b, d), rs.AddLine(c, d)] # rs.AddObjectsToGroup(lines, group) # from compas.geometry import centroid_points # rs.AddPoint(centroid_points([a, b, c, d])) # # sphere centre #rs.EnableRedraw(True) cells = [] for a, b, c, d in simplices: #print a, b, c, d halffaces = [[a, b, c], [a, b, d], [a, c, d], [b, c, d]] cells.append(halffaces) #halffaces.append([a, b, c]) #halffaces.append([c, b, a]) #halffaces.append([a, b, d])
def forward(self, dist): movement = rs.VectorScale(self.direction, dist) prevPos = rs.PointCoordinates(self.point) rs.MoveObject(self.point, movement) currentPos = rs.PointCoordinates(self.point) rs.AddLine(prevPos, currentPos)
#import RhinoScript Library import rhinoscriptsyntax as rs #find the closest point u, v = rs.SurfaceClosestPoint(srf, pt) #get closest point closest_pt = rs.EvaluateSurface(srf, u, v) #calculate direction from closest point to test point dir = rs.PointCoordinates(pt) - closest_pt #calculate surface normal normal = rs.SurfaceNormal(srf, [u, v]) #compare the two directions using the dot product a = dir * normal
def isPointOnCplane(obj): return (math.fabs(rs.PointCoordinates(obj)[2]) < 1e-6)