Exemple #1
0
def main():
    counts = [0, 0, 0]
    spacings = [10, 10, 10]
    rotations = [0, 0, 0]

    counts[0] = rs.GetInteger("number in x direction", minimum=1)
    # counts[1] = rs.GetInteger("number in y direction", minimum=1)
    # counts[2] = rs.GetInteger("number in z direction", minimum=1)

    spacings[0] = rs.GetReal("x spacing")
    # spacings[1] = rs.GetReal("y spacing")
    # spacings[2] = rs.GetReal("z spacing")

    rotations[0] = rs.GetReal("rotation of each object along x axis")
    # rotations[1] = rs.GetReal("y spacing")
    # rotations[2] = rs.GetReal("z spacing")

    print "count", counts
    print "spacing", spacings
    print "rotation", rotations

    for ix in range(counts[0]):
        newobj = rs.CopyObject(obj, [spacings[0] * ix, 0, 0])
        bbox = rs.BoundingBox(newobj)
        if bbox:
            centroid = rs.PointSubtract(bbox[0], bbox[6])
            print bbox[6], bbox[0]
            print centroid
            rs.AddPoint(centroid)
        else:
            print "no bbox"
def DrawParametricCurve(parametric_equation):
    "Create a interpolated curve based on a parametric equation."
    # Get the minimum parameter
    t0 = rs.GetReal("Minimum t value", 0.0)
    if( t0==None ): return
    
    # Get the maximum parameter
    t1 = rs.GetReal("Maximum t value", 1.0)
    if( t1==None ): return

    # Get the number of sampling points to interpolate through
    count = rs.GetInteger("Number of points", 50, 2)
    if count<1: return

    arrPoints = list()
    #Get the first point
    point = parametric_equation(t0)
    arrPoints.append(point)

    #Get the rest of the points
    for x in xrange(1,count-2):
        t = (1.0-(x/count))*t0 + (x/count)*t1
        point = parametric_equation(t)
        arrPoints.append(point)
  
    #Get the last point
    point = parametric_equation(t1)
    arrPoints.append(point)
    
    #Add the curve
    rs.AddInterpCurve(arrPoints)
def meshfunction_xy():
    zfunc, domain, resolution = loadfunctiondata()
    zfunc = rs.StringBox( zfunc, "Specify a function f(x,y[,D,A])", "Mesh function")
    if not zfunc: return

    while True:
        prompt = "Function domain x{%f,%f} y{%f,%f} @%d" % (domain[0], domain[1], domain[2], domain[3], resolution)
        result = rs.GetString(prompt, "Insert", ("xMin","xMax","yMin","yMax","Resolution","Insert"))
        if not result: return
        result = result.upper()
        if result=="XMIN":
            f = rs.GetReal("X-Domain start", domain[0])
            if f is not None: domain[0]=f
        elif result=="XMAX":
            f = rs.GetReal("X-Domain end", domain[1])
            if f is not None: domain[1]=f
        elif result=="YMIN":
            f = rs.GetReal("Y-Domain start", domain[2])
            if f is not None: domain[2]=f
        elif result=="YMAX":
            f = rs.GetReal("Y-Domain end", domain[3])
            if f is not None: domain[3]=f
        elif result=="RESOLUTION":
            f = rs.GetInteger("Resolution of the graph", resolution)
            if f is not None: resolution=f
        elif result=="INSERT": break

    verts = createmeshvertices(zfunc, domain, resolution)
    faces = createmeshfaces(resolution)
    rs.AddMesh(verts, faces)
Exemple #4
0
def DistributeCirclesOnSphere():
    sphere_radius = rs.GetReal("Radius of sphere", 10.0, 0.01)
    if not sphere_radius: return

    circle_radius = rs.GetReal("Radius of packing circles",
                               0.05 * sphere_radius, 0.001,
                               0.5 * sphere_radius)
    if not circle_radius: return

    vertical_count = int((math.pi * sphere_radius) / (2 * circle_radius))

    rs.EnableRedraw(False)
    phi = -0.5 * math.pi
    phi_step = math.pi / vertical_count
    while phi < 0.5 * math.pi:
        horizontal_count = int((2 * math.pi * math.cos(phi) * sphere_radius) /
                               (2 * circle_radius))
        if horizontal_count == 0: horizontal_count = 1
        theta = 0
        theta_step = 2 * math.pi / horizontal_count
        while theta < 2 * math.pi - 1e-8:
            circle_center = (sphere_radius * math.cos(theta) * math.cos(phi),
                             sphere_radius * math.sin(theta) * math.cos(phi),
                             sphere_radius * math.sin(phi))
            circle_normal = rs.PointSubtract(circle_center, (0, 0, 0))
            circle_plane = rs.PlaneFromNormal(circle_center, circle_normal)
            rs.AddCircle(circle_plane, circle_radius)
            theta += theta_step
        phi += phi_step
    rs.EnableRedraw(True)
Exemple #5
0
def RunCommand(is_interactive):
    """Interactive Rhino Command Creates 90 Lap joint on a seleceted Beam 

    Return:
    ------
    None
    """
    #load Derivation and model
    derivation = Derivation.from_json(rhino_UI_utilities.get_json_file_location())
    model = derivation.get_next_step()

    #Select mesh 
    Obj_ref = rs.GetObject(message = "select mesh(es)", filter = 32, preselect = False, subobjects = True)
    selected_beam_name = (rs.ObjectName(Obj_ref)[:-5])

    #Loop through all beams in model to identify the selected beam
    selected_beam = None
    for beam in model.beams:
        if(beam.name == selected_beam_name):
            selected_beam = beam
            break
    assert (selected_beam != None)

    #list of user inputs(face needs to be implemented through UI)
    face_id = rs.GetInteger("face_id",None,0,5)
    helper = UI_helpers()
    joint_point = helper.Get_SelectPointOnMeshEdge("Select mesh edge","Pick point on edge")

    ext_start = rs.GetReal("extension start ",200,None,None)
    ext_end = rs.GetReal("extension end ",200,None,None)
    name = create_id() 
    
    #adding joints to selected Beam 
    #joint_distance_from_start = Get_distancefromBeamYZFrame(selected_beam,joint_point)
    joint_distance_from_start = selected_beam.Get_distancefromBeamYZFrame(joint_point)
    match_beam_origin =  model.rule_90lap(selected_beam,joint_distance_from_start,face_id,ext_start,ext_end,name) 
     


    #Save Derivation (Model is also saved)
    derivation.to_json(rhino_UI_utilities.get_json_file_location(), pretty = True)

    #Visualization
    viz_point = []
    for pt in match_beam_origin:
        a = (pt[0],pt[1],pt[2])
        viz_point.append({
            'pos': a,
            'color': (0,255,0)
        })


    #Visualization 
    artist = MeshArtist(None, layer ='BEAM::Beams_out')
    artist.clear_layer()
    artist.draw_points(viz_point)
    for beam in model.beams:
        artist = MeshArtist(beam.mesh, layer ='BEAM::Beams_out')#.mesh is not ideal fix in beam and assemble class
        artist.draw_faces(join_faces=True)
Exemple #6
0
def Main():
    crvs = rs.GetObjects("please select curves", rs.filter.curve)
    paths = rs.GetObjects("please select depression paths", rs.filter.curve)
    startPt = rs.GetObject("please select entry point", rs.filter.point)
    radius = rs.GetReal("please enter path radius", .1)
    power = rs.GetReal("please enter standard dev", .5)
    crvs = depressCrvs(crvs, paths, startPt, radius, power)
    return crvs
Exemple #7
0
def RunCommand(is_interactive):
    global params

    center = rs.GetPoint(message="Select center point")

    n = rs.GetInteger(message="Number of teeth", number=params["n"], minimum=4)

    r = rs.GetReal(message="Outside Diameter", number=params["r"])

    m = rs.GetReal(message="Gear module", number=params["m"])

    pa = rs.GetReal(message="Pressure angle",
                    number=params["pa"],
                    minimum=0,
                    maximum=45)

    bool_opts = rs.GetBoolean(message="Output options",
                              items=(("PitchCircle", "No", "Yes"), ),
                              defaults=(params["pc"], ))

    if None in [center, n, m, pa, bool_opts]:
        return 1  # Cancel

    pc = bool_opts[0]

    params["n"] = n
    params["m"] = m
    params["r"] = r
    params["pa"] = pa
    params["pc"] = pc

    cplane = rs.ViewCPlane()  # Get current CPlane
    cplane = rs.MovePlane(cplane, center)
    xform = rs.XformChangeBasis(cplane, rs.WorldXYPlane())

    rs.EnableRedraw(False)
    old_plane = rs.ViewCPlane(plane=rs.WorldXYPlane())

    gear = generate_gear_crv_with_outside(teeth=params["n"],
                                          module=params["m"],
                                          outside_diam=params["r"],
                                          pressure_angle=params["pa"])

    rs.ViewCPlane(plane=old_plane)
    rs.TransformObjects(gear, xform)

    rs.EnableRedraw(True)

    if pc:
        circle = generate_pitch_circle_crv(teeth=params["n"],
                                           module=params["m"])
        rs.TransformObjects(circle, xform)
        rs.SelectObjects([gear, circle])
    else:
        rs.SelectObjects(gear)

    return 0  # Success
Exemple #8
0
def Main():
    crvs = rs.GetObjects("please select srf curves", rs.filter.curve)
    paths = rs.GetObjects("please select depression paths", rs.filter.curve)
    startPt = rs.GetObject("please select entry point", rs.filter.point)
    radius = rs.GetReal("please enter path radius", 2)
    sd = rs.GetReal("please enter standard dev", .25)
    srf = rs.GetObject("please enter surface", rs.filter.surface)
    crvs = depressCrvs(srf, crvs, paths, startPt, radius, sd)
    return crvs
def testDuplications():
    print("\n testDuplications commands \n")

    obj_ids = rs.GetObjects(
        "Select object(s) from which to create the rectangular matrix", 0,
        True, True)
    if obj_ids is None: return

    box = rs.BoundingBox(obj_ids)
    if not isinstance(box, list): return
    origin = rs.PointDivide(rs.PointAdd(box[0], box[6]), 2)

    nXdups = rs.GetInteger("Duplications X", 1, 1)
    rXdups = rs.GetReal("Duplications X rand", 0, 0, 100) / 100

    nYdups = rs.GetInteger("Duplications Y", 1, 1)
    rYdups = rs.GetReal("Duplications Y rand", 0, 0, 100) / 100

    nZdups = rs.GetInteger("Duplications Z", 1, 1)
    rZdups = rs.GetReal("Duplications Z rand", 0, 0, 100) / 100

    rKeep = 1 - rs.GetReal("Percent to erase", 0, 0, 100) / 100

    endpt = rs.GetPoint("To point")

    calc_val_real = lambda val, rand: val + random.uniform(
        -rand * val, rand * val)
    calc_val_int = lambda val, rand: val + int(
        round(random.uniform(-rand * val, rand * val)))

    xspace = 3
    yspace = 3
    zspace = 3

    xdups = calc_val_int(nXdups, rXdups)
    ydups = calc_val_int(nYdups, rYdups)
    zdups = calc_val_int(nZdups, rZdups)

    translations = []
    # Copy Points with Spacing
    for k in range(zdups):
        for j in range(ydups):
            for i in range(xdups):
                newpt = [
                    origin[0] + i * xspace, origin[1] + j * yspace,
                    origin[2] + k * zspace
                ]
                translations = translations + [rs.VectorCreate(endpt, newpt)]

    nObjs = len(translations)
    print(nObjs)
    objs_to_keep = random.sample(range(nObjs), int(round(nObjs * rKeep)))
    translations = [translations[i] for i in objs_to_keep]

    copied_objs = []
    for tr in translations:
        copied_objs = copied_objs + rs.CopyObjects(obj_ids, tr)
Exemple #10
0
def set_target_areas(area_dict):

    go = Rhino.Input.Custom.GetOption()
    go.SetCommandPrompt("Enter target areas")

    # face key -----------------------------------------------------------------
    sortedkeys = sorted(area_dict.keys())
    key_strings = [str("key_" + str(key)) for key in sortedkeys]
    fkey_index = 0
    key_list = go.AddOptionList("pick_face", ["All"] + key_strings, fkey_index)

    # assign new target areas --------------------------------------------------
    new_area_dict = deepcopy(area_dict)

    while True:

        opt = go.Get()

        if go.CommandResult() != Rhino.Commands.Result.Success:
            break

        elif opt == Rhino.Input.GetResult.Option:  # keep picking options
            if go.OptionIndex() == key_list:
                fkey_index = int(go.Option().CurrentListOptionIndex)

                if fkey_index == 0:
                    avg = sum(area_dict.values()) / len(area_dict)

                    target_area = rs.GetReal("Enter target area for ALL faces",
                                             avg, 0, 1000.0)
                    if target_area:
                        for key in new_area_dict:
                            new_area_dict[key] = target_area

                else:
                    fkey_key = sortedkeys[fkey_index - 1]
                    current_area = area_dict[fkey_key]
                    target_area = rs.GetReal("Enter target area value",
                                             current_area, 0, 1000.0)
                    if target_area:
                        new_area_dict[fkey_key] = target_area

            # print current targets --------------------------------------------
            print(
                '-----------------------------------------------------------')
            for fkey in new_area_dict:
                print("face", fkey, "has target area of :",
                      new_area_dict[fkey])
            print(
                '-----------------------------------------------------------')

            continue

        break

    return new_area_dict
Exemple #11
0
def RunCommand(is_interactive):
    global params

    pitch_line = rs.GetObject(message="Select pitch line",
                              filter=rs.filter.curve,
                              preselect=True)
    if pitch_line is None:
        return 1  # Cancel

    if not rs.IsLine(pitch_line):
        print "Selected curve is not a line!"
        return 1  # Cancel

    rs.SelectObjects(pitch_line)

    m = rs.GetReal(message="Rack module", number=params["m"])
    pa = rs.GetReal(message="Pressure angle",
                    number=params["pa"],
                    minimum=0,
                    maximum=45)

    if m is None or pa is None:
        return 1  # Cancel

    params["m"] = m
    params["pa"] = pa

    pitch_line_center = rs.CurveMidPoint(pitch_line)
    pitch_line_start = rs.CurveStartPoint(pitch_line)
    pitch_line_end = rs.CurveEndPoint(pitch_line)
    angle, reflex_angle = rs.Angle2(line1=((0, 0, 0), (1, 0, 0)),
                                    line2=(pitch_line_start, pitch_line_end))

    x_vector = rs.VectorCreate(pitch_line_end, pitch_line_start)
    y_vector = rs.VectorRotate(x_vector, 90.0, [0, 0, 1])
    cplane = rs.PlaneFromFrame(origin=pitch_line_center,
                               x_axis=x_vector,
                               y_axis=y_vector)

    xform = rs.XformChangeBasis(cplane, rs.WorldXYPlane())

    rs.EnableRedraw(False)
    old_plane = rs.ViewCPlane(plane=rs.WorldXYPlane())

    rack = draw_rack(length=rs.CurveLength(pitch_line),
                     module=params["m"],
                     pressure_angle=params["pa"])

    rs.ViewCPlane(plane=old_plane)
    rs.TransformObjects(rack, xform)

    rs.EnableRedraw(True)
    rs.UnselectAllObjects()
    rs.SelectObjects(rack)

    return 0  # Success
Exemple #12
0
def MakeStair_Button():
    tol = rs.UnitAbsoluteTolerance()
    objs = rs.GetObjects("Select guide path")
    if objs is None: return

    height = rs.GetReal("Stair Height", number=120)
    if height is None: return

    width = rs.GetReal("Stair Width", number=30)
    if width is None: return

    for obj in objs:
        MakeStair(obj, width, height)
Exemple #13
0
def Main():
    mesh = rs.GetObject("please select mesh", rs.filter.mesh)
    src = rs.GetObject("please select path", rs.filter.curve)
    ang = rs.GetReal("please enter angle", 20)
    length = rs.GetReal("please enter length", 8)
    gen = rs.GetInteger("please enter number of generations", 4)
    end = rs.CurveEndPoint(src)
    start = rs.CurveStartPoint(src)
    vec = rs.VectorCreate(end, start)
    vec = rs.VectorUnitize(vec)
    vec = vec * length
    tree = vine(mesh, start, vec, ang)
    for i in range(gen):
        tree.grow()
Exemple #14
0
def main():
    path = rs.GetObject("Select Ramp Path", rs.filter.curve, True)
    if path is None: return

    if 'ramp-widthDefault' in sc.sticky:
        widthDefault = sc.sticky['ramp-widthDefault']
    else:
        widthDefault = 36
    if 'ramp-slopeDefault' in sc.sticky:
        slopeDefault = sc.sticky['ramp-slopeDefault']
    else:
        slopeDefault = 8.333

    width = rs.GetReal("Ramp Clear Width", widthDefault, minimum=36)
    if width is None: return
    slope = rs.GetReal("Ramp slope (e.g. 8.33%(1:12) is 8.33)", slopeDefault)
    if slope is None: return

    sc.sticky['ramp-widthDefault'] = width
    sc.sticky['ramp-slopeDefault'] = slope

    rs.EnableRedraw(False)
    rampGeoList = Ramp_HeightSlope(path, width, slope / 100)
    try:
        layers.AddLayerByNumber(402, False)
        layerName = layers.GetLayerNameByNumber(402)

        rs.ObjectLayer(rampGeoList[0], layerName)
        try:
            if rampGeoList[2] is not None:
                layers.AddLayerByNumber(106, False)
                layerName = layers.GetLayerNameByNumber(106)

                rs.ObjectLayer(rampGeoList[2], layerName)
        except:
            pass
        result = True
    except:
        result = False

    utils.SaveFunctionData('Architecture-ramp', [
        width, slope,
        str([(pt.X, pt.Y, pt.Z) for pt in rs.CurveEditPoints(path)]), result
    ])

    rs.EnableRedraw(True)

    print rampGeoList[1]

    utils.SaveToAnalytics('architecture-ramp')
def main():

    cyls = []
    radius = 0

    gname = "Enclosure"

    extantGroups = rs.GroupNames()
    print "groups: ", extantGroups
    enclosures = [s for s in extantGroups if "Enclosure" in s]
    print "enclosures: ", enclosures

    if rs.IsGroup("Enclosure"):
        num = len(enclosures)
        gname += "_" + ` num `
    encGroup = rs.AddGroup(gname)
    print "group: ", encGroup

    focus = rs.GetPoint("center of fence")
    if (focus is None): return
    rpt = rs.GetPoint("enclosure radius", focus)
    if (rpt is None): return
    else:
        radius = (rpt - focus).Length
        rs.AddObjectsToGroup(rs.AddCircle(focus, radius), encGroup)

    count = rs.GetInteger("number of cylinders")
    if (count is None): return
    cyldiam = rs.GetReal("cylinder diameter")
    if (cyldiam is None): return
    minheight = rs.GetReal("minimum height")
    if (minheight is None): return
    maxheight = rs.GetReal("maximum height")
    if (maxheight is None): return
    #   arcjitter = rs.GetReal("amount of arc jitter")
    #   if (arcjitter is None): return
    #   radialjitter = rs.GetReal("amount of radial jitter")
    #   if (radialjitter is None): return

    for i in range(count):
        cyl = rs.AddCylinder(rpt, random.uniform(minheight, maxheight),
                             cyldiam / 2, True)
        rs.RotateObject(cyl, focus, (360 / count) * (i + 1))
        cyls.append(cyl)
    if cyls: rs.AddObjectsToGroup(cyls, encGroup)
    print "Enclosure built:"
    print "focus: (", focus, ")"
    print "radius:", radius
    print "cylinders:", count, "ranging from", minheight, "to", maxheight, "units in length."
def Main():
    try:
        data_name = "Rect2DogBone"
        curves = rs.GetObjects("Rectangle curve", rs.filter.curve, True, True)
        diam = rs.GetInteger(
            "DogBone circle diameter",
            16 if not rs.GetDocumentData(data_name, "diam_external") else
            float(rs.GetDocumentData(data_name, "diam_external")))
        diam_barrenos = rs.GetInteger(
            "Circle at centroid (0=None -1=Point n=Diameter)",
            0 if not rs.GetDocumentData(data_name, "diam_barrenos") else float(
                rs.GetDocumentData(data_name, "diam_barrenos")))
        tol = float(
            rs.GetReal(
                "External offset",
                0 if not rs.GetDocumentData(data_name, "tolerance") else float(
                    rs.GetDocumentData(data_name, "tolerance"))))
        if curves and diam:
            rs.EnableRedraw(False)
            dogbone(curves, diam, diam_barrenos, tol)
            rs.SetDocumentData(data_name, "diam_external", str(diam))
            rs.SetDocumentData(data_name, "diam_barrenos", str(diam_barrenos))
            rs.SetDocumentData(data_name, "tolerance", str(tol))
            rs.EnableRedraw(True)
        print("%s DogBones created" % len(curves))

    except Exception as e:
        print("Error: %s" % e)
Exemple #17
0
def duplicateAndRotate():
    obj_ids = rs.GetObjects("Select object(s) to duplicate and rotate", 0,
                            True, True)
    if obj_ids is None: return

    box = rs.BoundingBox(obj_ids)
    if not isinstance(box, list): return
    origin = rs.PointDivide(rs.PointAdd(box[0], box[6]), 2)

    endpt = rs.GetPoint("To point")
    ndups = rs.GetInteger("Number of duplications")
    maxd = rs.GetReal("Max Distance")

    translation = rs.VectorCreate(endpt, origin)
    for i in range(0, ndups, 1):
        xr = random() if random() < 0.5 else -1 * random()
        yr = random() if random() < 0.5 else -1 * random()
        zr = random() if random() < 0.5 else -1 * random()
        newpt = [xr * maxd, yr * maxd, zr * maxd]
        translation1 = rs.VectorCreate(endpt, newpt)
        translation2 = rs.VectorCreate(translation1, origin)
        copied_obj_ids = rs.CopyObjects(obj_ids, translation2)
        xyp = rs.WorldXYPlane()
        rs.RotateObjects(copied_obj_ids, newpt, random() * 360, xyp[0])
        rs.RotateObjects(copied_obj_ids, newpt, random() * 360, xyp[1])
        rs.RotateObjects(copied_obj_ids, newpt, random() * 360, xyp[2])
Exemple #18
0
def createSphere():
    sphereRadius = rs.GetReal(message='Of what radius? ', minimum=0.1)
    x, y, z = [float(n) for n in raw_input('where?: "x y z"').split()]
    id = rs.AddSphere((x, y, z), sphereRadius)
    spheres.append(id)
    rs.SetUserText(id, key="Sphere", value=str(len(spheres)))
    print('Done.')
def ChamferButton():
    objs = rs.GetObjects("Select curves to chamfer", preselect=True)
    if objs is None: return

    dist1 = rs.GetReal('Distance 1', 30)
    if dist1 is None: return
    dist2 = rs.GetReal('Distance 2', 60)
    if dist2 is None: return

    finalCurves = []
    for obj in objs:
        rhobj = rs.coercecurve(obj)
        finalCurves.append(ChamferCurve(rhobj, dist1, dist2))
        rs.DeleteObject(obj)

    return finalCurves
Exemple #20
0
def RunCommand(is_interactive):

    #load Derivation and model
    derivation = Derivation.from_json(
        rhino_UI_utilities.get_json_file_location())
    model = derivation.get_next_step()

    #user input
    rc, corners = Rhino.Input.RhinoGet.GetRectangle()
    if rc != Rhino.Commands.Result.Success:
        return rc
    plane = Rhino.Geometry.Plane(corners[0], corners[1], corners[2])
    beam_frame = Frame(plane[0], plane[1], plane[2])
    length = rs.GetReal("length", 4000, 300, None)

    #Generate unique name for the Beam
    name = create_id()

    #Create Beam
    model.rule_create_beam(beam_frame, length, 100, 100, name)

    #Save Derivation (Model is also saved)
    derivation.to_json(rhino_UI_utilities.get_json_file_location(),
                       pretty=True)

    #Visualization
    artist = MeshArtist(None, layer='BEAM::Beams_out')
    artist.clear_layer()
    for beam in model.beams:
        artist = MeshArtist(
            beam.mesh, layer='BEAM::Beams_out'
        )  #.mesh is not ideal fix in beam and assemble class
        artist.draw_faces(join_faces=True)
    return 0
def blendcorners():
    polyline_id = rs.GetObject("Polyline to blend", 4, True, True)
    if not polyline_id: return

    vertices = rs.PolylineVertices(polyline_id)
    if not vertices: return

    radius = rs.GetReal("Blend radius", 1.0, 0.0)
    if radius is None: return

    between = lambda a, b: (a + b) / 2.0
    newverts = []
    for i in range(len(vertices) - 1):
        a = vertices[i]
        b = vertices[i + 1]
        segmentlength = rs.Distance(a, b)
        vec_segment = rs.PointSubtract(b, a)
        vec_segment = rs.VectorUnitize(vec_segment)

        if radius < (0.5 * segmentlength):
            vec_segment = rs.VectorScale(vec_segment, radius)
        else:
            vec_segment = rs.VectorScale(vec_segment, 0.5 * segmentlength)

        w1 = rs.PointAdd(a, vec_segment)
        w2 = rs.PointSubtract(b, vec_segment)
        newverts.append(a)
        newverts.append(between(a, w1))
        newverts.append(w1)
        newverts.append(between(w1, w2))
        newverts.append(w2)
        newverts.append(between(w2, b))
    newverts.append(vertices[len(vertices) - 1])
    rs.AddCurve(newverts, 5)
    rs.DeleteObject(polyline_id)
Exemple #22
0
def main():
    heightRel2FFL = rs.GetReal("Cut level (relative to FFL):", number=1)
    levelsElev = setLevels.getFloorLevels()
    rs.EnableRedraw(False)
    deleteExistingPlans()
    heights = []

    for leveli in levelsElev:
        heights.append(leveli + heightRel2FFL)
    layers = rs.GetLayers()
    if layers is None:
        return
    layersToCut = []
    for layer in layers:
        if rs.LayerVisible(layer):
            layersToCut.append(layer)
    for i in range(0, len(heights)):
        for layer in layersToCut:
            rs.CurrentLayer(layer)
            if i < 9:
                levelNum = "0" + str(i + 1)
            else:
                levelNum = str(i + 1)
            cutAtPlan(heights[i], levelNum)
    rs.EnableRedraw(True)
    return None
def innerPanel():
    objs = rs.GetObjects("Select objects to add frame to", filter = 24, group = True,preselect = True)
    if objs is None:
        return
    dist = rs.GetReal("Offset Distance")
    if dist is None:
        return
    rs.EnableRedraw(False)
    
    srfs = []
    
    for obj in objs:
        if rs.IsPolysurface(obj):
            srfs = srfs + rs.ExplodePolysurfaces(obj)
        else:
            srfs.append(rs.CopyObject(obj))
    
    for srf in srfs:
        if rs.IsSurfacePlanar(srf):
            edgeCrvs = rs.DuplicateEdgeCurves(srf)
            border = rs.JoinCurves(edgeCrvs, True)
            innerEdge = rs.OffsetCurveOnSurface(border, srf, dist)
            #rs.SplitBrep(srf, innerEdge)
            rs.AddPlanarSrf(innerEdge)
            rs.DeleteObject(innerEdge)
            rs.DeleteObject(border)
        else:
            print "A surface was not planar"
    rs.DeleteObjects(srfs)
    rs.EnableRedraw(True)
Exemple #24
0
def createcurvaturegraph():
    curve_ids = rs.GetObjects("Curves for curvature graph", 4, False, True,
                              True)
    if not curve_ids: return

    samples = 10
    scale = 1.0

    preview = []
    while True:
        rs.EnableRedraw(False)
        for p in preview:
            rs.DeleteObjects(p)
        preview = []
        for id in curve_ids:
            cg = addcurvaturegraph(id, samples, scale)
            preview.append(cg)
        rs.EnableRedraw(True)

        result = rs.GetString("Curvature settings", "Accept",
                              ("Samples", "Scale", "Accept"))
        if not result:
            for p in preview:
                rs.DeleteObjects(p)
            break
        result = result.upper()
        if result == "ACCEPT": break
        elif result == "SAMPLES":
            numsamples = rs.GetInteger("Number of samples per knot-span",
                                       samples, 3, 100)
            if numsamples: samples = numsamples
        elif result == "SCALE":
            sc = rs.GetReal("Scale of the graph", scale, 0.01, 1000.0)
            if sc: scale = sc
Exemple #25
0
def divide_curve():
    # get user input
    res, obj_refs = RhinoGet.GetMultipleObjects("Curves to divide",
        False, ObjectType.EdgeFilter | ObjectType.Curve)
    if res <> Result.Success: return res
    curves = [obj_ref.Curve() for obj_ref in obj_refs]

    distance_between_divisions = rs.GetReal(
      message = "Distance between divisions",
      number = 5.0, minimum = 1.0)
    if distance_between_divisions == None: return

    # generate the points
    points = []
    for curve in curves:
      t0 = curve.Domain.Min
      points.append(curve.PointAt(t0))

      sphere_center = curve.PointAt(t0)
      t = t0
      rest_of_curve = curve
      while True:
        sphere = Sphere(sphere_center, distance_between_divisions)
        b, overlapCurves, intersectPoints = Intersection.CurveBrep(
                               rest_of_curve, sphere.ToBrep(), 0.0)
        if b == False or (overlapCurves.Length == 0 and intersectPoints.Length == 0):
          break
        t, point = nextIntersectParamAndPoint(
          overlapCurves, intersectPoints, rest_of_curve)
        points.append(point)
        sphere_center = point
        rest_of_curve = curve.Split(t)[1]

    rs.AddPoints(points)
    rs.Redraw()
def OffsetMulticrvs2SidesWEnds():
    #user input section
    msg = "Select planar curve(s) to offset both sides"
    crvs = rs.GetObjects(msg, 4, preselect=True, custom_filter=plcrv_filt)
    if not crvs: return

    tol = sc.doc.ModelAbsoluteTolerance
    t_choice = ["Sharp", "Round", "Smooth", "Chamfer"]
    e_choice = ["None", "Straight", "Arc", "OffsetStraight"]

    #Get previous settings
    if "OffsetCrvs_Dist" in sc.sticky: old_dist = sc.sticky["OffsetCrvs_Dist"]
    else: old_dist = 1.0
    if "OffsetCrvs_TChoice" in sc.sticky:
        old_trans = sc.sticky["OffsetCrvs_TChoice"]
    else:
        old_trans = "Sharp"
    if "OffsetCrvs_EChoice" in sc.sticky:
        old_ends = sc.sticky["OffsetCrvs_EChoice"]
    else:
        old_ends = "None"

    off_dist = rs.GetReal("Distance to offset", old_dist, tol)
    if not off_dist: return

    trans_type = rs.GetString("Offset transition?", old_trans, t_choice)
    if not trans_type: return
    if trans_type == "Sharp": tt = 1
    elif trans_type == "Round": tt = 2
    elif trans_type == "Smooth": tt = 3
    elif trans_type == "Chamfer": tt = 4
    else: return

    end_type = rs.GetString("End connection type?", old_ends, e_choice)
    if not end_type: return
    if end_type == "None": conn = -1
    elif end_type == "Straight": conn = 0
    elif end_type == "Arc": conn = 1
    elif end_type == "OffsetStraight": conn = 2
    else: return

    rs.EnableRedraw(False)
    rs.UnselectAllObjects

    count = 0
    for crv in crvs:
        success = OffsetCurve2Sides(crv, off_dist, tt, conn, tol)
        if success: count += 1

    if count < len(crvs):
        err_msg = " Unable to offset {} curves".format(len(crvs) - count)
    else:
        err_msg = ""
    print "Successfully offset {} curves.".format(count) + err_msg

    #Set preferences
    sc.sticky["OffsetCrvs_Dist"] = off_dist
    sc.sticky["OffsetCrvs_TChoice"] = trans_type
    sc.sticky["OffsetCrvs_EChoice"] = end_type
Exemple #27
0
def createCone():
    coneRadius = rs.GetReal(message='Of what radius? ', minimum=0.1)
    x1, y1, z1 = [float(n) for n in raw_input('From where?: "x y z"').split()]
    x2, y2, z2 = [float(n) for n in raw_input('To where?: "x y z"').split()]
    id = rs.AddCone((x1, y1, z1), (x2, y2, z2), coneRadius, cap=True)
    cones.append(id)
    rs.SetUserText(id, key="Cone", value=str(len(cones)))
    print('Done.')
def Main():
    mesh=rs.GetObjects("select mesh",rs.filter.mesh)
    start=rs.GetObject("select start points",rs.filter.point)
    refVec = rs.GetObject("select crv direction",rs.filter.curve)
    ang=rs.GetReal("enter branching angle",30)
    length=rs.GetReal("enter branch length",15)
    gen=rs.GetInteger("enter number of generations",3)
    lines=rs.AddLayer("branch",[255,0,0])
    rs.EnableRedraw(False)
    rs.CurrentLayer(lines)
    vec=tanVec(refVec,start)
    centers=rs.MeshFaceCenters(mesh)
    index=rs.PointArrayClosestPoint(centers,start)
    norm=rs.MeshFaceNormals(mesh)[index]
    vec=rs.VectorRotate(vec,0,norm)
    branches=baseBranch(mesh,start,vec,ang,length,gen)
    return branches
Exemple #29
0
def RunCommand(is_interactive):
    ringSize = rs.GetReal("Ring size", 8.5, 0, 16)
    center = rs.GetPoint("Location")

    plane = rs.MovePlane(rs.ViewCPlane(), center)
    radius = (11.63 + 0.8128 * ringSize) * 0.5
    objId = rs.AddCircle(plane, radius)
    rs.SelectObject(objId)
Exemple #30
0
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 ()