Example #1
0
def main():
    # first, select objects in three orthogonal planes

    xs = rs.GetObjects("select X objects", filter=16)
    # polysurface
    ys = rs.GetObjects("select Y objects", filter=16)
    zs = rs.GetObjects("select Z objects", filter=16)

    subdivisions = rs.GetInteger(message="enter subdivisions (odd)",
                                 number=5,
                                 minimum=2,
                                 maximum=None)

    for positive, negative, hidden in ((xs, ys, zs), (xs, zs, ys), (ys, zs,
                                                                    xs)):
        rs.HideObjects(hidden)
        make_fingers(positive, negative, subdivisions)
        rs.ShowObjects(hidden)

    # each time make_fingers is run, it fills guid_to_difference
    # with more fingers to subtract.
    # after all the fingers are subtracted at once
    for guid, objs in guid_to_difference.items():
        if objs:
            rs.BooleanDifference(guid, objs)
Example #2
0
    def draw_line_select(self):
        # Create an instance of a GetPoint class and add a delegate for the DynamicDraw event
        gp = Rhino.Input.Custom.GetPoint()
        # gp = Rhino.Input.Custom.PickContext()
        gp.DynamicDraw += GetPointDynamicDrawFuncSelect
        gp.Get()

        obj_all = rs.HiddenObjects()
        rs.ShowObjects(obj_all)
Example #3
0
def main():
  # first, select objects in three orthogonal planes
  xs = rs.GetObjects("select X objects", filter=16); # polysurface
  ys = rs.GetObjects("select Y objects", filter=16);
  zs = rs.GetObjects("select Z objects", filter=16);

  subdivisions = rs.GetInteger(message="enter subdivisions (o)", number=5, minimum=2, maximum=None)

  for positive, negative, hidden in ((xs, ys, zs), (xs, zs, ys), (ys, zs, xs)):
    rs.HideObjects(hidden)
    finger.make_fingers(positive, negative, subdivisions)
    rs.ShowObjects(hidden)

  finger.perform_subtraction()
def UnisolateObjLayer():
    try:
        rs.EnableRedraw(False)
        obj = rs.HiddenObjects()

        if obj:

            rs.ShowObjects(obj)
        rs.EnableRedraw(True)

    except:
        print("Failed to execute")
        rs.EnableRedraw(True)
        return
Example #5
0
def MakePlan(elevation, viewDepthZ, geos):
    objs = rs.CopyObjects(geos)
    rs.HideObjects(geos)

    ############################################################################
    print "Cutting Plan"
    allCrvs = []

    #Make plane
    plane = Rhino.Geometry.Plane(rs.coerce3dpoint((0, 0, elevation)),
                                 rs.coerce3dvector((0, 0, 1)))
    planeNeg = Rhino.Geometry.Plane(rs.coerce3dpoint((0, 0, viewDepthZ)),
                                    rs.coerce3dvector((0, 0, 1)))

    ############################################################################
    #Partition the geometry

    partitionedObjs = PartitionGeometry(objs, elevation, viewDepthZ)

    ############################################################################
    #Intersection Curves

    #interCrvs = IntersectGeos(partitionedObjs[1], plane)

    ############################################################################
    #Split Geometry
    #Get the bottom half of intersecting objs
    belowObjs = SplitGeometry(partitionedObjs[1], plane)
    print "A"

    #Get the top half of that previous geometry
    visibleObjs = SplitGeometry(partitionedObjs[0] + belowObjs, planeNeg, -1)

    rs.SelectObjects(visibleObjs)
    objs2del = rs.InvertSelectedObjects()
    rs.DeleteObjects(objs2del)
    print "A"
    ############################################################################
    #Make 2D
    allCrvs += ProjectPlan(visibleObjs, plane)

    rs.DeleteObjects(visibleObjs)

    print "Plan Cut"
    rs.ShowObjects(geos)
    rs.HideObjects(allCrvs)
    return allCrvs
Example #6
0
    def findFitness(point):
        def testArrangement(sortedCurves, factor):
            totalBox = rs.BoundingBox(sortedCurves)
            sqrtSource = rs.Distance(totalBox[0], totalBox[1])
            minLength = sqrtSource**0.5

            minLength = minLength**factor

            def meetsLength(len, startCrv, endCrv):
                objects = [startCrv, endCrv]
                boundingBox = rs.BoundingBox(objects, in_world_coords=True)
                curLen = rs.Distance(boundingBox[0], boundingBox[1])
                if curLen >= len:
                    return True
                else:
                    return False

            #Then, defining a list of the resulting lists.
            listOfLists = []
            s = 0  #"Start"
            e = 0  #"End"

            #Loop that splits the list into smaller lists.
            while True:
                if (s + e) == len(sortedCurves) or s == len(sortedCurves):
                    listOfLists.append(sortedCurves[s:s + e])
                    break
                elif meetsLength(minLength, sortedCurves[s],
                                 sortedCurves[s + e]) == True:
                    listOfLists.append(sortedCurves[s:s + e])
                    s = s + e
                    e = 1
                    continue
                else:
                    e += 1
                    continue

            #Now to move them vertically. First, like with the horizontal movement, we need to create a function that finds the vertical offset between each line.
            def findVOffset(curCrv):
                currentBox = rs.BoundingBox(curCrv, in_world_coords=True)
                vHeight = rs.Distance(currentBox[0], currentBox[3])
                offset = vHeight * 1.125
                offset = 0 - offset
                return offset

            #And to move them.
            for i in range(len(listOfLists)):
                if i == len(listOfLists) - 1:
                    break
                else:
                    rs.MoveObject(
                        listOfLists[i + 1],
                        rs.VectorCreate(findAnchorPoint(listOfLists[i]),
                                        findAnchorPoint(listOfLists[i + 1])))
                    rs.MoveObject(listOfLists[i + 1],
                                  (0, findVOffset(listOfLists[i + 1]), 0))

        sList = rs.CopyObjects(oList)
        rs.ShowObjects(sList)
        testArrangement(sList, point[0])

        shapeBox = rs.BoundingBox(sList)
        width = rs.Distance(shapeBox[0], shapeBox[1])
        height = rs.Distance(shapeBox[0], shapeBox[3])

        numerator = abs(width - height)
        denominator = width + height
        denominator = denominator / 2
        fitness = numerator / denominator
        fitness = fitness * 100
        rs.DeleteObjects(sList)
        return fitness
Example #7
0
                "How many GENERATIONS would you like to iterate?", 1, 1, 100)
            print " "
            print "CONTINUING iterating for [", count, "] GENERATIONS."
            rs.EnableRedraw(False)
            continue
    print " "
    print "The iterations have ENDED. [", totalAttempts, "] solutions were tested."
    print "Your final best fit had a FACTOR of [", bestPoint[
        0], "] and a FITNESS of [", bestPoint[1], "]."
    fFactor = bestPoint[0]
    return fFactor


rs.HideObjects(sortedCurves)
minLenFactor = devLenFactor(sortedCurves)
rs.ShowObjects(sortedCurves)
minLength = minLength**minLenFactor


#Now, split the list into smaller lists, first with defining a function that tests whether the length meets the criteria. Returns either True or False.
def meetsLength(len, startCrv, endCrv):
    objects = [startCrv, endCrv]
    boundingBox = rs.BoundingBox(objects, in_world_coords=True)
    curLen = rs.Distance(boundingBox[0], boundingBox[1])
    if curLen >= len:
        return True
    else:
        return False


#Then, defining a list of the resulting lists.
Example #8
0
if __name__ == '__main__':

    crvs = rs.GetObjects("Select mesh edges", 4)
    lines = get_line_coordinates(crvs)

    mesh = Mesh.from_lines(lines, delete_boundary_face=True)

    artist = MeshArtist(mesh, layer='new_lines')
    artist.draw_edges()
    artist.redraw()

    # select edge
    rs.HideObjects(crvs)
    edge = mesh_select_edge(mesh, "select a mesh edge")
    rs.ShowObjects(crvs)

    # select edge
    artist.clear_edges()

    # find "every second" edge (joint lines)
    new_lines = []

    para_edges = get_parallel_edges(mesh, edge)
    for u, v in para_edges[2::2]:
        new_lines.append((u, v))

    # draw new lines
    artist.draw_edges(keys=new_lines, color=(255, 0, 0))
    artist.redraw()
Example #9
0
def show_hidden_objects_on_layer(name):
    rs.ShowObjects(
        [guid for guid in rs.HiddenObjects() if rs.ObjectLayer(guid) == name])
Example #10
0
if __name__ == '__main__':
    
    edge_crvs = rs.GetObjects("Select edges", 4)
    lines = get_line_coordinates(edge_crvs)
    
    mesh = Mesh.from_lines(lines, delete_boundary_face=True)

    # draw edges for selection
    artist = MeshArtist(mesh, layer='joint_lines')
    artist.draw_edges()
    artist.redraw()
    
    # select edge
    rs.HideObjects(edge_crvs)
    edges = mesh_select_edges(mesh)
    rs.ShowObjects(edge_crvs)
    
    # clear edges
    artist.clear_edges()
        
    # find "every second" edge (joint lines)
    joint_lines = []
    for i, uv in enumerate(edges):
        para_edges = get_parallel_edges(mesh,uv)
        for u, v in para_edges[i%2::2]:
            joint_lines.append((u,v))
            
    # draw joint lines
    artist.draw_edges(keys=joint_lines, color=(255,0,0))
    artist.redraw()
def relax_mesh_on_surface():

    polylines = rs.ObjectsByLayer("re_02_polys")
    pts_objs = rs.ObjectsByLayer("re_03_points")

    vis = 5
    kmax = 2000
    dis = 0.3
    dev_threshold = 0.003
    angle_max = 30

    pts = get_points_coordinates(pts_objs)

    mesh = Mesh()

    for i, pt in enumerate(pts):
        mesh.add_vertex(str(i), {'x': pt[0], 'y': pt[1], 'z': pt[2]})

    polys = get_polyline_points(polylines)
    tris = get_faces_from_polylines(polys, pts)

    for tri in tris:
        mesh.add_face(tri)

    rs.EnableRedraw(False)

    pts = []
    for key, a in mesh.vertices_iter(True):

        pt1 = (a['x'], a['y'], a['z'])
        pts.append(pt1)
        vec = mesh.vertex_normal(key)
        vec = scale(normalize(vec), dis)
        pt2 = add_vectors(pt1, vec)

        pt2 = add_vectors(pt1, vec)
        a['x2'] = pt2[0]
        a['y2'] = pt2[1]
        a['z2'] = pt2[2]

        a['normal'] = vec
        #rs.AddLine(pt1,pt2)

    faces_1 = draw(mesh, dev_threshold)
    rs.HideObjects(faces_1)

    for k in range(kmax):
        nodes_top_dict = {key: [] for key in mesh.vertices()}
        polys = []
        max_distances = []
        for u, v in mesh.edges():
            pt1 = mesh.vertex_coordinates(u)
            pt2 = mesh.vertex_coordinates(v)
            pt3 = mesh.vertex[u]['x2'], mesh.vertex[u]['y2'], mesh.vertex[u][
                'z2']
            pt4 = mesh.vertex[v]['x2'], mesh.vertex[v]['y2'], mesh.vertex[v][
                'z2']
            points = [pt1, pt2, pt3, pt4]

            points = rs.coerce3dpointlist(points, True)
            rc, plane = Rhino.Geometry.Plane.FitPlaneToPoints(points)
            pt3, pt4 = [plane.ClosestPoint(pt) for pt in points[2:]]

            vec = scale(normalize(subtract_vectors(pt3, pt1)), dis)
            pt3 = add_vectors(pt1, vec)

            vec = scale(normalize(subtract_vectors(pt4, pt2)), dis)
            pt4 = add_vectors(pt2, vec)

            nodes_top_dict[u].append(pt3)
            nodes_top_dict[v].append(pt4)

            distances = [
                distance(pt1, pt2) for pt1, pt2 in zip(points[2:], [pt3, pt4])
            ]
            max_distances.append(max(distances))

        for key, a in mesh.vertices_iter(True):
            cent = centroid(nodes_top_dict[key])
            pt = mesh.vertex_coordinates(key)
            vec = subtract_vectors(cent, pt)
            norm = a['normal']

            if angle_smallest(vec, norm) < angle_max:
                a['x2'] = cent[0]
                a['y2'] = cent[1]
                a['z2'] = cent[2]

        if k % vis == 0:
            rs.Prompt(
                "Iteration {0} of {1} with with deviation sum {2}".format(
                    k, kmax, round(sum(max_distances), 4)))
            draw_light(mesh, temp=True)
        if max(max_distances) < dev_threshold or k == kmax:
            print "Iteration {0} of {1} with deviation sum {2}".format(
                k, kmax, round(sum(max_distances), 4))
            break

    dfaces_2 = draw(mesh, dev_threshold)
    rs.ShowObjects(faces_1)
    rs.EnableRedraw(True)
    print max(max_distances)
Example #12
0
    #Prepare the shot
    rs.CurrentView('Back')
    rs.CurrentView('Front')
    rs.HideObjects(obj_all)
    rs.UnselectAllObjects()

    #Take the shot
    img_des = dir_tar + dir_mai + dir_sec + pfx_sec + str(i) + '.png'
    rs.Command('-_ViewCaptureToFile ' + img_des + ' _DrawGrid=No' +
               ' _Width=' + str(img_wid) + ' _Height=' + str(img_hei) +
               ' _Scale=' + str(img_sca) + ' _TransparentBackground=No' +
               ' _Enter' + ' _Enter')

    #Prepare the environment for the next iteration
    pla_pos[1] = pla_pos[1] - vis_ste
    rs.ShowObjects(obj_all)
    rs.DeleteObjects(pla_obj)
    sec_cur = rs.ObjectsByType(4)
    rs.DeleteObjects(sec_cur)

if 'Default' in lay_lis:
    rs.CurrentLayer(layer='Default')
else:
    rs.AddLayer(name='Default')
    rs.CurrentLayer(layer='Default')

#Leave the rest of the layers as they were at start
rs.CurrentLayer(lay_act)
for i in lay_vis:
    rs.LayerVisible(i, visible=True)
Example #13
0
import rhinoscriptsyntax as rs

#delete all existing objects
rs.ShowObjects(rs.HiddenObjects())
rs.DeleteObjects(rs.AllObjects('select'))

#variables
flowerRadius = 10  #radius of the flower
centerRadius = 2  #radius of the center of the flower
petalCount = 15
flowerCenter = (0, 0, 0)
petalWidth = 10  #width of the petals
petals = []  #store petal curves here

#print out the variables
textToPrint = 'flowerRadius = %d\ncenterRadius = %d\npetalCount = %d\npetalWidth = %d' % (
    flowerRadius, centerRadius, petalCount, petalWidth)
rs.AddText(textToPrint, ((flowerRadius + 1), 2, 0), height=1.0)

#draw outer circle
outerCircle = rs.AddCircle(flowerCenter, flowerRadius)

#divide to get the point of each petal
points = rs.AddPoints(rs.DivideCurve(outerCircle, petalCount))

#draw each petal
for i in range(len(points)):
    #draw line from center to point of the petal
    centerLine = rs.AddLine(points[i], flowerCenter)

    #find the midpoint
Example #14
0
from objects_to_mesh import nurbs_to_mesh
import rhinoscriptsyntax as rs

if __name__ == '__main__':

    poly_srf = rs.GetObjects("Select Objects", 8 + 16)

    if poly_srf:
        srfs_explo = rs.ExplodePolysurfaces(poly_srf)

    if srfs_explo:
        srfs = srfs_explo
    else:
        srfs = poly_srf

    trg_len = rs.GetReal("Target Edges Length", 0.75)
    rhino_meshes = []
    for i, srf in enumerate(srfs):
        print("Computing Surface {0} of {1}".format(i + 1, len(srfs) + 1))
        rs.EnableRedraw(False)
        rs.HideObject(srf)
        rhino_meshes.append(nurbs_to_mesh(srf, trg_len, vis=5))
        if srfs_explo:
            rs.DeleteObject(srf)

    rs.ShowObjects(srfs)
    rs.JoinMeshes(rhino_meshes, True)