示例#1
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
示例#2
0
def show_only(layer):
    rs.LayerVisible("Default", True)
    rs.CurrentLayer("Default")
    for sub in rs.LayerNames():
        if sub == "Default":
            continue
        if sub in conf['blocks']:
            rs.LayerVisible(sub, True)
            continue
        rs.LayerVisible(sub, False)

    for block in conf['blocks']:
        for blockchild in rs.LayerChildren(block):
            rs.LayerVisible(blockchild, True)

    # show parent layers, if nested (two up, max)
    p_layer = rs.ParentLayer(layer)
    if p_layer:
        pp_layer = rs.ParentLayer(p_layer)
        if pp_layer:
            rs.LayerVisible(pp_layer, True)
        rs.LayerVisible(p_layer, True)

    # show the target layer
    rs.LayerVisible(layer, True)
    rs.CurrentLayer(layer)
    rs.LayerVisible("Default", False)
示例#3
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)
示例#4
0
 def _draw_rule(cls, rule_spec, layer_name, left_frame_position):
     """Receives:
         rule_spec       (   left_labeled_shape_spec, 
                             right_labeled_shape_spec)
         layer_name      str. The name of the layer
     Draws the left and right shapes at the specified position on the 
     specified layer. Returns:
         layer_name      str. The name of the layer, if successful
         None            otherwise
     """
     left_labeled_shape_spec, right_labeled_shape_spec = rule_spec
     right_frame_position = s.Settings.get_right_frame_position(
         left_frame_position)
     rs.CurrentLayer(layer_name)
     left_okay = cls._draw_labeled_shape(left_labeled_shape_spec,
                                         left_frame_position)
     right_okay = cls._draw_labeled_shape(right_labeled_shape_spec,
                                          right_frame_position)
     rs.CurrentLayer(s.Settings.default_layer_name)
     all_okay = left_okay and right_okay
     if all_okay:
         return_value = layer_name
     else:
         return_value = None
     return return_value
示例#5
0
def import_file(name):
    """Import file with name specified relative to script path."""

    if (name[-4:] == "json"):

        layer = name[:-5]

        rs.AddLayer(layer)

        rs.CurrentLayer(layer)

        json_file_path = geo_path + name

        with open(json_file_path) as json_file:
            json_data = json.load(json_file)

        features = json_data["features"]

        for feature in features:

            sublayer = get_sublayer_name(feature["properties"])

            rs.AddLayer(sublayer, parent=layer)
            rs.CurrentLayer(layer + '::' + sublayer)

            import_feature(feature)
def cutAtPlan(level):
    planPlane = rs.AddPlaneSurface([-1000,-1000,level], 3000, 3000)
    baseLayer = rs.AddLayer("60_PLANS")
    newParent = rs.AddLayer("PLAN_"+str(level), parent = baseLayer)
    origLayer = rs.CurrentLayer()
    shortName = rs.LayerName(origLayer, fullpath = False)
    
    #newChildsParent = rs.AddLayer( , parent = newParent)
    newChild = rs.AddLayer(shortName, parent = newParent, color = rs.LayerColor(origLayer))
    rs.CurrentLayer(newChild)
    
    objs = rs.ObjectsByLayer(origLayer)
    #if len(objs)<1:
    #    skip = True
    intersectCrvs = []
    tempCrv = None
    for obj in objs:
        if rs.IsBrep(obj):
            
            tempCrv = rs.IntersectBreps(obj, planPlane)
        if tempCrv != None:
            intersectCrvs.append(tempCrv)
    
    for crv in intersectCrvs:
        if not None:
            rs.ObjectLayer(crv, newChild)
    
    rs.DeleteObject(planPlane)
    rs.CurrentLayer(origLayer)
示例#7
0
文件: drawing.py 项目: elidim/compas
    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, **kwargs)

        if redraw:
            rs.EnableRedraw(True)

        if layer:
            rs.CurrentLayer(previous)

        return res
示例#8
0
def RunCommand(is_interactive):

    if not rs.IsLayer("Dim"):
        util.initCaadLayer("Dim")
    oldLayer = rs.CurrentLayer("Dim")
    rs.Command("_DimAligned")
    rs.CurrentLayer(oldLayer)
示例#9
0
 def new(cls, layer, position):
     """Receives:
         layer           str. The name of the layer
         position        point3d. The position of the arrow
     Creates an arrow-name group with the name <name>-labeled-arrow. 
     Inserts it at the arrow position. Returns:
         group_out       str. The name of the new group, if successful. 
                         None otherwise.
     """
     group = '%s-labeled-arrow' % layer
     arrow_instance = a.Arrow.new_instance(layer, position)
     text_position = rs.PointAdd(position,
                                 s.Settings.arrow_label_offset_from_arrow)
     rs.CurrentLayer(layer)
     arrow_text = rs.AddText(layer,
                             text_position,
                             height=2,
                             justification=2)
     rs.CurrentLayer(s.Settings.default_layer_name)
     group_out = rs.AddGroup(group)
     n_objects_added = rs.AddObjectsToGroup([arrow_instance, arrow_text],
                                            group)
     if n_objects_added:
         return_value = group_out
     else:
         return_value = None
     return return_value
示例#10
0
def _draw_triangle_12_on_layer():
    name = ish.InitialShape.add_subsequent()
    rs.CurrentLayer(name)
    tri_12 = _make_triangle_12_spec()
    tri_12_origin = (0, 50, 0)
    _draw_labeled_shape(tri_12, tri_12_origin)
    rs.CurrentLayer('Default')
示例#11
0
 def _new_definition(cls):
     """Requires:
         A frame definition does not already exist
         A layer named <frame_layer_name> does not already exist
     Creates a frame definition on its own layer. Returns:
         frame_name_out  str. The name of the frame definition
     """
     (   layer_name, 
         color_name
     ) = (
         s.Settings.frame_layer_name, 
         s.Settings.frame_color_name)
     rs.AddLayer(layer_name, color_name)
     rs.CurrentLayer(layer_name)
     (   line_guids, 
         base_point, 
         frame_name_in,
         delete_input
     ) = (
         cls._get_guids(), 
         s.Settings.frame_base_point,
         s.Settings.frame_name,
         True)
     frame_name_out = rs.AddBlock(
         line_guids, base_point, frame_name_in, delete_input)
     (   default_layer_name
     ) = (
         s.Settings.default_layer_name)
     rs.CurrentLayer(default_layer_name)
     return frame_name_out
def iterate():
    colDelta = 20
    origLayer = rs.GetLayer("Select Layer to Iterate")
    if origLayer is None:
        return

    shortName = origLayer.split("::")[-1]
    parentLay = rs.ParentLayer(origLayer)
    nameParts = shortName.split("_")
    if len(nameParts) > 1:
        num = int(nameParts[1]) + 1
    else:
        num = 1
    if len(str(num)) == 1:
        newNum = "0" + str(num)
    else:
        newNum = str(num)
    newName = nameParts[0] + "_" + newNum
    lay1 = rs.CurrentLayer(origLayer)

    #MAterials
    matIndex = rs.LayerMaterialIndex(lay1)

    #New Color
    oldCol = rs.LayerColor(lay1)
    oldRed = rs.ColorRedValue(oldCol)
    oldGreen = rs.ColorGreenValue(oldCol)
    oldBlue = rs.ColorBlueValue(oldCol)

    newRed = oldRed + randCol(colDelta)
    if newRed > 255:
        newRed = 255 - (newRed - 255)
    if newRed < 0:
        newRed = abs(newRed)

    newGreen = oldGreen + randCol(colDelta)
    if newGreen > 255:
        newGreen = 255 - (newGreen - 255)
    if newGreen < 0:
        newGreen = abs(newGreen)

    newBlue = oldBlue + randCol(colDelta)
    if newBlue > 255:
        newBlue = 255 - (newBlue - 255)
    if newBlue < 0:
        newBlue = abs(newBlue)
    newCol = (newBlue, newGreen, newBlue)
    newLay = rs.AddLayer(newName, color=newCol, parent=parentLay)
    #print nameParts
    #print newName
    finalLayer = rs.CurrentLayer(newLay)
    #sc.doc.Layers.CurrentLayer.RenderMaterialIndex = 3
    #c = sc.doc.Layers.CurrentLayer.RenderMaterialIndex
    #sc.doc.Layers.Modify(
    #Rhino.DocObjects.Tables.LayerTable.CurrentLayer.r
    #sc.doc.Views.Redraw()
    #b = sc.doc.Layers.CurrentLayer
    #print ""
    return
def _add_one_frame():
    layer_name = s.Settings.first_rule_layer_name
    frame_name = layer_name
    rs.CurrentLayer(layer_name)
    origin = (30, 30, 0)
    frame_guid = f.Frame.new_instance(frame_name, layer_name, origin)
    rs.CurrentLayer(s.Settings.default_layer_name)
    return frame_guid
示例#14
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); 
def draw_labeled_shape(lshape_spec, lshape_name, lshape_origin):
    rs.CurrentLayer(lshape_name)
    line_specs, lpoint_specs = lshape_spec
    for spec in line_specs:
        draw_line(spec, lshape_origin)
    for spec in lpoint_specs:
        draw_lpoint(spec, lshape_origin)
    rs.CurrentLayer('Default')
示例#16
0
def plot_reaction_forces(structure, step, layer=None, scale=1.0):
    """ Plots reaction forces for the Structure analysis results.

    Parameters
    ----------
    structure : obj
        Structure object.
    step : str
        Name of the Step.
    layer : str
        Layer name for plotting.
    scale : float
        Scale of the arrows.

    Returns
    -------
    None

    """

    if not layer:
        layer = '{0}-{1}'.format(step, 'reactions')

    rs.CurrentLayer(rs.AddLayer(layer))
    rs.DeleteObjects(rs.ObjectsByLayer(layer))
    rs.EnableRedraw(False)

    rfx = structure.results[step]['nodal']['rfx']
    rfy = structure.results[step]['nodal']['rfy']
    rfz = structure.results[step]['nodal']['rfz']

    nkeys = rfx.keys()
    v = [scale_vector([rfx[i], rfy[i], rfz[i]], -scale * 0.001) for i in nkeys]
    rm = [length_vector(i) for i in v]
    rmax = max(rm)
    nodes = structure.nodes_xyz(nkeys)

    for i in nkeys:

        if rm[i] > 0.001:
            l = rs.AddLine(nodes[i], add_vectors(nodes[i], v[i]))
            rs.CurveArrows(l, 1)
            col = [
                int(j) for j in colorbar(rm[i] / rmax, input='float', type=255)
            ]
            rs.ObjectColor(l, col)
            vector = [rfx[i], rfy[i], rfz[i]]
            name = json.dumps({
                'rfx': rfx[i],
                'rfy': rfy[i],
                'rfz': rfz[i],
                'rfm': length_vector(vector)
            })
            rs.ObjectName(l, '_' + name)

    rs.CurrentLayer(rs.AddLayer('Default'))
    rs.LayerVisible(layer, False)
    rs.EnableRedraw(True)
def _add_lines():
    layer_name = s.Settings.first_rule_layer_name
    l.Layer.new(layer_name)
    rs.CurrentLayer(layer_name)
    line_specs = [((0, 0, 0), (20, 20, 0)), ((0, 20, 0), (20, 0, 0))]
    for line_spec in line_specs:
        p1, p2 = line_spec
        rs.AddLine(p1, p2)
    rs.CurrentLayer(s.Settings.default_layer_name)
示例#18
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); 
def _add_lpoints():
    lpoints = [('a', (0, 10, 0)), ('a', (20, 10, 0))]
    layer_name = s.Settings.first_rule_layer_name
    l.Layer.new(layer_name)
    rs.CurrentLayer(layer_name)
    for lpoint in lpoints:
        text, point = lpoint
        rs.AddTextDot(text, point)
    rs.CurrentLayer(s.Settings.default_layer_name)
示例#20
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)
示例#21
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)
def annotation_balloon():
    """
    Adds a numbered balloon to the document based on the numbering in part list.
    Works only with block items, similar to how this works in 'solid modelers'
    on parts in assemblies
    www.studiogijs.nl
    
    version 1.1: option for choosing between all or only top level blocks
    
    """
    
    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]
    
    name = get_blockname()
    if not name:
        return
    
    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")
    
    block_nr = get_block_index(name)+1 
    
    curve, size = get_input()
    if curve and size:
        aCircle, aText, aCurve = add_annotation_circle(curve, block_nr, size)
        aEndDot = add_end_dot(curve, size)
    else:
        rs.CurrentLayer(previous_layer)
        return
    #create annotation object
    groupname = 'annotation-object_'+str(block_nr)
    rs.AddGroup(groupname)
    rs.AddObjectsToGroup([aCircle, aText, aCurve, aEndDot], groupname)
    
    groups = sc.doc.ActiveDoc.Groups
    for group in groups:
        if group.Name == groupname:
            group.SetUserString("group-nr", str(block_nr))
            group.SetUserString("block-name", name)
    #change back to previous layer
    rs.CurrentLayer(previous_layer)
def main():
    rs.EnableRedraw(enable=False)

    notes = sc.doc.Notes
    if notes:
        variables = notes.split("\r")
        vardict = {}
        for variable in variables:
            var = variable.split("=")
            var = list([x.strip() for x in var])
            vardict[var[0]] = var[1]

    allLayers = rs.LayerNames()
    topList = []
    for layer in allLayers:
        if rs.LayerChildCount(layer) > 0:
            if re.search("::", layer):
                layer = layer.split("::")[0]
            if re.search("^L\d", layer) or re.search(
                    "^R\d", layer) or re.search("^M\d", layer) or re.search(
                        "^P\d",
                        layer) or re.search("^SECTION ", layer) or re.search(
                            "^ROOFPLAN", layer) or re.search("^SOLIDS", layer):
                topList.append(layer)
    topList = sorted(list(set(topList)))
    thisLayer = rs.CurrentLayer()

    topList.append("TURN ALL ON")
    destinationLayer = rs.ListBox(topList, "Layer To Activate")

    if not destinationLayer:
        print("No Layer Selected")
        return None
    elif destinationLayer == "TURN ALL ON":
        topList.remove(destinationLayer)
        for layer in topList:
            sc.doc = Rhino.RhinoDoc.ActiveDoc
            rs.LayerVisible(layer, True)
            rs.ExpandLayer(layer, False)
    else:
        topList.remove("TURN ALL ON")
        topList.remove(destinationLayer)
        rs.CurrentLayer(layer=destinationLayer)
        rs.ExpandLayer(destinationLayer, True)
        for layer in topList:
            sc.doc = Rhino.RhinoDoc.ActiveDoc
            rs.LayerVisible(layer, False)
            rs.ExpandLayer(layer, False)
    print(destinationLayer)
    rs.EnableRedraw(enable=True)
def _add_two_frames():
    layer_name = s.Settings.first_rule_layer_name
    l.Layer.new(layer_name)
    frame_name = layer_name
    frame_specs = [("%s_L" % frame_name, layer_name, (20, 20, 0)),
                   ("%s_R" % frame_name, layer_name, (40, 40, 0))]
    rs.CurrentLayer(layer_name)
    frame_guids = []
    for frame_spec in frame_specs:
        frame_name, layer_name, origin = frame_spec
        frame_guid = f.Frame.new_instance(layer_name, origin)
        frame_guids.append(frame_guid)
    rs.CurrentLayer(s.Settings.default_layer_name)
    return frame_guids
示例#25
0
def convertToPolylines(obj):

    # get object properties
    text            = rs.TextObjectText(obj)
    pt              = rs.TextObjectPoint(obj)
    origin          = rs.coerce3dpoint([0,0,0])
    ht              = rs.TextObjectHeight(obj)
    object_layer    = rs.ObjectLayer(obj)
    plane           = rs.TextObjectPlane(obj)
        
    diff = rs.coerce3dpoint([pt.X, pt.Y, pt.Z])

    p1 = rs.WorldXYPlane()
        
    matrix = rs.XformRotation4(p1.XAxis, p1.YAxis, p1.ZAxis, plane.XAxis, plane.YAxis, plane.ZAxis)


    rs.DeleteObject(obj)
        


    # set current layer to put strings in
    prevlayer = rs.CurrentLayer()
    layer = rs.AddLayer('temptextlayer')
    rs.CurrentLayer('temptextlayer')

    # split text at enters
    text = text.split('\r\n')
    opts='GroupOutput=No FontName="timfont" Italic=No Bold=No Height='+ str(ht)
    opts+=" Output=Curves AllowOpenCurves=Yes LowerCaseAsSmallCaps=No AddSpacing=No "
    
    origin.Y += ht * len(text) *1.2
    for item in text:
        rs.Command("_-TextObject " + opts + '"'+item+'"' + " " + str(origin) , False)
        origin.Y -= ht *1.5
        
    #restore current layer
    rs.CurrentLayer(prevlayer)

    
    #select newly created texts
    polylines = rs.ObjectsByLayer('temptextlayer')
    
    # transform to old position
    rs.TransformObjects(polylines, matrix, copy=False)
    rs.MoveObjects(polylines, diff)
    
    rs.ObjectLayer(polylines, object_layer)
    
    return polylines
示例#26
0
    def DrawDoubleLines(cls, layer, offsetType):
        # startPoint
        gp = Rhino.Input.Custom.GetPoint()
        gp.SetCommandPrompt("Pick first point")
        gp.Get()
        if gp.CommandResult() != Rhino.Commands.Result.Success:
            return gp.CommandResult()
        point1 = gp.Point()
        gp.Dispose()

        # secondPoint
        line00 = None
        line01 = None
        oldLayer = rs.CurrentLayer(layer)
        while True:
            gp = Rhino.Input.Custom.GetPoint()
            gp.SetCommandPrompt("Pick second point")
            gp.DrawLineFromPoint(point1, True)
            gp.EnableDrawLineFromPoint(True)
            gp.Get()
            if gp.CommandResult() != Rhino.Commands.Result.Success:
                rs.CurrentLayer(oldLayer)
                return gp.CommandResult()
            point2 = gp.Point()
            if point2:
                doubleLine = cls.MakeDoubleLine(config.DOUBLELINEWIDTH, point1,
                                                point2, offsetType)
                if (line00 != None) and (line01 != None):
                    line10, line11 = doubleLine.draw()
                    p0 = rs.LineLineIntersection(line00, line10)
                    p1 = rs.LineLineIntersection(line01, line11)
                    rs.AddLine(rs.CurveStartPoint(line00), p0[0])
                    rs.AddLine(rs.CurveStartPoint(line01), p1[0])
                    rs.DeleteObject(line00)
                    rs.DeleteObject(line01)
                    line00 = rs.AddLine(p0[1], rs.CurveEndPoint(line10))
                    line01 = rs.AddLine(p1[1], rs.CurveEndPoint(line11))
                    rs.DeleteObject(line10)
                    rs.DeleteObject(line11)
                else:
                    line00, line01 = doubleLine.draw()

                point1 = point2
            else:
                sc.errorhandler()
                break
            gp.Dispose()

        rs.CurrentLayer(oldLayer)
示例#27
0
def draw_mesh_as_faces(mesh,
                       layer=None,
                       clear_layer=False,
                       facecolor=None,
                       redraw=True):

    guids = compas_rhino.get_objects(
        name='{0}.*'.format(mesh.attributes['name']))
    compas_rhino.delete_objects(guids)

    if clear_layer:
        if not layer:
            compas_rhino.clear_current_layer()
        else:
            compas_rhino.clear_layer(layer)

    facecolor = facecolor or {}

    meshes = []

    for fkey in mesh.faces():
        vertices = mesh.face_coordinates(fkey)
        faces = [range(len(vertices))]
        color = facecolor.get(fkey, (255, 255, 255))
        guid = compas_rhino.xdraw_mesh(vertices,
                                       faces,
                                       None,
                                       '{0}.face.{1}'.format(
                                           mesh.attributes['name'], fkey),
                                       layer=layer,
                                       clear=False,
                                       redraw=False)
        compas_rhino.set_mesh_vertex_colors(
            guid, [color for i in range(len(vertices))])
        meshes.append(guid)

    if layer:
        previous = rs.CurrentLayer(layer)

    guid = rs.JoinMeshes(meshes, delete_input=True)

    if layer:
        rs.CurrentLayer(previous)

    rs.ObjectName(guid, '{0}'.format(mesh.attributes['name']))

    rs.EnableRedraw()
    rs.Redraw()
示例#28
0
文件: rh_trial.py 项目: tanyaroi/PyGH
def pre_process():
    # delete all previous user text
    all_objs = rs.AllObjects()
    for obj in all_objs:
        rh_obj = rs.coercerhinoobject(obj)
        rh_obj.Attributes.DeleteAllUserStrings()

    # remove all blocks
    for block in rs.BlockNames():
        rs.DeleteBlock(block)

    # set current layer
    rs.CurrentLayer(relevant_layers_dict["buildings"])

    # remove redundant layers
    for layer_name in rs.LayerNames():
        if layer_name not in relevant_layers_dict.values():
            rs.PurgeLayer(layer_name)

    # get all objects in building layer
    building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"])

    for building_obj in building_objs:
        if rs.IsCurve(building_obj) and rs.IsCurveClosed(building_obj):

            # flatten curve to XY plane
            matrix = rs.XformPlanarProjection(rg.Plane.WorldXY)
            rs.TransformObject(building_obj, matrix, copy=False)

            # delete all object with a surface grater or smaller from MIN_BUILDING_AREA_SQ by TOLERANCE or just smaller than MIN_BUILDING_AREA_SQ
            TOLERANCE = 2
            if rs.CurveArea(building_obj)[0] < MIN_BUILDING_AREA_SQM or abs(
                    rs.CurveArea(building_obj)[0] -
                    MIN_BUILDING_AREA_SQM) < TOLERANCE:
                rs.DeleteObject(building_obj)
示例#29
0
def visualize_rays(room, keys=None, ref_order=None, layer='Default', dot=None):

    rs.CurrentLayer(layer)
    if not keys:
        keys = room.ray_lines.keys()
    for rk in keys:
        if ref_order:
            ref_k = ref_order
            if ref_k in room.ray_lines[rk]:
                u, v = room.ray_lines[rk][ref_k]
                line = rs.AddLine(u, v)
        else:
            lkeys = room.ray_lines[rk]
            for lk in lkeys:
                u, v = room.ray_lines[rk][lk]
                line = rs.AddLine(u, v)
                if dot == 'w':
                    w = room.ray_powers[rk][lk][
                        100]  # this needs to be better, user given
                    rs.AddTextDot(str(w), rs.CurveMidPoint(line))
                if dot == 't':
                    t = room.ray_times[rk][lk]
                    rs.AddTextDot(str(t), rs.CurveMidPoint(line))
                if dot == 'key':
                    rs.AddTextDot(str(lk), rs.CurveMidPoint(line))
def main():
    rs.EnableRedraw(enable=False)

    walls = []
    parentFolder = rs.CurrentLayer()
    if re.search("::", parentFolder):
        parentFolder = parentFolder.rsplit("::", 1)[0]
    walls = []
    for wallLayer in wallLayers:
        try:
            walls.extend(rs.ObjectsByLayer(parentFolder + "::" + wallLayer))
        except ValueError:
            print("No curves on layer " + parentFolder + "::" + wallLayer)
            pass

    if not walls:
        print("No walls on this floor.")
        return None

    curves = []

    for wall in walls:
        if rs.IsCurve(wall):
            curves.append(wall)
    rs.SelectObjects(curves)

    rs.EnableRedraw(enable=True)