Exemplo n.º 1
0
def deleteExistingPlans():
    if rs.IsLayer("60_PLANS"):
        #delete all sublayers
        levelLayers = rs.LayerChildren("60_PLANS")
        for levelLayer in levelLayers:
            childLayers = rs.LayerChildren(levelLayer)
            for childLayer in childLayers:
                objects = rs.ObjectsByLayer(childLayer)
                rs.DeleteObjects(objects)
                rs.DeleteLayer(childLayer)
            rs.DeleteLayer(levelLayer)
    else:
        return
Exemplo n.º 2
0
def makePlan():
    """
    make2d from above.
    input: list of layers to make2d
    returns: None
    """
    objs = rs.ObjectsByGroup("Below")
    
    #Make2d
    rs.SelectObjects(objs)
    rs.Command("-_make2d _D _U _Enter")
    projLines = rs.GetObjects("", preselect = True)
    
    #Get make2d root layer
    make2dRootRaw = rs.ObjectLayer(projLines[0])
    make2dRoot = make2dRootRaw.split("::")[0]
    
    #Rename make2d layers
    root  = rs.AddLayer("60_PLANS")
    roofLay = rs.AddLayer("Roof", parent = root)
    for projLine in projLines:
        linesLayer = rs.ObjectLayer(projLine)
        linesColor = rs.ObjectColor(projLine)
        linesLayerName = rs.LayerName(linesLayer, fullpath = False)
        newLayers = rs.AddLayer(linesLayerName, parent = roofLay, color = linesColor)
        rs.ObjectLayer(projLine,newLayers)
        rs.ObjectColor(projLine, (200,200,200))
    
    #Delete make2d Layers
    rs.DeleteLayer(make2dRoot)
    return
Exemplo n.º 3
0
def select_quad_mesh_polyedge(mesh):
    """Select quad mesh polyedge. Selecting one edge is equivalent to selecting one polyedge.

	Parameters
	----------
	mesh : QuadMesh
		The quad mesh.

	Returns
	-------
	list
		The list of polyedge vertices.
	"""

    artist = rhino_artist.MeshArtist(mesh, layer='mesh_artist')
    artist.clear_layer()
    artist.draw_edgelabels()
    artist.redraw()

    edge = rhino_helper.mesh_select_edge(mesh)

    artist.clear_layer()
    artist.redraw()
    rs.DeleteLayer('mesh_artist')

    return mesh.polyedge(*edge)
Exemplo n.º 4
0
def add_handle_artist(mesh):
    """Select two mesh faces and add handle.

	Parameters
	----------
	mesh : Mesh
		The mesh.

	Returns
	-------
	fkeys
		The new face keys from the handle.

	"""

    artist = rhino_artist.MeshArtist(mesh, layer='mesh_artist')
    artist.clear_layer()

    artist.draw_facelabels()
    artist.redraw()
    fkey_1 = rhino_helper.mesh_select_face(mesh, message='fkey_1')
    if fkey_1 is not None:
        fkey_2 = rhino_helper.mesh_select_face(mesh, message='fkey_2')
        if fkey_2 is not None:
            fkeys = add_handle(mesh, fkey_1, fkey_2)

        else:
            fkeys = []
    else:
        fkeys = []

    artist.clear()
    rs.DeleteLayer('mesh_artist')

    return fkeys
Exemplo n.º 5
0
def Export():
    count = 0
    folder = ChooseFolderPath()
    layer_names = rs.LayerNames()
    newDefaultLayer = 'NewDefault'
    rs.AddLayer(newDefaultLayer)
    rs.CurrentLayer(newDefaultLayer)

    for l in layer_names:
        if l != newDefaultLayer:
            for t in layer_names:
                if rs.IsLayer(l):
                        if l != newDefaultLayer:
                            rs.LayerVisible(t, False)
                else:
                    print "The layer does not exist."
            rs.LayerVisible(l, True)
            if rs.CurrentLayer() == l:
                break
            """answer = rs.MessageBox("Continue?", 1 | 32)
            if answer is 2: break
            rs.Sleep(1000)"""
            Render(folder, count)
            count += 1
            rs.LayerVisible(l, False)
    for l in layer_names:
        if l != newDefaultLayer:
            rs.LayerVisible(l, False)
            rs.CurrentLayer(l)
    rs.DeleteLayer(newDefaultLayer)
Exemplo n.º 6
0
def select_mesh_polyedge(mesh):
    """Select mesh polyedge.

	Parameters
	----------
	mesh : Mesh
		The mesh.

	Returns
	-------
	polyedge : list
		The list of polyedge vertices.
	"""

    # add layer
    artist = rhino_artist.MeshArtist(mesh, layer='mesh_artist')
    artist.clear_layer()

    # collect polyedge vertices
    polyedge = []
    lines = []
    while True:

        # define candidate vertices for polyedge
        if len(polyedge) == 0:
            vkey_candidates = mesh.vertices()
        else:
            vkey_candidates = mesh.vertex_neighbors(polyedge[-1])

        # get vertex among candidates
        artist.draw_vertexlabels(
            text={key: str(key)
                  for key in vkey_candidates})
        artist.redraw()

        vkey = rhino_helper.mesh_select_vertex(mesh, message='vertex')

        artist.clear_layer()
        artist.redraw()

        # stop if no vertex is added
        if vkey is None:
            break

        # add vertex to polyedge
        polyedge.append(vkey)

        if len(polyedge) > 1:
            u = mesh.vertex_coordinates(polyedge[-2])
            v = mesh.vertex_coordinates(polyedge[-1])
            guid = rs.AddLine(u, v)
            rs.ObjectColor(guid, [255, 255, 0])
            lines.append(guid)

    rs.DeleteLayer('mesh_artist')
    rs.DeleteObjects(lines)

    return polyedge
Exemplo n.º 7
0
def editing_geometry_moving(coarse_pseudo_quad_mesh):
    """Edit the geometry of a pattern with moving.

    Parameters
    ----------
    coarse_pseudo_quad_mesh : CoarsePseudoQuadMesh
            The pattern to edit.

    """

    mesh_to_modify = rs.GetString('mesh to modify?',
                                  strings=[
                                      'coarse_pseudo_quad_mesh',
                                      'pseudo_quad_mesh', 'polygonal_mesh'
                                  ])
    if mesh_to_modify == 'coarse_pseudo_quad_mesh':
        mesh = coarse_pseudo_quad_mesh
    elif mesh_to_modify == 'pseudo_quad_mesh':
        mesh = coarse_pseudo_quad_mesh.get_quad_mesh()
    elif mesh_to_modify == 'polygonal_mesh':
        mesh = coarse_pseudo_quad_mesh.get_polygonal_mesh()
    else:
        return 0

    while True:

        rs.EnableRedraw(False)
        artist = rhino_artist.MeshArtist(mesh)
        guid = artist.draw_mesh()
        rs.EnableRedraw(True)

        artist = rhino_artist.MeshArtist(mesh, layer='mesh_artist')
        artist.clear_layer()
        artist.draw_vertexlabels(
            text={key: str(key)
                  for key in mesh.vertices()})
        artist.redraw()
        vkeys = rhino_helper.mesh_select_vertices(mesh,
                                                  message='vertices to move')
        artist.clear_layer()
        artist.redraw()
        rs.DeleteLayer('mesh_artist')

        if vkeys == []:
            rs.DeleteObject(guid)
            break

        rhino_helper.mesh_move_vertices(mesh, vkeys)
        rs.DeleteObject(guid)

    if mesh_to_modify == 'coarse_pseudo_quad_mesh':
        coarse_pseudo_quad_mesh = mesh
    elif mesh_to_modify == 'pseudo_quad_mesh':
        coarse_pseudo_quad_mesh.set_quad_mesh(mesh)
        coarse_pseudo_quad_mesh.set_polygonal_mesh(mesh.copy())
    elif mesh_to_modify == 'polygonal_mesh':
        coarse_pseudo_quad_mesh.set_polygonal_mesh(mesh)
Exemplo n.º 8
0
def select_mesh_polyedge(mesh):
    """Select polyedge vertices via artist.

	Parameters
	----------
	mesh : Mesh
		The mesh.

	Returns
	-------
	polyedge : list
		The list of polyedge vertices.
	"""

    # add layer
    artist = rhino_artist.MeshArtist(mesh, layer='mesh_artist')
    artist.clear_layer()

    # collect polyedge vertices
    polyedge = []
    count = mesh.number_of_vertices() + 1
    while count > 0:
        count -= 1

        # define candidate vertices ofr polyedge
        if len(polyedge) == 0:
            vkey_candidates = mesh.vertices()
        else:
            vkey_candidates = mesh.vertex_neighbors(polyedge[-1])

        # get vertex among candidates
        artist.draw_vertexlabels(text={
            key: str(key)
            for key in vkey_candidates if key not in polyedge[1:]
        })
        artist.redraw()
        vkey = rhino_helper.mesh_select_vertex(mesh, message='vertex')

        artist.clear_layer()
        artist.redraw()

        # stop if no vertex is added
        if vkey is None:
            break

        # add vertex to polyedge
        polyedge.append(vkey)

        # stop if polyedge is closed
        if len(polyedge) != 1 and vkey == polyedge[0]:
            break

    rs.DeleteLayer('mesh_artist')

    return polyedge
Exemplo n.º 9
0
 def _clear_layers(cls):  ##  clear only user layers
     """Deletes all layers. Leaves Default layer
     """
     default_layer_name = s.Settings.default_layer_name
     layer_names = rs.LayerNames()
     if not default_layer_name in layer_names:
         rs.AddLayer(default_layer_name)
     rs.CurrentLayer(default_layer_name)
     for layer_name in layer_names:
         if not layer_name == default_layer_name:
             value = rs.DeleteLayer(layer_name)
             print('Cleared layer %s: %s' % (layer_name, value))
Exemplo n.º 10
0
def RemoveMasterRootLayer(masterRoot):
    rs.EnableRedraw(False)

    subRoots = []
    allLayers = rs.LayerNames()
    for each in allLayers:
        if rs.ParentLayer(each) == masterRoot:
            subRoots.append(each)

    for eachLayer in subRoots:
        rs.ParentLayer(eachLayer, '')
    rs.DeleteLayer(masterRoot)
    rs.EnableRedraw(True)
Exemplo n.º 11
0
def mergeLayers(layA, layB):
    """
    layA is kept, layB is deleted
    input: (layA, layB) each is a layer, the top parent in a tree to merge with another.
    returns: None
    """
    rs.EnableRedraw(False)
    Alayers = rs.LayerChildren(layA)
    Blayers = rs.LayerChildren(layB)
    AlayersShort = []
    BlayersShort = []
    for Alayer in Alayers:
        AlayersShort.append(rs.LayerName(Alayer, False))
    for Blayer in Blayers:
        BlayersShort.append(rs.LayerName(Blayer, False))
    uniqueLayers = list(set(BlayersShort) - set(AlayersShort))
    #move unique layers
    for uniqueLayer in uniqueLayers:
        rs.ParentLayer(uniqueLayer, layA)

    #get duplicate name layers
    duppedLayers = list(set(BlayersShort) - set(uniqueLayers))

    #move objects to layA twin
    for duppedLayer in duppedLayers:
        newParent = layA + "::" + duppedLayer
        duppedObjs = rs.ObjectsByLayer(layB + "::" + duppedLayer)
        for duppedObj in duppedObjs:
            rs.ObjectLayer(duppedObj, newParent)
        #if it has children, recursively move them
        if rs.LayerChildCount(layB + "::" + duppedLayer) > 0:
            mergeLayers(layA + "::" + duppedLayer, layB + "::" + duppedLayer)
        else:
            rs.DeleteLayer(layB + "::" + duppedLayer)
            rs.DeleteLayer(layB)
    rs.EnableRedraw(True)
    return None
Exemplo n.º 12
0
def new(units="Meter"):

    # create new file
    successNew = rs.Command("-_New None")

    # change units
    successProp = rs.Command("-_DocumentProperties Units UnitSystem " + units +
                             " No Enter Enter")

    # delete all but one layer
    layerCt = rs.LayerCount()
    for i in range(layerCt - 1):
        layer = rs.CurrentLayer()
        rs.DeleteLayer(layer)

    return successNew and successProp
Exemplo n.º 13
0
def delete_layers(layers):
    """Delete layers and all contained objects.

    Parameters
    ----------
    layers : dict
        A dictionary of layers with the keys representing layer names,
        and the values also dictionaries defining optional nested layers.

    Examples
    --------
    .. code-block:: python

        layers = {'COMPAS': {'layers': {'Datastructures': {'layers': {'Mesh': {}, 'Network': {}}}}}}

        create_layers(layers)

        delete_layers(['COMPAS::Datastructures::Network'])
        delete_layers({'COMPAS': {'layers': {'Datastructures': {'layers': {'Mesh': {}}}}}})

    """
    to_delete = []

    def recurse(layers, parent=None):
        for name in layers:
            if not name:
                continue
            fullname = name
            if parent:
                fullname = parent + '::' + name
            try:
                attr = layers[name]
            except TypeError:
                attr = {}
            if 'layers' in attr:
                recurse(attr['layers'], fullname)
            to_delete.append(fullname)

    rs.EnableRedraw(False)
    recurse(layers)
    for layer in to_delete:
        if rs.IsLayer(layer):
            rs.DeleteLayer(layer)
    rs.EnableRedraw(True)
Exemplo n.º 14
0
	def ConfirmLayer():
		print("■start confirmlayer■")
		sc.doc = Rhino.RhinoDoc.ActiveDoc
		layers = rs.LayerNames()
		if "Make2D" in layers:
			dellayer = rs.MessageBox("既に存在する'Make2D'レイヤーは削除されます 問題ないですか?", 4, "レイヤーの確認")
			if dellayer == int(6):# Massageboxのはいは6で返却される
				rs.DeleteLayer("Make2D")# 作図中にMake2Dレイヤーが作成されるため、前もって削除
				layer = True
				print("deleted layer")
			else:
				rs.MessageBox("作図をキャンセルしました")
				layer = False
				print("canceled writing")
		else:
			layer = True
			print("no make2d layer")
		sc.doc = ghdoc
		print("■end confirmfolder■")
		return layer# "Make2D"レイヤーが存在しないor削除するときはTrueを返却
Exemplo n.º 15
0
def ExportAsSKP(objs, newFolder, newFolderName):
    tempLayers = []
    
    copiedObjs = []
    
    rs.StatusBarProgressMeterShow('Exporting to SKP', 0, len(objs))
    
    for i, obj in enumerate(objs):
        tempCopy = rs.CopyObject(obj)
        rs.ObjectLayer(tempCopy, rs.ObjectLayer(obj))
        copiedObjs.append(tempCopy)
        rs.StatusBarProgressMeterUpdate(i)
    
    for obj in copiedObjs:
        shortName = rs.LayerName(rs.ObjectLayer(obj), False)
        layerName = newFolderName + '_' + shortName
        if rs.IsLayer(layerName):
            rs.ObjectLayer(obj, layerName)
        else:
            matIndex = rs.LayerMaterialIndex(rs.ObjectLayer(obj))
            newLayer = rs.AddLayer(layerName, rs.LayerColor(rs.ObjectLayer(obj)))
            rs.LayerMaterialIndex(newLayer, matIndex)
            tempLayers.append(newLayer)
            rs.ObjectLayer(obj, newLayer)
    rs.StatusBarProgressMeterHide()
    
    try:
        filepath = os.path.join(newFolder,newFolderName + '.skp')
        rs.SelectObjects(copiedObjs)
        rs.Command('-_Export ' + '"' + filepath + '"' + ' s SketchUp2015 Enter ', False)
        
        #CLEANUP
        rs.UnselectAllObjects() 
        try:
            rs.DeleteObjects(copiedObjs)
        except:
            rs.DeleteObject(copiedObjs)
        for layer in tempLayers:
            rs.DeleteLayer(layer)
    except:
        print "export failed"
Exemplo n.º 16
0
def makeRoofPlan(layers):
    """
    make2d from above.
    input: list of layers to make2d
    returns: None
    """
    rs.EnableRedraw(False)
    #Get the objects
    objsRaw = []
    for layer in layers:
        objsRaw.append(rs.ObjectsByLayer(layer))
    objs = [item for sublist in objsRaw for item in sublist]

    #Make2d
    rs.SelectObjects(objs)
    rs.Command("-_make2d _D _U _Enter")
    projLines = rs.GetObjects("", preselect=True)

    #Get make2d root layer
    make2dRootRaw = rs.ObjectLayer(projLines[0])
    make2dRoot = make2dRootRaw.split("::")[0]

    #Rename make2d layers
    root = rs.AddLayer("60_PLANS")
    roofLay = rs.AddLayer("Roof", parent=root)
    for projLine in projLines:
        linesLayer = rs.ObjectLayer(projLine)
        linesColor = rs.ObjectColor(projLine)
        linesLayerName = rs.LayerName(linesLayer, fullpath=False)
        newLayers = rs.AddLayer(linesLayerName,
                                parent=roofLay,
                                color=linesColor)
        rs.ObjectLayer(projLine, newLayers)

    #Delete make2d Layers
    rs.DeleteLayer(make2dRoot)
    rs.EnableRedraw(True)
    return
Exemplo n.º 17
0
def delete_layers(layers):
    to_delete = []

    def recurse(layers, parent=None):
        for name in layers:
            if not name:
                continue
            fullname = name
            if parent:
                fullname = parent + '::' + name
            try:
                attr = layers[name]
            except TypeError:
                attr = {}
            if 'layers' in attr:
                recurse(attr['layers'], fullname)
            to_delete.append(fullname)
    rs.EnableRedraw(False)
    recurse(layers)
    for layer in to_delete:
        if rs.IsLayer(layer):
            rs.DeleteLayer(layer)
    rs.EnableRedraw(True)
Exemplo n.º 18
0
def editing(mesh):
    """Edit a mesh.

    Parameters
    ----------
    planar_mesh : Mesh
        A planar mesh to remap on the surface.
    spatial_surface : Rhino surface guid
        A spatial Rhino surface on which to remap the mesh.

    Returns
    -------
    mesh: Mesh
        The remapped mesh.

    Raises
    ------
    -

    """

    # temporary layer for visualisation
    rs.AddLayer('temp')

    # grammar rules
    rules_subdivide = [
        'simple_split', 'double_split', 'flat_corner_2', 'flat_corner_3',
        'flat_corner_33', 'split_35', 'split_35_diag', 'split_26'
    ]
    rules_poles = [
        'face_pole', 'edge_pole', 'vertex_pole', 'insert_pole',
        'insert_partial_pole'
    ]
    rules_strips = ['face_strip_collapse', 'face_strip_insert']
    rules_genus = [
        'add_opening', 'close_opening', 'add_handle', 'close_handle',
        'close_handle_2'
    ]
    rules_others = [
        'singular_boundary_1', 'singular_boundary_2',
        'singular_boundary_minus_1', 'rotate_vertex'
    ]
    rules_geometry = ['move_vertices', 'project_on_surface']

    rule_cluster = [
        'subdivide', 'poles', 'strips', 'genus', 'others', 'geometry',
        'propagate'
    ]

    clusters = {
        'subdivide': rules_subdivide,
        'poles': rules_poles,
        'strips': rules_strips,
        'genus': rules_genus,
        'others': rules_others,
        'geometry': rules_geometry
    }
    # regular vertices of initial mesh
    regular_vertices = list(mesh.vertices())

    # first visualisation
    rs.EnableRedraw(False)
    copy_mesh = mesh.to_mesh()
    edges = [
        rs.AddLine(copy_mesh.vertex_coordinates(u),
                   copy_mesh.vertex_coordinates(v))
        for u, v in copy_mesh.edges() if u != v and
        geometric_key([float(xyz)
                       for xyz in copy_mesh.vertex_coordinates(u)]) !=
        geometric_key([float(xyz) for xyz in copy_mesh.vertex_coordinates(v)])
    ]
    rs.ObjectLayer(edges, 'temp')
    rs.EnableRedraw(True)

    # start editing
    count = 1000
    while count > 0:
        count -= 1

        #ask for rule
        cluster = rs.GetString('rule cluster?', strings=rule_cluster)
        rs.EnableRedraw(False)

        # intermediary propagation
        if cluster == 'propagate':
            mesh_propagation(mesh, regular_vertices)
            for vkey in mesh.vertices():
                # update regualr vertices
                regular = True
                for fkey in mesh.vertex_faces(vkey):
                    if len(mesh.face_vertices(fkey)) > 4:
                        regular = False
                        break
                if regular and vkey not in regular_vertices:
                    regular_vertices.append(vkey)

        # apply editing rule
        elif cluster in rule_cluster:
            if cluster in clusters.keys():
                rule = rs.GetString('rule?', strings=clusters[cluster])
                apply_rule(mesh, rule)

        # if nothing, check if mesh is valid after a final propagation
        else:
            # propapgate
            mesh_propagation(mesh, regular_vertices)
            rs.DeleteObjects(edges)
            rs.DeleteLayer('temp')
            break

        # update regular vertices
        for vkey in mesh.vertices():
            regular = True
            for fkey in mesh.vertex_faces(vkey):
                if len(mesh.face_vertices(fkey)) != 4:
                    regular = False
                    break
            if regular and vkey not in regular_vertices:
                regular_vertices.append(vkey)

        # update edges
        rs.EnableRedraw(False)
        rs.DeleteObjects(edges)
        copy_mesh = mesh.to_mesh()
        edges = [
            rs.AddLine(copy_mesh.vertex_coordinates(u),
                       copy_mesh.vertex_coordinates(v))
            for u, v in copy_mesh.edges() if u != v and geometric_key(
                [float(xyz)
                 for xyz in copy_mesh.vertex_coordinates(u)]) != geometric_key(
                     [float(xyz) for xyz in copy_mesh.vertex_coordinates(v)])
        ]
        rs.ObjectLayer(edges, 'temp')
        rs.EnableRedraw(True)

    return mesh
Exemplo n.º 19
0
    )

    #
    # add sublayer for the new toolpath
    #
    nrOfPaths = rs.LayerChildCount("Toolpaths")
    pathLayerName = "path%03d" % nrOfPaths
    rs.AddLayer(name="Toolpaths::" + pathLayerName, color=[255, 0, 0])
    rs.CurrentLayer(pathLayerName)

    #
    # generate the toolpath
    #
    rc = prepareToolpaths(pathLayerName, objects, mode, totalDepth, passDepth,
                          toolDiameter)

    #
    # remove toolpath layer if the operation failed
    #
    if rc == False:
        print "Removing layer"
        rs.CurrentLayer("Toolpaths")
        rs.DeleteLayer("Toolpaths::" + pathLayerName)

    #
    # enable Layer change event listener
    #
    func = layerChangeEvent
    scriptcontext.sticky["MyLayerChangeEvent"] = func
    Rhino.RhinoDoc.LayerTableEvent += func
Exemplo n.º 20
0
def importTEN_CAD():
    savePath0 = rs.OpenFileName("Open", "Autocad (*.dwg)|*.dwg||")
    items = [["Units", "Meters", "Millimeters"]]
    defaults = [False]
    CADinMilli = rs.GetBoolean("Is that CAD file in meters or mm?", items,
                               defaults)[0]

    explodeBlockBoo = True

    if savePath0 is None:
        return
    rs.EnableRedraw(False)

    #setup the layers
    rs.AddLayer("7_REF")
    rs.AddLayer("CAD", parent="7_REF")

    fileNameExt = savePath0.split('\\')[-1]
    fileName = fileNameExt.split('.')[0]
    savePath1 = '"' + savePath0 + '"'

    #create layer name
    now = datetime.date.today()
    dateList = []
    if len(str(now.month)) > 1:
        month = str(now.month)
    else:
        month = "0" + str(now.month)
    if len(str(now.day)) > 1:
        day = str(now.day)
    else:
        day = "0" + str(now.day)
    time = str(now.year) + month + day
    layerName = time + "_" + fileName + "_01"
    children = rs.LayerChildren("7_REF::CAD")
    finalNums = []
    for child in children:
        num = rs.LayerName(child, fullpath=False).split("_")[-1]
        try:
            finalNums.append(int(num))
        except:
            finalNums.append(0)
    finalNums.sort()
    if rs.IsLayer("7_REF::CAD::" + layerName):
        num = int(finalNums[-1]) + 1
        if len(str(num)) < 2:
            finalNum = "0" + str(num)
        else:
            finalNum = str(num)
        layerName = time + "_" + fileName + "_" + finalNum
    par = rs.AddLayer("7_REF")
    cat = rs.AddLayer("CAD", parent=par)
    element = rs.AddLayer(layerName, parent=cat)
    rs.CurrentLayer(element)

    #get intial list of all layers in the file
    currentLayers = rs.LayerNames()

    rs.Command('_-Import ' + savePath1 + ' _Enter')

    #get new layers added
    endLayersNames = rs.LayerNames()
    #newLayers = [item for item in currentLayers if item not in endLayersNames]
    newLayers = diff(endLayersNames, currentLayers)
    print newLayers

    for layer in newLayers:
        rs.ParentLayer(layer, element)
        objects = rs.ObjectsByLayer(layer)
        if rs.IsLayerEmpty(layer):
            rs.DeleteLayer(layer)
        else:
            for obj in objects:
                if rs.IsDimension(obj):
                    rs.DeleteObject(obj)
                elif rs.IsHatch(obj):
                    rs.DeleteObject(obj)

    #Get all the imported geometry
    allObjects = []
    finalLayers = rs.LayerChildren(rs.CurrentLayer())
    for finalLayer in finalLayers:
        allObjects.append(rs.ObjectsByLayer(finalLayer))
    finalAllObjects = [item for sublist in allObjects for item in sublist]

    #Format Coordinate
    try:
        rawCoordinate = rs.GetDocumentData("Project Info",
                                           "CAD coordinate (X,Y,Z)")
    except:
        print "No CAD Coordinate specified in the Project Info"
        rawCoordinate = (0, 0, 0)
    coordinate = rawCoordinate.split(",")
    print "Aa"

    try:
        for i in range(0, 3):
            coordinate[i] = float(coordinate[i])
    except:
        coordinate = None
    if coordinate is None:
        print "CAD coordinate has an error"

    else:  #move all objects
        negVec = rs.VectorReverse(coordinate)
        rs.MoveObjects(finalAllObjects, negVec)

    if CADinMilli:
        rs.ScaleObjects(finalAllObjects, [0, 0, 0], [.001, .001, .001])

    importGroup = rs.AddGroup(str(layerName))

    rs.AddObjectsToGroup(finalAllObjects, importGroup)

    rs.ZoomSelected()
    print "Import EXECUTED"
    rs.EnableRedraw(True)
    return None
Exemplo n.º 21
0
# Origin https://discourse.mcneel.com/t/the-best-way-to-identify-layers-without-objects-to-delete/7690/4

import rhinoscriptsyntax as rs
layers = rs.LayerNames()
for layer in layers:
    if rs.IsLayerEmpty(layer): rs.DeleteLayer(layer)
Exemplo n.º 22
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                                          
Exemplo n.º 23
0
def customed_constraints(mesh, constraints, surface_boundaries, surface_constraint):

    count = 1000
    while count > 0:
        count -= 1


        all_curve_constraints = []
        for vkey, constraint in constraints.items():
            constraint_type, constraint_object = constraint
            if constraint_type == 'curve' and constraint_object not in all_curve_constraints:
                all_curve_constraints.append(constraint_object)
        n  = len(all_curve_constraints)
        rs.EnableRedraw(False)
        dots = []
        for i, crv in enumerate(all_curve_constraints):
            dot = rs.AddTextDot(i, rs.CurveMidPoint(crv))
            dots.append(dot)
            rs.ObjectColor(dot, [0, float(i) / n * 255, (n - float(i)) / n * 255])
        rs.EnableRedraw(True)

        # display  vertices to select with colour code
        vertex_colors = {}
        for vkey, constraint in constraints.items():
            contraint_type, constraint_object = constraint
            if contraint_type == 'point':
                rgb = [255, 0, 255]
            elif contraint_type == 'curve':
                i = all_curve_constraints.index(constraint_object)
                rgb = [0, float(i) / n * 255, (n - float(i)) / n * 255]
            elif contraint_type == 'surface':
                rgb = [255, 255, 255]
            else:
                rgb = [0, 0, 0]
            vertex_colors[vkey] = rgb

        artist = rhino.artists.MeshArtist(mesh, layer='mesh_artist')
        artist.clear_layer()
        
        artist.draw_vertices(color = vertex_colors)
        artist.redraw()
        vkeys = rhino.helpers.mesh_select_vertices(mesh, message = 'change vertex constraints?')
        artist.clear_layer()
        artist.redraw()
        
        rs.DeleteLayer('mesh_artist')

        if vkeys == []:
            rs.DeleteObjects(dots)
            return constraints

        rs.EnableRedraw(True)

        constraint_types = ['point', 'curve', 'surface', 'none', 'move']
        new_constraint_type = rs.GetString('constraint type?', strings = constraint_types)

        # set new point constraint
        if new_constraint_type == 'point':
            for vkey in vkeys:
                constraints[vkey] = ['point', mesh.vertex_coordinates(vkey)]

        # set new curve constraint
        elif new_constraint_type == 'curve':
            curve_constraint = rs.GetObject('curve constraint?', filter = 4)
            for vkey in vkeys:
                constraints[vkey] = ['curve', curve_constraint]

        # set new surface constraint
        elif new_constraint_type == 'surface':
            for vkey in vkeys:
                constraints[vkey] = ['surface', surface_constraint]

        # remove constraint
        elif new_constraint_type == 'none':
            for vkey in vkeys:
                constraints[vkey] = ['none', None]

        # move nodes
        elif new_constraint_type == 'move':
            x0, y0, z0 = rs.GetPoint('from...')
            x1, y1, z1 = rs.GetPoint('...to')
            for vkey in vkeys:
                attr = mesh.vertex[vkey]
                attr['x'] += x1 - x0
                attr['y'] += y1 - y0
                attr['z'] += z1 - z0
            # udpdate drawn mesh
            layer = 'pattern_topology'
            mesh_guid = rs.ObjectsByLayer(layer)[0]
            rs.DeleteObject(mesh_guid)
            mesh_guid = draw_mesh(mesh)
            rs.ObjectLayer(mesh_guid, layer)
            rs.EnableRedraw(True)
            rs.EnableRedraw(False)

        rs.DeleteObjects(dots)

        rs.EnableRedraw(False)

    return constraints
Exemplo n.º 24
0
def Main():
    
    if not LANG: return
        
    if not rs.IsLayer(OFFSET_LAYER):
        rs.AddLayer(OFFSET_LAYER)
    else:
        rs.DeleteObjects(rs.ObjectsByLayer(OFFSET_LAYER))
    if not rs.IsLayer(TRASH_LAYER):
        rs.AddLayer(TRASH_LAYER)
    else:
        rs.DeleteObjects(rs.ObjectsByLayer(TRASH_LAYER))

    original_layer = rs.CurrentLayer()
    
    machining_settings = False
    general_settings = False
    user_data = False
    

#     if rs.IsAlias(alias_name):
#         if rs.AliasMacro(alias_name) != "-_RunPythonScript (\"%s\")" % os.path.realpath(__file__):
#             if rs.MessageBox("Rhino tiene registrado esta ubicacion en el comando de %s:\n\n%s\n\nDeseas cambiarla por esta?\n\n%s\n" % (alias_name,rs.AliasMacro(alias_name),os.path.realpath(__file__)) , 4 | 32) == 6:
#                 rs.DeleteAlias(alias_name)
#                 rs.AddAlias(alias_name,"-_RunPythonScript (\"%s\")" % os.path.realpath(__file__))
#             else:
#                 pass
#     else:
#         if rs.MessageBox("Vincular el comando \"%s\" a este archivo?\n\n%s\n\nPodras ejecutar directamente el plugin escribiendo \"%s\" en la consola." %  (alias_name,os.path.realpath(__file__),alias_name) , 4 | 32) == 6:
#             rs.AddAlias(alias_name,"-_RunPythonScript (\"%s\")" % os.path.realpath(__file__))
#         else:
#             pass

    try:
        machining_settings =  eval(rs.GetDocumentData(REGISTRY_SECTION,"machining_settings"))
   
    except:
        pass
    try:
        general_settings =  eval(rs.GetDocumentData(REGISTRY_SECTION,"general_settings"))
    except:
        pass
    try:
        
        f = open(SETTINGS_FILE,"r")
        r = f.read()
        f.close()
        persistant = eval(r)        
        
        if machining_settings != False:
            machining_settings.update(persistant)
        else:
            machining_settings = persistant
    except:
        pass
    try:
        user_data =  eval(rs.GetDocumentData(REGISTRY_SECTION,"user_data"))
        if not user_data["save_path"]:
            user_data["save_path"] = rs.DocumentPath().replace(".3dm","_gcode.txt") if rs.DocumentPath() else False
    except:
        pass
    
    if user_data and user_data["selected_preset"] not in machining_settings:
        user_data["selected_preset"] = False
   
    print TXT["init"]
    
    ui = SettingsControl(general_settings,machining_settings,user_data)
    Rhino.UI.Dialogs.ShowSemiModal(ui.form)

    temporal = {}
    persistant = {}
    
    for name in ui.machining_settings:

        if ui.machining_settings[name]["persistant"]:
            temporal[name] = ui.machining_settings[name]
        else:
            persistant[name] = ui.machining_settings[name]
    
    f = open(SETTINGS_FILE,"w")
    f.write(str(persistant))
    f.close()
    
    rs.SetDocumentData(REGISTRY_SECTION,"machining_settings",str(temporal))
    rs.SetDocumentData(REGISTRY_SECTION,"general_settings",str(ui.general_settings))
    rs.SetDocumentData(REGISTRY_SECTION,"user_data",str(ui.user_data))

#     print "to registry...."
#     print "machining_settings",str(ui.machining_settings)
#     print "general_settings",str(ui.general_settings)
#     print "user_data",str(ui.user_data)
#     print "temp",str([i for i in temporal])
#     print "persistant",str([i for i in persistant])
    
    ui.code_thread = False
    rs.CurrentLayer(original_layer)
    rs.DeleteObjects(rs.ObjectsByLayer(OFFSET_LAYER))
    rs.DeleteObjects(rs.ObjectsByLayer(TRASH_LAYER))
    rs.DeleteLayer(OFFSET_LAYER)
    rs.DeleteLayer(TRASH_LAYER)
    
    print TXT["bye"]
Exemplo n.º 25
0
def editing_geometry_smoothing(coarse_pseudo_quad_mesh):
    """Edit the geometry of a pattern with smoothing.

    Parameters
    ----------
    coarse_pseudo_quad_mesh : CoarsePseudoQuadMesh
            The pattern to edit.

    """

    mesh_to_smooth = rs.GetString('mesh to smooth?',
                                  strings=[
                                      'coarse_pseudo_quad_mesh',
                                      'pseudo_quad_mesh', 'polygonal_mesh'
                                  ])
    if mesh_to_smooth == 'coarse_pseudo_quad_mesh':
        mesh = coarse_pseudo_quad_mesh
    elif mesh_to_smooth == 'pseudo_quad_mesh':
        mesh = coarse_pseudo_quad_mesh.get_quad_mesh
    elif mesh_to_smooth == 'polygonal_mesh':
        mesh = coarse_pseudo_quad_mesh.get_polygonal_mesh()
    else:
        return 0

    settings = {'iterations': 50, 'damping': .5, 'constraints': {}}

    while True:

        rs.EnableRedraw(False)
        artist = rhino_artist.MeshArtist(mesh)
        guid = artist.draw_mesh()
        rs.EnableRedraw(True)

        operation = rs.GetString(
            'edit smoothing settings?',
            strings=['smooth', 'iterations', 'damping', 'constraints', 'exit'])

        if operation is None or operation == 'exit':
            if type(guid) == list:
                rs.DeleteObjects(guid)
            else:
                rs.DeleteObject(guid)
            break

        elif operation == 'iterations':
            settings[operation] = rs.GetInteger('iterations',
                                                number=settings[operation],
                                                minimum=0)

        elif operation == 'damping':
            settings[operation] = rs.GetReal('damping',
                                             number=settings[operation],
                                             minimum=0.,
                                             maximum=1.)

        elif operation == 'constraints':
            count = 100
            while count:
                count -= 1
                guids = display_smoothing_constraints(mesh,
                                                      settings[operation])
                constraint_type = rs.GetString('type of constraints?',
                                               strings=[
                                                   'automated_from_surface',
                                                   'automated_from_objects',
                                                   'customised', 'reset',
                                                   'exit'
                                               ])
                rs.DeleteObjects(guids)
                if constraint_type == 'automated_from_surface':
                    settings[
                        operation] = automated_smoothing_surface_constraints(
                            mesh,
                            RhinoSurface(
                                rs.GetObject('surface constraints', filter=8)))
                elif constraint_type == 'automated_from_objects':
                    object_constraints = rs.GetObjects('object constraints')
                    point_constraints = [
                        obj for obj in object_constraints
                        if rs.ObjectType(obj) == 1
                    ]
                    curve_constraints = [
                        obj for obj in object_constraints
                        if rs.ObjectType(obj) == 4
                    ]
                    surface_constraint = [
                        obj for obj in object_constraints
                        if rs.ObjectType(obj) == 8
                    ]
                    if len(surface_constraint) > 1:
                        print(
                            'More than one surface constraint! Only the first one is taken into account.'
                        )
                    if len(surface_constraint) == 0:
                        surface_constraint = None
                    else:
                        surface_constraint = surface_constraint[0]
                    settings[operation] = automated_smoothing_constraints(
                        mesh, point_constraints, curve_constraints,
                        surface_constraint)
                elif constraint_type == 'customised':
                    settings[operation] = customized_smoothing_constraints(
                        mesh, settings[operation])
                elif constraint_type == 'reset':
                    artist = rhino_artist.MeshArtist(mesh, layer='mesh_artist')
                    artist.clear_layer()
                    artist.draw_vertices()
                    artist.redraw()
                    vkeys = rhino_helper.mesh_select_vertices(
                        mesh, message='vertices')
                    if vkeys is None:
                        vkeys = list(mesh.vertices())
                    artist.clear_layer()
                    artist.redraw()
                    rs.DeleteLayer('mesh_artist')
                    for vkey in vkeys:
                        if vkey in settings[operation]:
                            del settings[operation][vkey]
                else:
                    break

        elif operation == 'smooth':
            constrained_smoothing(mesh,
                                  kmax=settings['iterations'],
                                  damping=settings['damping'],
                                  constraints=settings['constraints'],
                                  algorithm='area')

        if type(guid) == list:
            rs.DeleteObjects(guid)
        else:
            rs.DeleteObject(guid)

    if mesh_to_smooth == 'coarse_pseudo_quad_mesh':
        coarse_pseudo_quad_mesh = mesh
    elif mesh_to_smooth == 'pseudo_quad_mesh':
        coarse_pseudo_quad_mesh.set_quad_mesh(mesh)
        coarse_pseudo_quad_mesh.set_polygonal_mesh(mesh.copy())
    elif mesh_to_smooth == 'polygonal_mesh':
        coarse_pseudo_quad_mesh.set_polygonal_mesh(mesh)
Exemplo n.º 26
0
import Rhino.Geometry as rg
import rhinoscriptsyntax as rs

# Clear canvas
rs.DeleteObjects(rs.AllObjects(select=True))

# Add relevant layers (if they don't exist)
layers = {
    'Structure': ['s_points', 's_lines', 's_areas'],
    'Strip A': ['CSA', 'MSA'],
    'Strip B': ['CSB', 'MSB']
}

for key in layers.keys():
    if rs.IsLayer(key):
        rs.DeleteLayer(key)
    rs.AddLayer(key)
    sublayers = layers[key]
    for sublayer in sublayers:
        rs.AddLayer(sublayer, parent=key)

# Change layer colors for strips (increase visibility)
rs.LayerColor('CSA', color=(255, 0, 0))
rs.LayerColor('CSB', color=(255, 0, 0))
rs.LayerColor('MSA', color=(0, 0, 255))
rs.LayerColor('MSB', color=(0, 0, 255))

# Load data
with open('data.json') as fh:
    data = json.load(fh)
Exemplo n.º 27
0
def exportToRenderSKP():
    #try:
    #Get Objects
    objs = rs.GetObjects("Select objects to export", preselect = True)
    if objs is None: return
    
    #Default Name
    if 'exportToRenderSKP-prevName' in sc.sticky:
        prevName = sc.sticky['exportToRenderSKP-prevName']
        defaultFilename = utils.UpdateString(prevName)
    else:
        defaultFilename = utils.GetDatePrefix() + '_OPTION_01'
    
    #Default Folder
    if 'exportToRenderSKP-path' in sc.sticky:
        defaultFolder = sc.sticky['exportToRenderSKP-path']
    elif utils.IsSavedInProjectFolder():
        origPath = rs.DocumentPath()
        path = os.path.normpath(origPath)
        pathParts = path.split(os.sep)
        projectFolder = os.path.join(pathParts[0],'\\' ,pathParts[1])
        referenceFolder = os.path.join(projectFolder, r'03 DRAWINGS\02 RENDERING\0_copy 3d  folder structure\Reference')
        if os.path.isdir(referenceFolder):
            print "Reference folder exists"
            defaultFolder = referenceFolder
        else:
            print "Reference folder not found"
            defaultFolder = rs.DocumentPath()
    else:
        defaultFolder = rs.DocumentPath()
    fileName = rs.SaveFileName("Export to render", "Sketchup 2015 (*.skp)|*.skp||", folder = defaultFolder, filename = defaultFilename)
    if fileName is None: return
    sc.sticky['exportToRenderSKP-prevName'] = os.path.splitext(fileName)[0]
    sc.sticky['exportToRenderSKP-path'] = os.path.dirname(fileName)
    
    tempLayers = []
    copiedObjs = []
    seperator = ' > '
    baseName = os.path.splitext(os.path.basename(fileName))[0]

    #Copy all objects to export
    rs.StatusBarProgressMeterShow('Exporting to SKP', 0, len(objs))
    for i, obj in enumerate(objs):
        tempCopy = rs.CopyObject(obj)
        if rs.IsBlockInstance(tempCopy):
            explodedObjs = list(rs.ExplodeBlockInstance(obj, True))
            copiedObjs += explodedObjs
        else:
            copiedObjs.append(tempCopy)
        rs.StatusBarProgressMeterUpdate(i)

    #Move all copies to a different layer
    for i, obj in enumerate(copiedObjs):
        layerFullName = rs.ObjectLayer(obj)
        shortName = layerFullName.replace('::', seperator)
        layerName = baseName + seperator + shortName
        if rs.IsLayer(layerName):
            rs.ObjectLayer(obj, layerName)
        else:
            matIndex = rs.LayerMaterialIndex(rs.ObjectLayer(obj))
            newLayer = rs.AddLayer(layerName, rs.LayerColor(rs.ObjectLayer(obj)))
            rs.LayerMaterialIndex(newLayer, matIndex)
            tempLayers.append(newLayer)
            rs.ObjectLayer(obj, newLayer)
    rs.StatusBarProgressMeterHide()

    try:
        rs.SelectObjects(copiedObjs)
        rs.Command('-_Export ' + '"' + fileName + '"' + ' s SketchUp2015 Enter ', False)

        #CLEANUP
        rs.UnselectAllObjects()
        try:
            rs.DeleteObjects(copiedObjs)
        except:
            rs.DeleteObject(copiedObjs)
        for layer in tempLayers:
            rs.DeleteLayer(layer)
    except:
        print "export failed"
    result = True
    #except:
    #    result = False
    try:
        pass
        #utils.SaveFunctionData('IO-Export to Render[SKP]', [fileName, baseName, os.path.getsize(fileName),len(objs), result])
    except:
        print "Failed to save function data"
    return result
Exemplo n.º 28
0
def translateLayer(layer):
    """
    translates from Rhino Name to CAD Name
    input: one layer
    returns: new layer name
    """
    rhinoLayerFilePath = "C:\\Users\\Tim\\Desktop\\temp\\RhinoLayersV2.csv"
    #Read the CSV
    file = open(rhinoLayerFilePath, "r")
    contents = file.readlines()
    file.close()

    #Variables
    CategoryCol = 1
    RhinoLayerCol = 2
    CADNameCol = 9
    CADColorCol = 10
    CADLineweightCol = 11
    found = False
    layerShort = rs.LayerName(layer, False)
    newLayerName = ""

    #Check the CSV
    for row in contents:
        rowParts = row.split(",")
        if row.split(",")[RhinoLayerCol] == str(
                layerShort):  #if layer name exists in CSV

            CADName = row.split(",")[CADNameCol]
            CADColor = translateColor(layer, row.split(",")[CADColorCol])
            CADLineweight = row.split(",")[CADLineweightCol]

            #if Rhino name found but no CAD name associated with it
            if not CADName:
                CADName = "A-RHINO-" + layerShort
                newLayerName = CADName
            if len(CADLineweight) < 2:
                CADLineweight = 0

            #Check if layer already exists.
            parent = rs.ParentLayer(layer)
            existLayers = rs.LayerChildren(parent)
            isExisting = False

            for existLayer in existLayers:
                #if new name already exists as a layer
                if rs.LayerName(existLayer, False) == CADName:
                    layersObjs = rs.ObjectsByLayer(layer)
                    for layersObj in layersObjs:
                        rs.ObjectLayer(layersObj, existLayer)
                    rs.DeleteLayer(layer)
                    newLayerName = rs.LayerName(existLayer, False)
                    print "Layer {} merged with existing layer {}.".format(
                        layerShort, rs.LayerName(layer, False))
                    isExisting = True
                    break

            #if layer does not already exist
            if isExisting == False:
                rs.LayerColor(layer, CADColor)
                rs.LayerPrintWidth(layer, float(CADLineweight))
                newLayerName = CADName
                rs.RenameLayer(layer, CADName)
                print "Layer {} changed to layer {}.".format(
                    layerShort, CADName)

            found = True
            break
    if not found:
        layerShort = rs.LayerName(layer, False)
        CADName = "A-RHINO-" + layerShort
        newLayerName = CADName
        rs.RenameLayer(layer, CADName)
        print "Layer {} has no matching CAD layer.".format(layerShort)
        return newLayerName

    return newLayerName
Exemplo n.º 29
0
def importCAD(filePath, scaleDWG = False):
    explodeBlockBoo = True

    #setup the layers
    importLayerNumber = 6000
    importLayerObj = layers.AddLayerByNumber(importLayerNumber, False)
    importLayerName = layers.GetLayerNameByNumber(importLayerNumber)

    #Shorten cad file name
    fileNameExt = os.path.basename(filePath)
    fileName = os.path.splitext(fileNameExt)[0]

    #create layer name
    time = utils.GetDatePrefix()
    iter = "01"
    layerName = time+"_"+fileName+"_"+iter

    #Check if this layer already exists
    while rs.IsLayer(importLayerName + "::" + time + "_" + fileName + "_" + iter):
        iterInt = int(iter)+1
        if len(str(iterInt))<2:
            iter = "0" + str(iterInt)
        else:
            iter = str(iterInt)

    elementLayerName = importLayerName + "::" + time + "_" + fileName + "_" + iter
    elementLayer = rs.AddLayer(elementLayerName)

    rs.CurrentLayer(elementLayer)

    #get intial list of all layers in the file
    currentLayers = rs.LayerNames()

    rs.Command('_-Import "' + filePath + '" _IgnoreThickness=Yes _ModelUnits=Inches _Enter', False)

    #get new layers added
    endLayersNames = rs.LayerNames()
    newLayers = diff(endLayersNames, currentLayers)

    for layer in newLayers:
        rs.ParentLayer(layer, elementLayer)
        objects = rs.ObjectsByLayer(layer)
        if rs.IsLayerEmpty(layer):
            rs.DeleteLayer(layer)
        else:
            for obj in objects:
                if rs.IsDimension(obj):
                    rs.DeleteObject(obj)
                elif rs.IsHatch(obj):
                    rs.DeleteObject(obj)

    #Get all the imported geometry
    allObjects = []
    finalLayers = rs.LayerChildren(rs.CurrentLayer())
    blockNames = []
    for finalLayer in finalLayers:
        layerObjects = rs.ObjectsByLayer(finalLayer)
        for layerObject in layerObjects:
            if rs.IsBlockInstance(layerObject):
                blockNames.append(rs.BlockInstanceName(layerObject))
                allObjects.append(rs.ExplodeBlockInstance(layerObject, True))
            else:
                allObjects.append(layerObject)
    finalAllObjects = list(flatten(allObjects))

    for eachBlock in blockNames:
        try:
            rs.DeleteBlock(eachBlock)
        except:
            pass

    #Scale objects
    if scaleDWG:
        rs.ScaleObjects(finalAllObjects, [0,0,0], [.001, .001, .001])

    #Collapse layers
    try:
        rootLay = sc.doc.Layers.FindId(rs.coerceguid(rs.LayerId(elementLayerName)))
        rootLay.IsExpanded = False
    except:
        pass
    print "Import Successful"
    return finalAllObjects
Exemplo n.º 30
0
"""
SHL Architects 30-01-2019
Sean Lamb (Developer)
[email protected]
-better handling of different brep types
"""

import rhinoscriptsyntax as rs
layers = rs.LayerNames()
num_layers = 0
for layer in layers:
    if rs.IsLayerEmpty(layer):
        if rs.IsLayerCurrent(layer):
            print "Current layer is empty but will not be removed."
        else:
            rs.DeleteLayer(layer)
            num_layers += 1
print "%d empty layers removed." % num_layers