def CreatePyramidPoints(treeIn, ratioIn, treeOut): for i in range(treeIn.BranchCount): treeBranch = treeIn.Branch(i) ratioBranch = ratioIn.Branch(i) treePath = treeIn.Path(i) P1 = treeBranch[0] P2 = treeBranch[1] P3 = treeBranch[2] P4 = treeBranch[3] ratioX = ratioBranch[0] ratioY = ratioBranch[1] line1 = rs.AddLine(P1, P2) line1 = rs.coercecurve(line1) pointXmin = rh.Geometry.Curve.PointAtNormalizedLength( line1, ratioY) line2 = rs.AddLine(P3, P4) line2 = rs.coercecurve(line2) pointXmax = rh.Geometry.Curve.PointAtNormalizedLength( line2, ratioY) line3 = rs.AddLine(pointXmin, pointXmax) line3 = rs.coercecurve(line3) point = rh.Geometry.Curve.PointAtNormalizedLength( line3, ratioX) path = ghpath(treePath.CullElement()) treeOut.Add(point, path)
def trimOffsetCurves(crvGuids): intersectParams = {} for x in range(0, crvGuids.Count): intersectParams[x] = [] for x in range(0, crvGuids.Count - 1): for y in range(x + 1, crvGuids.Count): if crvGuids[x] != crvGuids[y]: #Check Intersect Curves crvA = rs.coercecurve(crvGuids[x]) crvB = rs.coercecurve(crvGuids[y]) intersections = rg.Intersect.Intersection.CurveCurve( crvA, crvB, sc.doc.ModelAbsoluteTolerance, sc.doc.ModelAbsoluteTolerance) if intersections.Count > 0: intersectParams[x].append(intersections[0].ParameterA) intersectParams[y].append(intersections[0].ParameterB) retGuids = [] for x in range(0, crvGuids.Count): if intersectParams[x][0] > intersectParams[x][1]: tA = intersectParams[x][1] tB = intersectParams[x][0] else: tA = intersectParams[x][0] tB = intersectParams[x][1] guid = rs.TrimCurve(crvGuids[x], (tA, tB)) if guid != None: retGuids.append(guid) return retGuids
def process_floor(in_objects, floor_outline, outline_cut_height=None): """function used to process an individual floor. input: in_objects: the internal curves and breps selected for this floor floor_outline: the outline brep for the envelope outline_cut_height: height to cut at. output: (crv,[crv]) crv: the offset boundary curve for the floor [crv]: the internal curves for the floor pt: lower-left reference point bdims = bounding dims of this floor """ #classify the inputs in_crvs, in_breps = brep_or_crv(in_objects) #get list of crvs to project brep_sections = [] for b in in_breps: cut_height = wge.get_brep_height(b) / 2 pcurves = wge.get_brep_plan_cut(rs.coercebrep(b), cut_height, D_TOL) brep_sections.extend(pcurves) b_section_guids = wru.add_curves_to_layer(brep_sections, LCUT_INDICES[0]) in_crvs.extend(b_section_guids) #get the outline brep curve if not outline_cut_height: outline_cut_height = wge.get_brep_height(floor_outline) floor_outline_crvs = wge.get_brep_plan_cut(rs.coercebrep(floor_outline), outline_cut_height, D_TOL) floor_outline_crvs = wru.add_curves_to_layer(floor_outline_crvs, LCUT_INDICES[1]) #get bounding info for the floor outline bb = rs.BoundingBox(floor_outline) corner = bb[0] bdims = wge.get_bounding_dims(floor_outline) proj_srf = rs.AddSrfPt([bb[0], bb[1], bb[2], bb[3]]) internal_crvs = rs.ProjectCurveToSurface(in_crvs, proj_srf, [0, 0, -1]) if in_crvs else [] offset_floor_crv = rs.ProjectCurveToSurface(floor_outline_crvs, proj_srf, [0, 0, -1]) #rs.DeleteObjects(in_crvs) rs.DeleteObjects(floor_outline_crvs) rs.DeleteObject(proj_srf) out_floor_crvs = rs.coercecurve(offset_floor_crv) out_internal_crvs = [rs.coercecurve(x) for x in internal_crvs] rs.DeleteObject(offset_floor_crv) rs.DeleteObjects(internal_crvs) rs.DeleteObjects(b_section_guids) #TODO: make sure objects are being deleted return out_floor_crvs, out_internal_crvs, corner, bdims
def CollectChairs(): # collect chairs + CLs chair0 = rs.coercebrep(rs.ObjectsByLayer("chair0")) chair0_CL = rs.coercecurve(rs.ObjectsByLayer("chair0_CL")) chair1 = rs.coercebrep(rs.ObjectsByLayer("chair1")) chair1_CL = rs.coercecurve(rs.ObjectsByLayer("chair1_CL")) # create chair objects chair0_Obj = Chair(chair0, chair0_CL) chair1_Obj = Chair(chair1, chair1_CL) return([chair0_Obj, chair1_Obj])
def RemoveOverlappingCurves(setA, setB, tolerance=0.1): # doc.ModelAbsoluteTolerance ''' Compare low/high precision Curve sets and remove low precision Cuve when overlapping. Parameters: setA : list<Rhino.DocObjects.RhinoObject> Low precision Curve identifiers setB : list<Rhino.DocObjects.RhinoObject> High precision Curve identifiers tolerance : float ''' for i2, obj1 in enumerate(setA): c1 = rs.coercecurve(obj1) if c1: for i2, obj2 in enumerate(setB): c2 = rs.coercecurve(obj2) if c2: result = Intersect.Intersection.CurveCurve( c1, c2, tolerance, tolerance) if result: for event in result: if event.IsOverlap: deviation = Curve.GetDistancesBetweenCurves( c1, c2, tolerance) # minA = deviation[5] maxaA = deviation[2] # maxB = deviation[3] # minB = deviation[6] # minDeviation = deviation[4] maxDeviation = deviation[1] if maxDeviation < tolerance: l1 = c1.Length if hasattr( c1, 'Length') else c1.GetLength() l2 = c2.Length if hasattr( c2, 'Length') else c2.GetLength() # Keep if longer otherwise delete low precision Curve if l1 > l2: rs.DeleteObject(obj2) else: rs.DeleteObject(obj1)
def slice_sequence(crvs, seq_count): pt_slice = [] frame = 1 / seq_count # print frame for i in xrange(len(crvs)): crv = crvs[i] crv = rs.coercecurve(crv) start_pt, end_pt = rs.CurveDomain(crv) # print start_pt, "to", end_pt ### [0 to len(Curves)] param_slice = [] for j in xrange(int(end_pt)): for k in xrange(seq_count): value = j + k * frame param_slice.append(value) param_slice.append(end_pt) # print param_slice # print len(param_slice) sub_list = [] for l in xrange(len(param_slice)): pt = rg.Curve.PointAt(crv, param_slice[l]) sub_list.append(pt) pt_slice.append(sub_list) return pt_slice
def hatchthis(s): #offset all segments s = rs.coercecurve(s) offsets = s.Offset(plane, scale / 2, tol, style) if offsets: p1, p2, curve1 = getPointsAndLines(offsets) offsets = s.Offset(plane, -scale / 2, tol, style) if offsets: p3, p4, curve2 = getPointsAndLines(offsets) if not (p1 and p2 and p3 and p4): return #create end lines between the two offset curves line1 = rs.AddLine(p1, p3) line2 = rs.AddLine(p2, p4) polyline = rs.JoinCurves([line1, line2, curve1, curve2], True, tol) # FINALLY: hatch the bloody thing hatch = rs.AddHatch(polyline, 'Solid') #clean up rs.DeleteObject(polyline) return hatch
def set_pipe_lengths(self, _input=[], _ghdoc=None, _ghenv=None): """Will try and find the lengths of the things input Arguments: _input: (float: curve:) If input is number, uses that. Otherwise gets curve from Rhino _ghdoc: (ghdoc) _ghenv: (ghenv) """ output = [] with context_rh_doc( _ghdoc ): for geom_input in _input: try: output.append( float(convert_value_to_metric(geom_input, 'M')) ) except AttributeError as e: crv = rs.coercecurve(geom_input) if crv: pipeLen = ghc.Length(crv) else: pipeLen = False if not pipeLen: crvWarning = "Something went wrong getting the Pipe Geometry length?\n"\ "Please ensure you are passing in only curves / polyline objects or numeric values.?" _ghenv.Component.AddRuntimeMessage(ghK.GH_RuntimeMessageLevel.Warning, crvWarning) else: output.append(pipeLen) self.length = output
def GetSegmentLengths(obj): rhobj = rs.coercecurve(obj) segments = rhobj.DuplicateSegments() distances = [] for segment in segments: distances.append(segment.GetLength()) return distances
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 GenerateCrossSection(sectionPoints, radius, rotation, smooth, curve, samples, p, q): points = [] avoidRoundoff = 0.01 for angle in rs.frange(0.0, 360.0+avoidRoundoff, 360.0/sectionPoints): points.append(rs.Polar((0.0, 0.0, 0.0), angle, radius)) rotXform = rs.XformRotation2(rotation, (0, 0, 1), (0, 0, 0)) points = rs.PointArrayTransform(points, rotXform) t = curve.Domain[0] crossSections = [] curveCurvature = curve.CurvatureAt(t) crossSectionPlane = None if not curveCurvature: crvPoint = curve.PointAt(t) crvTangent = curve.TangentAt(t) crvPerp = (0,0,1) crvNormal = Rhino.Geometry.Vector3d.CrossProduct(crvTangent, crvPerp) crossSectionPlane = Rhino.Geometry.Plane(crvPoint, crvPerp, crvNormal) else: crvPoint = curve.PointAt(t) crvTangent = curve.TangentAt(t) crvPerp = curve.CurvatureAt(t) crvPerp.Unitize crvNormal = Rhino.Geometry.Vector3d.CrossProduct(crvTangent, crvPerp) crossSectionPlane = Rhino.Geometry.Plane(crvPoint, crvPerp, crvNormal) if crossSectionPlane: xform = rs.XformChangeBasis(crossSectionPlane, rs.WorldXYPlane()) sectionVerts = rs.PointArrayTransform(points, xform) if (smooth): # Degree 3 curve to smooth it sectionCurve = Rhino.Geometry.Curve.CreateControlPointCurve(sectionVerts, 3) else: # Degree 1 curve (polyline) sectionCurve = Rhino.Geometry.Curve.CreateControlPointCurve(sectionVerts, 1) crossSection = rs.coercecurve(sectionCurve) return crossSection
def SampleEditPoints(): obj_id = rs.GetObject('Select curve', rs.filter.curve) if not obj_id: return crv = rs.coercecurve(obj_id) if not crv: return nc = crv.ToNurbsCurve() # NurbsCurve.GrevilleParameters always returns all parameters, even for # perodic curves. Otherwise, it would not be possible to determine # which subset of the full list of Greville abcissae was returned. t_list = nc.GrevilleParameters() # Filter out what we don't want so it looks like what we'd see if # we ran the EditPtOn command if t_list: t = 0 t_count = t_list.Count if nc.IsPeriodic: t_count -= nc.Order - 1 rc = 0 while True: if rc < nc.Order - 1 and t_list[t] < nc.Knots[nc.Order - 2]: rc += 1 t += 1 continue break elif nc.IsClosed: t_count -= 1 for n in range(t, t + t_count): rs.AddPoint(nc.PointAt(t_list[n]))
def circleWithRadiusOf10GeometryFilter(rhObject, geometry, componentIndex): isCircleWithRadiusOf10 = False c = rs.coercecurve(geometry) if c: b, circle = c.TryGetCircle() if b: isCircleWithRadiusOf10 = circle.Radius <= 10.0 + Rhino.RhinoMath.ZeroTolerance and circle.Radius >= 10.0 - Rhino.RhinoMath.ZeroTolerance return isCircleWithRadiusOf10
def circleWithRadiusOf10GeometryFilter (rhObject, geometry, componentIndex): isCircleWithRadiusOf10 = False c = rs.coercecurve(geometry) if c: b, circle = c.TryGetCircle() if b: isCircleWithRadiusOf10 = circle.Radius <= 10.0 + Rhino.RhinoMath.ZeroTolerance and circle.Radius >= 10.0 - Rhino.RhinoMath.ZeroTolerance return isCircleWithRadiusOf10
def __init__(self, siteBdy, noIterations): self.siteBdyGUID = siteBdy self.segments = rs.ExplodeCurves(siteBdy) self.initialSegment = rs.coercecurve(self.segments[0]) self.siteBdy = rs.coercecurve(siteBdy) self.boundaries = [] self.boundaries.append(self.siteBdyGUID) self.roadSegments = [] self.cuttingLines = [] self.offsetLines = [] self.noIterations = noIterations self.makeSegments(self.initialSegment, self.boundaries, noIterations, -1, 1)
def calc_overlap_area_ratio(c1, c2): c1 = rs.coercecurve(c1) c2 = rs.coercecurve(c2) geo_area = rs.CurveArea(c1)[0] overlap_region = c1.CreateBooleanIntersection(c1, c2) if overlap_region: overlap_area = rg.AreaMassProperties.Compute(overlap_region).Area overlap_area_ratio = (overlap_area / geo_area) * 100 debug_print("overlap area ratio: {}%".format( round(overlap_area_ratio, 1))) return overlap_area_ratio else: return 0
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 FindMostDistantPointInCurve(obj, resolution = 20): """ Returns the approximately most distant point within a closed curve inputs: obj (curve): closed planar curves resolution (int)[optional]: numbers of sample points in a resolutionXresolution grid returns: point (point): point furthest from curve """ if rs.IsCurve(obj) == False: print "Curves supported only" return None if rs.IsCurvePlanar(obj) == False: print "Curve not planar" return None if rs.IsCurveClosed(obj) == False: print "Curve not closed" return None rhobj = rs.coercecurve(obj) bbox = rhobj.GetBoundingBox(rs.WorldXYPlane()) minX = bbox.Min[0] minY = bbox.Min[1] minZ = bbox.Min[2] maxX = bbox.Max[0] maxY = bbox.Max[1] maxZ = bbox.Max[2] xVals = [] yVals = [] for i in range(resolution): xVals.append(i) yVals.append(i) newXvals = RemapList(xVals, minX, maxX) newYvals = RemapList(yVals, minY, maxY) furthestPt = None furthestDist = 0 maxDist = 99999 for xVal in newXvals: for yVal in newYvals: newPt = rc.Geometry.Point3d(xVal, yVal, minZ) result = rhobj.Contains(newPt, rs.WorldXYPlane()) if result == rc.Geometry.PointContainment.Inside: param = rhobj.ClosestPoint(newPt, maxDist) crvPt = rhobj.PointAt(param[1]) dist = rs.Distance(crvPt, newPt) if dist > furthestDist: furthestPt = newPt furthestDist = dist if furthestDist == 0: return None return furthestPt
def ccx_points(c1, c2): c1 = rs.coercecurve(c1) c2 = rs.coercecurve(c2) # Calculate the intersection intersection_tolerance = 0.001 overlap_tolerance = 0.0 events = Rhino.Geometry.Intersect.Intersection.CurveCurve( c1, c2, intersection_tolerance, overlap_tolerance) # Process the results if not events: return False else: pts = [] for ccx_event in events: pts.append(sc.doc.Objects.AddPoint(ccx_event.PointA)) return pts
def isSubCrvLine(rhObject,geometry, componentIndex): isSubCrvLine = False print componentIndex.Index #if componentIndex.Index < 1: return False c = rs.coercecurve(geometry) if c: isSubCrvLine, line = c.TryGetLine() return isSubCrvLine
def SampleSetCurveWeight(): crv_id = rs.GetObject(preselect=True) crv = rs.coercecurve(crv_id) nc = crv.ToNurbsCurve() SetCurveWeight(nc, 2, 0.1) sc.doc.Objects.Replace(crv_id, nc) sc.doc.Views.Redraw()
def main(north, _boundary, timeperiod, monthRange, location, height): if sc.sticky.has_key('ladybug_release'): try: if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component): return -1 if sc.sticky['ladybug_release'].isInputMissing(ghenv.Component): return -1 except: warning = "You need a newer version of Ladybug to use this compoent." + \ "Use updateLadybug component to update userObjects.\n" + \ "If you have already updated userObjects drag Ladybug_Ladybug component " + \ "into canvas and try again." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, warning) return -1 latitude, longitude, timeZone, elevation = readLocation(location) year = datetime.datetime.now().year day = 21 s_mth, e_mth = MONTH_DICT[monthRange][0], MONTH_DICT[monthRange][1] s_snoon = get_solarnoon(s_mth, year, timeZone, day, latitude, longitude) e_snoon = get_solarnoon(e_mth, year, timeZone, day, latitude, longitude) """solar variables""" shourlst, ehourlst, day = getSolarData(timeperiod, s_snoon, e_snoon) """work with curves""" curve_ = rs.coercecurve(_boundary, -1, True) boundary_lst = checkConcaveConvex(curve_) chull_lst = [] top_lst = [] # for testing purposes if type(boundary_lst) != type([]): boundary_lst = [_boundary] for boundary_ in boundary_lst: boundary = clean_curve(boundary_) bcurve,tc = getSolarGeom(boundary,height,latitude,\ shourlst,ehourlst,day,north,longitude,timeZone,s_mth,e_mth) chull_lst.append(bcurve) top_lst.extend(tc) b2ch = Curve2ConvexHull3d() breplst, ptlst = b2ch.get_convexhull(chull_lst) L = map(lambda m: rs.coercebrep(m), breplst) CB = CleanBrep(TOL, L) map(lambda id: sc.doc.Objects.Delete(id, True), breplst) #delete breplst return CB.cleanBrep() ##bcurve = boundary_lst ## for testing purposes ##top_curves = top_lst ## for testing purposes else: print "You should first let the Ladybug fly..." ghenv.Component.AddRuntimeMessage( ERROR_W, "You should first let the Ladybug fly...")
def DimAngles(obj, offset): curve = rs.coercecurve(obj) segments = curve.DuplicateSegments() for i, segment in enumerate(segments): if i == len(segments) - 1: break DimSegmentAngle(segments[i], segments[i + 1], offset) print "" if rs.IsCurveClosed(obj): DimSegmentAngle(segments[-1], segments[0], offset)
def sweep1(rail, cross_sections): rail_crv = rs.coercecurve(rail) if not rail_crv: return 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.MiterType = 2 sweep.SweepTolerance = scriptcontext.doc.ModelAbsoluteTolerance sweep.SetToRoadlikeTop() breps = sweep.PerformSweep(rail_crv, cross_sections) guids=[] for brep in breps: rc = scriptcontext.doc.Objects.AddBrep(brep) guids.append(rc) scriptcontext.doc.Views.Redraw() return guids
def get_camera_by_curve(guid): """ Given a curve guid, return an origin and target. """ curve = rs.coercecurve(guid, -1, True) origin = curve.PointAt(0) target = curve.PointAt(1) return origin, target
def ReverseCurves(): crvs = rs.GetObjects("Select curves to reverse", rs.filter.curve) if not crvs: return for crvid in crvs: crv = rs.coercecurve(crvid) if not crv: continue dup = crv.DuplicateCurve() if dup: dup.Reverse() doc.Objects.Replace(crvid, dup)
def IsPointOnLeftSide(point, curve): rhcrv = rs.coercecurve(curve) closestPtParam = rhcrv.ClosestPoint(point)[1] closestPt = rhcrv.PointAt(closestPtParam) vec = rs.VectorCreate(closestPt, point) tanVec = rhcrv.TangentAt(closestPtParam) x = tanVec.VectorAngle(tanVec, vec, rs.WorldXYPlane()) if math.degrees(x) - 180 > 0: return False else: return True
def GetCornerAngles(obj): internalCornerAngles = [] rhobj = rs.coercecurve(obj) segments = rhobj.DuplicateSegments() plane = rs.WorldXYPlane() for i in range(1, len(segments)): internalCornerAngles.append(GetAngleBetween2Segments(segments[i-1], segments[i], plane)) if rhobj.IsClosed: internalCornerAngles.append(GetAngleBetween2Segments(segments[-1], segments[0], plane)) return internalCornerAngles
def main(): obj = rs.GetObject("Select Objects", preselect = True) obj = rs.coercecurve(obj) cw, cc = SplitSelfIntersection(obj) #bbox = minBoundingBox(obj) for crv in cw: sc.doc.Objects.AddCurve(crv) for crv in cc: sc.doc.Objects.AddCurve(crv)
def GenerateCylindricalSlot(): filled = False radius = 6 + random.random()*6 length = 15 + random.random()*5 centerPoint = Rhino.Geometry.Point3d(0,0,0) orientation = Rhino.Geometry.Vector3d(1,0,0) brepCylinder = AddCylinder(centerPoint,orientation,radius,length) curveLength = 3 + random.random()*(2*math.pi*radius -3) angleCovered = (curveLength/2*math.pi*radius)*2*math.pi startAngle = 0 + random.random()*(2*math.pi-angleCovered) endAngle = startAngle + angleCovered widthOfSlot = 2 + random.random()*(6-2); randomPointOnALength = 2 + random.random()*(length -2 - widthOfSlot/2); curvPoint1 = Rhino.Geometry.Point3d(randomPointOnALength,radius*(math.cos(startAngle)),radius*(math.sin(startAngle))) curvPoint2 = Rhino.Geometry.Point3d(randomPointOnALength,radius*(math.cos(startAngle*0.5 + endAngle*0.5)),radius*(math.sin(startAngle*0.5 + endAngle*0.5))) curvPoint3 = Rhino.Geometry.Point3d(randomPointOnALength,radius*(math.cos(endAngle)),radius*(math.sin(endAngle))) arc = rs.AddArc3Pt(curvPoint1,curvPoint3,curvPoint2) arcBrep = rs.coercecurve(arc) height = 2 + random.random()*(4-2) point1 = Rhino.Geometry.Point3d(randomPointOnALength - widthOfSlot/2 ,(radius+height/2)*math.cos(startAngle),(radius+height/2)*math.sin(startAngle)) point2 = Rhino.Geometry.Point3d(randomPointOnALength - widthOfSlot/2 ,(radius-height/2)*math.cos(startAngle),(radius-height/2)*math.sin(startAngle)) point3 = Rhino.Geometry.Point3d(randomPointOnALength + widthOfSlot/2 ,(radius-height/2)*math.cos(startAngle),(radius-height/2)*math.sin(startAngle)) point4 = Rhino.Geometry.Point3d(randomPointOnALength + widthOfSlot/2 ,(radius+height/2)*math.cos(startAngle),(radius+height/2)*math.sin(startAngle)) point5 = point1 points = [point1,point2,point3,point4,point5] rectSrf = rs.AddPolyline(points) rectSurfBrep = rs.coercecurve(rectSrf) rs.DeleteObjects(arc) rs.DeleteObjects(rectSrf) breps = Rhino.Geometry.Brep.CreateFromSweep(arcBrep,rectSurfBrep,True,scriptcontext.doc.ModelAbsoluteTolerance) brepsCurveBox = Rhino.Geometry.Brep.CapPlanarHoles(breps[0],scriptcontext.doc.ModelAbsoluteTolerance) brepArray = Rhino.Geometry.Brep.CreateBooleanDifference([brepCylinder],[brepsCurveBox],scriptcontext.doc.ModelAbsoluteTolerance) scriptcontext.doc.Views.Redraw() if(brepArray is not None and brepCylinder.GetBoundingBox(Rhino.Geometry.Vector3d(0,0,1)).Volume == brepArray[0].GetBoundingBox(Rhino.Geometry.Vector3d(0,0,1)).Volume): for brep in brepArray: scriptcontext.doc.Objects.AddBrep(brep) scriptcontext.doc.Views.Redraw() return 1 else : return 0
def OffsetCurveOnSurface(self, border, face, offsetDist): success = False glzArea = 0 direction = 1 # Try RhinoCommon glzCurve = border.OffsetOnSurface(face.Faces[0], offsetDist, tolerance) if glzCurve==None: glzCurve = border.OffsetOnSurface(face.Faces[0], -offsetDist, tolerance) direction = -1 if glzCurve == None: # Magically Steve Baer's script works in many cases that RhinoCommon Fails # I checked the source code in gitHub and it looks exactly the same as the lines above! # I have no idea what am I doing wrong! [Jan 19 2013] print "RhinoCommon failed to offsetCurveOnSurface... Testing Steve Baer's magic!" rsborder = sc.doc.Objects.AddCurve(border) rsface = sc.doc.Objects.AddSurface(face.Faces[0]) glzCurve = rs.OffsetCurveOnSurface(rsborder, rsface, offsetDist) if glzCurve==None: glzCurve = rs.OffsetCurveOnSurface(rsborder, rsface, -offsetDist) direction = -1 rs.DeleteObjects([rsface, rsborder]) if glzCurve!=None: try: glzCurve = [rs.coercecurve(glzCurve)] except: glzCurve = [rs.coercecurve(glzCurve[0])] print "Magic worked!" if glzCurve!=None: glzCurve = glzCurve[0] splitter = rc.Geometry.Surface.CreateExtrusion(glzCurve, self.getSrfAreaAndCenPt(face, calArea = False)[2]).ToBrep() splittedSrfs = face.Split(splitter, sc.doc.ModelAbsoluteTolerance) try: glzSrf = splittedSrfs[-1] glzArea = glzSrf.GetArea() success = True joinedSrf = rc.Geometry.Brep.JoinBreps(splittedSrfs, tolerance)[0] except Exception, e: print "Split surface failed!\n" + `e` return True, glzArea, glzCurve, None
def RunCommand(): crvA = rs.GetCurveObject("first curve")[0] crvA = rs.coercecurve(crvA) crvB = rs.GetCurveObject("second curve")[0] crvB = rs.coercecurve(crvB) if crvA == None or crvB == None: return Rhino.Commands.Result.Failure maxa, maxb, maxd, mina, minb, mind = rs.CurveDeviation(crvA, crvB) if mind <= Rhino.RhinoMath.ZeroTolerance: mind = 0.0; maxDistPtA = crvA.PointAt(maxa) maxDistPtB = crvB.PointAt(maxb) minDistPtA = crvA.PointAt(mina) minDistPtB = crvB.PointAt(minb) print "Minimum deviation = {0} pointA({1}, {2}, {3}), pointB({4}, {5}, {6})".format( mind, minDistPtA.X, minDistPtA.Y, minDistPtA.Z, minDistPtB.X, minDistPtB.Y, minDistPtB.Z) print "Maximum deviation = {0} pointA({1}, {2}, {3}), pointB({4}, {5}, {6})".format( maxd, maxDistPtA.X, maxDistPtA.Y, maxDistPtA.Z, maxDistPtB.X, maxDistPtB.Y, maxDistPtB.Z)
def main(north,_boundary,timeperiod,monthRange,location,height): if sc.sticky.has_key('ladybug_release'): try: if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component): return -1 if sc.sticky['ladybug_release'].isInputMissing(ghenv.Component): return -1 except: warning = "You need a newer version of Ladybug to use this compoent." + \ "Use updateLadybug component to update userObjects.\n" + \ "If you have already updated userObjects drag Ladybug_Ladybug component " + \ "into canvas and try again." w = gh.GH_RuntimeMessageLevel.Warning ghenv.Component.AddRuntimeMessage(w, warning) return -1 latitude,longitude,timeZone,elevation = readLocation(location) year = datetime.datetime.now().year day = 21 s_mth,e_mth = MONTH_DICT[monthRange][0], MONTH_DICT[monthRange][1] s_snoon = get_solarnoon(s_mth,year,timeZone,day,latitude,longitude) e_snoon = get_solarnoon(e_mth,year,timeZone,day,latitude,longitude) """solar variables""" shourlst,ehourlst,day = getSolarData(timeperiod,s_snoon,e_snoon) """work with curves""" curve_ = rs.coercecurve(_boundary, -1, True) boundary_lst = checkConcaveConvex(curve_) chull_lst = [] top_lst = [] # for testing purposes if type(boundary_lst) != type([]): boundary_lst = [_boundary] for boundary_ in boundary_lst: boundary = clean_curve(boundary_) bcurve,tc = getSolarGeom(boundary,height,latitude,\ shourlst,ehourlst,day,north,longitude,timeZone,s_mth,e_mth) chull_lst.append(bcurve) top_lst.extend(tc) b2ch = Curve2ConvexHull3d() breplst,ptlst = b2ch.get_convexhull(chull_lst) L = map(lambda m: rs.coercebrep(m),breplst) CB = CleanBrep(TOL,L) map(lambda id: sc.doc.Objects.Delete(id,True), breplst) #delete breplst return CB.cleanBrep() ##bcurve = boundary_lst ## for testing purposes ##top_curves = top_lst ## for testing purposes else: print "You should first let the Ladybug fly..." ghenv.Component.AddRuntimeMessage(ERROR_W, "You should first let the Ladybug fly...")
def CreateDomeGrid(treeIn, treeOut): for i in range(treeIn.BranchCount): treeBranch = treeIn.Branch(i) treePath = treeIn.Path(i) path = ghpath(treePath.CullElement()) if treeBranch[0] != treeBranch[1]: curves = rs.AddCurve(treeBranch) curves = rs.coercecurve(curves) treeOut.Add(curves, path)
def RunCommand(): crvA = rs.GetCurveObject("first curve")[0] crvA = rs.coercecurve(crvA) crvB = rs.GetCurveObject("second curve")[0] crvB = rs.coercecurve(crvB) if crvA == None or crvB == None: return Rhino.Commands.Result.Failure maxa, maxb, maxd, mina, minb, mind = rs.CurveDeviation(crvA, crvB) if mind <= Rhino.RhinoMath.ZeroTolerance: mind = 0.0 maxDistPtA = crvA.PointAt(maxa) maxDistPtB = crvB.PointAt(maxb) minDistPtA = crvA.PointAt(mina) minDistPtB = crvB.PointAt(minb) print "Minimum deviation = {0} pointA({1}, {2}, {3}), pointB({4}, {5}, {6})".format( mind, minDistPtA.X, minDistPtA.Y, minDistPtA.Z, minDistPtB.X, minDistPtB.Y, minDistPtB.Z) print "Maximum deviation = {0} pointA({1}, {2}, {3}), pointB({4}, {5}, {6})".format( maxd, maxDistPtA.X, maxDistPtA.Y, maxDistPtA.Z, maxDistPtB.X, maxDistPtB.Y, maxDistPtB.Z)
def _set_params_from_rhino_obj(self, _duct_input): if not self._ghdoc: return None if not self._duct_input: return None rhino_guids = [] with LBT2PH.helpers.context_rh_doc(self._ghdoc): for input in _duct_input: try: rs.coercecurve(input) rhino_guids.append(input) except: pass if rhino_guids: le, wd, tk, la = self._calculate_segment_params(rhino_guids) self._duct_length = [le] self._duct_width = [wd] self._insulation_thickness = [tk] self._insulation_lambda = [la]
def inset_rhino_surface(_srfc, _inset_dist=0.001, _srfc_name=""): """ Insets/shrinks a Rhino Brep some dimension Arg: _srfc: A Rhino Brep _inset_dist: float: Default=0.001m _srfc_name: str: The name of the surface, used for error messages Returns: new_srfc: A new Rhino surface, shrunk/inset by the specified amount """ #----------------------------------------------------------------------- # Get all the surface params needed srfc_Center = ghc.Area(_srfc).centroid srfc_normal_vector = brep_avg_surface_normal(_srfc) srfc_edges = ghc.DeconstructBrep(_srfc).edges srfc_perimeter = ghc.JoinCurves(srfc_edges, False) #----------------------------------------------------------------------- # Try to inset the perimeter Curve inset_curve = rs.OffsetCurve(srfc_perimeter, srfc_Center, _inset_dist, srfc_normal_vector, 0) #----------------------------------------------------------------------- # In case the new curve goes 'out' and the offset fails # Or is too small and results in multiple offset Curves if len(inset_curve)>1: warning = 'Error. The surface: "{}" is too small. The offset of {} m"\ "can not be done. Check the offset size?'.format(_srfc_name, _inset_dist) print(warning) inset_curve = rs.OffsetCurve(srfc_perimeter, srfc_Center, 0.001, srfc_normal_vector, 0) inset_curve = rs.coercecurve( inset_curve[0] ) else: inset_curve = rs.coercecurve( inset_curve[0] ) new_srfc = ghc.BoundarySurfaces(inset_curve) return new_srfc
def projectPtOnSrf(attractorPt, targetSrf, pt): r = rs.AddLine(attractorPt, pt) r = rs.ScaleObject(r, attractorPt, (10, 10,10)) dom = rs.CurveDomain(r) crv = rs.coercecurve(r) srf = rs.coercesurface(targetSrf).ToNurbsSurface() inv = Interval(dom[0], dom[1]) rs.DeleteObject(r) xobj = Intersection.CurveSurface(crv, inv, srf, 0.1, 1) return xobj[0].PointB
def projectPtOnSrf(attractorPt, targetSrf, pt): r = rs.AddLine(attractorPt, pt) r = rs.ScaleObject(r, attractorPt, (10, 10, 10)) dom = rs.CurveDomain(r) crv = rs.coercecurve(r) srf = rs.coercesurface(targetSrf).ToNurbsSurface() inv = Interval(dom[0], dom[1]) rs.DeleteObject(r) xobj = Intersection.CurveSurface(crv, inv, srf, 0.1, 1) return xobj[0].PointB
def UpdateGeometry(self, data): self.surface = None self.surfaceBBox = None tempVerts = TorusKnotVerts(data.p, data.q, data.pathPointCount, data.zScale) self.railCurve = Rhino.Geometry.Curve.CreateControlPointCurve(tempVerts, 3) self.railCurveBBox = self.railCurve.GetBoundingBox(False) rail = rs.coercecurve(self.railCurve) # Generate a section curve at the start of the rail self.crossSection = GenerateCrossSection(data.crossSecPointCount, data.crossSecRadius, data.crossSecRotation, data.smoothCrossSec, self.railCurve, data.pathPointCount, data.p, data.q) if (data.outputSurface): # Sweep it out about the rail curve tolerance = scriptcontext.doc.ModelAbsoluteTolerance breps = Rhino.Geometry.Brep.CreateFromSweep(rail, self.crossSection, rail.IsClosed, tolerance) self.surface = breps[0] self.surfaceBBox = self.surface.GetBoundingBox(False) scriptcontext.doc.Views.Redraw()
def extrude_solid(pt,cp,b): # int_solid: (listof pt) pt curve -> (listof solid) lo_solid = [] ptlst = rs.CurvePoints(b) srf = rs.AddPlanarSrf(rs.AddCurve(ptlst,1)) # make curve and extrude line = rs.AddCurve([cp,pt],1) max = get_max_side(b) curve = rs.ExtendCurveLength(line,0,1,max*40) #extrude surface brep = rs.coercebrep(srf, True) curve = rs.coercecurve(curve, -1, True) newbrep = brep.Faces[0].CreateExtrusion(curve, True) if newbrep: rc = sc.doc.Objects.AddBrep(newbrep) sc.doc.Views.Redraw() return rc
def RunCommand(): srfid = rs.GetObject("select surface", rs.filter.surface | rs.filter.polysurface) if not srfid: return crvid = rs.GetObject("select curve", rs.filter.curve) if not crvid: return result = rs.CurveBrepIntersect(crvid, srfid) if result == None: print "no intersection" return curves, points = result for curve in curves: doc.Objects.AddCurve(rs.coercecurve(curve)) for point in points: rs.AddPoint(point) doc.Views.Redraw()
def clean_curve(b): """Clean curve geometry 1. Checks if guid or object 2. Simplifiebs 3. Reverse curve dirn 4. Closes curve if not already closed """ if type(b) == type(rs.AddPoint(0,0,0)): # already guid pass else: b = sc.doc.Objects.AddCurve(b) rs.SimplifyCurve(b) # reverse curve direction boundarybrep = rs.coercecurve(b) Rhino.Geometry.Curve.Reverse(boundarybrep) sc.doc.Objects.Replace(b,boundarybrep) if rs.IsCurveClosed(b): return b else: return rs.CloseCurve(b)
def main(north,_boundary,timeperiod,monthRange,location,height): if sc.sticky.has_key('ladybug_release'): latitude,longitude,timeZone,elevation = readLocation(location) year = datetime.datetime.now().year day = 21 s_mth,e_mth = MONTH_DICT[monthRange][0], MONTH_DICT[monthRange][1] s_snoon = get_solarnoon(s_mth,year,timeZone,day,latitude,longitude) e_snoon = get_solarnoon(e_mth,year,timeZone,day,latitude,longitude) """solar variables""" shourlst,ehourlst,day = getSolarData(timeperiod,s_snoon,e_snoon) """work with curves""" curve_ = rs.coercecurve(_boundary, -1, True) boundary_lst = checkConcaveConvex(curve_) chull_lst = [] top_lst = [] # for testing purposes if type(boundary_lst) != type([]): boundary_lst = [_boundary] for boundary_ in boundary_lst: boundary = clean_curve(boundary_) bcurve,tc = getSolarGeom(boundary,height,latitude,\ shourlst,ehourlst,day,north,longitude,timeZone,s_mth,e_mth) chull_lst.append(bcurve) top_lst.extend(tc) b2ch = Curve2ConvexHull3d() breplst,ptlst = b2ch.get_convexhull(chull_lst) L = map(lambda m: rs.coercebrep(m),breplst) CB = CleanBrep(TOL,L) map(lambda id: sc.doc.Objects.Delete(id,True), breplst) #delete breplst return CB.cleanBrep() ##bcurve = boundary_lst ## for testing purposes ##top_curves = top_lst ## for testing purposes else: print "You should first let the Ladybug fly..." ghenv.Component.AddRuntimeMessage(ERROR_W, "You should first let the Ladybug fly...")
allLineConstraints = [] for i in range(lineConstrainedPoints.BranchCount): if len(lineConstrainedPoints.Branch(i))>1 and lineConstrainedPoints.Branch(i)[0] is not None: vect = lineConstrainedPoints.Branch(i)[0] pts = [] for j in itertools.islice(lineConstrainedPoints.Branch(i),1,None): if j is not None: pts.append (j) parts = DynamicRelaxation.makeForceConstraintsFromList(ps,makePtsFromRhino(pts),makePtFromRhino(vect), False) allLineConstraints.append(parts) #### rail constrained points allRailConstraints = [] for i in range(railConstrainedPoints.BranchCount): if len(railConstrainedPoints.Branch(i))>1 and railConstrainedPoints.Branch(i)[1] is not None: rail = CurveConstraint(rs.coercecurve(railConstrainedPoints.Branch(i)[0])) pts = [] for j in itertools.islice(railConstrainedPoints.Branch(i),1,None): if j is not None: pts.append (rs.coerce3dpoint(j)) parts, springs = DynamicRelaxation.makePositionSpringConstraintsFromList(ps, makePtsFromRhino(pts),rail.apply, 1000, 0) allRailConstraints.append(parts) #### plane constrained points allPlaneConstraintPoints = [] for i in range(planeConstrainedPoints.BranchCount): if len(planeConstrainedPoints.Branch(i))>1: plVect = makePtFromRhino(planeConstrainedPoints.Branch(i)[0]) pts = [] for j in itertools.islice(planeConstrainedPoints.Branch(i),1,None): if j is not None:
"""---------------- Miru Abstract BEM ----------------""" import copy import scriptcontext as sc import clr import rhinoscriptsyntax as rs clr.AddReference("Grasshopper") from Grasshopper.Kernel.Data import GH_Path from Grasshopper import DataTree if run: rule = DataTree[object]() bem_center = rs.coercecurve(bem_center) rule_ = [\ ['abstract_bem', True],\ ['grammar_key','abstract_bem'],\ ['bem_tol',bem_tol],\ ['bem_center',bem_center],\ ['end_rule']] for i, r in enumerate(rule_): rule.Add(r) else: rule = []
import scriptcontext as sc import rhinoscriptsyntax as rs import clr Grammar = sc.sticky["Grammar"] clr.AddReference("Grasshopper") from Grasshopper.Kernel.Data import GH_Path from Grasshopper import DataTree if run: #coerce geom if set as reference if stepback_ref: G = Grammar() type_info = G.helper_get_type(stepback_ref[0]) if type_info == "geometry": stepback_ref = map(lambda l: rs.coercecurve(l),stepback_ref) else: stepback_ref = [-1] rule = DataTree[object]() rule_ = [\ ['stepback', True],\ ['grammar_key','stepback'],\ ['stepback_data', height_stepback],\ ['stepback_ref', stepback_ref],\ ['stepback_randomize', randomize],\ ['stepback_tol', stepback_tol],\ ['stepback_dir', from_rear],\ ['end_rule']] for i, r in enumerate(rule_): rule.Add(r)
def test_IncreaseByOne(self): self.assertTrue(rs.ChangeCurveDegree(self.id, 4)) self.assertEqual(4, rs.coercecurve(self.id).ToNurbsCurve().Degree)
def test_CurveIsALine(self): id = rs.AddLine(g.Point3d.Origin, (10, 10, 10)) self.assertTrue(rs.ChangeCurveDegree(id, 3)) self.assertTrue(3, rs.coercecurve(id).ToNurbsCurve().Degree)
import scriptcontext as sc import clr import rhinoscriptsyntax as rs clr.AddReference("Grasshopper") from Grasshopper.Kernel.Data import GH_Path from Grasshopper import DataTree ghenv.Component.Message = 'Bibil' Bula = sc.sticky['Bula'] if run: rule = DataTree[object]() canyon_center = rs.coercecurve(canyon_center) B = Bula() srf_data = B.ghtree2nestlist(srf_data) rule_ = [\ ['extract_canyon', True],\ ['grammar_key','extract_canyon'],\ ['canyon_tol',canyon_tol],\ ['canyon_center',canyon_center],\ ['srf_data',srf_data],\ ['end_rule']] for i, r in enumerate(rule_): rule.Add(r) else: rule = []