def main():
    objs = rs.VisibleObjects()
    cutLevel = 12
    rs.EnableRedraw(False)
    objsCopy = rs.CopyObjects(objs)
    splitModel(objsCopy, cutLevel)
    rs.EnableRedraw(True)
Esempio n. 2
0
def addJoin(lns, nJoins, xThick, yThick):

    joins = []
    joins_3 = []

    points = rs.DivideCurve(lns, nJoins)
    lenP = len(points)

    for i in range(lenP):
        joins.append(rs.AddPoint(points[i]))

    joins_2 = rs.CopyObjects(joins, [xThick, yThick, 0])
    joins_2.remove(joins_2[0])
    joins_2.append([0, 0, 0])

    for j in range(0, len(joins), 2):
        c = j + 2
        addList(joins, joins_2, joins_3, j, c)

    joins_3.remove(joins_3[len(joins_3) - 1])
    joins_3.remove(joins_3[len(joins_3) - 1])
    joined = rs.AddPolyline(joins_3)
    rs.DeleteObject(lns)

    return joined
def CopyObjectsToLayer():
    "Copy selected objects to a different layer"
    # Get the objects to copy
    objectIds = rs.GetObjects("Select objects")
    # Get all layer names
    layerNames = rs.LayerNames()
    if (objectIds == None or layerNames == None): return

    # Make sure select objects are unselected
    rs.UnselectObjects(objectIds)

    layerNames.sort()
    # Get the destination layer
    layer = rs.ComboListBox(layerNames,
                            "Destination Layer <" + rs.CurrentLayer() + ">")
    if layer:
        # Add the new layer if necessary
        if (not rs.IsLayer(layer)): rs.AddLayer(layer)
        # Copy the objects
        newObjectIds = rs.CopyObjects(objectIds)

        # Set the layer of the copied objects
        [rs.ObjectLayer(id, layer) for id in newObjectIds]
        # Select the newly copied objects
        rs.SelectObjects(newObjectIds)
Esempio n. 4
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])
Esempio n. 5
0
def cut_building_volumes(terrain_section_breps, bldg_section_breps):
    """
	input: list of lists of extruded terrain breps and section breps.
	first level of list is section heights, second level is breps.
	output: the new terrain breps
	"""
    #boolean problem is caused by non-manifold error. need to scale the B_breps prior to booleaning.
    new_terrain_section_breps = []
    for i, brep_level in enumerate(terrain_section_breps):
        new_level_terrain_section_breps = []
        for A_brep in brep_level:
            #rs.ObjectLayer(A_brep,"s10") #debug
            B_breps = rs.CopyObjects(bldg_section_breps[i])
            #[rs.ObjectLayer(B_brep,"s11") for B_brep in B_breps] #debug
            boolean_result = rs.BooleanDifference([A_brep], B_breps, False)
            if boolean_result:
                c = [rs.CopyObject(x) for x in boolean_result]
                rs.DeleteObjects(boolean_result)
                new_level_terrain_section_breps.extend(c)
            else:
                new_level_terrain_section_breps.append(rs.CopyObject(A_brep))
            #print new_level_terrain_section_breps
            rs.DeleteObjects(A_brep)
            rs.DeleteObjects(B_breps)
        rs.DeleteObjects(B_breps)  #possibly not needed
        rs.DeleteObjects(boolean_result)
        #rs.ObjectLayer(new_level_terrain_section_breps,"s3")
        new_terrain_section_breps.append(new_level_terrain_section_breps)
    return new_terrain_section_breps
Esempio n. 6
0
def transformMatrix():
    obj_ids = rs.GetObjects("Select object(s) from which to create 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)
    endpt = rs.GetPoint("To point")

    newpt = [1, 1, 1]
    translation1 = rs.VectorCreate(endpt, newpt)
    translation2 = rs.VectorCreate(translation1, origin)
    copied_obj_ids = rs.CopyObjects(obj_ids, translation2)

    for obj in copied_obj_ids:
        matrix = []
        degrees = 90.0  # Some angle
        radians = math.radians(degrees)
        c = math.cos(radians)
        s = math.sin(radians)
        matrix.append([c, -s, 0, 0])
        matrix.append([s, c, 0, 0])
        matrix.append([0, 0, 1, 0])
        matrix.append([0, 0, 0, 1])
        pprint.pprint(matrix)
        rs.ScaleObject(obj, newpt, [3, 1, -9])
        plane = rs.ViewCPlane()
        pprint.pprint(plane)
        rs.RotateObject(obj, newpt, uniform(0, 360), plane.XAxis)
        rs.RotateObject(obj, newpt, uniform(0, 360), plane.YAxis)
        rs.RotateObject(obj, newpt, uniform(0, 360), plane.ZAxis)
Esempio n. 7
0
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)
Esempio n. 8
0
def copyToOrigin(objs):

    #get left bottom
    selection_base = rs.GetPoint("Pick export base point")
    #box = rs.BoundingBox(objs)
    if selection_base:
        #selection_base = [box[0].X, box[0].Y, box[0].Z]
        vector = rs.VectorSubtract(selection_base, [0, 0, 0])

        return rs.CopyObjects(objs, rs.VectorReverse(vector))
Esempio n. 9
0
def draw_coaming(c):
    pts = [[0, 0, 0]]
    half = [[(i + 1) * c.spacing, c.points[i], 0]
            for i in range(len(c.points))]
    pts.extend(half)
    pts.append([c.length, 0, 0])
    half = [[(i + 1) * c.spacing, -c.points[i], 0]
            for i in range(len(c.points))]
    half.reverse()
    pts.extend(half)
    pts.append([0, 0, 0])
    crv = rs.AddInterpCurve(pts,
                            degree=3,
                            knotstyle=0,
                            start_tangent=[0, 1, 0],
                            end_tangent=[0, 1, 0])
    strip = [crv, rs.OffsetCurve(crv, [-1, 0, 0], c.width1)]
    rs.CopyObjects(strip, [0, c.beam + 2 * c.width1, 0])
    strip2 = [rs.CopyObjects(crv), rs.OffsetCurve(crv, [-1, 0, 0], c.width2)]
    rs.MoveObjects(strip2, [0, -c.beam - c.width1 - c.width2, 0])
Esempio n. 10
0
def change_object_layers(guids, layName, copy=False):
    """change layer of objects.
	params: [guids], str layName. bool copy
	return: new objects on layer (or original objects with reassigned layer if copy==False)"""

    if (not rs.IsLayer(layName)): add_layer(layName, sd.Color.White)

    if copy == True: guids = rs.CopyObjects(guids)

    [rs.ObjectLayer(id, layName) for id in guids]
    return guids
Esempio n. 11
0
def change_object_layers(guids, layName, copy):
    if (not rs.IsLayer(layName)): add_layer(layName, sd.Color.White)

    if copy == True: guids = rs.CopyObjects(guids)

    [rs.ObjectLayer(id, layName) for id in guids]
    [rs.ObjectPrintWidthSource(id, 0) for id in guids]
    [rs.ObjectPrintColorSource(id, 0) for id in guids]
    [rs.ObjectColorSource(id, 0) for id in guids]

    return guids
Esempio n. 12
0
def checkPos(objs):
    # if ok, start export
    copies = rs.CopyObjects( objs)
    copies = ce.explodeBlock( copies )
    
    # filter objects to only curves and points
    copies = filterObjects(copies) 
    if not ce.checkCurvePosition(copies):
        rs.DeleteObjects(copies)    
        return False
        
    rs.DeleteObjects(copies)  
Esempio n. 13
0
 def genFuncObj_Site(self):
     s = site_obj(self.site)
     pts = s.getPts()
     s.displayPts()
     poly_list = []
     for i in self.req_obj:
         for j in range(i.getNumber()):
             obj = i
             T = False
             k = 0
             this_gen_poly = None
             while (T == False and k < 50):
                 x = random.randint(1, len(pts) - 2)
                 p = pts[x - 1]
                 q = pts[x]
                 r = pts[x + 1]
                 poly = obj.getConfig1(p, q, r)
                 sum = 0
                 if (poly is not None and len(poly) > 0):
                     sum = 0
                     if (poly_list and len(poly_list) > 0):
                         for m in poly_list:
                             polyY = rs.AddPolyline(m)
                             G = self.checkPoly(poly, polyY)
                             rs.DeleteObject(polyY)
                             if (G == False):
                                 sum += 1
                                 break
                         if (sum == 0):
                             T = True
                             if (poly not in poly_list):
                                 this_gen_poly = poly
                                 poly_list.append(poly)
                     elif (poly is not None and len(poly) > 0):
                         if (poly not in poly_list):
                             this_gen_poly = poly
                             poly_list.append(poly)
                 k += 1
             if (this_gen_poly is not None):
                 i.setGenPoly(rs.AddPolyline(this_gen_poly))
     for i in self.req_obj:
         poly = i.getGenPoly()
         num_flrs = i.getNumFloors()
         num_crvs = len(i.getGenPoly())
         fin_num_flrs = int(num_flrs / num_crvs)
         i.setNumFloors(fin_num_flrs)
         for j in poly:
             i.genIntPoly(j)
             npoly = i.getReqPoly()
             for k in range(fin_num_flrs):
                 rs.CopyObjects(npoly, [0, 0, 4 * k])
             pass
def main():
    objs = rs.VisibleObjects()
    cutLevel = 12
    rs.EnableRedraw(False)
    objsCopy = rs.CopyObjects(objs)
    splitModel(objsCopy, cutLevel)
    makePlan()
    rs.DeleteObjects(rs.ObjectsByGroup("Above"))
    rs.DeleteObjects(rs.ObjectsByGroup("Below"))
    cutAtPlan(cutLevel, False)
    rs.Command('_SelDupAll _delete')
    cutAtPlan(cutLevel, True)
    rs.Command('_SelDup _delete')
    rs.EnableRedraw(True)
Esempio n. 15
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
Esempio n. 16
0
def get_preview_geometry(arr_curves):
	"""duplicate the geometry for extension"""
	arr_exploded = []

	arr_lines = []

	for x in arr_curves:
		if rs.IsLine(x):
			arr_exploded.append(x)

	for i in xrange(len(arr_curves)):
		if rs.IsLine(arr_curves[i]):
			arr_lines.append(arr_curves[i])

	arr_preview_exploded = rs.ExplodeCurves(arr_curves,False)
	arr_preview_lines = rs.CopyObjects(arr_lines)

	#Get locked objects
	return arr_preview_exploded + arr_preview_lines
def send2CAD(objs, newCoord, CADinMeters):
    if CADinMeters:
        transVec = rs.VectorCreate(newCoord, [0,0,0])
    else:
        transVec = rs.VectorScale(newCoord, .001)
    newObjs = rs.CopyObjects(objs, transVec)
    
    if CADinMeters:
        rs.ScaleObjects(newObjs, [0,0,0], [.001,.001,.001])
        print  "scaled"
    
    rs.SelectObjects(newObjs)
    
    loc = " D:\\temp.dwg"
    
    rs.Command('_-Export '+loc+' _Enter')
    
    rs.DeleteObjects(newObjs)
    print "Sent"
    return None
Esempio n. 18
0
def make_join(edge, n_joins, dx, dy, inner, truncate):

    pts = rs.DivideCurve(edge, n_joins)
    outer_pts, inner_pts, pairs_ordered = [], [], []
    extrapt = None

    outer_pts = rs.AddPoints(pts)
    inner_pts = rs.CopyObjects(outer_pts, [dx, dy, 0])
    if inner == True:
        extrapt = outer_pts[0]
        outer_pts = outer_pts[1:]
    else:
        extrapt = inner_pts[0]
        inner_pts = inner_pts[1:]

    pairs_o = zip(outer_pts[0::2], outer_pts[1::2])
    pairs_i = zip(inner_pts[0::2], inner_pts[1::2])

    if inner is True:
        pairs_ordered = flatten(zip(pairs_i, pairs_o))
        endpts = [inner_pts[-2], inner_pts[-1]]
    else:
        pairs_ordered = flatten(zip(pairs_o, pairs_i))
        endpts = [outer_pts[-2], outer_pts[-1]]

    pairs_ordered = pairs_ordered + endpts

    if truncate is True:
        v = rs.VectorUnitize(
            rs.VectorCreate(pairs_ordered[0], pairs_ordered[1]))
        v = rs.VectorScale(v, T_OBOX)
        rs.MoveObject(pairs_ordered[-1], v)
        rs.MoveObject(pairs_ordered[0], rs.VectorReverse(v))

    pl = rs.AddPolyline(pairs_ordered)
    rs.DeleteObject(extrapt)
    rs.DeleteObjects(outer_pts)
    rs.DeleteObjects(inner_pts)
    return pl
Esempio n. 19
0
if not HV3:
    HV3 = HV1
if not DiagV2:
    DiagV2 = DiagV1
if not DiagV3:
    DiagV3 = 9
if not No_Shed:
    No_Shed = 2
if not Plano:
    Plano = rs.WorldXYPlane()

#decompoe o plano de trabalho nos componentes Origem e os eixos xyz
pOr, eX, eY, eZ = Plano

#-Copiando Curva inicial
Curva = rs.CopyObjects(Curva, 10 * eY)
BzSup1 = rs.coercecurve(Curva)

#----Primeiro ponto do Eixo de Simetria----
#A variável Eixo_de_Simetria por entrada um float entre o e 1 ou
#uma reta que intercepta a Curva no ponto do eixo
#caso seja um float:
if type(Eixo_de_Simetria) == float:
    #ptX1 = coordenadas da curva no ponto de interceção com o eixo de simetria
    #vct1 = tangente da curva no ponto
    #prm1 = parametro da curva no ponto
    ptX1, vtc1, prm1 = gh.EvaluateLength(BzSup1, Eixo_de_Simetria, True)
    ptAux = gh.Move(ptX1, -eY)[0]
    #-desenhando linha do Exio de simetria
    Eixo_de_Simetria = rs.AddLine(ptX1, ptAux)
#caso seja uma linha
    for j in xrange(len(points) - 1):
        if j < (len(points) - 2):
            vertex_ = [(c_index, int(j), int(j) + 1, int(j) + 1)]
            # print(vertex_)
            m = rs.AddMesh(points, vertex_)
            meshes.append(m)
        else:
            vertex_ = [(c_index, int(j), 0, 0)]
            # print(vertex_)
            m = rs.AddMesh(points, vertex_)
            meshes.append(m)

    mesh_joined = rs.JoinMeshes(meshes)

    return mesh_joined


points = point_polyline(CURVE)
# print(points)

point_cp_0 = rs.coerce3dpointlist(rs.CopyObjects(points))
point_cp_1 = rs.coerce3dpointlist(rs.CopyObjects(points))

step = construct_mesh_step(point_cp_0)
center = construct_mesh_center(point_cp_1)

POINTS_ = points
MESH_STEP_ = step
MESH_CENTER_ = center
Esempio n. 21
0
def createRectangularMatrix():
    print("\n createRectangularMatrix 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, 10) / 100

    nXspace = rs.GetReal("Spacing X", 1, 0)
    rXspace = rs.GetReal("Spacing X rand", 0, 0, 100)

    nYspace = rs.GetReal("Spacing Y", 1, 0)
    rYspace = rs.GetReal("Spacing Y rand", 0, 0, 100)

    nZspace = rs.GetReal("Spacing Z", 1, 0)
    rZspace = rs.GetReal("Spacing Z rand", 0, 0, 100)

    nXscale = rs.GetReal("Scale X", 1, 0)
    rXscale = rs.GetReal("Scale X rand", 0, 0, 100)

    nYscale = rs.GetReal("Scale Y", 1, 0)
    rYscale = rs.GetReal("Scale Y rand", 0, 0, 100)

    nZscale = rs.GetReal("Scale Z", 1, 0)
    rZscale = rs.GetReal("Scale Z rand", 0, 0, 100)

    nXrotate = rs.GetReal("Rotate X", 0, 0)
    rXrotate = rs.GetReal("Rotate X rand", 0, 0, 100)

    nYrotate = rs.GetReal("Rotate Y", 0, 0)
    rYrotate = rs.GetReal("Rotate Y rand", 0, 0, 100)

    nZrotate = rs.GetReal("Rotate Z", 0, 0)
    rZrotate = rs.GetReal("Rotate Z rand", 0, 0, 100)

    endpt = rs.GetPoint("To point")

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

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

    xspace = calc_val_real(nXspace, rXspace)
    yspace = calc_val_real(nYspace, rYspace)
    zspace = calc_val_real(nZspace, rZspace)

    xscale = calc_val_real(nXscale, rXscale)
    yscale = calc_val_real(nYscale, rYscale)
    zscale = calc_val_real(nZscale, rZscale)

    xrotate = calc_val_real(nXrotate, rXrotate)
    yrotate = calc_val_real(nYrotate, rYrotate)
    zrotate = calc_val_real(nZrotate, rZrotate)

    # 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
                ]
                translation1 = rs.VectorCreate(endpt, newpt)
                #                translation2 = rs.VectorCreate(translation1, origin)
                copied_obj_ids = rs.CopyObjects(obj_ids, translation1)
                for obj in copied_obj_ids:
                    rs.ScaleObject(obj, newpt, [xscale, yscale, zscale])
                    plane = rs.ViewCPlane()
                    rs.RotateObject(obj, newpt, xrotate, plane.XAxis)
                    rs.RotateObject(obj, newpt, yrotate, plane.YAxis)
                    rs.RotateObject(obj, newpt, zrotate, plane.ZAxis)
 def matchWObj(self, geoList):
     ref = rs.AddPoint(0, 0, 0)
     vec = rs.VectorCreate(rs.AddPoint(self.WObj), ref)
     rot = rs.RotateObjects(geoList, rs.AddPoint(0, 0, 0), -90, copy=True)
     return rs.CopyObjects(rot, vec)
def testDuplicationsAndSpaceAndScaleAndRotate():
    print("\n testDuplicationsAndSpaceAndScaleAndRotate 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("Max Duplications X", 1, 1)
    nYdups = rs.GetInteger("Max Duplications Y", 1, 1)
    nZdups = rs.GetInteger("Max Duplications Z", 1, 1)

    nXspace = rs.GetReal("Spacing X", 1, 0)
    rXspace = rs.GetReal("Spacing X rand", 0, 0, 100) / 100

    nYspace = rs.GetReal("Spacing Y", 1, 0)
    rYspace = rs.GetReal("Spacing Y rand", 0, 0, 100) / 100

    nZspace = rs.GetReal("Spacing Z", 1, 0)
    rZspace = rs.GetReal("Spacing Z rand", 0, 0, 100) / 100

    nXscale = rs.GetReal("Scale X", 1, 0)
    rXscale = rs.GetReal("Scale X rand", 0, 0, 100) / 100

    nYscale = rs.GetReal("Scale Y", 1, 0)
    rYscale = rs.GetReal("Scale Y rand", 0, 0, 100) / 100

    nZscale = rs.GetReal("Scale Z", 1, 0)
    rZscale = rs.GetReal("Scale Z rand", 0, 0, 100) / 100

    nXrotate = rs.GetReal("Rotate X", 0, 0, 360)
    rXrotate = rs.GetReal("Rotate X rand", 0, 0, 100) / 100

    nYrotate = rs.GetReal("Rotate Y", 0, 0, 360)
    rYrotate = rs.GetReal("Rotate Y rand", 0, 0, 100) / 100

    nZrotate = rs.GetReal("Rotate Z", 0, 0, 360)
    rZrotate = rs.GetReal("Rotate Z rand", 0, 0, 100) / 100

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

    endpt = rs.GetPoint("To point")

    sample_near_val = lambda val, rand: random.uniform(-rand * val, rand * val)

    translations = []
    # Copy Points with Spacing
    for k in range(nZdups):
        for j in range(nYdups):
            for i in range(nXdups):
                newpt = [
                    origin[0] + i * nXspace +
                    sample_near_val(nXspace, rXspace), origin[1] +
                    j * nYspace + sample_near_val(nYspace, rYspace),
                    origin[2] + k * nZspace +
                    sample_near_val(nZspace, rZspace)
                ]
                translations = translations + [rs.VectorCreate(endpt, newpt)]

    nObjs = len(translations)
    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)

    for obj in copied_objs:
        bb = rs.BoundingBox(obj)
        if bb:
            center_point = rs.PointDivide(rs.PointAdd(bb[0], bb[6]), 2)
            # pt = rs.SurfaceVolumeCentroid(obj)
            rs.ScaleObject(obj, center_point, [
                nXscale + sample_near_val(nXscale, rXscale),
                nYscale + sample_near_val(nYscale, rYscale),
                nZscale + sample_near_val(nZscale, rZscale)
            ])
            plane = rs.ViewCPlane()
            rs.RotateObject(obj, center_point,
                            nXrotate + sample_near_val(nXrotate, rXrotate),
                            plane.XAxis)
            rs.RotateObject(obj, center_point,
                            nYrotate + sample_near_val(nYrotate, rYrotate),
                            plane.YAxis)
            rs.RotateObject(obj, center_point,
                            nZrotate + sample_near_val(nZrotate, rZrotate),
                            plane.ZAxis)
 def divideLR(self, ptList):
     Llist = rs.CopyObjects(ptList[0:][::2])
     Rlist = rs.CopyObjects(ptList[1:][::2])
     self.shift(Rlist, 4)
     return Llist, Rlist
Esempio n. 25
0
    pattern_A.append(rs.AddLine(joins[i],joins[i+1]))

#----------Generate pattern B----------#
joins_2 = []
joins_2.append(a)
p_2 = rs.CopyObject(a,[(d/2),0,0])
joins_2.append(p_2)

for i in range (1, (xint+1)):
    c_2 = rs.CopyObject(p_2,[l,0,0])
    joins_2.append(c_2)
    p_2 = rs.CopyObject(c_2,[d,0,0])
    joins_2.append(p_2)

pattern_B = []
for i in range (1, (len(joins_2)-1), 2):
    pattern_B.append(rs.AddLine(joins_2[i],joins_2[i+1]))

p_B = rs.MoveObjects(pattern_B, [0,s,0])

for i in range (0, (xint_2-1), 2):
    pattern_A = rs.CopyObjects(pattern_A, [0,s*2,0])
    p_B = rs.CopyObjects(p_B, [0,s*2,0])


rs.DeleteObjects(joins)
rs.DeleteObjects(joins_2)
rs.DeleteObject(obj_0)

rs.EnableRedraw(True)
def CopyObjectsToLayer(objs, layer):
    copies = rs.CopyObjects(objs)
    rs.ObjectLayer(copies, layer)
Esempio n. 27
0
    def lb_generate_analysis(self):
        
        try:
            if self.m_test_points == None: 
                print "missing grid objects"
                return      
                
            #prepare paramters
            window_groups = []   #not included yet in eto interface  
            name = 'default_name'#not included yet in eto interface  
            sun_path_panel = list(self.Parents)[-1].get_sun_path_panel()  
            sun_vectors = sun_path_panel.m_vectors
            hoys = sun_path_panel.m_hoys        
            timestep = sun_path_panel.m_timestep     
            #hb objects data 
            hb_object_ids = self.m_hb_object_ids
            hb_object_types, hb_object_mats = self.lb_get_hb_objects_data()
            #project data
            folder = self.m_project_path_picker.FilePath
            filename = self.m_project_name_text_box.Text            
            save_file_only = self.m_save_file_check_box.Checked
            
            #turn off last results layers
            if 'Eto_DisplayLayerIndex' in sc.sticky and sc.sticky['Eto_DisplayLayerIndex']:
                last_layer_index = sc.sticky['Eto_DisplayLayerIndex']
                last_layer = Rhino.RhinoDoc.ActiveDoc.Layers.FindIndex(last_layer_index)
                last_layer_name = rs.LayerName(last_layer.Id, True)
                last_parentLayer = rs.LayerName(last_layer.ParentLayerId, True) 
                rs.LayerVisible(last_parentLayer, False)  
            results_layer = None
            
            # generate one analysis merging points/vector and meshes
            points_item = []
            vectors_item = []
            for index in range(len(self.m_test_points)):
                points_item += self.m_test_points[index]
                vectors_item += self.m_pts_vectors[index]
            
            mesh_item = self.m_output_mesh.pop(0)
            if len(self.m_output_mesh):
                mesh_item.Append(self.m_output_mesh) 
            
            rs.EnableRedraw(False)
                
            LadybugEto.generateAnalysis(points_item,
                                        vectors_item,
                                        name,
                                        window_groups,
                                        sun_vectors,
                                        hoys,
                                        timestep,
                                        hb_object_ids,
                                        hb_object_types,
                                        hb_object_mats,
                                        folder,
                                        filename,
                                        save_file_only,
                                        [mesh_item])
                                        
            #consolidate multiple result objects into one layer (workaround to
            #solve current ladybug_ResultVisualization.bakeObjects behaviour)
            layer_index = sc.sticky['Eto_DisplayLayerIndex']
            last_layer = Rhino.RhinoDoc.ActiveDoc.Layers.FindIndex(layer_index)
            last_layer_name = rs.LayerName(last_layer.Id, True)
            p_layer_name = rs.LayerName(last_layer.ParentLayerId, True)  
            
            #use first analysis layers
            if index == 0: 
                results_layer_index = layer_index
                results_layer = last_layer_name
                results_p_layer = p_layer_name
            #delte all subsequent analysis layers
            elif last_layer_name <> results_layer:
                #Move all objects to analysis layer and delete layers       
                objects_id = rs.ObjectsByLayer(last_layer_name)
                res = list(rs.ObjectLayer(obj_id, results_layer) for obj_id in objects_id)  
                rs.DeleteLayer(last_layer_name)
                rs.DeleteLayer(p_layer_name)
                
            rs.EnableRedraw(True)
                
            #replace the sticky to results layer used    
            sc.sticky['Eto_DisplayLayerIndex'] = results_layer_index    
            
            #copy original analysis surfaces hb objects to analisys layer created
            rs.EnableRedraw(False)            

            #copy analysis grid
            new_layer_name = rs.AddLayer(results_p_layer+"::Analysis_grid_objects", color=Color.Red)
            gridsurfs_ids = list(item.Tag for item in self.m_gridsurfs_list_box.Items)
            new_grid_objects = rs.CopyObjects(gridsurfs_ids)
            res = list(rs.ObjectLayer(obj_id, new_layer_name) for obj_id in new_grid_objects)
            
            #copy hb objects 
            new_layer_name = rs.AddLayer(results_p_layer+"::HB_objects", color=Color.LightGreen)
            new_grid_objects = rs.CopyObjects(self.m_hb_object_ids)
            res = list(rs.ObjectLayer(obj_id, new_layer_name) for obj_id in new_grid_objects)  
             
            rs.EnableRedraw(True)
            
        except Exception as e:
            print e                                          
Esempio n. 28
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
Esempio n. 29
0
def main():
    global g_instances
    global g_parts
    global g_indent
    global g_materials

    #print(sys.version_info) # (2, 7, 0, 'beta', 0)

    dlg = rc.UI.SaveFileDialog()
    dlg.DefaultExt = "model"
    dlg.Filter = "RocketScience 3D Model (*.model)"
    dlg.InitialDirectory = os.path.dirname(sc.doc.Path)
    if not dlg.ShowSaveDialog(): return None

    selectedObjects = rs.SelectedObjects()

    objects = []
    origin = [0, 0, 0]

    for object in selectedObjects:
        name = rs.ObjectName(object)
        type = rs.ObjectType(object)
        if type == rs.filter.point:
            if name.startswith("Origin"):
                origin = rs.PointCoordinates(object)
        else:
            objects.append(object)

    print("Processing " + str(len(objects)) + " object(s)")
    print("Origin is [%.2f,%.2f,%.2f]" % (origin[0], origin[1], origin[2]))

    rootInstance = \
    {
            "name" : "*",
        "fullName" : "*",
            "type" : "*",
           "xform" : None,
         "parents" : [],
           "parts" : [],
         "touched" : False,
    }

    g_instances.append(rootInstance)

    objectsCopied = rs.CopyObjects(objects, rs.VectorScale(origin, -1))
    for object in objectsCopied:
        processObject(object, [rootInstance])

    output = open(dlg.FileName, "w")

    #output.write("# i <instance-type> <instance-name> "
    #    "<parent-instance-name>\n")
    #output.write("# x <x-axis-x> <y-axis-x> <z-axis-x> <translation-x>\n")
    #output.write("# x <x-axis-y> <y-axis-y> <z-axis-y> <translation-y>\n")
    #output.write("# x <x-axis-z> <y-axis-z> <z-axis-z> <translation-z>\n")
    #output.write("# m <material-name> <ambient> <diffuse> <emission>\n")
    #output.write("# p <part-name> <instance-name> <material-name> "
    #    "<vertices> <triangles>\n")
    #output.write("# v <pos-x> <pos-y> <pox-z> <norm-x> <norm-y> <norm-z>\n")
    #output.write("# t <vertex-1> <vertex-2> <vertex-3>\n")
    #output.write("\n")

    g_instances.sort(key=instanceSortKey)
    for instance in g_instances:
        parentCount = len(instance["parents"])

        indent = g_indent * (parentCount - 1)

        parentName = "*"
        if instance["parents"]:
            parentName = instance["parents"][-1]["name"]
        line = format(
            "i%s %s %s %s" %
            (indent, instance["type"], instance["fullName"], parentName))

        print(line)
        output.write(line + "\n")

        if parentCount < 1:
            xform = rc.Geometry.Transform(1.0)
        else:
            xform = instance["xform"]

        indent += "  "
        output.write("x " + indent + formatHexFloats(
            [xform.M00, xform.M01, xform.M02, xform.M03], True) + "\n")
        output.write("x " + indent + formatHexFloats(
            [xform.M10, xform.M11, xform.M12, xform.M13], True) + "\n")
        output.write("x " + indent + formatHexFloats(
            [xform.M20, xform.M21, xform.M22, xform.M23], True) + "\n")

    for materialName, materialIdx in g_materials.iteritems():
        material = sc.doc.Materials[materialIdx]

        ambient = material.AmbientColor
        diffuse = material.DiffuseColor
        emission = material.EmissionColor

        line = format(
            "m %s %s" %
            (materialName, formatColors([ambient, diffuse, emission])))

        print(line)
        output.write(line + "\n")

    g_parts.sort(key=partSortKey)
    for part in g_parts:
        mesh = part["mesh"]

        line = format(
            "p %s %s %s %d %d" %
            (part["name"], part["instance"]["fullName"], part["material"],
             mesh.Vertices.Count, mesh.Faces.Count))

        print(line)
        output.write(line + "\n")

        indent = "  "

        for vertexIdx in range(0, mesh.Vertices.Count):
            vertex = mesh.Vertices[vertexIdx]
            normal = mesh.Normals[vertexIdx]
            output.write("v " + indent + formatHexFloats(
                [vertex.X, vertex.Y, vertex.Z, normal.X, normal.Y, normal.Z]) +
                         "\n")

        line = lineInit = "t" + indent
        for faceIdx in range(0, mesh.Faces.Count):
            face = mesh.Faces[faceIdx]
            if not face.IsTriangle:
                print("WARNING: Non-triangle face %d" % (faceIdx))
            part = format(" %d %d %d" % (face.A, face.B, face.C))
            if len(line) + len(part) > 100:
                output.write(line + "\n")
                line = lineInit
            line += part
        if len(line) > 0:
            output.write(line + "\n")

    output.close()
                                "WindowVisibility"):  #Panel has a window?
                        panelBlockList += item[0].GetPanelProperty(
                            "BlockInstances")

            panelBlockList = panelBlockList[0:-1:int(
                stepNumber)]  #Nth panel filtering

            #--Collect current objects in key layers before exploding targeted blocks
            initDocGlassSet = set(rs.ObjectsByLayer("_P_Glass"))
            initDocMullionSet = set(rs.ObjectsByLayer("_P_Mullions"))
            initDocShadingSet = set(rs.ObjectsByLayer("_P_Shading"))
            initDocWallSet = set(rs.ObjectsByLayer("_P_Wall"))

            #Explode blocks of seleted panels
            tmpPanelElements = []
            tmpPanelBlockList = rs.CopyObjects(panelBlockList)
            for tmpPanelBlock in tmpPanelBlockList:
                tmpPanelElements += rs.ExplodeBlockInstance(tmpPanelBlock)

            #--Collect new objects in key layers
            newDocGlassSet = set(rs.ObjectsByLayer("_P_Glass"))
            newDocMullionSet = set(rs.ObjectsByLayer("_P_Mullions"))
            newDocShadingSet = set(rs.ObjectsByLayer("_P_Shading"))
            newDocWallSet = set(rs.ObjectsByLayer("_P_Wall"))

            #Store Ladybug elements and delete leftovers
            lbGlassSet = set()
            lbMullionSet = set()
            lbShadingSet = set()
            lbWallSet = set()
            lbGlassSet = newDocGlassSet - initDocGlassSet