Example #1
0
 def get_frame_instance(cls, initial_shape):
     """Receives:
         initial_shape   str. The name of a layer containing one frame 
                         instance (i.e., an initial shape layer). The value 
                         is guaranteed
     Returns:
         frame_instance  guid. The guid of the frame instance on the layer 
                         Isn't this redundant?
     """
     if not rs.IsLayer(initial_shape):
         message = "There is no layer named '%s'" % initial_shape
     all_frame_instances = rs.BlockInstances(s.Settings.frame_name)
     frame_instances_on_layer = []
     for frame_instance in all_frame_instances:
         if rs.ObjectLayer(frame_instance) == initial_shape:
             frame_instances_on_layer.append(frame_instance)
     n_instances = len(frame_instances_on_layer)
     if n_instances == 0:
         message = "%s %s" % (
             "There is no frame instance", 
             "on the layer '%s'" % initial_shape)
         return_value = None
     elif n_instances == 1:
         message = None
         return_value = frame_instances_on_layer.pop()
     else:
         message = "%s %s" % (
             "There is more than 1 frame instance", 
             "on the layer '%s'" % initial_shape)
         return_value = None
     if message:
         print(message)
     return return_value
Example #2
0
def lay_rand():

    if rs.IsLayer("Temporary"):
        str_rand = str(random.randrange(0, 9999999999))
        print str_rand
        if not rs.IsLayer(str_rand):
            lay_temp = rs.AddLayer(str_rand,randomcolor())
            rs.ParentLayer(lay_temp,"Temporary")
            rs.CurrentLayer(lay_temp)
            return lay_temp
        else:
            lay_rand();
            print "The random already exists, rerandomizing"
    else:
        rs.AddLayer("Temporary",Color.DarkViolet)
        lay_rand();
Example #3
0
def RunCommand(is_interactive):

    if not rs.IsLayer("Dim"):
        util.initCaadLayer("Dim")
    oldLayer = rs.CurrentLayer("Dim")
    rs.Command("_DimAligned")
    rs.CurrentLayer(oldLayer)
Example #4
0
    def AddThisLayer(thisLayerData, counter):
        ##########################
        isRoot = False
        try:
            counter += 1
            if counter > 4:
                print "Loooop detected"
                return
            int(thisLayerData[parentColumn])
            parentLayData = layerData[thisLayerData[parentColumn]]
            parentLay = AddThisLayer(parentLayData, counter)
        except:
            isRoot = True
            parentLay = None
        ##########################
        if rs.IsLayer(thisLayerData[fullLayerNameColumn]):
            rootLayers.append(thisLayerData[fullLayerNameColumn])

            return thisLayerData[fullLayerNameColumn]
        newLayer = rs.AddLayer(thisLayerData[fullLayerNameColumn],
                               thisLayerData[colorColumn])
        rs.LayerLinetype(newLayer, thisLayerData[linetypeColumn])
        rs.LayerPrintColor(newLayer, thisLayerData[printcolorColumn])
        rs.LayerPrintWidth(newLayer, thisLayerData[printwidthColumn])
        try:
            MaterialToLayer(newLayer, thisLayerData[materialColumn])
        except:
            print "Material failed"
            #pass

        if isRoot:
            rootLayers.append(newLayer)
        return newLayer
Example #5
0
def clear_layers(layers,
                 include_children=True,
                 include_hidden=True,
                 purge=True):
    """Delete the objects of the specified layers.

    Parameters
    ----------
    layers : list of str
        A list of layer names as fully qualified hierarchical paths.
    include_children : bool, optional
        Include the objects of any child layers.
        Default is ``True``.
    include_hidden : bool, optional
        Include all hidden objects.
        Default is ``True``.
    purge : bool, optional
        Purge history after deleting.
        Default is ``True``.
    """
    rs.EnableRedraw(False)
    to_delete = []
    for name in layers:
        if rs.IsLayer(name):
            to_delete += find_objects_on_layer(name, include_hidden,
                                               include_children)
    if purge and purge_object:
        for guid in to_delete:
            obj = find_object(guid)
            if not obj:
                continue
            purge_object(obj.RuntimeSerialNumber)
    else:
        rs.DeleteObjects(to_delete)
    rs.EnableRedraw(True)
Example #6
0
def main():
    object_id = rs.GetObject("Select an object to sort")
    if object_id is None: return

    object_type = rs.ObjectType(object_id)
    if object_type is None: return

    layer_name = "Unsorted"
    if object_type == 1 or object_type == 2:
        layer_name = "Points"
    elif object_type == 4:
        layer_name = "Curves"
    elif object_type == 8 or object_type == 16:
        layer_name = "PolySurfaces"
    elif object_type == 32:
        layer_name = "Meshes"
    elif object_type == 256:
        layer_name = "Lights"
    elif object_type == 512 or object_type == 8192:
        layer_name = "Annotations"
    elif object_type == 2048 or object_type == 4096:
        layer_name = "Blocks"

    if not rs.IsLayer(layer_name):
        rs.AddLayer(layer_name)
    rs.ObjectLayer(object_id, layer_name)
Example #7
0
 def _set_up_first_initial_shape(cls):
     """Required state:
         There must be no layer with the first initial shape layer name
     Adds a new layer with the first initial shape layer name and one 
     frame instance. Should be executed only once. Returns:
         layer_name      str. The name of the layer, if successful. None, 
                         otherwise
     """
     method_name = '_set_up_first_initial_shape'
     try:
         layer_name = s.Settings.first_initial_shape_layer_name
         (layer_name_is_in_use) = (rs.IsLayer(layer_name))
         if layer_name_is_in_use:
             raise ValueError
     except ValueError:
         message = "The layer name '%s' is in use" % layer_name
         print("%s.%s:\n    %s" % (cls.__name__, method_name, message))
         return_value = None
     else:
         frame_instance_position = (
             s.Settings.first_initial_shape_frame_position)
         return_value = cls._set_up_initial_shape(layer_name,
                                                  frame_instance_position)
     finally:
         return return_value
Example #8
0
    def wrapper(*args, **kwargs):
        layer  = kwargs.get('layer', None)
        clear  = kwargs.get('clear', False)
        redraw = kwargs.get('redraw', True)

        if layer:
            if not rs.IsLayer(layer):
                create_layers_from_path(layer)
            previous = rs.CurrentLayer(layer)

        if clear:
            if not layer:
                clear_current_layer()
            else:
                clear_layer(layer)

        rs.EnableRedraw(False)
        res = f(*args)

        if redraw:
            rs.EnableRedraw(True)

        if layer:
            rs.CurrentLayer(previous)

        return res
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)
Example #10
0
def exportAllPlansToCAD():
    if rs.IsLayer("6_DRAWINGS"):
        children = rs.LayerChildren("6_DRAWINGS")
        items = []
        for child in children:
            items.append(rs.LayerName(child, False))
        #level = rs.ComboListBox(items)
        print rs.DocumentPath()
        pathParts = rs.DocumentPath().split("\\")
        if pathParts[0] == "P:":
            defaultPath = pathParts[0] + "\\" + pathParts[
                1] + "\\" + pathParts[2] + "\\" + pathParts[3]
            folder = rs.BrowseForFolder(
                folder=defaultPath,
                message="Select Folder to export plans.",
                title="Export Plans")
        else:
            folder = rs.BrowseForFolder()
        RhinoFile = rs.DocumentName()
        rhinoName = RhinoFile.split(".")[0] + "_P_"

        for item in items:
            levelNum = item.split("_")[-1]
            fileName = "\\" + rhinoName + levelNum + ".dwg"
            savePath = folder + fileName
            #savePath = rs.SaveFileName("Save", "Autocad (*.dwg)|*.dwg||")
            if savePath is not None:
                exportPlanToCAD(item, savePath)
    else:
        print "No plans currently cut. Use CutPlans."
    return
Example #11
0
def RunCommand(is_interactive):

    gp = Rhino.Input.Custom.GetPoint()
    gp.SetCommandPrompt(
        "get a point as a locaiton and setting frame size, scale 1:" +
        str(config.DRAWINGSCALE))
    sizeValues = "A5", "A4", "A3", "A2", "A1", "A0"
    sizeValue = config.FRAMESIZE
    sizeIndex = sizeValues.index(sizeValue)
    opList = gp.AddOptionList("FrameSize", sizeValues, sizeIndex)

    gp.DynamicDraw += GetPointDynamicDrawFunc
    while True:
        get_rc = gp.Get()
        if gp.CommandResult() != Rhino.Commands.Result.Success:
            return gp.CommandResult()

        if get_rc == Rhino.Input.GetResult.Point:
            point = gp.Point()
            if not rs.IsLayer("Dim"):
                util.initCaadLayer("Dim")
            oldLayer = rs.CurrentLayer("Dim")
            Dim.DrawFrameBySize(sizeValue, point, config.FRAMERIGHTMARGIN,
                                config.FRAMELEFTMARGIN)
            rs.CurrentLayer(oldLayer)

        elif get_rc == Rhino.Input.GetResult.Option:
            if gp.OptionIndex() == opList:
                sizeIndex = gp.Option().CurrentListOptionIndex
                sizeValue = sizeValues[sizeIndex]
                config.FRAMESIZE = sizeValue
            continue
        break
    return Rhino.Commands.Result.Success
Example #12
0
def RunCommand(is_interactive):
    config = get_sisufile()
    if not config:
        print('Sisufile not configured')
        return Rhino.Commands.Result.Failure

    items = config['data']
    out = []
    failed_objects = []
    result = {}
    for item in items:
        if not 'code' in item:
            print('failed to process item: code not found')
            continue

        # calc existing layer only
        layer_name = item['layer'][0]
        if not rs.IsLayer(layer_name):
            continue

        c = item.get('code')
        units = c.get('units')
        if not units:
            print('failed to process dc item: units not specified')

        if units == UNIT_PIECE:
            upd, failed = calc_piece(c)
            failed_objects = failed_objects + failed
            result.update(upd)

        if units == UNIT_M2:
            upd, failed = calc_m2(c)
            failed_objects = failed_objects + failed
            result.update(upd)

        if units == UNIT_M:
            upd, failed = calc_m(c)
            failed_objects = failed_objects + failed
            result.update(upd)

    if len(failed_objects) > 0:
        print('failed to calc')
        rs.SelectObjects([x.Id for x in failed_objects])
    else:
        now = datetime.date.today()
        prefix = now.strftime('%Y%m%d')
        doc = rs.DocumentPath()
        filename = '%s-SISU_CALC.csv' % prefix
        filepath = os.path.join(doc, filename)
        print('saving to file... %s' % filepath)
        save_sisu_calc_report(result, filepath)
    #    try:
    #        conf = get_layer_config(code)
    #        conf.update(item)
    #        out.append(conf)
    #    except Exception as e:
    #        print('DC failed. Fill defaults', code, e)
    ##        conf.update(default_config)

    return Rhino.Commands.Result.Success
Example #13
0
def create_layers_from_path(path, separator='::'):
    """Create a nested layer structure from a hierarchical path string.

    Parameters
    ----------
    path : str
        The path string.
    separator : str, optional

    Examples
    --------
    The following snippet will created 3 nested layers,
    with "COMPAS" at the root level, "Datastructures" at the first nested level, and "Mesh" at the deepest level.

    * COMPAS
      * Datastructures
        * Mesh

    .. code-block:: python

        create_layers_from_path("COMPAS::Datastructures::Mesh")

    """
    names = path.split(separator)
    parent = None
    for name in names:
        if parent:
            name = parent + separator + name
        if not rs.IsLayer(name):
            rs.AddLayer(name)
        parent = name
Example #14
0
def clear_layer(name, include_hidden=True, include_children=True, purge=True):
    """Delete all objects of a layer.

    Parameters
    ----------
    name : str
        The full, hierarchical name of the layer.
    include_hidden : bool, optional
        If True, include all hidden objects.
    include_children : bool, optional
        If True, include the objects of child layers.
    purge : bool, optional
        If True, purge history after deleting.

    Returns
    -------
    None

    """
    if not rs.IsLayer(name):
        return
    guids = find_objects_on_layer(name, include_hidden, include_children)
    rs.EnableRedraw(False)
    if purge and purge_object:
        for guid in guids:
            obj = find_object(guid)
            if not obj:
                continue
            purge_object(obj.RuntimeSerialNumber)
    else:
        rs.DeleteObjects(guids)
    rs.EnableRedraw(True)
Example #15
0
def line2wall(layer):

    go = Rhino.Input.Custom.GetOption()
    go.AcceptNothing(True)
    go.SetCommandPrompt("set wall width")
    # set up the options
    widthOption = Rhino.Input.Custom.OptionDouble(
        config.DOUBLELINEWIDTH, config.DOUBLELINEWIDTHLIMIT[0],
        config.DOUBLELINEWIDTHLIMIT[1])
    go.AddOptionDouble("Width", widthOption)
    while True:
        get_rc = go.Get()
        if go.CommandResult() != Rhino.Commands.Result.Success:
            print go.CommandResult()
            break
        if get_rc == Rhino.Input.GetResult.Option:
            continue
        break

    if go.CommandResult() != Rhino.Commands.Result.Cancel:
        config.DOUBLELINEWIDTH = widthOption.CurrentValue

        if not rs.IsLayer("Axis"):
            util.initCaadLayer("Axis")
        if not rs.IsLayer(layer):
            util.initCaadLayer(layer)

        go = Rhino.Input.Custom.GetObject()
        go.SetCommandPrompt("Select lines")
        go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
        go.GetMultiple(1, 0)
        if go.CommandResult() != Rhino.Commands.Result.Success:
            return go.CommandResult()

        oldLayer = rs.CurrentLayer(layer)
        for lineCurveId in go.Objects():
            if rs.IsLine(lineCurveId):
                # make axis
                rs.ObjectLayer(lineCurveId, "Axis")

                # make wall
                point0 = rs.CurveStartPoint(lineCurveId)
                point1 = rs.CurveEndPoint(lineCurveId)
                doubleLine = DoubleLine.MakeDoubleLine(config.DOUBLELINEWIDTH,
                                                       point0, point1)
                doubleLine.draw()
        rs.CurrentLayer(oldLayer)
Example #16
0
def set_layer(obj, name, r, g, b, visible=True):
    if not rs.IsLayer(name):
        layer = rs.AddLayer(name, [r, g, b], visible, locked=False, parent=None)
    else:
        layer = rs.LayerId(name)

    # オブジェクトをライヤーに割り当て
    rs.ObjectLayer(obj, layer)
Example #17
0
def layer(name):
    if rs.IsLayer(name):
        return name
    else:
        if name != "porcupines":
            return rs.AddLayer(name, parent="porcupines")
        else:
            return rs.AddLayer(name)
Example #18
0
def initDoorBlock():
    if not rs.IsLayer("Opening"): 
        initCaadLayer("Opening")
    oldLayer = rs.CurrentLayer("Opening"); 
    line = rs.AddLine( (0.0, 0.0, 0.0), (0.0, 1000.0, 0.0) )
    arc = rs.AddArcPtTanPt( (1000,0,0), (0,1,0), (0,1000,0))
    block = rs.AddBlock((line,arc), (500,0,0), "door", True)
    rs.CurrentLayer(oldLayer); 
Example #19
0
 def _is_available(cls, name):
     """Receives:
         name            str. The name of a layer
     Returns:
         boolean         True, if the name is available. False, otherwise
     """
     return_value = not rs.IsLayer(name)
     return return_value
Example #20
0
    def checkName():
        block_name = rs.GetString("enter block name")
        if block_name == '' or block_name == None:
            print "block name can't be empty"
            return checkName()
        #check if layer Block_Definitions exist, else create it
        if not rs.IsLayer("Block_Definitions"):
            rs.AddLayer("Block_Definitions")

        #check if layer with block name exists, else create it
        if not rs.IsLayer("Block_Definitions::" + block_name):
            block_layer = rs.AddLayer(block_name, parent="Block_Definitions")

        else:
            print "block definition with this name already exists"
            return checkName()
        return block_layer, block_name
Example #21
0
def setLayer():
    # ---emblem
    if not rs.IsLayer("emblem"):
        ptsLayer = rs.AddLayer("emblem",
                               Color.FromArgb(0, 0, 0),
                               visible=True,
                               locked=False,
                               parent=None)

    # ---emblem.lineBlack
    if not rs.IsLayer("lineBlack"):
        ptsLayer = rs.AddLayer("lineBlack",
                               Color.FromArgb(0, 0, 0),
                               visible=True,
                               locked=False,
                               parent="emblem")
    # ---emblem.lineGray
    if not rs.IsLayer("lineGray"):
        ptsLayer = rs.AddLayer("lineGray",
                               Color.FromArgb(200, 200, 200),
                               visible=True,
                               locked=False,
                               parent="emblem")
    # ---emblem.rhomboidText
    if not rs.IsLayer("textRhomboid"):
        ptsLayer = rs.AddLayer("textRhomboid",
                               Color.FromArgb(0, 0, 0),
                               visible=True,
                               locked=False,
                               parent="emblem")
    # ---emblem.lineGray
    if not rs.IsLayer("srfRhomboid"):
        ptsLayer = rs.AddLayer("srfRhomboid",
                               Color.FromArgb(200, 200, 200),
                               visible=True,
                               locked=False,
                               parent="emblem")
    # ---emblem.line,srf
    for i in range(12):
        if not rs.IsLayer("line%s" % i):
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            ptsLayer = rs.AddLayer("line%s" % i,
                                   Color.FromArgb(r, g, b),
                                   visible=True,
                                   locked=False,
                                   parent="emblem")
            ptsLayer = rs.AddLayer("srf%s" % i,
                                   Color.FromArgb(r, g, b),
                                   visible=True,
                                   locked=False,
                                   parent="emblem")
    # ---emblem.parallelLine.lineText
    if not rs.IsLayer("textLine"):
        ptsLayer = rs.AddLayer("textLine",
                               Color.FromArgb(0, 0, 0),
                               visible=True,
                               locked=False,
                               parent="emblem")
Example #22
0
def delete_layers(layers):
    """Delete layers and all contained objects.

    Parameters
    ----------
    layers : :obj:`dict` or :obj:`list` of :obj:`str`
        Can be given as either a list of strings or as a dictionary.

        When given as a list the list elements should be name of layers given
        with ``"::"`` as a separator between hierarchies.

        It can also be defined as 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):
            if rs.IsLayerCurrent(layer):
                print(
                    "Can't delete {} as it is the current layer".format(layer))
                continue

            rs.PurgeLayer(layer)

    rs.EnableRedraw(True)
Example #23
0
def initWindowBlock():
    if not rs.IsLayer("Opening"): 
        initCaadLayer("Opening")
    oldLayer = rs.CurrentLayer("Opening"); 
    line0 = rs.AddLine( (0.0, 0.0, 0.0), (1000.0, 0.0, 0.0) )
    line1 = rs.AddLine( (0.0, 50.0, 0.0), (1000.0, 50.0, 0.0) )
    line2 = rs.AddLine( (0.0, 100.0, 0.0), (1000.0, 100.0, 0.0) )
    block = rs.AddBlock((line0,line1,line2), (500,50,0), "window", True)
    rs.CurrentLayer(oldLayer); 
Example #24
0
def create_layers_from_path(path, separator='::'):
    names = path.split(separator)
    parent = None
    for name in names:
        if parent:
            name = parent + separator + name
        if not rs.IsLayer(name):
            rs.AddLayer(name)
        parent = name
Example #25
0
def main():
    """
    Creates a part list for all blocks in a document. Numbers will correspond with 
    balloons, but balloons don't need to be present for the table to be generated
    
    version 1.3
    www.studiogijs.nl
    
    version 1.1 adds table heading
    version 1.2 option for choosing between all or only top level blocks
    version 1.3 adds block description. Use change_block_description.py
    or change in block manager
   
    """
    t = sc.sticky['top_level_only'] if sc.sticky.has_key(
        'top_level_only') else 0  #0 = top level only, 1= all blocks
    if t == None:
        t = 0
    top_level_only = rs.GetBoolean("annotate top level blocks only?",
                                   ["top_level_only", "yes", "no"], t)
    if not top_level_only:
        return
    sc.sticky['top_level_only'] = top_level_only[0]

    previous_layer = rs.CurrentLayer()
    #check if layer 'annotation' exist, else create it
    if not rs.IsLayer("annotation"): rs.AddLayer("annotation")
    rs.LayerColor("annotation", Col.Black)

    rs.CurrentLayer("annotation")

    groups = sc.doc.ActiveDoc.Groups
    partlist = []

    blocknames = get_block_names()
    if not blocknames:
        print "This file does not contain block items (titleblock will be ignored)"
        return
    #add headings
    texts = ["ITEM", "PART NAME", "DESCR", "QTY"]
    partlist.append(texts)
    texts = []
    for block_nr, blockname in enumerate(blocknames, 1):
        texts.append(str(block_nr))
        texts.append(blockname)
        description = rs.BlockDescription(blockname)
        if description is None:
            description = ""
        texts.append(description)
        blockcount = get_block_count(blockname)
        texts.append(str(blockcount))
        partlist.append(texts)
        texts = []
    create_table(partlist)
    #change back to previous layer
    rs.CurrentLayer(previous_layer)
Example #26
0
def drawOpening(distance, length, block=0):
    if block == 1 and rs.IsBlock("window") == False:
        util.initWindowBlock()
    if block == 2 and rs.IsBlock("door") == False:
        util.initDoorBlock()
    if not rs.IsLayer("Axis"):
        util.initCaadLayer("Axis")

    twoLines = findTwoParallelLines()
    if not twoLines:
        return 0
    pi, linei, linej = twoLines
    if not linej:
        return 0
    pj = linej.CurveGeometry.Line.ClosestPoint(pi, False)

    oldLockMode = rs.LayerLocked("Axis", True)
    # side=0 start from startPoint , side=1 start from endPoint
    if rs.Distance(linei.CurveGeometry.Line.From, pi) <= rs.Distance(
            pi, linei.CurveGeometry.Line.To):
        side = 0
    else:
        side = 1

    # direct:
    #  0 | 1
    # -------
    #  2 | 3
    vji = rs.VectorCreate(pj, pi)
    vi = linei.CurveGeometry.Line.Direction
    angle = rs.Angle((0, 0, 0),
                     rs.VectorRotate(vji, -rs.Angle((0, 0, 0), vi)[0],
                                     (0, 0, 1)))
    if abs(angle[0] - 90) < sc.doc.ModelAbsoluteTolerance:
        line0 = linei
        line1 = linej
        if side == 0:
            direct = 2
        else:
            direct = 3
    elif abs(angle[0] + 90) < sc.doc.ModelAbsoluteTolerance:
        line0 = linej
        line1 = linei
        if side == 0:
            direct = 0
        else:
            direct = 1

    dl = DoubleLine(line0.CurveGeometry.Line, line1.CurveGeometry.Line)
    newLayer = rs.ObjectLayer(line0.Id)
    oldLayer = rs.CurrentLayer(newLayer)
    dl.drawOpening(distance, length, side, block, direct)
    rs.DeleteObject(line0.Id)
    rs.DeleteObject(line1.Id)
    rs.CurrentLayer(oldLayer)
    rs.LayerLocked("Axis", oldLockMode)
Example #27
0
def Transfer(origin, destination):
    '''
    Transfer object to layer. Use in place of `rs.RenameLayer()`

    Parameters:
        origin : str
        destination : str
    '''
    # Ensure destination layer exists
    if not rs.IsLayer(destination):
        rs.AddLayer(destination)

    if rs.IsLayer(origin):
        Visible(origin, True)  # rs.LayerVisible(origin, True, True)

        for id in rs.ObjectsByLayer(origin, True):
            rs.ObjectLayer(id, destination)

    doc.Views.Redraw()
Example #28
0
 def initLayers(self):
     #propagate required layers
     parent = get_layer_name('LOCKEDLAYERS')
     rs.AddLayer(get_layer_name('LOCKEDLAYERS'), locked=False)
     for phase in PHASES:
         lay = get_layer_name(phase)
         if not rs.IsLayer(lay): rs.AddLayer(lay, locked=False)
         else: rs.LayerLocked(lay, False)
         #rs.ParentLayer(lay,parent)
     rs.ExpandLayer(parent, False)
Example #29
0
def setObjectToLayer(objs, layerName):
    rs.EnableRedraw(False)
    if not rs.IsLayer(layerName):
        rs.AddLayer(layerName, randomColor())


#        rs.AddLayer(layerName,Color.LightSlateGray);
    for obj in objs:
        rs.ObjectLayer(obj, layerName)
    rs.EnableRedraw(True)
    def CreateReferenceLayers(self, parentPrefix, refLayers, norefLayers,
                              colours):
        # get timestamp
        ts = time.strftime("%y%m%d_%H-%M")

        # create parent layer name
        parentLayername = parentPrefix + ts
        self.Message = "Referenced: " + str(parentLayername)

        # check if parent layer exists
        sc.doc = Rhino.RhinoDoc.ActiveDoc
        exists = rs.IsLayer(parentLayername)

        if exists:
            self.AddRuntimeMessage(
                self.RuntimeMessageLevel.Remark,
                "Parent Layer already exists! Returning valid existing layers."
            )
            # get all children layers
            allchildren = rs.LayerChildren(parentLayername)
            # check all children layers for validity
            validchildren = [parentLayername + "::" + vc for vc in refLayers]
            realchildren = []
            for c in allchildren:
                if c in validchildren:
                    realchildren.append(c)
            # set sticky to real found child layers
            st[self.LNKEY] = realchildren

            # switch back to ghdoc
            sc.doc = ghdoc

            # return layer names
            return realchildren
        else:
            # switch to Rhino doc
            sc.doc = Rhino.RhinoDoc.ActiveDoc
            # create parent layer
            parentLayer = rs.AddLayer(parentLayername, Color.Black)

            # create referenced layers
            newLayers = []
            for i, rl in enumerate(refLayers + norefLayers):
                lay = rs.AddLayer(rl, colours[i], parent=parentLayername)
                if rl in refLayers:
                    newLayers.append(lay)

            # add them to the sticky
            st[self.LNKEY] = newLayers

            # switch back to ghdoc
            scdoc = ghdoc

            # return layer names/paths
            return newLayers