예제 #1
0
파일: test.py 프로젝트: tmshv/sisu
def test_is_curve_planar(options):
    layer_name = options['layer']

    objs = get_geometry_by_layer(layer_name)
    for x in objs:
        if not rs.IsCurvePlanar(x.Id):
            return False, None
    return True, None
예제 #2
0
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
예제 #3
0
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
예제 #4
0
파일: test.py 프로젝트: tmshv/sisu
def test_is_curve_planar(options):
    layer_name = options['layer']

    # log('Test: curves on layer {} should be planar'.format(layer_name))

    objs = get_geometry_by_layer(layer_name)
    for x in objs:
        if not rs.IsCurvePlanar(x.Id):
            return False
    return True
예제 #5
0
 def test_get_boundary_polyline(self):
     #deprivated, since now in general not drwaing lines
     #However, if needed can easily specifically draw cut lines
     island.make_five_by_five_square_island(self.island)
     self.island.clear()
     self.island.draw_edges()
     boundary = self.island.get_boundary_polyline()
     self.assertTrue(rs.IsPolyCurve(boundary))
     self.assertTrue(rs.IsCurveClosed(boundary))
     self.assertTrue(rs.IsCurvePlanar(boundary))
     self.island.clear()
예제 #6
0
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
예제 #7
0
 def is_overlapping(self, other_island):
     this_perimeter = self.get_boundary_polyline()
     other_perimeter = other_island.get_boundary_polyline()
     assert rs.IsCurvePlanar(
         this_perimeter), "curve of this island not planar"
     assert rs.IsCurvePlanar(
         other_perimeter), "curve of other island not planar"
     assert rs.IsCurveInPlane(
         this_perimeter,
         island_plane), "this island not in {} plane".format(island_plane)
     assert rs.IsCurveInPlane(
         other_perimeter,
         island_plane), "input island not in {} plane".format(island_plane)
     relation = rs.PlanarClosedCurveContainment(this_perimeter,
                                                other_perimeter)
     rs.DeleteObjects([this_perimeter, other_perimeter])
     assert relation != None, "PlanarClosedCurveContainment failed"
     if relation != 0:
         return True
     else:
         return False
예제 #8
0
def curveErrorCheck(curve):

    if rs.IsCurveClosed(curve):
        error = False
    else:
        print "Failed...Curve must be closed"
        error = True

    if rs.IsCurvePlanar(curve):
        error = error
    else:
        print "Failed...Curve must be planar"
        error = True
    return error
예제 #9
0
def setCurveDir(objs):
    count = 0
    for obj in objs:

        # if rs.IsCurve(obj) and rs.IsCurvePlanar(obj):
        if rs.IsCurve(obj) and rs.IsCurvePlanar(obj):
            normal = rs.CurveNormal(obj)

            if normal and normal[2] < 0:
                count += 1
                rs.ReverseCurve(obj)
                normal2 = rs.CurveNormal(obj)

                print "Curve {} flipped {}{}".format(obj, normal, normal2)

    print "reversed " + str(count) + " curves"
예제 #10
0
def setCurveDir(objs):
    count = 0
    for obj in objs:
        if rs.IsCurve(obj) and rs.IsCurvePlanar(obj):

            sp = rs.AddPoint(rs.CurveEndPoint(obj))

            tangent = rs.CurveTangent(obj, rs.CurveDomain(obj)[0])
            print tangent

            p2 = rs.CopyObject(sp, tangent * -10)

            rs.AddPoint(p2)

            # rs.Command("Dir")
            # for i in range(0,rs.PolyCurveCount(obj)):
            # l = rs.CurveLength(obj,i)
            # if l < 4:
            # print l

            # layer=rs.ObjectLayer(obj)
            # segments = rs.ExplodeCurves(obj, True)
            # obj = rs.JoinCurves(segments, True)
            # rs.ObjectLayer(obj, layer)

            # rs.ObjectLayer(obj, layer)

            normal = rs.CurveNormal(obj)
            result = rs.CurveAreaCentroid(obj)

            if result:
                print normal

                start = result[0]
                end = (result[0].X + 100 * normal[0],
                       result[0].Y + 100 * normal[1],
                       result[0].Z + 100 * normal[2])
                rs.AddLine(result[0], end)
                if normal and normal[2] < 0:
                    count += 1
                    rs.ReverseCurve(obj)

                    # print "Curve {} flipped {}{}".format(obj, normal, normal2)

            # try to find discontinuities

    print "reversed " + str(count) + " curves"
예제 #11
0
def IsRectangle(obj):
    """
    Checks if a curve is a rectangle. Must be closed, planar, 4 line segments, all 90 degrees. Uses UnitAngleTolerance
    inputs:
        obj (curve): curve to evaluate
    returns (list):
        [0] (Boolean): If rectangle
        [1] (String): explaination of why it failed
    """
    explaination = ''
    tol = rs.UnitAngleTolerance()
    rhobj = rs.coercecurve(obj)
    if rs.IsCurveClosed(obj):
        if rs.IsCurvePlanar(obj):
            segments = rhobj.DuplicateSegments()
            if len(segments) == 4:
                for segment in segments:
                    if segment.Degree != 1:
                        explaination = "Not all segments are lines"
                        return [False, explaination]
                for i in range(3):
                    angle = rs.Angle2(segments[i], segments[i+1])
                    dist1 = abs(abs(180 - angle[0])-90)
                    dist2 = abs(abs(180 - angle[1])-90)
                    if dist1 > tol or dist2 > tol:
                        explaination = "Angle not 90"
                        return [False, explaination]
                angle = rs.Angle2(segments[-1], segments[0])
                dist1 = abs(abs(180 - angle[0])-90)
                dist2 = abs(abs(180 - angle[1])-90)
                if dist1 > tol or dist2 > tol:
                    explaination = "Final angle not 90"
                    return [False, explaination]
                explaination = "ITS A RECTANGLE"
                return [True, explaination]
            else:
                explaination = "Curve does not have 4 sides"
                return [False, explaination]
        else:
            explaination = "Curve not planar"
            return [False, explaination]
    else:
        explaination = "Curve not closed"
        return [False, explaination]
예제 #12
0
    def SetPlanarCurve(self, type="Any", guid=None):
        if (type == "Any"): prompt = "Select a planar pitch curve"
        elif (type == "Circle"): prompt = "Select the pitch circle"

        newCurve = rs.GetCurveObject(prompt, True,
                                     True) if guid is None else [guid]
        if (newCurve is None):
            Rhino.RhinoApp.WriteLine("Exit: No curve was selected")
            return False
        isPlanar = rs.IsCurvePlanar(newCurve[0])
        if (isPlanar == False):
            newCurve = None
            Rhino.RhinoApp.WriteLine("Exit: Selected curve was not planar")
            return False

        self.curve = newCurve  #Accept the curve into the object because the curve exists and it is planar
        self.isClosed = rs.IsCurveClosed(self.curve[0])
        self.normal = rs.CurveNormal(
            self.curve[0])  #For non planar curves the script already exited.

        self.isCircle = rs.IsCircle(self.curve[0])
        if (type == "Circle" and self.isCircle != True):
            Rhino.RhinoApp.WriteLine("Exit: Selected curve was not a circle")
            return False

        self.crvLen = rs.CurveLength(self.curve[0])
        if (self.isCircle == True):
            Rhino.RhinoApp.WriteLine("Selected: Circle")
            self.origin = rs.CircleCenterPoint(self.curve[0])
            self.plane = rs.PlaneFromNormal(
                self.origin, self.normal,
                rs.CurveStartPoint(self.curve[0]) -
                self.origin)  #PlaneFromNormal(origin, normal, xaxis=None)
            self.SetPD()  #Propagate the value updates
            self.SetBC()  #Propagate the value updates
            return
        if (self.isClosed == True):
            Rhino.RhinoApp.WriteLine(
                "Selected: Closed non-circular planar curve")
            return
        else:
            Rhino.RhinoApp.WriteLine("Selected: Open planar curve")
예제 #13
0
def dimensionPline(pline, offsetDist):
    try:
        if rs.IsCurvePlanar(pline):
            pass
        else:
            print "Curve must be planar"
            return

        segments = []
        dimGroup = rs.AddGroup("Pline Dims")

        dir = rs.ClosedCurveOrientation(pline)
        if dir == -1:
            rs.ReverseCurve(pline)

        normal = rs.CurvePlane(pline).ZAxis

        segments = rs.ExplodeCurves(pline)
        if len(segments)<1:
            segments = [rs.CopyObject(pline)]
        for seg in segments:
            if rs.IsLine(seg):
                endPt = rs.CurveEndPoint(seg)
                stPt = rs.CurveStartPoint(seg)
                tanVec = rs.VectorCreate(stPt, endPt)
                offsetVec = rs.VectorRotate(tanVec, 90, normal)
                offsetVec = rs.VectorUnitize(offsetVec)
                offsetVec = rs.VectorScale(offsetVec, offsetDist)
                offsetPt = rs.VectorAdd(stPt, offsetVec)
                dim = rs.AddAlignedDimension(stPt, endPt, rs.coerce3dpoint(offsetPt), 'PCPA_12')
                rs.AddObjectToGroup(dim, dimGroup)
        rs.DeleteObjects(segments)
        result = True
    except:
        result = False
    return [dimGroup, result]
예제 #14
0
def AreaTag(obj, decPlaces):
    try:
        rhsrf = rs.coercesurface(obj)
        if rs.IsCurve(obj):
            if rs.IsCurvePlanar(obj) == False:
                return [0, False]
            if rs.IsCurveClosed(obj) == False:
                return [0, False]

        #get area
        if rs.UnitSystem() == 8:
            if rs.IsCurve(obj):
                area = rs.CurveArea(obj)[0]*0.0069444444444444
            else:
                area = rs.Area(obj)*0.0069444444444444
            areaText = utils.RoundNumber(area, decPlaces) + " SF"
        else:
            print "WARNING: Your units are not in inches"
            area = rs.CurveArea(obj)[0]
            areaText = area + ' ' + rs.UnitSystemName(False, True, True)

        #add annotation style
        dimStyle = sc.doc.DimStyles.FindName('PCPA_12')

        ###########################################################################
        #CURVES
        if rs.IsCurve(obj):
            if utils.IsRectangle(obj)[0]:
                #RECTANGLES
                srf = rs.AddPlanarSrf(obj)
                plane = HorizPlaneFromSurface(srf)
                rs.DeleteObject(srf)
            else:
                #OTHER CURVES
                srf = rs.AddPlanarSrf(obj)
                plane = HorizPlaneFromSurface(srf)
                rs.DeleteObject(srf)
        ###########################################################################
        #HATCHES
        elif rs.IsHatch(obj):
            rhobj = rs.coercegeometry(obj)
            boundaryCrvs = []
            crvs = rhobj.Get3dCurves(False)
            for crv in crvs:
                boundaryCrvs.append(crv)
            for crv in rhobj.Get3dCurves(True):
                boundaryCrvs.append(crv)
            srf = sc.doc.Objects.AddBrep(rc.Geometry.Brep.CreatePlanarBreps(boundaryCrvs)[0])
            plane = HorizPlaneFromSurface(srf)
            rs.DeleteObject(srf)
        ###########################################################################
        #SURFACES
        elif rs.IsSurface(obj):
            plane = HorizPlaneFromSurface(obj)

        ###########################################################################
        #OTHER/ERROR
        else:
            pts = rs.BoundingBox(obj)
            centerPoint = (pts[0] + pts[6]) / 2


        if dimStyle is not None:
            textHeight = dimStyle.TextHeight
            areaTag = rs.AddText(areaText, plane, height = textHeight, justification = 131074)
        else:
            areaTag = rs.AddText(areaText, plane, height = 1, justification = 131074)

        #Change layers
        hostLayer = layers.AddLayerByNumber(8103, False)
        rs.ObjectLayer(areaTag, layers.GetLayerNameByNumber(8103))
        return [area, True, areaTag]
    except:
        return [0, False]
예제 #15
0
#This script creates a point grid and prompts the user to reference a planar curve.
#the curve is copied from its center point to the new center points as defined by the grid.
#This will be in an XY plane at the Z height of the input curve's center Z
#A vector derived from the grid points to the attractor point describes the translation
#for another copy of the curve at a specified Z height
#the new curve pairs are lofted and capped to create a polysurface.

import rhinoscriptsyntax as rs

#ask the user for a curve to reference
myCrv = rs.GetObject("Please select reference curve", 4)
#make sure we have a planar curve
while rs.IsCurvePlanar(myCrv) == False:
    rs.MessageBox("Curve must be planar")
    myCrv = rs.GetObject("Please select reference curve", 4)

#get the bounding box and check the max length of the box sides, we use this to set default spacing
bBox = rs.BoundingBox(myCrv)
#bounding boxes are rectangular so we only need to compare one set of adjacent sides
spacing = max(rs.Distance(bBox[0], bBox[1]), rs.Distance(bBox[1], bBox[2]))

#get the center of the referenced curve
myCtr = rs.CurveAreaCentroid(myCrv)

#Command Line prompt the user for an x and y range for the loops
xRange= rs.GetInteger("Please select number of Curves in X", 10)
yRange= rs.GetInteger("Please select number of Curves in Y", 10)

#prompt user to overide grid spacing
spacing = rs.GetReal("Please enter spacing", spacing)
예제 #16
0
def hatchedCurve():
    """
    this script divides a curve by length and makes a hatch-dashed version of it'
    works only in world top
    version 1.1
    www.studiogijs.nl
    """

    projection = Rhino.Geometry.Vector3d(0, 0, 1)
    viewprojection = sc.doc.Views.ActiveView.ActiveViewport.CameraZ
    if not viewprojection == projection:
        print " this script only works in top view"
        return
    getcurves = rs.GetObjects(
        "select curves to change into hatch-dashed-style", 4, preselect=True)
    rs.UnselectAllObjects()
    if not getcurves:
        return

    s = sc.sticky['scale'] if sc.sticky.has_key('scale') else 1
    scale = rs.GetReal("line-width of the hatch-dashed curve", s, .5, 5)

    if not scale:
        return
    sc.sticky['scale'] = scale

    f = sc.sticky['factor'] if sc.sticky.has_key('factor') else 5
    factor = rs.GetReal("line-length factor of the hatch-dashed curve", f, 1,
                        10)

    if not factor:
        return
    sc.sticky['factor'] = factor

    #turn of the lights, magic should be done in darkness
    rs.EnableRedraw(False)

    style = Rhino.Geometry.CurveOffsetCornerStyle.Sharp
    tol = sc.doc.ModelAbsoluteTolerance
    plane = Rhino.Geometry.Plane.WorldXY

    subcurvelist = []
    offset_curves = []
    for curve in getcurves:
        # ------------------------------------------------------
        # offset curves inward and outward to create the borders
        # ------------------------------------------------------
        c = rs.coercecurve(curve)
        if not rs.IsCurvePlanar(curve):
            continue
        #else:
        #rs.HideObject(curve)

        offsets = c.Offset(plane, scale / 2, tol, style)
        if offsets:
            offset = sc.doc.Objects.Add(offsets[0])
            offset_curves.append(offset)
        offsets = c.Offset(plane, -scale / 2, tol, style)
        if offsets:
            offset = sc.doc.Objects.Add(offsets[0])
            offset_curves.append(offset)
        # -----------------------------------
        # explode c into segments if possible
        # -----------------------------------
        exploded = rs.ExplodeCurves(c)
        if exploded:
            for segment in exploded:
                subcurvelist.append(segment)
        else:
            #it appears this is for single lines only
            subcurvelist.append(rs.CopyObject(curve))

    segments = []
    # -------------------------------------------------------
    # divide subcurves into shorter segments (dashed pattern)
    # -------------------------------------------------------
    for curve in subcurvelist:
        closed = False
        if rs.coercecurve(curve).IsClosed:
            closed = True
        if rs.CurveLength(curve) > (scale * factor):
            segment_count = int(rs.CurveLength(curve) / (scale * factor / 2))
            while True:
                #we need to start with 1/2 segment, then full space, then half segment
                #so #of segments needs to be a multiple of 4
                if segment_count % 4 == 0: break
                else: segment_count += 1

            pts = rs.DivideCurve(curve, segment_count)

            if closed:
                pts = pts[
                    1:]  #remove only first point, since last point == first
            pts = pts[1:-1]  #remove first and last point

            pts = pts[::2]  #remove every other point
            # --------------
            # dash the curve
            # --------------
            for i, pt in enumerate(pts):
                t = rs.CurveClosestPoint(curve, pt)
                curves = rs.SplitCurve(curve, t)
                curve = curves[1]
                segment = curves[0]
                if closed:
                    #delete every odd segment
                    if i % 2 == 0:
                        rs.DeleteObject(segment)
                    else:
                        segments.append(segment)
                else:
                    #delete every even segment
                    if i % 2 == 1:
                        rs.DeleteObject(segment)
                    else:
                        segments.append(segment)

            #append the remaining part
            segments.append(curve)

    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

    if segments:
        segments = rs.JoinCurves(segments, True)
        layer = "hatched_curves"
        if not rs.IsLayer(layer):
            rs.AddLayer(layer)

        hatches = []
        #create the hatches
        for s in segments:
            rs.ObjectLayer(hatchthis(s), layer)
        for offset in offset_curves:
            rs.ObjectLayer(offset, layer)

    #clean up
    rs.DeleteObjects(segments)
    rs.HideObjects(getcurves)
    rs.DeleteObjects(curves)
    #put on the lights, it's the result that counts
    rs.EnableRedraw(True)
예제 #17
0
def Crv2ViewLoose():
    curve1 = rs.GetObject("select first curve", rs.filter.curve)
    if curve1 != None:
        rs.LockObject(curve1)
    curve2 = rs.GetObject("select second curve", rs.filter.curve)
    if curve1 == None or curve2 == None:
        return

    degree1 = rs.CurveDegree(curve1)
    degree2 = rs.CurveDegree(curve2)
    pts1 = rs.CurvePoints(curve1)
    pts2 = rs.CurvePoints(curve2)
    error = False
    errors = []
    if rs.IsPolyCurve(curve1) or rs.IsPolyCurve(curve2):
        errors.append("Error: This script only works for single open curves")
        error = True
    if not rs.IsCurvePlanar(curve1) or not rs.IsCurvePlanar(curve2):
        errors.append("Error: One or more of the input curves is not planar.")
        error = True
    if rs.IsCurvePeriodic(curve1) or rs.IsCurvePeriodic(curve2):
        errors.append("Error: This script only works with open curves")
        error = True
    if len(pts1) != len(pts2):
        errors.append(
            "Error: Input curves need to have same amount of control points")
        error = True
    if rs.CurveDegree(curve1) != rs.CurveDegree(curve2):
        errors.append("Error: Input curves need to be of same degree")
        error = True
    if error:
        for err in errors:
            print err
        rs.UnlockObject(curve1)
        return

    top = 0
    right = 0
    front = 0
    if rs.CurvePlane(curve1).ZAxis[2] != 0:  #top view curve
        top = 1

    if rs.CurvePlane(curve2).ZAxis[2] != 0:  #top view curve
        top = 2

    if rs.CurvePlane(curve1).ZAxis[0] != 0:  #right view curve
        right = 1

    if rs.CurvePlane(curve2).ZAxis[0] != 0:  #right view curve
        right = 2

    if rs.CurvePlane(curve1).ZAxis[1] != 0:  #front view curve
        front = 1

    if rs.CurvePlane(curve2).ZAxis[1] != 0:  #front view curve
        front = 2

    pts3 = []  #array to store the points for the new curve
    if top == 1 and right == 2:
        for i in range(0, len(pts1)):
            pts1[i][2] = pts2[i][2]
            pts1[i][1] = (pts1[i][1] + pts2[i][1]
                          ) / 2  #average out y-coordinate of each point
            pts3.append(pts1[i])
    if top == 2 and right == 1:
        for i in range(0, len(pts1)):
            pts2[i][2] = pts1[i][2]
            pts2[i][1] = (pts1[i][1] + pts2[i][1]
                          ) / 2  #average out y-coordinate of each point
            pts3.append(pts2[i])
    if top == 1 and front == 2:
        for i in range(0, len(pts1)):
            pts1[i][2] = pts2[i][2]
            pts1[i][0] = (pts1[i][0] + pts2[i][0]
                          ) / 2  #average out x-coordinate of each point
            pts3.append(pts1[i])
    if top == 2 and front == 1:
        for i in range(0, len(pts1)):
            pts2[i][2] = pts1[i][2]
            pts2[i][0] = (pts1[i][0] + pts2[i][0]
                          ) / 2  #average out x-coordinate of each point
            pts3.append(pts2[i])
    rs.UnlockObject(curve1)

    if (right == 0 and front == 0) or (top == 0
                                       and right == 0) or (top == 0
                                                           and front == 0):
        print "Error: Curves need to be placed on orthogonal views"
        return
    else:

        rs.AddCurve(pts3, degree1)
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
#Generate grid of points
base_points = []
for i in range(0,count_x):
    i += i
    for j in range (0, count_y):
        j += j
        x = distance_x * i
        y = distance_y * j
        p = rs.AddPoint(x, y, 0)
        base_points.append(p)
 

# Cull points outside curve
culled_pts = []
  
if rs.IsCurveClosed(boundary_curve) and rs.IsCurvePlanar(boundary_curve): # Checking curve is ok
    for i in base_points:
        if i:
            result = rs.PointInPlanarClosedCurve(i, boundary_curve)
            if result==0:
                pass
                #print ('The point is outside of the closed curve.')
            elif result==1:
                #print('The point is inside of the closed curve.')
                culled_pts.append(i)
                
else:
    ghenv.Component.AddRuntimeMessage(e, 'The curve must be planar and closed')


예제 #20
0
def OffsetCrvLoose():

    crv = rs.GetObject("select curve to offset loosely", rs.filter.curve, True)
    if crv == None:
        return
    if not rs.IsCurvePlanar(crv):
        print "Sorry, but that curve is not planar."
        return
    if rs.IsPolyCurve(crv):
        print "This simple script works only for single open or closed curves"
        return
    offset = rs.GetReal("offset amount", 5)

    if offset == None or offset == 0:
        return
    both_sides = rs.GetBoolean("Offset both sides?",
                               ["both_sides", "off", "on"], False)[0]
    bPeriodic = False
    #rs.EnableRedraw(False)
    pts = rs.CurvePoints(crv)
    degree = rs.CurveDegree(crv)
    if rs.IsCurvePeriodic(crv):
        pts = rs.CullDuplicatePoints(pts, 0.01)
        bPeriodic = True
    offset_pts = []
    offset_pts2 = []  #if both_sides=true
    plane = rs.CurvePlane(crv)
    axis = plane.ZAxis
    for pt in pts:
        cp = rs.CurveClosestPoint(crv, pt)
        v = rs.CurveTangent(crv, cp)
        v = rs.VectorUnitize(v)
        v *= offset
        v = rs.VectorRotate(v, 90, axis)
        pt_ = rs.AddPoint(pt)
        #create points for offset on one side of the curve
        movedpt = rs.MoveObject(pt_, v)
        newpt = rs.coerce3dpoint(movedpt)
        offset_pts.append(newpt)
        #create points for offset on other side of the curve
        movedpt = rs.MoveObject(pt_, -2 * v)
        newpt = rs.coerce3dpoint(movedpt)
        offset_pts2.append(newpt)
        rs.DeleteObject(pt_)
    nc = Rhino.Geometry.NurbsCurve.Create(bPeriodic, degree, offset_pts)
    nc2 = Rhino.Geometry.NurbsCurve.Create(bPeriodic, degree, offset_pts2)

    if not both_sides:
        if nc.GetLength(0.1) > nc2.GetLength(0.1):  #get the longest curve...
            if offset > 0:  #...and add it to the document for positive offsets...
                sc.doc.Objects.AddCurve(nc)
            else:  #...or the shortest for negative offsets.
                sc.doc.Objects.AddCurve(nc2)
        else:
            if offset > 0:
                sc.doc.Objects.AddCurve(nc2)
            else:
                sc.doc.Objects.AddCurve(nc)
    else:  #add both curves to the document
        sc.doc.Objects.AddCurve(nc)
        sc.doc.Objects.AddCurve(nc2)

    rs.EnableRedraw(True)
    sc.doc.Views.Redraw()
def SampleExportCurvesAsJSON():

    # Select curves to export
    ids = rs.GetObjects('Select curves to export', 4, True, True)
    if not ids: return

    # Name of filename to creat
    fname = rs.SaveFileName('Save', 'JSON File (*.json)|*.json||')
    if not fname: return

    # The json data (dictionary)
    data = {}

    # The version of this data format
    data['version'] = 1.0

    # The Rhino version
    data['rhino'] = rs.ExeVersion()

    # The date
    data['date'] = time.strftime('%d/%m/%Y')

    # The number of curve records
    data['curve_count'] = len(ids)

    # The curve records (list)
    data['curves'] = []

    for id in ids:

        # Create a curve record (dictionary)
        rec = {}

        # The id
        rec['id'] = id.ToString()

        # The dimension
        rec['dim'] = rs.CurveDim(id)

        # Is rational
        rec['rational'] = rs.IsCurveRational(id)

        # The degree
        rec['degree'] = rs.CurveDegree(id)

        # The control point count
        rec['cv_count'] = rs.CurvePointCount(id)

        # The control points
        rec['cvs'] = []
        pts = rs.CurvePoints(id)
        wht = rs.CurveWeights(id)
        for i in range(len(pts)):
            pt = pts[i]
            rec['cvs'].append([pt[0], pt[1], pt[2], wht[i]])

        # The knot count
        rec['knot_count'] = rs.CurveKnotCount(id)

        # The knots
        rec['knots'] = []
        knots = rs.CurveKnots(id)
        for i in range(len(knots)):
            rec['knots'].append(knots[i])

        # Some other (unnecessary) properties
        rec['closed'] = rs.IsCurveClosed(id)
        rec['periodic'] = rs.IsCurvePeriodic(id)
        rec['planar'] = rs.IsCurvePlanar(id)

        # Append the curve record
        data['curves'].append(rec)

    # Write the json data
    with open('c:/users/dale/desktop/data.json', 'w') as outfile:
        json.dump(data, outfile)
def plcrv_filt(rhino_object, geometry, component_index):
    return rs.IsCurvePlanar(geometry)