def get_polygon_coordinates(guids): """Get the point coordinates of polygons. Parameters ---------- guids : list[System.Guid] Polygon curve identifiers. Returns ------- list[list[[float, float, float]]] A list of point coordinates per polygon. """ if isinstance(guids, System.Guid): points = rs.CurvePoints(guids) coords = [] if points: coords = [list(point) for point in points] return coords polygons = [] if guids: for guid in guids: points = rs.CurvePoints(guid) coords = [] if points: coords = map(list, points) polygons.append(coords) return polygons
def getSolarGeom(boundary,ht,lat,shourlst,ehourlst,day,north,long,timeZ,s_mth,e_mth): CH = ConvexHull2d() boundary_pts = rs.CurvePoints(boundary) # you'll need this later boundary_pts.pop(-1) bchullpts = CH.convex_hull(boundary_pts) centerPt = rs.CurveAreaCentroid(rs.AddCurve(bchullpts + [bchullpts[0]],1))[0] #centerPt = rs.CurveAreaCentroid(boundary)[0] boundary_plane = rs.PlaneFitFromPoints(boundary_pts) top_plane = get_plane(boundary,ht) # project curve to user_defined height sun_pts = get_sunpt(lat,centerPt,s_mth,day,shourlst,north_=north,lon=long,tZ=timeZ,scale_=100) sun_pts.extend(get_sunpt(lat,centerPt,e_mth,day,ehourlst,north_=north,lon=long,tZ=timeZ,scale_=100)) top_lst = project_curve(sun_pts,centerPt,top_plane,boundary) top_curves = map(lambda x: rs.coercecurve(x),top_lst) # temp for viz top_lst = map(lambda x: rs.CurvePoints(x),top_lst) top_pts = map(lambda x: rs.coerce3dpoint(x),\ reduce(lambda i,j:i+j,top_lst)) # convex hull methods chull_pts = CH.convex_hull(top_pts) chull_crv = rs.AddCurve(chull_pts + [chull_pts[0]],1) #chull_centerPt = rs.CurveAreaCentroid(chull_crv)[0] # adjust curve directions #if not rs.CurveDirectionsMatch(boundary,chull_crv): # rs.ReverseCurve(boundary) #b = rs.CurvePoints(boundary) + rs.CurvePoints(chull_crv) #c = rs.CurvePoints(chull_crv) return (boundary,chull_crv),top_curves
def shape_from_ref(r): with parameter(immediate_mode, False): obj = _geometry_from_id(r) ref = native_ref(r) if isinstance(obj, geo.Point): return point.new_ref(ref, fromPt(obj.Location)) elif isinstance(obj, geo.Curve): if rh.IsLine(r) or rh.IsPolyline(r): if rh.IsCurveClosed(r): return polygon.new_ref( ref, [fromPt(p) for p in rh.CurvePoints(r)[:-1]]) else: return line.new_ref(ref, [fromPt(p) for p in rh.CurvePoints(r)]) elif obj.IsCircle(Rhino.RhinoMath.ZeroTolerance): return circle.new_ref(ref, fromPt(rh.CircleCenterPoint(r)), rh.CircleRadius(r)) elif rh.IsCurveClosed(r): return closed_spline.new_ref( ref, [fromPt(p) for p in rh.CurvePoints(r)]) else: return spline.new_ref(ref, [fromPt(p) for p in rh.CurvePoints(r)]) elif rh.IsObject(r) and rh.IsObjectSolid(r): return solid(native_ref(r)) elif rh.IsSurface(r) or rh.IsPolysurface(r): return surface(native_ref(r)) else: raise RuntimeError("{0}: Unknown Rhino object {1}".format( 'shape_from_ref', r))
def isCurveBelowCPlane(obj): data = rs.CurvePoints(obj) for pt in data: if (pt.Z < -1e-8): return True return False
def get_polygon_coordinates(guids): if isinstance(guids, System.Guid): points = rs.CurvePoints(guids) coords = [] if points: coords = [list(point) for point in points] return coords polygons = [] if guids: for guid in guids: points = rs.CurvePoints(guid) coords = [] if points: coords = map(list, points) polygons.append(coords) return polygons
def ProjectOnSrfLoose(): crv = rs.GetObject("select curve to loosely project", rs.filter.curve) srf = rs.GetObject("Select surface to loosely project onto", rs.filter.surface) if crv == None or srf == None: return degree = rs.CurveDegree(crv) bPeriodic = False pts = rs.CurvePoints(crv) if rs.IsCurvePeriodic(crv): pts = rs.CullDuplicatePoints(pts, 0.01) bPeriodic = True pts_projected = [] curveplane = rs.CurvePlane(crv) projection_dir = curveplane.ZAxis for pt in pts: pp = rs.ProjectPointToSurface(pt, srf, projection_dir) if len(pp) > 0: pt_projected = pp[0] pts_projected.append(pt_projected) if len(pts_projected) <= 2: return if len(pts_projected) < len(pts): bPeriodic = False nc = Rhino.Geometry.NurbsCurve.Create(bPeriodic, degree, pts_projected) sc.doc.Objects.AddCurve(nc) sc.doc.Views.Redraw()
def unroll(self): x = 0 for i in range(len(self.srfList)): g = rs.AddGroup() s, p = rs.UnrollSurface(self.srfList[i], False, self.unrollList[i]) s = rs.JoinSurfaces(s, True) p = rs.MoveObjects(p, [x, self.name * 10, 0]) s = rs.MoveObject(s, [x, self.name * 10, 0]) b = rs.DuplicateSurfaceBorder(s, 1) rs.ObjectLayer(b, "cut") rs.AddObjectsToGroup(b, g) rs.AddObjectsToGroup(p, g) bb = rs.BoundingBox(s) x += fabs(bb[0].X - bb[1].X) + 1 t = rs.AddText( str(self.name) + "-" + str(i), util.averagePt(rs.CurvePoints(b)), 0.3) t = util.makeEngravingFont(t) rs.AddObjectsToGroup(t, g) rs.DeleteObjects(s)
def get_convexhull(self, lot): brep_lst = [] pt_lst = [] rs.EnableRedraw(False) for T in lot: bound = rs.CurvePoints(T[0])[:-1] chull = rs.CurvePoints(T[1])[:-1] Rhino.Geometry.Point3d.CullDuplicates(bound, TOL) Rhino.Geometry.Point3d.CullDuplicates(chull, TOL) pts = self.convert_pts(chull + bound) brep = self.call_convexhull(pts, 0) if brep == None: 'brep=none -sv' brep_lst.append(brep) pt_lst.append(bound + chull) rs.EnableRedraw() return brep_lst, pt_lst
def genHalfPlanes(site_crv, int_crv): B = rs.BoundingBox(site_crv) polyBB = rs.AddPolyline([B[0], B[1], B[2], B[3], B[0]]) diagB = 2 * rs.Distance(B[0], B[2]) rays = [] int_pts = rs.CurvePoints(int_crv) bsp_tree = [] bsp_tree.append(site_crv) for i in range(len(int_pts) - 1): a = int_pts[i] b = int_pts[i + 1] m = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, 0] p = [ m[0] + (a[0] - m[0]) * diagB / (rs.Distance(a, m)), m[1] + (a[1] - m[1]) * diagB / (rs.Distance(a, m)), 0 ] q = [ m[0] + (b[0] - m[0]) * diagB / (rs.Distance(b, m)), m[1] + (b[1] - m[1]) * diagB / (rs.Distance(b, m)), 0 ] u = [q[0] - p[0], q[1] - p[1], 0] v = [-u[1], u[0], 0] r = [p[0] + v[0], p[1] + v[1], 0] s = [q[0] + v[0], q[1] + v[1], 0] w = [u[1], -u[0], 0] R = [p[0] + w[0], p[1] + w[1], 0] S = [q[0] + w[0], q[1] + w[1], 0] polyA = rs.AddPolyline([p, q, s, r, p]) polyB = rs.AddPolyline([p, q, S, R, p]) used_crv = [] new_crv = [] for bsp_crv in bsp_tree: sum = 0 try: crvA = rs.CurveBooleanIntersection(bsp_crv, polyA) new_crv.append(crvA) sum += 1 except: pass try: crvB = rs.CurveBooleanIntersection(bsp_crv, polyB) new_crv.append(crvB) sum += 1 except: pass if (sum > 0): used_crv.append(bsp_crv) for crv in new_crv: bsp_tree.append(crv) for crv in used_crv: bsp_tree.remove(crv) rs.DeleteObject(crv) rs.DeleteObject(polyA) rs.DeleteObject(polyB) rs.DeleteObject(polyBB) return bsp_tree
def isCurveOnCPlane(obj): data = rs.CurvePoints(obj) for pt in data: if (math.fabs(pt.Z) > 1e-6): return False return True
def getIntxCrv(self, poly): intxCrv=rs.CurveBooleanIntersection(self.SITECRV,poly) if(len(intxCrv)>0): maxCrv=intxCrv[0] maxAr=0.0 for i in intxCrv: ar=rs.CurveArea(i)[0] if(ar>maxAr): maxAr=ar maxCrv=i crvpts=rs.CurvePoints(maxCrv) rs.DeleteObjects(intxCrv) for i in intxCrv: try: rs.DeleteObject(i) pass except: print("#1. curve not deleted") return crvpts else: for i in intxCrv: try: rs.DeleteObject(i) except: print("#2. curve not deleted") return
def get_dist(pt,poly): # find closest point on axis curve param = rs.CurveClosestPoint(axis, pt) # get plane perpendicular to curve ck,pl = axis.PerpendicularFrameAt(param) # part responsible for flat end caps # if distance from point to plane is bigger than 0, # return that distance pp = rs.PlaneClosestPoint(pl,pt) d2 = rs.Distance(pt,pp) if d2>0.01: return d2 # else change the basis of the polygon from world xy # to that plane to check for distance and inside/outside pm = (param-axis.Domain[0])/(axis.Domain[1]-axis.Domain[0]) wxy = rs.WorldXYPlane() tf = rg.Transform.PlaneToPlane(wxy,pl) ang = sa + pm*(ea-sa) tr = rg.Transform.Rotation(ang, pl.Normal, pl.Origin) tpts = rs.CurvePoints(poly) for p in tpts: p.Transform(tf) p.Transform(tr) ply = rs.AddPolyline(tpts) prm = rs.CurveClosestPoint(ply,pt) cp = rs.EvaluateCurve(ply,prm) d = rs.Distance(pt,cp) # if the point is inside the curve, reverse the distance bln = rs.PointInPlanarClosedCurve(pt,ply,pl) if bln: d *= -1 return d
def translateToGcode(id): path = rs.ConvertCurveToPolyline(id) points = rs.CurvePoints(path) rs.DeleteObject(path) feedrate = int(rs.GetUserText(id, "Feedrate")) for pointId in points:
def isCurveOnCPlane(obj): if rs.IsCurvePlanar(obj): data = rs.CurvePoints(obj) for pt in data: if (math.fabs(pt.Z) < 1e-8): return True return False
def enter_in_ledgers(self, line): """Receives a line Guid Guid Records the line in the coord and line ledgers """ # check for line Guid point_object_1, point_object_2 = rs.CurvePoints(line) coord1, coord2 = self.get_coords(point_object_1, point_object_2) coord_index_1, coord_index_2 = self.get_coords_by_index(coord1, coord2) self.enter_in_line_ledger(coord_index_1, coord_index_2)
def get_polyline_coordinates(polyline): coordinates = [] pts = rs.CurvePoints(polyline) for pt in pts: x = float('%.4f' % pt[0]) y = float('%.4f' % pt[1]) coordinates.append([x, y]) # del coordinates[-1] ensure_counter_clockwise_triangle(coordinates) return coordinates
def getMax(self): max = 0 crv_pts = rs.CurvePoints(self.site_crv) for i in range(len(crv_pts)): p0 = crv_pts[i] for j in range(len(crv_pts)): p1 = crv_pts[j] d = rs.Distance(p0, p1) if (d > max): max = d return max
def writeCurve(curve): polyLine = rs.ConvertCurveToPolyline(curve, a_tolerance, tolerance) points = rs.CurvePoints(polyLine) # insert division points as line for pt in points: write("G01", pt.X, pt.Y, pt.Z) # remove objects after use rs.DeleteObjects(polyLine)
def isCurveOnCPlane(obj): if not rs.IsCurvePlanar(obj): return False else: data = rs.CurvePoints(obj) for pt in data: if (math.fabs(pt.Z) > 1e-6): print "Point height: {}".format(pt.Z) return False return True
def makePolygon(crv, domClass, o, stroke, fill): #polgons are generated as SVG paths #<path d="M 0 0 L 100 0 L 100 100 L 0 100 Z"></path> #polygon points are formatted as a single string under the attribute "d" #M precedes the first coordinate #L precedes following coordinates (using a lower-case "l" denotes relative position (not absolute) to first coordinate) #Z ends polygon pts = rs.CurvePoints(crv) pts = [ getRelDim(o,p,rotate) for p in pts ] pts = [ "%f %f"%(p[0]+pad, p[1]+pad) for p in pts ] pt_str = " L ".join(pts) return "<path d=\"M %s\" stroke=\"%s\" fill=\"%s\" stroke-width=\"1px\"></path>" %(pt_str,stroke,fill)
def _get_line_coords(self, line_guid): """Receives a line guid: guid Returns the line guid's coord pair: [(num, num, num), (num, num, num)] """ point_pair = rs.CurvePoints(line_guid) coord_pair = [] for point in point_pair: coord = (point.X, point.Y, point.Z) coord_pair.append(coord) return coord_pair
def _get_line_spec(self, line_guid): """Receives a line guid: Guid Returns a line spec: ((num, num, num,), (num, num, num)) """ point_pair = rs.CurvePoints(line_guid) coord_pair = [] for point in point_pair: coord = self._point_to_coord(point) coord_pair.append(coord) return (coord_pair[0], coord_pair[1])
def main(): diameter = rs.GetReal("enter cutter diameter", number=0.25) diameter = diameter*1.1 # first, select objects in three orthogonal planes obj = rs.GetObject("select object", filter=4) # curve curve_points = rs.CurvePoints(obj)[:-1] circles = [] while True: point = rs.GetPoint("select point") if point is None: break try: idx = curve_points.index(point) print "clicked index", idx except ValueError: print "invalid point" continue points = [ curve_points[(idx+1)%len(curve_points)], curve_points[idx ], curve_points[(idx-1)%len(curve_points)], ] print points angle = rs.Angle2( (points[1], points[0]), (points[1], points[2]), ) angle = angle[0] point = rs.VectorAdd( points[1], rs.VectorRotate(0.5*diameter*rs.VectorUnitize(rs.VectorSubtract(points[2], points[1])), angle/2, (0,0,1)) ) #p0 = (point.X, point.Y, point.Z + 1000) #p1 = (point.X, point.Y, point.Z - 1000) circle = rs.AddCircle(point, diameter/2.0) circles.append(circle) #extrusion = rs.ExtrudeCurveStraight(circle, p0, p1) for circle in circles: before_obj = obj obj = rs.CurveBooleanDifference(obj, circle) rs.DeleteObject(before_obj) rs.DeleteObjects(circles)
def postProcess(self): REDO=False ar=0.0 for i in self.FPOLY: rs.RotateObject(i, CP, -ANGLE) for i in self.FPOLY: try: ar+=rs.CurveArea(i)[0] except: pass mean_ar=ar/len(self.FPOLY) min_ar_per=0.2*mean_ar j=0 for i in self.FPOLY: pts=rs.CurvePoints(i) if(rs.CurveArea(i)[0]<min_ar_per): REDO=True break p=rs.BoundingBox(pts) max_poly=rs.AddPolyline([p[0],p[1],p[2],p[3],p[0]]) max_poly_ar=rs.CurveArea(max_poly)[0] actual_poly_ar=rs.CurveArea(i)[0] if((max_poly_ar/actual_poly_ar)>2): REDO=True rs.DeleteObject(max_poly) break else: rs.DeleteObject(max_poly) ab=int(rs.Distance(p[0],p[1])) ad=int(rs.Distance(p[0],p[3])) if((ab>ad) and (ab/ad)>5): REDO=True break elif((ab<ad) and (ab/ad)<0.2): REDO=True break j+=1 if(REDO==True and self.counter<MAX_REC): self.counter+=1 print("Redo %s" %(self.counter)) rs.DeleteObjects(self.FPOLY) self.start() self.recSplit(bsp.BBpts, 0) self.postProcess() else: j=0 for i in self.FPOLY: c=rs.CurveAreaCentroid(i)[0] rs.AddTextDot(str(j), c) j+=1
def move_to_origin(self, curves): """moves a list of points to 0,0,0 """ point_sample = rs.CurvePoints(curves[0]) min_z = point_sample[0].Z self.target = rg.Point3d(0, 0, min_z) target_transform = rg.Transform.Translation(-self.target.X, -self.target.Y, -self.target.Z + 0.001) self.target.Transform(target_transform) for n in curves: n.Transform(target_transform)
def smoothcurve(curve_id, s): curve_points = rs.CurvePoints(curve_id) new_curve_points = [] for i in range(len(curve_points) - 1): vm = smoothingvector(curve_points[i], curve_points[i - 1], curve_points[i + 1], s) new_curve_points.append(rs.PointAdd(curve_points[i], vm)) knots = rs.CurveKnots(curve_id) degree = rs.CurveDegree(curve_id) weights = rs.CurveWeights(curve_id, 0) newcurve_id = rs.AddNurbsCurve(new_curve_points, knots, degree, weights) if newcurve_id: rs.DeleteObject(curve_id) return newcurve_id
def make_new_coord_ledger(self, lines): """Receives a list of line Guids: [Guid, ...] Returns a list of coords: [(num, num, num), ...] """ coords = [] for line in lines: points = rs.CurvePoints(line) for p in points: coord = (p.X, p.Y, p.Z) coords.append(coord) coord_ledger = ledger.Ledger(coords) print('coord ledger: %s' % coord_ledger.elements) return coord_ledger
def genIntPoly(self, poly): cen=rs.CurveAreaCentroid(poly)[0] pts=rs.CurvePoints(poly) a=[(pts[0][0]+pts[1][0])/2,(pts[0][1]+pts[1][1])/2,0] b=[(pts[0][0]+pts[3][0])/2,(pts[0][1]+pts[3][1])/2,0] vec1=rs.VectorScale(rs.VectorUnitize(rs.VectorCreate(cen,a)),self.d0/2) vec2=rs.VectorScale(rs.VectorUnitize(rs.VectorCreate(cen,b)),self.d1/2) p=rs.PointAdd(cen,vec1) q=rs.PointAdd(cen,-vec1) r=rs.PointAdd(p,vec2) u=rs.PointAdd(p,-vec2) t=rs.PointAdd(q,vec2) s=rs.PointAdd(q,-vec2) poly=rs.AddPolyline([r,u,s,t,r]) self.req_poly.append(poly)
def is_polyline(self): """Determine if the curve is a polyline. Returns ------- bool Tue if the curve is a polyline. False otherwise. Notes ----- A curve is a polyline if it consists of linear segments between a sequence of points. """ return (rs.IsPolyline(self.guid) and rs.CurveDegree(self.guid) == 1 and len(rs.CurvePoints(self.guid)) > 2)
def is_line(self): """Determine if the curve is a line. Returns ------- bool Tue if the curve is a line. False otherwise. Notes ----- A curve is a line if it is a linear segment between two points. """ return (rs.IsLine(self.guid) and rs.CurveDegree(self.guid) == 1 and len(rs.CurvePoints(self.guid)) == 2)