def depressCrvs(srf, crvs, paths, startPt, radius, sd): newCrvs = [] for i in range(len(crvs)): divPts = rs.DivideCurve(crvs[i], 400) for j in range(len(divPts)): path = rs.PointClosestObject(divPts[j], paths)[0] param = rs.CurveClosestPoint(path, divPts[j]) close = rs.EvaluateCurve(path, param) srfParam = rs.SurfaceClosestPoint(srf, close) vec = rs.SurfaceNormal(srf, srfParam) dist = rs.Distance(close, divPts[j]) vec = rs.VectorUnitize(vec) border = 1 entry = 1 if j > len(divPts) / 2: border = rs.Distance(rs.CurveEndPoint(crvs[i]), divPts[j]) else: border = rs.Distance(rs.CurveStartPoint(crvs[i]), divPts[j]) if border < sd * 3: border = border / (sd * 3) else: border = 1 entryDist = rs.Distance(startPt, divPts[j]) if entryDist < sd * 10: entry = entryDist / (sd * 10) else: entry = 1 if dist < sd * 2: val = radius * (bellCrv(dist, sd)) divPts[j] = rs.PointAdd(divPts[j], vec * val * border * entry) newCrvs.append(rs.AddCurve(divPts)) return divPts
def setNormalVec(self): #set normal vector from selected base surface #if selected base surface isn't planar, return False self.baseSurface = rs.GetSurfaceObject( "Select surface to be addded object") if self.baseSurface == None: return False rs.SelectObject(self.baseSurface[0]) if not rs.IsSurfacePlanar(self.baseSurface[0]): print( "Selected Surface is not planar\nPlease select planar surface") return False print("Confirm direction to add object") rs.Command("Dir") self.normalVec = rs.SurfaceNormal(self.baseSurface[0], [0, 0]) rs.UnselectAllObjects() self.setAngleOfBaseSurface() return True
def ArrayPointsOnSurface(): # Get the surface object surface_id = rs.GetObject("Select surface", rs.filter.surface) if surface_id is None: return # Get the number of rows rows = rs.GetInteger("Number of rows", 2, 2) if rows is None: return # Get the number of columns columns = rs.GetInteger("Number of columns", 2, 2) if columns is None: return # Get the number of columns hairlength = rs.GetInteger("Length of Hair", 2, 2) if hairlength is None: return # Get the domain of the surface U = rs.SurfaceDomain(surface_id, 0) V = rs.SurfaceDomain(surface_id, 1) if U is None or V is None: return # Add the points for i in xrange(0, rows): param0 = U[0] + (((U[1] - U[0]) / (rows - 1)) * i) for j in xrange(0, columns): param1 = V[0] + (((V[1] - V[0]) / (columns - 1)) * j) point = rs.EvaluateSurface(surface_id, param0, param1) rs.AddPoint(point) arrNormal = rs.SurfaceNormal(surface_id, point) rs.AddLine(point, point - arrNormal * hairlength)
def faces(): surfaces = rs.GetObjects("select surfaces", filter=rs.filter.surface) points = [ rs.EvaluateSurface(surface, *rs.SurfaceParameter(surface, (0.5, 0.5))) for surface in surfaces ] x = reduce(lambda s, point: s + point.X, points, 0) / len(points) y = reduce(lambda s, point: s + point.Y, points, 0) / len(points) z = reduce(lambda s, point: s + point.Z, points, 0) / len(points) # find the center of the object mass_center = rs.AddPoint(x, y, z) extrude_curves = {} # find the appropriate extrusion curve with the lowest dot product for surface in surfaces: surface_center = rs.EvaluateSurface( surface, *rs.SurfaceParameter(surface, (0.5, 0.5))) center_vector = rs.VectorCreate(surface_center, mass_center) normals = [] normals.append( rs.SurfaceNormal(surface, rs.SurfaceParameter(surface, (0.5, 0.5)))) normals.append(-rs.SurfaceNormal( surface, rs.SurfaceParameter(surface, (0.5, 0.5)))) if (rs.VectorDotProduct(normals[0], center_vector) < rs.VectorDotProduct(normals[1], center_vector)): extrude_curve = normals[0] else: extrude_curve = normals[1] extrude_curve = rs.VectorUnitize(extrude_curve) extrude_curve = rs.VectorScale(extrude_curve, 0.25) extrude_curve = [ surface_center, rs.VectorAdd(surface_center, extrude_curve) ] extrude_curve = rs.AddCurve(extrude_curve) rs.ExtrudeSurface(surface, extrude_curve) rs.DeleteObject(extrude_curve) rs.DeleteObject(surface) rs.DeleteObject(mass_center)
def getWindowBasics(_in): with idf2ph_rhDoc(): # Get the Window Geometry geom = rs.coercegeometry(_in) windowSurface = ghc.BoundarySurfaces(geom) # Inset the window just slightly. If any windows touch one another or the zone edges # will failt to create a proper closed Brep. So shink them ever so slightly. Hopefully # not enough to affect the results. windowPerim = ghc.JoinCurves(ghc.DeconstructBrep(windowSurface).edges, preserve=False) try: windowPerim = ghc.OffsetonSrf( windowPerim, 0.004, windowSurface) # 0.4mm so hopefully rounds down except: windowPerim = ghc.OffsetonSrf(windowPerim, -0.004, windowSurface) windowSurface = ghc.BoundarySurfaces(windowPerim) # Pull in the Object Name from Rhino Scene windowName = None try: windowName = rs.ObjectName(_in) except: warning = "Can't get the Window name from Rhino for some reason?\n"\ "If you are passing in Rhino Geometry, double check you have named all the surfaces?\n"\ "If you are passing in Grasshopper geometry though, ignore this message." ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Remark, warning) windowName = windowName if windowName != None else 'Unnamed_Window' windowName = cleanUpName(windowName) # Double check that the surface Normal didn't get flipped c1 = ghc.Area(geom).centroid n1 = rs.SurfaceNormal(geom, c1) c2 = ghc.Area(windowSurface).centroid n2 = rs.SurfaceNormal(windowSurface, c2) normAngleDifference = ghc.Degrees(ghc.Angle(n1, n2).angle) if round(normAngleDifference, 0) != 0: # Flip the surface if it doesn't match the source windowSurface = ghc.Flip(windowSurface).surface return windowName, windowSurface
def getSrfNormal(srf): domainU = rs.SurfaceDomain(srf, 0) domainV = rs.SurfaceDomain(srf, 1) u = domainU[1] / 2.0 v = domainV[1] / 2.0 point = rs.EvaluateSurface(srf, u, v) param = rs.SurfaceClosestPoint(srf, point) return rs.SurfaceNormal(srf, param)
def GetFracture (): dx = rs.GetReal("Enter x-axis direction:") if not dx: dx = 0.0 print "x-axis direction: ", dx objs = rs.ObjectsByType(8,False) cir_objs = rs.ObjectsByType(4) #delete all circles for cur_obj in cir_objs: if rs.IsCircle(cur_obj): rs.DeleteObject(cur_obj) occor = [] radius = [] center = [] #for all surface for obj in objs: rs.UnselectAllObjects() rs.SelectObject(obj) rs.Command ("_Silhouette") created_objs = rs.LastCreatedObjects() #not a circle if len(created_objs) !=1: rs.DeleteObjects(created_objs) print "unvailded surface" continue created_objs = created_objs[0] #not a circle if not rs.IsCircle(created_objs): rs.DeleteObject(created_objs) print "unvailded surface, not circle" continue point = rs.CircleCenterPoint(created_objs) center.append(point) r = rs.CircleRadius(created_objs) radius.append(r) normal = rs.SurfaceNormal(obj,[0,0]) occor.append(GetDirDip(normal,dx)) rs.DeleteObject(created_objs) print center print occor print radius path = rs.DocumentPath() path_l = path.split("\\") path_l[len(path_l)-1] = "fracture.dat" file = open("\\".join(path_l),"w") file.write(str(len(occor))) file.write('\n') for i in range (len(occor)): file.write("%.15f " % center[i][0]) file.write("%.15f " % center[i][1]) file.write("%.15f " % center[i][2]) file.write ("%.15f " % occor[i][0]) file.write ("%.15f " % occor[i][1]) file.write ("%.15f " % radius[i]) file.write ("0.0001 0.1 30\n") file.close ()
def offset_vector(self, point, cross_section_index, point_index): modulo = len(self.point_lists[cross_section_index - 1]) prev_point_1 = self.point_lists[cross_section_index - 1][ (point_index - 2) % modulo] if cross_section_index % 2 == 0 else self.point_lists[ cross_section_index - 1][(point_index - 1) % modulo] prev_point_2 = self.point_lists[cross_section_index - 1][ (point_index - 1) % modulo] if cross_section_index % 2 == 0 else self.point_lists[ cross_section_index - 1][point_index] in_between_vector = rs.VectorAdd(rs.VectorCreate(prev_point_1, point), rs.VectorCreate(prev_point_2, point)) normal_vector = rs.SurfaceNormal( self.brep, rs.SurfaceClosestPoint(self.brep, point)) plane = rs.PlaneFromFrame(point, in_between_vector, normal_vector) vector = rs.SurfaceNormal(rs.AddPlaneSurface(plane, 1, 1), [0, 0]) unit_vector = rs.VectorUnitize(vector) return [rs.VectorScale(unit_vector, 2), in_between_vector]
def isHorizontalUpSrf(srf,tolerance=TOLERANCE): boundary=rs.DuplicateSurfaceBorder(srf) if type(boundary is list):boundary=boundary[0] sp=rs.CurveStartPoint(boundary) uv=rs.SurfaceClosestPoint(srf,sp) normal=rs.SurfaceNormal(srf,uv) normal=rs.VectorUnitize(normal) nz=normal[2] rs.DeleteObject(boundary) if abs(nz-1)<tolerance:return True return False
def XYZ_To_UVW(srf_id, pXYZ): pUVW = [] for point in pXYZ: uvClosest = rs.SurfaceClosestPoint(srf_id, point) ptClosest = rs.EvaluateSurface(srf_id, uvClosest) srfNormal = rs.SurfaceNormal(srf_id, uvClosest) pPositive = rs.PointAdd(ptClosest, srfNormal) pNegative = rs.PointSubtract(ptClosest, srfNormal) fDistance = rs.Distance(ptClosest, point) if rs.Distance(point,pPositive) > rs.Distance(point, pNegative): fDistance = -fDistance pUVW.append( (uvClosest[0], uvClosest[1], fDistance) ) return pUVW
def ConvertToUVW(srf_id, xyz_points): uvw_points = [] for point in xyz_points: Suv = rs.SurfaceClosestPoint(srf_id, point) Sxyz = rs.EvaluateSurface(srf_id, Suv) Snormal = rs.SurfaceNormal(srf_id, Suv) dirPos = rs.PointAdd(Sxyz, Snormal) dirNeg = rs.PointSubtract(Sxyz, Snormal) Sdist = rs.Distance(Sxyz, point) if rs.Distance(point, dirPos) > rs.Distance(point, dirNeg): Sdist = -Sdist uvw_points.append((Suv(0), Suv(1), Sdist)) return uvw_points
def main(): to_delete = [] rs.ProjectOsnaps(False) positive_object = rs.GetObject("select positive object", 16) negative_object = rs.GetObject("select negative object", 16) rs.HideObject(negative_object) polysurface, face = GetSubSurface("select tenon surface") to_delete.append(face) normal = rs.VectorUnitize(rs.SurfaceNormal(face, (0.5, 0.5))) plane = rs.PlaneFromNormal(rs.EvaluateSurface(face, 0.5, 0.5), normal) rs.ViewCPlane(plane=plane) rs.ProjectOsnaps(True) tenon_rects = rs.GetObjects(message="select tenon curves", filter=4) tenon_faces = [] for rect in tenon_rects: tenon_faces.append(rs.AddPlanarSrf(rect)[0]) rs.ShowObject(negative_object) rs.ProjectOsnaps(False) height_pt = rs.GetPoint("enter height point") # compule a vector normal to plane of the desired height extrude_vec_a = rs.EvaluateSurface(face, 0.5, 0.5) dist = rs.DistanceToPlane(plane, height_pt) extrude_vec_b = [dist * el for el in normal] extrude_vec_b = rs.VectorAdd(extrude_vec_a, extrude_vec_b) extrude_curve = rs.AddCurve((extrude_vec_a, extrude_vec_b)) to_delete.append(extrude_curve) tenons = [] for tenon_face in tenon_faces: tenon = rs.ExtrudeSurface(tenon_face, extrude_curve) tenons.append(tenon) rs.BooleanUnion([positive_object] + tenons, delete_input=False) rs.BooleanDifference([negative_object], tenons, delete_input=False) to_delete.append(positive_object) to_delete.append(negative_object) rs.DeleteObjects(to_delete) rs.DeleteObjects(tenon_faces) rs.DeleteObjects(tenons)
def isHorizonalSrf(srf,return_dir=False,tolerance=TOLERANCE): boundary=rs.DuplicateSurfaceBorder(srf) if type(boundary is list):boundary=boundary[0] sp=rs.CurveStartPoint(boundary) uv=rs.SurfaceClosestPoint(srf,sp) normal=rs.SurfaceNormal(srf,uv) normal=rs.VectorUnitize(normal) direct=normal[2] nz=abs(normal[2]) rs.DeleteObject(boundary) if abs(nz-1)<tolerance: if return_dir:return True,direct return True if return_dir:return False,direct return False
def SurfacePoints3(self): ptMTX = {} srfNORM = {} rndNORM = {} #rndptlist3 = [] Udomain = rs.SurfaceDomain(self.strsrf, 0) Vdomain = rs.SurfaceDomain(self.strsrf, 1) stepU = (Udomain[1] - Udomain[0]) / self.intu stepV = (Vdomain[1] - Vdomain[0]) / self.intv #PLOT POINTS ON SURFACE count = 0 self.rndvectorlist = self.rndvector() for i in range(self.intu + 1): for j in range(self.intv + 1): #define u and v in terms of step values and i and j u = Udomain[0] + stepU * i v = Vdomain[0] + stepV * j point = rs.EvaluateSurface(self.strsrf, u, v) ptMTX[(i, j)] = point #find normals at u,v parameters srfNORM[(i, j)] = rs.SurfaceNormal(self.strsrf, (u, v)) #CREATE GRID OF OFFSET POINTS DEFINED BY SURFACE NORMALS self.Dis = self.distance() for i in range(self.intu + 1): for j in range(self.intv + 1): srfNORM[(i, j)] = rs.VectorScale(srfNORM[(i, j)], 120000 / self.Dis[(i, j)]) srfNORM[(i, j)] = rs.PointAdd(ptMTX[(i, j)], srfNORM[(i, j)]) rndNORM[(i, j)] = rs.VectorAdd( srfNORM[(i, j)], self.rndvectorlist[count] * (800 / self.Dis[(i, j)])) count = count + 1 #rs.AddPoint(rndNORM[(i,j)]) #rs.AddPoint(ptMTX[(i,j)]) self.rndptlist3.append(rndNORM[(i, j)]) #rs.DeleteObject(rndptlist3) return self.rndptlist3
def detectParalellSurface(self): #fix layer height #self.paralellIntersectedCurve #self.indexParalellSurfaces explodedSurfaces = rs.ExplodePolysurfaces(self.addtiveObj) for surface in explodedSurfaces: #normals.append(rs.SurfaceNormal(surface)) tmpNormal = rs.SurfaceNormal(surface, [0, 0]) gotAngle = rs.VectorAngle(tmpNormal, self.normalVec) if gotAngle == 0 or gotAngle == 180: tmpPoints = rs.SurfaceEditPoints(surface) tmpPlane = rs.PlaneFromNormal(tmpPoints[0], self.normalVec) distance = rs.DistanceToPlane(tmpPlane, self.basePointForPlane) distance *= (1.0 / math.cos(math.radians(self.angleOfSurface))) print("distance") print(distance) paralellLayer = int(distance / self.fixedLayerHeight) if paralellLayer < 0: paralellLayer *= -1 if paralellLayer == int( self.distancePrinting / self.fixedLayerHeight) or int(distance) == 0: continue self.indexParalellSurfaces.append(int(paralellLayer)) print("paralellLayer") print(paralellLayer) print("layer num") print(self.distancePrinting / self.fixedLayerHeight) #there is object to delete self.paralellIntersectedCurves.append( rs.JoinCurves(rs.DuplicateEdgeCurves(surface))) rs.DeleteObjects(explodedSurfaces) """
def FaceCamera(): try: frames = rs.GetObjects("Select Picture Frames", filter=8, preselect=True) # rotate surfaces around z axis towards camera point if frames: rs.EnableRedraw(False) cam = rs.ViewCamera() camz = (cam.X, cam.Y, 0) angle = 1 for i in frames: angle = 1 while angle >= 1: # get mid point of surface and move to z 0 pointmid = rs.SurfaceAreaCentroid(i) pointmidz = (pointmid[0].X, pointmid[0].Y, 0) # Get center UV of surface domainU = rs.SurfaceDomain(i, 0) domainV = rs.SurfaceDomain(i, 1) u = domainU[1] / 2.0 v = domainV[1] / 2.0 # Get normal vector of surface and cam vector vec1 = rs.SurfaceNormal(i, (u, v)) vec1 = vec1.X, vec1.Y, 0 vec2 = rs.VectorCreate(camz, pointmidz) # find angle difference between the two vectors angle = rs.VectorAngle(vec1, vec2) angle = round(angle) # Rotate Object rs.RotateObject(i, pointmidz, angle) continue rs.EnableRedraw(True) except: print("Failed to execute") rs.EnableRedraw(True) return
def main(): rs.AddLayer("laydown") while True: panel, face = getsubsurface.GetSubSurface("select down face") if panel is None or face is None: break # compute the plane normal = rs.VectorUnitize(rs.SurfaceNormal(face, (0.5,0.5))) plane = rs.PlaneFromNormal(rs.EvaluateSurface(face, 0.5, 0.5), normal) rs.ViewCPlane(plane=plane) box = rs.BoundingBox(face, rs.ViewCPlane(), in_world_coords=True) proj_coords = [rs.SurfaceClosestPoint(face, coord) + (0,) for coord in box] laydown = rs.OrientObject(panel, box[0:3], proj_coords[0:3], flags=1) rs.ObjectLayer(laydown, "laydown") rs.DeleteObject(face) rs.HideObject(panel)
def makeSliceSurface(surface, maxAngle): explodedSurfaces = rs.ExplodePolysurfaces(surface) newSurfaces = [] rs.DeleteObject(surface) baseVec = (0, 0, 1) for i in explodedSurfaces: vec = rs.SurfaceNormal(i, [0, 0]) angle = rs.VectorAngle(baseVec, vec) if angle > maxAngle: rs.DeleteObject(i) else: newSurfaces.append(i) joinedSurface = rs.JoinSurfaces(newSurfaces) return joinedSurface
def splitSrfVerticallyByPts(srf,pts): normals=[] up=(0,0,1000000000) half=(0,0,500000000) cutters=[] for p in pts: uv=rs.SurfaceClosestPoint(srf,p) normal=rs.SurfaceNormal(srf,uv) normal=rs.VectorScale(normal,1000) normals.append(normal) botStart=rs.VectorAdd(rs.VectorSubtract(p,half),normal) botEnd=rs.VectorSubtract(rs.VectorSubtract(p,half),normal) l=rs.AddLine(botStart,botEnd) path=rs.AddLine(botStart,rs.VectorAdd(botStart,up)) cutter=rs.ExtrudeCurve(l,path) rs.DeleteObjects([l,path]) #print(rs.IsBrep(cutter)) #print(cutter) cutters.append(cutter) # rs.SelectObjects(cutters) srfs=splitSrfBySrfs(srf,cutters) return srfs
def Main(): rectangle = rs.GetObject( "Select rectangle to create mortise and tenon from", rs.filter.curve, True, True) if rs.IsCurveClosed(rectangle): x = 0 else: print "Failed....Curve must be closed and rectangular" return if rs.IsCurvePlanar(rectangle): x = 0 else: print "Failed....Curve must be planar" return lines = rs.ExplodeCurves(rectangle) count = 0 for line in lines: count = count + 1 if count != 4: print "Failed....To many line segments, redraw rectangle" return if rs.IsLine(lines[0]): x = 0 else: print "Failed....Curve must be rectangular" return if rs.IsLine(lines[1]): x = 0 else: print "Failed....Curve must be rectangular" return if rs.IsLine(lines[2]): x = 0 else: print "Failed....Curve must be rectangular" return if rs.IsLine(lines[3]): x = 0 else: print "Failed....Curve must be rectangular" return face = rs.GetObject("Select tenon surface", rs.filter.surface, False, True, None, True) length = rs.GetReal("Enter tenon length", number=None) if length and length != 0: x = 0 else: print "Failed....No length was entered" return depth = rs.GetReal("Enter mortise depth", number=length + 0.05) if depth and depth != 0: x = 0 else: print "Failed....No depth was entered" return fit = rs.GetReal("Enter mortise fit", number=0.01) line1 = rs.AddLine(rs.CurveStartPoint(lines[0]), rs.CurveEndPoint(lines[0])) line2 = rs.AddLine(rs.CurveStartPoint(lines[1]), rs.CurveEndPoint(lines[1])) line3 = rs.AddLine(rs.CurveStartPoint(lines[2]), rs.CurveEndPoint(lines[2])) line4 = rs.AddLine(rs.CurveStartPoint(lines[3]), rs.CurveEndPoint(lines[3])) rs.DeleteObjects(lines) lines = line1, line2, line3, line4 if rs.CurveLength(lines[0]) > rs.CurveLength(lines[1]): smallside = rs.CurveLength(lines[1]) longside1 = lines[0] longside2 = lines[2] else: smallside = rs.CurveLength(lines[0]) longside1 = lines[1] longside2 = lines[3] filletRadius = smallside / 2 fillet1 = rs.CurveFilletPoints(lines[0], lines[1]) fillet2 = rs.CurveFilletPoints(lines[1], lines[2]) fillet3 = rs.CurveFilletPoints(lines[2], lines[3]) fillet4 = rs.CurveFilletPoints(lines[3], lines[0]) arc1 = rs.AddFilletCurve(lines[0], lines[1], radius=filletRadius) arc2 = rs.AddFilletCurve(lines[1], lines[2], radius=filletRadius) arc3 = rs.AddFilletCurve(lines[2], lines[3], radius=filletRadius) arc4 = rs.AddFilletCurve(lines[3], lines[0], radius=filletRadius) arcs = arc1, arc2, arc3, arc4 arcs = rs.JoinCurves(arcs) arcEnd1 = rs.CurveEndPoint(arcs[0]) arcStart1 = rs.CurveStartPoint(arcs[0]) arcEnd2 = rs.CurveEndPoint(arcs[1]) arcStart2 = rs.CurveStartPoint(arcs[1]) if rs.Distance(arcEnd1, arcEnd2) > rs.Distance(arcEnd1, arcStart2): temp = arcEnd2 arcEnd2 = arcStart2 arcStart2 = temp line1 = rs.AddLine(arcEnd1, arcEnd2) line2 = rs.AddLine(arcStart1, arcStart2) curves = line1, arcs[0], arcs[1], line2 tenonOut = rs.JoinCurves(curves) tenonSurf = rs.AddPlanarSrf(tenonOut) point = rs.SurfacePoints(face) param = rs.SurfaceClosestPoint(face, point[0]) normal = rs.SurfaceNormal(face, param) normal = normal * length vect = rs.AddLine(arcEnd1, arcEnd1 + normal) tenon = rs.ExtrudeSurface(tenonSurf, vect, cap=True) rs.DeleteObjects(curves) arcs = arc1, arc2, arc3, arc4 rs.DeleteObjects(arcs) rs.DeleteObject(rectangle) rs.ExtendCurveLength(longside1, 0, 0, fit) rs.ExtendCurveLength(longside1, 0, 1, fit) rs.ExtendCurveLength(longside2, 0, 0, fit) rs.ExtendCurveLength(longside2, 0, 1, fit) if rs.Distance(rs.CurveEndPoint(longside1), rs.CurveEndPoint(longside2)) < rs.Distance( rs.CurveStartPoint(longside1), rs.CurveEndPoint(longside2)): line1Start = rs.CurveEndPoint(longside1) line1End = rs.CurveEndPoint(longside2) line2Start = rs.CurveStartPoint(longside1) line2End = rs.CurveStartPoint(longside2) else: line1Start = rs.CurveStartPoint(longside1) line1End = rs.CurveEndPoint(longside2) line2Start = rs.CurveEndPoint(longside1) line2End = rs.CurveStartPoint(longside2) shortside1 = rs.AddLine(line1Start, line1End) shortside2 = rs.AddLine(line2Start, line2End) arc1 = rs.AddFilletCurve(longside1, shortside1, radius=filletRadius) arc2 = rs.AddFilletCurve(shortside1, longside2, radius=filletRadius) arc3 = rs.AddFilletCurve(longside2, shortside2, radius=filletRadius) arc4 = rs.AddFilletCurve(shortside2, longside1, radius=filletRadius) arcs = arc1, arc2, arc3, arc4 arcs = rs.JoinCurves(arcs) arcEnd1 = rs.CurveEndPoint(arcs[0]) arcStart1 = rs.CurveStartPoint(arcs[0]) arcEnd2 = rs.CurveEndPoint(arcs[1]) arcStart2 = rs.CurveStartPoint(arcs[1]) if rs.Distance(arcEnd1, arcEnd2) > rs.Distance(arcEnd1, arcStart2): temp = arcEnd2 arcEnd2 = arcStart2 arcStart2 = temp line1 = rs.AddLine(arcEnd1, arcEnd2) line2 = rs.AddLine(arcStart1, arcStart2) curves = line1, arcs[0], arcs[1], line2 mortiseOut = rs.JoinCurves(curves) mortiseSurf = rs.AddPlanarSrf(mortiseOut) param = rs.SurfaceClosestPoint(face, point[0]) normal = rs.SurfaceNormal(face, param) normal = normal * depth vect = rs.AddLine(arcEnd1, arcEnd1 + normal) mortise = rs.ExtrudeSurface(mortiseSurf, vect, cap=True) rs.DeleteObject(shortside1) rs.DeleteObject(shortside2) rs.DeleteObject(mortiseOut) rs.DeleteObject(mortiseSurf) rs.DeleteObjects(curves) rs.DeleteObjects(lines) arcs = arc1, arc2, arc3, arc4 rs.DeleteObjects(arcs) rs.DeleteObject(rectangle) rs.DeleteObject(tenonOut) rs.DeleteObject(tenonSurf) return
def main(): global inner_curves, outer_curves, curve_coords # save for later orig_hidden_objects = rs.HiddenObjects() # we put reference points in the dogbone-ref layer, so create it if it doesn't exist rs.AddLayer("dogbone-ref") panel, face = getsubsurface.GetSubSurface("select dogbone face") diameter = rs.GetReal("enter cutter diameter", number=0.25) diameter = diameter * 1.1 rs.EnableRedraw(False) # compute the plane normal = rs.VectorUnitize(rs.SurfaceNormal(face, (0.5, 0.5))) plane = rs.PlaneFromNormal(rs.EvaluateSurface(face, 0.5, 0.5), normal) rs.ViewCPlane(plane=plane) rs.ProjectOsnaps(True) outer_curves = rs.DuplicateSurfaceBorder(face, 1) inner_curves = rs.DuplicateSurfaceBorder(face, 2) # make a dict mapping each curve to the coords in that curve curve_coords = dict() for curve in outer_curves + inner_curves: coords = rs.CurvePoints(curve)[:-1] curve_coords[curve] = coords # make a dict mapping each curve to the z component of its cross product at each index curve_cross_zs = dict() for curve, coords in curve_coords.items(): proj_coords = [rs.SurfaceClosestPoint(face, coord) for coord in coords] cross_zs = [] for idx in range(len(proj_coords)): triplet = [ proj_coords[(idx + 1) % len(proj_coords)], proj_coords[idx], proj_coords[(idx - 1) % len(proj_coords)] ] v0 = (triplet[1][0] - triplet[0][0], triplet[1][1] - triplet[0][1], 0) v1 = (triplet[2][0] - triplet[1][0], triplet[2][1] - triplet[1][1], 0) cross_z = rs.VectorCrossProduct(v0, v1)[2] cross_zs.append(cross_z) curve_cross_zs[curve] = cross_zs points = [] bones = [] temp_points = [] rs.EnableRedraw(True) while True: coord = rs.GetPoint("select corner") if coord is None: break try: curve, idx = get_curve_and_idx_for_coord(coord) point = rs.AddPoint(coord) rs.ObjectColor(point, (255, 0, 0)) temp_points.append(point) bones.append((curve, idx)) except ValueError: print "invalid curve point" continue rs.EnableRedraw(False) rs.DeleteObjects(temp_points) # try to automatically identify dogbone points if user selected none if len(bones) == 0: for curve, coords in curve_coords.items(): proj_coords = [ rs.SurfaceClosestPoint(face, coord) for coord in coords ] for idx in range(len(proj_coords)): triplet = [ proj_coords[(idx + 1) % len(proj_coords)], proj_coords[idx], proj_coords[(idx - 1) % len(proj_coords)] ] if curve_cross_zs[curve][idx] > 0: bones.append((curve, idx)) # make the bones extrusions = [] for bone in bones: curve, idx = bone coords = curve_coords[curve] point = rs.AddPoint(coords[idx]) rs.ObjectLayer(point, "dogbone-ref") triplet = [ coords[(idx + 1) % len(coords)], coords[idx], coords[(idx - 1) % len(coords)], ] angle = rs.Angle2( (triplet[1], triplet[0]), (triplet[1], triplet[2]), ) angle = angle[0] # This is a hacky method to determine the handedness of the curve # the cross product SHOULD have worked here, but for some reason # it did not. v0 = triplet[2][0] - triplet[1][0], triplet[2][1] - triplet[1][1], 0 v1 = triplet[1][0] - triplet[0][0], triplet[1][1] - triplet[0][1], 0 _angle = math.degrees( math.atan2(v0[1], v0[0]) - math.atan2(v1[1], v1[0])) while _angle > 180: _angle -= 360 while _angle < -180: _angle += 360 if math.copysign(1, angle) != math.copysign(1, _angle): angle -= 180 point = rs.VectorAdd( triplet[1], rs.VectorRotate( 0.5 * diameter * rs.VectorUnitize(rs.VectorSubtract(triplet[2], triplet[1])), angle / 2, (0, 0, 1))) circle = rs.AddCircle((point.X, point.Y, -10), diameter / 2.0) circle_srf = rs.AddPlanarSrf(circle) p0 = (point.X, point.Y, -10) p1 = (point.X, point.Y, 10) line = rs.AddLine(p0, p1) extrusion = rs.ExtrudeSurface(circle_srf, line) extrusions.append(extrusion) rs.DeleteObjects([circle, circle_srf, line]) rs.BooleanDifference([panel], extrusions, delete_input=True) rs.DeleteObject(panel) rs.DeleteObjects(extrusions) rs.DeleteObjects(points) rs.DeleteObjects(inner_curves) rs.DeleteObjects(outer_curves) rs.DeleteObject(face) rs.ShowObject(rs.AllObjects()) rs.HideObjects(orig_hidden_objects) rs.EnableRedraw(True)
def rc_collapse_box(): go = Rhino.Input.Custom.GetObject() go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep default_KeepLayer = sc.sticky["KeepLayer"] if sc.sticky.has_key( "KeepLayer") else False default_IgnoreOpen = sc.sticky["IgnoreOpen"] if sc.sticky.has_key( "IgnoreOpen") else False opt_KeepLayer = Rhino.Input.Custom.OptionToggle(default_KeepLayer, "No", "Yes") opt_IgnoreOpen = Rhino.Input.Custom.OptionToggle(default_IgnoreOpen, "No", "Yes") go.SetCommandPrompt("Select Breps") go.AddOptionToggle("KeepLayer", opt_KeepLayer) go.AddOptionToggle("IgnoreOpenBreps", opt_IgnoreOpen) go.GroupSelect = True go.SubObjectSelect = False go.AcceptEnterWhenDone(True) go.AcceptNothing(True) go.EnableClearObjectsOnEntry(False) go.EnableUnselectObjectsOnExit(False) go.GroupSelect = True go.SubObjectSelect = False go.DeselectAllBeforePostSelect = False res = None bHavePreselectedObjects = True while True: res = go.GetMultiple(1, 0) if res == Rhino.Input.GetResult.Option: go.EnablePreSelect(False, True) continue #If not correct elif res != Rhino.Input.GetResult.Object: rs.Redraw() print "No breps were selected!" return Rhino.Commands.Result.Cancel if go.ObjectsWerePreselected: rs.Redraw() bHavePreselectedObjects = True go.EnablePreSelect(False, True) continue break OPT_IGNORE_OPEN = opt_IgnoreOpen.CurrentValue OPT_KEEP_LAYER = opt_KeepLayer.CurrentValue sticky["IgnoreOpen"] = OPT_IGNORE_OPEN sticky["KeepLayer"] = OPT_KEEP_LAYER rs.EnableRedraw(False) input_breps = [] for i in xrange(go.ObjectCount): b_obj = go.Object(i).Object() input_breps.append(b_obj.Id) current_cplane = sc.doc.Views.ActiveView.ActiveViewport.GetConstructionPlane( ) temp_cplane = current_cplane.Plane current_cplane.Plane = rs.WorldXYPlane() solid_brep_count = 0 for brep in input_breps: if not rs.IsObjectSolid(brep): solid_brep_count += 1 if OPT_IGNORE_OPEN: continue if OPT_KEEP_LAYER: brep_layer = rs.ObjectLayer(rs.coerceguid(brep)) exploded = rs.ExplodePolysurfaces(brep, True) remaining_srfs = [] for srf in exploded: norm = rs.SurfaceNormal(srf, [0.5, 0.5]) if 10 > rs.VectorAngle(norm, [0, 0, 1]) or 10 > rs.VectorAngle( norm, [0, 0, -1]): rs.DeleteObject(srf) else: remaining_srfs.append(srf) areas = [rs.SurfaceArea(s) for s in remaining_srfs] areas = [x[0] for x in areas] srfs, areas = zip( *sorted(zip(remaining_srfs, areas), key=lambda x: x[1])) pt1, _ = rs.SurfaceAreaCentroid(srfs[-1]) pt2, _ = rs.SurfaceAreaCentroid(srfs[-2]) vect = rs.VectorCreate(pt2, pt1) vect = rs.VectorDivide(vect, 2) rs.MoveObject(srfs[-1], vect) if OPT_KEEP_LAYER: rs.ObjectLayer(srfs[-1], brep_layer) rs.SelectObjects(srfs[-1]) rs.DeleteObjects(srfs[:-1]) rs.EnableRedraw(True) rs.Redraw() current_cplane.Plane = temp_cplane if solid_brep_count > 0: outcome = " and were not collapsed." if OPT_IGNORE_OPEN else " and may have been flattened incorrectly. Check input geometry." report = str(solid_brep_count) + " brep(s) were not closed" + outcome print report
#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
bndry = [] obj = rs.GetObject("Select polysurface to explode", rs.filter.polysurface, preselect=True) if rs.IsPolysurface(obj): faces = rs.ExplodePolysurfaces(obj) for face in faces: if rs.IsSurface(face): domainU = rs.SurfaceDomain(face, 0) domainV = rs.SurfaceDomain(face, 1) u = domainU[1] / 2.0 v = domainV[1] / 2.0 point = rs.EvaluateSurface(face, u, v) param = rs.SurfaceClosestPoint(face, point) normal = rs.SurfaceNormal(face, param) # print normal if normal.Z == -1: bndry.append(face) for bnd in bndry: area = rs.SurfaceArea(bnd)[0] areapy = area / 3.3058 print area, areapy txt = rs.ClipboardText(area) if faces: rs.DeleteObjects(faces) def calcArea(srfs): areas = []
#find the range of the surface by subtracint the max value and min value #what is the width and length of the surface uRange = uMax - uMin vRange = vMax - vMin uStep = uRange / numberUCells vStep = vRange / numberVCells U = uMin #we start at U and looping through all V #and then next U and looping thought all V #when this is done we establish a grid while U < uMax: V = vDomain while V < vMax: #SurfaceNormal function takes U and V as one tuple #in this function you have to take them in the paranthesis normal = rs.SurfaceNormal(srf, (U, V)) scaledNormal = rs.VectorScale(normal, 10) #pointOnSurface is base surface pointOnSurface = rs.EvaluateSurface(srf, U, V) #pointOffSurface is result of add vector to the base pointOffSurface = rs.VectorAdd(pointOnSurface, scaledNormal) rs.AddLine(pointOnSurface, pointOffSurface) V += vStep U += uStep
def GrevilleNormals(srf_id): uvGreville = rs.SurfaceEditPoints(srf_id, True, True) return [rs.SurfaceNormal(srf_id, g) for g in uvGreville]
Course_All.append(Course) for index in range(0, hori_no, 1): Course = rs.OffsetCurve(Course, bbox[3], ipHeight) Course_All.append(Course) Course = rs.OffsetCurve(Course1, bbox[3], Surf_Height) Course_All.append(Course) rs.ObjectColor(Course_All, [255, 0, 0]) return Course_All #Horizontal_Lines = HorizontalLines() surf_norm = rs.SurfaceNormal(surf[1], (0.5, 0.5)) surf_norm = (surf_norm) def WindowFrame(): surf_int_edge_all = rs.DuplicateSurfaceBorder(surf[1], type=2) print len(surf_int_edge_all) window_frame_all = [] for item in range(0, len(surf_int_edge_all), 1): surf_int_edge = surf_int_edge_all[item] surf_int_edge = rs.ExplodeCurves(surf_int_edge, True) trans1 = rs.XformTranslation((0, 0, 2 * ipThick))
import rhinoscriptsyntax as rs surf_id = rs.GetObject("Select a surface", 8) print surf_id area = rs.SurfaceArea(surf_id) domainU = rs.SurfaceDomain(surf_id, 0) domainV = rs.SurfaceDomain(surf_id, 1) print "area = ", area print "domain of u-direction = ", domainU print "domain of v-direction = ", domainV uv = (domainU[1] - domainU[0]) / 2, (domainV[1] - domainV[0]) / 2 center = rs.SurfaceEvaluate(surf_id, uv, 1) normal = rs.SurfaceNormal(surf_id, uv) print "xyz co-ordinate of center = ", center[0] print "normal vector = ", normal normal = rs.VectorUnitize(normal) normal = rs.VectorScale(normal, 5) start = center[0] end = rs.VectorAdd(start, normal) rs.AddPoint(center[0]) rs.AddLine(start, end)
import random pickedSurface = rs.GetObjects("pick a surface", 8) numUDivs = 20 numVDivs = 60 uDomain = rs.SurfaceDomain(pickedSurface, 0) vDomain = rs.SurfaceDomain(pickedSurface, 1) uMin = uDomain[0] uMax = uDomain[1] uRange = uMax - uMin uStep = uRange / numUDivs vMin = vDomain[0] vMax = vDomain[1] vRange = vMax - vMin vStep = vRange / numVDivs U = uMin while U < uMax : V = vMin while V < vMax : normal = rs.SurfaceNormal(pickedSurface, (U,V)) scaledNormal = rs.VectorScale(normal, 10) pointOnSurface = rs.EvaluateSurface(pickedSurface, U, V) pointOffSurface = rs.VectorAdd(pointOnSurface, scaledNormal) rs.AddLine(pointOnSurface, pointOffSurface) V += vStep U += uStep
def reflectLight(): """ This script will place a (pre)selected light on a surface or polysurface by reflection After the script has run, it will select the modified light, so you can quickly repeat the placement with this light script by Gijs de Zwart www.studiogijs.nl """ object = rs.GetObject("select light", preselect=True, filter=256) if not object: return light = rs.coercerhinoobject(object) loc = light.LightGeometry.Location dir = light.LightGeometry.Direction #rs.AddPoint(camLoc) #rs.AddPoint(camTar) #rs.AddLine([0,0,0],camDir) srf = rs.GetObject("select surface to reflect light on", filter=8, subobjects=True) #rs.GetObjects( if not srf: return pt = rs.GetPointOnSurface(srf) if not pt: return #if not sc.doc.Views.ActiveView.ActiveViewport.IsPerspectiveProjection: # print "this script needs a perspective view to start" # return camLoc = sc.doc.Views.ActiveView.ActiveViewport.CameraLocation camTar = sc.doc.Views.ActiveView.ActiveViewport.CameraTarget camDir = sc.doc.Views.ActiveView.ActiveViewport.CameraDirection pt_srf = rs.SurfaceClosestPoint(srf, pt) if not pt_srf: print "could not find surface point" return normal = rs.SurfaceNormal(srf, pt_srf) if not normal: print "could not calculate surface normal" return plane = Rhino.Geometry.Plane(pt, normal, -camDir) #sc.doc.Views.ActiveView.ActiveViewport.SetConstructionPlane(plane) #line = Rhino.Geometry.Line(camLoc, pt) #trans = Rhino.Geometry.Transform(angleRadians,rotationAxis, rotationCenter) trans = Rhino.Geometry.Transform.Rotation(math.pi, normal, pt) #rs.RotateObject(line, pt, 180, plane.XAxis, copy=True) #line.Transform(trans) camLoc.Transform(trans) newdir = rs.VectorCreate(pt, camLoc) newdir.Unitize() newplane = rs.PlaneFromNormal(camLoc, newdir) if light.LightGeometry.IsRectangularLight: lightX = light.LightGeometry.Width lightWidth = lightX.Length lightY = light.LightGeometry.Length lightHeight = lightY.Length lightO = light.LightGeometry.Location lightX = lightWidth * newplane.XAxis lightY = lightHeight * newplane.YAxis light.LightGeometry.Width = lightX light.LightGeometry.Length = lightY camLoc -= lightX / 2 camLoc -= lightY / 2 light.LightGeometry.Location = camLoc #mid = Rhino.Geometry.Vector3d(lightWidth/2, lightHeight/2, 0) #trans = Rhino.Geometry.Transform.ChangeBasis(Rhino.Geometry.Plane.WorldXY, lightPlane) #mid.Transform(trans) #light.LightGeometry.Location -=mid if light.LightGeometry.IsSpotLight: light.LightGeometry.Location = camLoc newdir *= rs.VectorLength(dir) light.LightGeometry.Direction = newdir #sc.doc.Objects.AddLine(line) sc.doc.Lights.Modify(object, light.LightGeometry) rs.SelectObject(object)