Exemplo n.º 1
0
def cutAtPlan(level, floorNum):
    planPlane = rs.AddPlaneSurface([-1000, -1000, level], 3000, 3000)
    baseLayer = rs.AddLayer("60_PLANS")
    newParent = rs.AddLayer("Level_" + floorNum, 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:
            objName = rs.ObjectName(obj)
            rs.ObjectName(tempCrv, objName)
            intersectCrvs.append(tempCrv)

    for crv in intersectCrvs:
        if not None:
            rs.ObjectLayer(crv, newChild)
            #rs.SetUserText(crv, "PlanID", "PLAN")

    rs.DeleteObject(planPlane)
    rs.CurrentLayer(origLayer)
Exemplo n.º 2
0
def get_faces(mesh, layer=None):
    out = None
    if layer:
        objs = rs.ObjectsByLayer(layer)
        selectable = []
        for obj in objs:
            if "face" in rs.ObjectName(obj):
                selectable.append(obj)
    else:
        selectable = None

    faces = rs.GetObjects("Select faces",
                          4,
                          group=True,
                          preselect=False,
                          select=False,
                          objects=selectable)
    fkeys = []
    if faces:
        for face in faces:
            if face:
                name = rs.ObjectName(face)
                fkey = name.split(".")[-1]
                if fkey:
                    fkeys.append(fkey)
    return fkeys
Exemplo n.º 3
0
def get_edge_keys_and_param(message='Select edge.', layer=None):
    if layer:
        objs = rs.ObjectsByLayer(layer)
        selectable = []
        for obj in objs:
            if "edge" in rs.ObjectName(obj):
                selectable.append(obj)
    else:
        selectable = None
    guid = rs.GetObjectEx(message, 4, False, False, selectable)
    uv = None
    t = None
    if guid:
        guid = guid[0]
        name = rs.ObjectName(guid).split('.')
        if 'edge' in name:
            pt = rs.GetPointOnCurve(guid, "Select point on edge")
            if not pt: return None, None
            param = rs.CurveClosestPoint(guid, pt)
            lb, ub = rs.CurveDomain(guid)
            t = (param - lb) / (ub - lb)
            print(lb, ub)
            key = name[-1]
            uv = tuple(key.split('-'))
    return uv, t
Exemplo n.º 4
0
def BlockLocation(object, scale):
    # WARNING: The basis describes a transformation of the Rhino basis
    # with respect to the Rhino basis, which might not match the
    # import environment world basis.
    x = rs.BlockInstanceXform(object)
    p0 = [x.M00, x.M10, x.M20]  # X Basis direction
    p1 = [x.M01, x.M11, x.M21]  # Y Basis direction
    p2 = [x.M02, x.M12, x.M22]  # Z Basis direction
    p3 = [x.M03, x.M13, x.M23]  # Origin position
    # Rescale transform units
    for i in range(3):
        p0[i] /= scale
        p1[i] /= scale
        p2[i] /= scale
    # Construct basis tetrahedron
    placeholder = LocationMesh(p3, [p0, p1, p2])

    # Unity import will render names unique with a _N suffix on the N copy
    # so block name is included as a prefix to facilitate matching
    # in the case that block objects names are not unique
    block = rs.BlockInstanceName(object)
    block_name = SafeObjectName(block)
    object_name = rs.ObjectName(object)
    rs.ObjectName(placeholder, block_name + "=" + object_name)
    rs.ObjectLayer(placeholder, rs.ObjectLayer(object))
    return placeholder
Exemplo n.º 5
0
def LightLocation(light, scale):
    if not rs.IsLight(light):
        return

    # Default light transform
    # NOTE: Point light direction is [0, 0, -1]
    position = rs.LightLocation(light)
    direction = rs.LightDirection(light)
    basis = BasisFromDirection(direction)

    # Modify transform according to light type
    lightType = "UnknownLight"
    if rs.IsPointLight(light):
        lightType = "PointLight"
        #clone = rs.AddPointLight(position)
    if rs.IsDirectionalLight(light):
        lightType = "DirectionalLight"
        #clone = rs.AddDirectionalLight(position, position + direction)
    if rs.IsSpotLight(light):
        lightType = "SpotLight"
        outer = rs.SpotLightRadius(light)
        inner = rs.SpotLightHardness(light) * outer
        # Encode spot parameters in basis lengths
        basis = [basis[0] * outer, basis[1] * inner, direction]
        #clone = rs.AddSpotLight(position + direction, outer, position)
        #rs.SpotLightHardness(clone, inner / outer)
    if rs.IsRectangularLight(light):
        # WARNING: Incomplete documentation for Rhino7 in RhinoScript reference:
        # https://developer.rhino3d.com/api/rhinoscript/light_methods/rectangularlightplane.htm
        lightType = "RectangularLight"
        quadVectors, quadLengths = rs.RectangularLightPlane(light)
        heightBasis = quadVectors[1] * quadLengths[0] / 2
        widthBasis = quadVectors[2] * quadLengths[1] / 2
        position = quadVectors[0] + heightBasis + widthBasis  # center
        direction = -quadVectors[3]  # negative of light direction
        # Encode quad dimensions in basis lengths
        basis = [widthBasis, heightBasis, direction]
        #corner = position - (widthBasis + heightBasis)
        #clone = rs.AddRectangularLight(corner, corner + widthBasis * 2, corner + heightBasis * 2)
    if rs.IsLinearLight(light):
        # Encode line segment in first basis
        lightType = "LinearLight"
        widthBasis = direction / 2
        position = position + widthBasis
        basis = [widthBasis, basis[1], -basis[0]]
        #clone = rs.AddLinearLight (position - widthBasis, position + widthBasis)

    # Create placeholder mesh
    # NOTE: light dimensions are not scaled
    placeholder = LocationMesh(position, basis)

    # NOTE: Lights have no corresponding exported block,
    # but the same notation will be used to configure lights in the exported model.
    # Unity import will render names unique with a _N suffix on the N copy
    # so block name is included as a prefix to facilitate matching
    # in the case that block instances names are not unique
    objectName = rs.ObjectName(light)
    rs.ObjectName(placeholder, lightType + "=" + objectName)
    rs.ObjectLayer(placeholder, rs.ObjectLayer(light))
    return placeholder
Exemplo n.º 6
0
def write_strip_data(layer, point_ind):
    # get all surfaces on layer
    strips = rs.ObjectsByLayer(layer)
    strip_ind = 1
    strip_dict = {}
    for strip in strips:
        # get only surfaces
        if rs.IsSurface(strip):
            if rs.IsSurfacePlanar(strip):
                strip_dict['Strip=' + layer + str(strip_ind)] = []
                strip_brep = rs.coercebrep(strip)
                edges = Rhino.Geometry.Brep.DuplicateEdgeCurves(strip_brep)
                edge_ids = []
                ind = 0
                for edge in edges:
                    edge_id = sc.doc.Objects.AddCurve(edge)
                    if edge_id:
                        rs.ObjectName(edge_id, 'active' + str(ind))
                        edge_ids.append(edge_id)
                        ind += 1
                # Get strip geometry
                # change color to help find strip
                rs.ObjectColor(strip, color=(255, 0, 255))
                start_edge = rs.GetObject('Select start edge.', 4, False,
                                          False, active_strip_filter)
                start_length = rs.CurveLength(start_edge)
                sp = rs.CurveMidPoint(start_edge)
                rs.ObjectName(rs.AddPoint(sp), name='SP_' + str(point_ind))
                end_edge = rs.GetObject('Select end edge.', 4, False, False,
                                        active_strip_filter)
                end_length = rs.CurveLength(end_edge)
                ep = rs.CurveMidPoint(end_edge)
                rs.ObjectName(rs.AddPoint(ep), name='SP_' + str(point_ind))
                # Clean up
                rs.DeleteObjects(edge_ids)
                rs.ObjectColor(strip, color=(128, 0, 128))
                # write to json
                start = {
                    'Point': point_ind,
                    'GlobalX': round(sp.X, 4),
                    'GlobalY': round(sp.Y, 4),
                    'WALeft': round(start_length * 0.5, 4),
                    'WARight': round(start_length * 0.5, 4),
                    'Autowiden': 'No'
                }
                point_ind += 1
                end = {
                    'Point': point_ind,
                    'GlobalX': round(ep.X, 4),
                    'GlobalY': round(ep.Y, 4),
                    'WBLeft': round(end_length * 0.5, 4),
                    'WBRight': round(end_length * 0.5, 4),
                }
                strip_dict['Strip=' + layer + str(strip_ind)].append(start)
                strip_dict['Strip=' + layer + str(strip_ind)].append(end)
                point_ind += 1
                strip_ind += 1
    return strip_dict
Exemplo n.º 7
0
def draw_hash():
    horizontals = [((10, 20, 0), (40, 20, 0)), ((10, 30, 0), (40, 30, 0))]
    verticals = [((20, 10, 0), (20, 40, 0)), ((30, 10, 0), (30, 40, 0))]
    for horizontal in horizontals:
        guid = rs.AddLine(horizontal[0], horizontal[1])
        rs.ObjectName(guid, 'h')
    for vertical in verticals:
        guid = rs.AddLine(vertical[0], vertical[1])
        rs.ObjectName(guid, 'v')
Exemplo n.º 8
0
def add_element_set(structure, guids, name):
    """ Adds element set information from Rhino curve and mesh guids.

    Parameters
    ----------
    structure : obj
        Structure object to update.
    guids : list
        Rhino curve and Rhino mesh guids.
    name : str
        Name of the new element set.

    Returns
    -------
    None

    Notes
    -----
    - Meshes representing solids must have 'solid' in their name.

    """

    elements = []

    for guid in guids:

        if rs.IsCurve(guid):

            sp = structure.check_node_exists(rs.CurveStartPoint(guid))
            ep = structure.check_node_exists(rs.CurveEndPoint(guid))
            element = structure.check_element_exists([sp, ep])
            if element is not None:
                elements.append(element)

        elif rs.IsMesh(guid):

            vertices = rs.MeshVertices(guid)
            faces = rs.MeshFaceVertices(guid)

            if rs.ObjectName(guid) and ('solid' in rs.ObjectName(guid)):
                nodes = [structure.check_node_exists(i) for i in vertices]
                element = structure.check_element_exists(nodes)
                if element is not None:
                    elements.append(element)
            else:
                for face in faces:
                    nodes = [
                        structure.check_node_exists(vertices[i]) for i in face
                    ]
                    if nodes[2] == nodes[3]:
                        del nodes[-1]
                    element = structure.check_element_exists(nodes)
                    if element is not None:
                        elements.append(element)

    structure.add_set(name=name, type='element', selection=elements)
Exemplo n.º 9
0
def RevertRename(name_map):
    selected = SelectedObjects()
    for object in selected:
        new_name = rs.ObjectName(object)
        if new_name in name_map:
            old_name = name_map[new_name]
            if old_name is None:
                old_name = ""  # Restores name is None state
            rs.ObjectName(object, old_name)
            del name_map[new_name]
Exemplo n.º 10
0
    def importSrfTypesFromScene(self):

        data = []
        srfs = rs.ObjectsByLayer('GENTYPESRF')
        for f in srfs:
            po = PhaseObject()
            po.guid = f
            po.phase = 'TYPESRF'
            po.typeIndex = int(rs.ObjectName(f))
            po.strTypeDescription = rs.ObjectName(f)
            data.append(po)
        self.data = data
Exemplo n.º 11
0
        def OnOKButtonClick(self, sender, e):
            # remove object name to avoid deletion
            generatedStair = rs.ObjectsByName(
                "GdC9V&^a^rGZZNgiWFH&aTRQLLscu*9AZCmhk8t2!a")
            generatedHandrail = rs.ObjectsByName(
                "qe7g&G5LzXEvbudtPT8xCxQbisusFVqCPqMsiHK2jc")
            rs.DeleteObjects(rs.ObjectsByName(
                "xAbJgNV6^bz6azN&6E$Q^WeX$Dd^vygCz5z7Hmynb5"))
            rs.DeleteObjects(rs.ObjectsByName("BC6#DT5LCQX*#8r97Tquf5gNF"))
            if generatedStair:
                rs.ObjectName(generatedStair, name="www.landarchtools.com")
            if generatedHandrail:
                rs.ObjectName(generatedHandrail, name="www.landarchtools.com")

            self.Close(True)
Exemplo n.º 12
0
def select_network_face(network, message='Select face.'):
    """Select one face of a network.

    Parameters:
        network (compas.datastructures.network.Network): The network object.
        message (str): Optional. The message to display to the user.
            Default is ``"Select network edges."``

    Returns:
        tuple: The key of the selected face.
        None: If no face was selected.

    See Also:
        * :func:`select_network_faces`

    """
    guid = rs.GetObjects(message, preselect=True, filter=rs.filter.textdot)
    if guid:
        prefix = network.attributes['name']
        name = rs.ObjectName(guid).split('.')
        if 'face' in name:
            if not prefix or prefix in name:
                key = name[-1]
                key = ast.literal_eval(key)
                return key
    return None
Exemplo n.º 13
0
def select_network_vertex(network, message="Select a network vertex"):
    """Select one vertex of a network.

    Parameters:
        network (compas.datastructures.network.Network): The network object.
        message (str): Optional. The message to display to the user.
            Default is ``"Select network vertex."``

    Returns:
        * str: The key of the selected vertex.
        * None: If no vertex was selected.

    See Also:
        * :func:`select_network_vertices`

    """
    guid = rs.GetObject(message, preselect=True, filter=rs.filter.point | rs.filter.textdot)
    if guid:
        prefix = network.attributes['name']
        name = rs.ObjectName(guid).split('.')
        if 'vertex' in name:
            if not prefix or prefix in name:
                key = name[-1]
                key = ast.literal_eval(key)
                return key
    return None
Exemplo n.º 14
0
def select_mesh_faces(mesh, message='Select mesh faces.'):
    """Select faces of a mesh.

    Parameters:
        mesh (compas.datastructures.mesh.Mesh): The mesh object.
        message (str): Optional. The message to display to the user.
            Default is ``"Select mesh edges."``

    Returns:
        list: The keys of the selected faces.

    Note:
        Selection of faces is based on naming conventions.
        When a mesh is drawn using the function :func:`draw_mesh`,
        the curve objects representing the edges get assigned a name that
        has the following pattern::

            '{0}.edge.{1}-{2}'.format(mesh.attributes['name'], u, v)

    Example:

        .. code-block:: python
            :emphasize-lines: 14

            import compas
            from compas.cad import rhino as compas_rhino as rhino

            from compas.datastructures.mesh import Mesh

            mesh = Mesh.from_obj(compas.get_data('faces.obj'))

            find_mesh_faces(mesh, mesh.leaves())

            compas_rhino.draw_mesh(mesh)
            compas_rhino.display_mesh_face_labels(mesh)

            fkeys = compas_rhino.select_mesh_faces(mesh)

            print(fkeys)


    See Also:
        * :func:`select_mesh_vertices`
        * :func:`select_mesh_edges`

    """
    keys = []
    guids = rs.GetObjects(message, preselect=True, filter=rs.filter.textdot)
    if guids:
        prefix = mesh.attributes['name']
        seen = set()
        for guid in guids:
            name = rs.ObjectName(guid).split('.')
            if 'face' in name:
                if not prefix or prefix in name:
                    key = name[-1]
                    if not seen.add(key):
                        key = ast.literal_eval(key)
                        keys.append(key)
    return keys
Exemplo n.º 15
0
def RunCommand(is_interactive):
    # Get existing props
    name_Exg = getAttrs(rs.SelectedObjects(), 'Object Name')
    act_Exg = getAttrs(rs.SelectedObjects(), 'Object Activ_Disc')

    dialog = Dialog_WindowProperties(name_Exg, act_Exg)
    rc = dialog.ShowModal(Rhino.UI.RhinoEtoApp.MainWindow)
    name_New, act_New = dialog.GetUserInput()

    try:
        update = dialog.GetUpdateStatus()
    except:
        update = False

    if update == True:
        for eachObj in rs.SelectedObjects():

            rs.SetUserText(eachObj, 'Object Name',
                           '%<ObjectName("{}")>%'.format(str(eachObj)))
            if 'varies' not in str(name_New): rs.ObjectName(eachObj, name_New)

            if 'varies' not in str(act_New):
                rs.SetUserText(eachObj, 'Object Activ_Disc', str(act_New))

    return 0
Exemplo n.º 16
0
 def add_quad(self, obj):
     
     attr = Description(rs.ObjectName(obj))
     no = attr.no
     
     corner_numbers = []
     
     pts = rs.SurfacePoints(obj)
     
     for pt in pts:
         n = self.add_node(Node(-1, pt, ""))
         corner_numbers.append(n.no)
             
     if (no == -1):
         
         no = self.quads.fan
         
     else:
         
         l = len(self.quads.list)
         
         for i in range(0, l):
             
             if (attr.no == self.quads.list[i].no) and (self.current_group == self.quads.list[i].grp):
                 
                 self.quads.list[i].no = self.quads.fan
                 
     q = Quad(self.current_group, no, corner_numbers, attr.prop)
     
     self.quads.list.append(q)
     self.output_quads += q.export()
     
     self.quads.update_fan(self.current_group)
Exemplo n.º 17
0
def _get_surface_rh_userText(_srfc_GUID, _ghdoc, _ghenv):
    """ Takes in an objects GUID and returns the full dictionary of
    Attribute UserText Key and Value pairs. Cleans up a bit as well.
    
    Args:
        _GUID: <Guid> the Rhino GUID of the surface object to try and read from
        _ghdoc: The Grasshopper Component 'ghdoc' object
        _ghenv: The Grasshopper Component 'ghenv' object
    Returns:
        output_dict: a dictionary object with all the keys / values found in the Object's UserText
    """
    output_dict = {}

    if not _srfc_GUID:
        return output_dict

    if _srfc_GUID.GetType() != System.Guid:
        remark = "Unable to get the stuff dude set _srfc input type hint to guid"
        _ghenv.Component.AddRuntimeMessage(ghk.GH_RuntimeMessageLevel.Remark,
                                           remark)
        return output_dict

    with helpers.context_rh_doc(_ghdoc):
        output_dict['Object Name'] = rs.ObjectName(_srfc_GUID)

        for eachKey in rs.GetUserText(_srfc_GUID):
            if 'Object Name' not in eachKey:
                val = rs.GetUserText(_srfc_GUID, eachKey)
                if val != 'None':
                    output_dict[eachKey] = val
                else:
                    output_dict[eachKey] = None

    return output_dict
Exemplo n.º 18
0
def select_network_edge(network, message="Select a network edge"):
    """Select one edge of a network.

    Parameters:
        network (compas.datastructures.network.Network): The network object.
        message (str): Optional. The message to display to the user.
            Default is ``"Select network edges."``

    Returns:
        tuple: The key of the selected edge.
        None: If no edge was selected.

    See Also:
        * :func:`select_network_edges`

    """
    guid = rs.GetObject(message, preselect=True, filter=rs.filter.curve | rs.filter.textdot)
    if guid:
        prefix = network.attributes['name']
        name = rs.ObjectName(guid).split('.')
        if 'edge' in name:
            if not prefix or prefix in name:
                key = name[-1]
                u, v = key.split('-')
                u = ast.literal_eval(u)
                v = ast.literal_eval(v)
                return u, v
    return None
Exemplo n.º 19
0
def get_rh_obj_UserText_dict(_ghdoc, _rh_obj_guid):
    """ Get any Rhino-side parameter data for the Object/Element

    Note: this only works in Rhino v6.0+ I believe...
    
    Args:
        _ghdoc (ghdoc): The 'ghdoc' object from the Grasshopper document.
        _rh_obj_guid (Rhino Guid): The Rhino Guid of the Object/Element.
    Returns:
        object_rh_UserText_dict (dict): A dictionary of all the data found
            in the Rhino object's UserText library.
    """
    
    def is_gh_guid(_guid):
        """If its GH generated geom, will have this GUID always """

        return str(_guid) == '00000000-0000-0000-0000-000000000000'

    if not _rh_obj_guid:
        return {}

    if is_gh_guid(_rh_obj_guid):
        return {}

    with context_rh_doc(_ghdoc):
        rh_obj = Rhino.RhinoDoc.ActiveDoc.Objects.Find( _rh_obj_guid )
        object_rh_UserText_dict = {k:rs.GetUserText(rh_obj, k) for k in rs.GetUserText(rh_obj)}
        
        # Fix the name
        object_name = rs.ObjectName(_rh_obj_guid)
        object_rh_UserText_dict['Object Name'] = object_name

    return object_rh_UserText_dict
Exemplo n.º 20
0
def xdraw_mesh(vertices, faces, name=None, color=None, **kwargs):
    guid = rs.AddMesh(vertices, faces)
    if color:
        rs.ObjectColor(guid, color)
    if name:
        rs.ObjectName(guid, name)
    return guid
Exemplo n.º 21
0
    def importSrfTypesFromScene(self):

        data = []
        # srfs=rs.ObjectsByLayer(get_layer_name('TYPESRF'))
        # for f in srfs:
        #     #rs.SelectObject(f)
        #     #rs.ObjectColor(f,(0,0,1))
        #     po=PhaseObject()
        #     po.guid=f
        #     po.phase='TYPESRF'
        #     po.typeIndex=int(rs.ObjectName(f))
        #     po.strTypeDescription=rs.ObjectName(f)
        #     self.updatePhaseObjectColor(po)
        #     data.append(po)
        # self.data=data
        # return
        objs = rs.ObjectsByLayer(get_layer_name('BLOCK'))
        for o in objs:
            po = PhaseObject()
            po.guid = o
            po.phase = 'BLOCK'
            name = rs.ObjectName(o)
            typeIndex = 0
            try:
                typeIndex = int(name)
            except:
                pass
            print(name, typeIndex)
            self.setObjectType(po, typeIndex, 0)
            data.append(po)

        self.data = data
Exemplo n.º 22
0
def xdraw_mesh(vertices, faces, color, name):
    guid = rs.AddMesh(vertices, faces)
    if color:
        rs.ObjectColor(guid, color)
    if name:
        rs.ObjectName(guid, name)
    return guid
Exemplo n.º 23
0
def mesh_select_vertices(mesh, message="Select vertices."):
    """Select multiple vertices of a mesh.

    Parameters
    ----------
    mesh: :class:`compas.datastructures.Mesh`
    message: str, optional

    Returns
    -------
    list of int
    """
    keys = []
    guids = rs.GetObjects(message,
                          preselect=True,
                          filter=rs.filter.point | rs.filter.textdot)
    if guids:
        prefix = mesh.attributes['name']
        seen = set()
        for guid in guids:
            name = rs.ObjectName(guid).split('.')
            if 'vertex' in name:
                if not prefix or prefix in name:
                    key = name[-1]
                    if not seen.add(key):
                        key = ast.literal_eval(key)
                        keys.append(key)
    return keys
    def __init__(self):

        if constrainToAxis <> None: self.__m_constrainToAxis = constrainToAxis

        if _geometry <> []:
            for index, obj in enumerate(_geometry):
                try:
                    if type(obj) == System.Guid:
                        if not rs.IsObject(obj):
                            self.warningData.append("Invalid geometry at #" +
                                                    str(index))
                            continue
                        objData = rs.ObjectName(obj)  #extract data if any
                        geo = rc.DocObjects.ObjRef(obj).Brep()
                        if geo == None: geo = rc.DocObjects.ObjRef(obj).Curve()
                        geo.SetUserString('Data', objData)
                        self.__m_geometry.append(geo)
                    else:
                        obj.SetUserString('Data', " ")
                        self.__m_geometry.append(obj)
                except:
                    self.warningData.append("Invalid geometry object item #" +
                                            str(index + 1))
                    continue
        if self.__m_geometry == []:
            self.warningData.append("Missing '_geometry' input")
            return

        if minDist <> None: self.__m_minDist = minDist
        if maxDist <> None: self.__m_maxDist = maxDist
        if multipliers <> []: self.__m_globalMultiplier = multipliers
        else: self.__m_globalMultiplier = [1]
        self.__m_instanceMultiplierCounter = 0
Exemplo n.º 25
0
def network_select_edges(network, message="Select edges."):
    """Select multiple edges of a network.

    Parameters
    ----------
    network: :class:`compas.datastructures.Network`
    message: str, optional

    Returns
    -------
    list of tuple of hashable
    """
    keys = []
    guids = rs.GetObjects(message,
                          preselect=True,
                          filter=rs.filter.curve | rs.filter.textdot)
    if guids:
        prefix = network.attributes['name']
        seen = set()
        for guid in guids:
            name = rs.ObjectName(guid).split('.')
            if 'edge' in name:
                if not prefix or prefix in name:
                    key = name[-1]
                    if not seen.add(key):
                        u, v = key.split('-')
                        u = ast.literal_eval(u)
                        v = ast.literal_eval(v)
                        keys.append((u, v))
    return keys
Exemplo n.º 26
0
def network_select_edge(network, message="Select an edge."):
    """Select a single edge of a network.

    Parameters
    ----------
    network: :class:`compas.datastructures.Network`
    message: str, optional

    Returns
    -------
    tuple of hashable, or None
    """
    guid = rs.GetObject(message,
                        preselect=True,
                        filter=rs.filter.curve | rs.filter.textdot)
    if guid:
        prefix = network.attributes['name']
        name = rs.ObjectName(guid).split('.')
        if 'edge' in name:
            if not prefix or prefix in name:
                key = name[-1]
                u, v = key.split('-')
                u = ast.literal_eval(u)
                v = ast.literal_eval(v)
                return u, v
    return None
Exemplo n.º 27
0
def exportToSvg(x, state='init'):
    points = flipY(rs.CurveEditPoints(x))
    parsed = [parse(i) + "\n" for i in points]
    parsed[-1] = parsed[-1][:-2]
    parsed = "".join(parsed)
    with open("{}{}.svg".format(state, rs.ObjectName(x)), "w") as f:
        f.write(header.format(minPoint(points), maxPoint(points), parsed))
Exemplo n.º 28
0
def RunCommand(is_interactive):
    """Interactive Rhino Command Creates 90 Lap joint on a seleceted Beam 

    Return:
    ------
    None
    """
    #load Derivation and model
    derivation = Derivation.from_json(rhino_UI_utilities.get_json_file_location())
    model = derivation.get_next_step()

    #Select mesh 
    Obj_ref = rs.GetObject(message = "select mesh(es)", filter = 32, preselect = False, subobjects = True)
    selected_beam_name = (rs.ObjectName(Obj_ref)[:-5])

    #Loop through all beams in model to identify the selected beam
    selected_beam = None
    for beam in model.beams:
        if(beam.name == selected_beam_name):
            selected_beam = beam
            break
    assert (selected_beam != None)

    #list of user inputs(face needs to be implemented through UI)
    face_id = rs.GetInteger("face_id",None,0,5)
    helper = UI_helpers()
    joint_point = helper.Get_SelectPointOnMeshEdge("Select mesh edge","Pick point on edge")

    ext_start = rs.GetReal("extension start ",200,None,None)
    ext_end = rs.GetReal("extension end ",200,None,None)
    name = create_id() 
    
    #adding joints to selected Beam 
    #joint_distance_from_start = Get_distancefromBeamYZFrame(selected_beam,joint_point)
    joint_distance_from_start = selected_beam.Get_distancefromBeamYZFrame(joint_point)
    match_beam_origin =  model.rule_90lap(selected_beam,joint_distance_from_start,face_id,ext_start,ext_end,name) 
     


    #Save Derivation (Model is also saved)
    derivation.to_json(rhino_UI_utilities.get_json_file_location(), pretty = True)

    #Visualization
    viz_point = []
    for pt in match_beam_origin:
        a = (pt[0],pt[1],pt[2])
        viz_point.append({
            'pos': a,
            'color': (0,255,0)
        })


    #Visualization 
    artist = MeshArtist(None, layer ='BEAM::Beams_out')
    artist.clear_layer()
    artist.draw_points(viz_point)
    for beam in model.beams:
        artist = MeshArtist(beam.mesh, layer ='BEAM::Beams_out')#.mesh is not ideal fix in beam and assemble class
        artist.draw_faces(join_faces=True)
Exemplo n.º 29
0
 def add_mesh_to_rhino(self):
     self.remove_rhino_objects()
     if self.is_terminal_step():
         for shape in self.post_execution_shapes:
             mesh = shape.representations['mesh']
             guid = Rhino.RhinoDoc.ActiveDoc.Objects.AddMesh(mesh)
             self.added_rhino_objects.append(guid)
             rs.ObjectName(guid, shape.name)
Exemplo n.º 30
0
def RunCommand(is_interactive):
    # First, get any properties of the existing object(s)
    tfa_Exg = getAttrs(rs.SelectedObjects(), 'TFA_Factor', _defaultVal=1)
    name_Exg = getAttrs(rs.SelectedObjects(), 'Object Name', _defaultVal=None)
    number_Exg = getAttrs(rs.SelectedObjects(),
                          'Room_Number',
                          _defaultVal=None)
    v_sup_Exg = getAttrs(rs.SelectedObjects(), 'V_sup', _defaultVal=0)
    v_eta_Exg = getAttrs(rs.SelectedObjects(), 'V_eta', _defaultVal=0)
    v_trans_Exg = getAttrs(rs.SelectedObjects(), 'V_trans', _defaultVal=0)
    use_Exg = getAttrs(rs.SelectedObjects(), 'useType', _defaultVal='-')
    lighting_Exg = getAttrs(rs.SelectedObjects(), 'lighting', _defaultVal='-')
    motion_Exg = getAttrs(rs.SelectedObjects(), 'motion', _defaultVal='-')

    # Call the Dialog Window
    dialog = Dialog_WindowProperties(tfa_Exg, name_Exg, number_Exg, v_sup_Exg,
                                     v_eta_Exg, v_trans_Exg, use_Exg,
                                     lighting_Exg, motion_Exg)
    rc = dialog.ShowModal(Rhino.UI.RhinoEtoApp.MainWindow)
    number_New, name_New, tfa_New, vSup, vEta, vTrans, use, lighting, motion = dialog.GetUserInput(
    )

    try:
        update = dialog.GetUpdateStatus()  #True if 'OK', False if 'Cancel'
    except:
        update = False  # on any error with the user input

    # Apply the User Inputs to the Object's Attributes if Update==True
    if update == True:
        for eachObj in rs.SelectedObjects():
            # Sort out the name
            rs.SetUserText(
                eachObj, 'Object Name',
                '%<ObjectName("{}")>%'.format(str(eachObj))
            )  # Formula to auto-set the obj's name in Attribute Inspector
            if 'varies' not in str(name_New): rs.ObjectName(eachObj, name_New)

            # Set the rest of the Surface Attributes
            if use != '<varies>': rs.SetUserText(eachObj, 'useType', use)
            if lighting != '<varies>':
                rs.SetUserText(eachObj, 'lighting', lighting)
            if motion != '<varies>': rs.SetUserText(eachObj, 'motion', motion)
            if number_New != '<varies>':
                rs.SetUserText(eachObj, 'Room_Number', number_New)
            if str(tfa_New) != '<varies>':
                rs.SetUserText(eachObj, 'TFA_Factor', str(tfa_New))
            if str(vSup) != '<varies>':
                rs.SetUserText(eachObj, 'V_sup', str(vSup))
            if str(vEta) != '<varies>':
                rs.SetUserText(eachObj, 'V_eta', str(vEta))
            if str(vTrans) != '<varies>':
                rs.SetUserText(eachObj, 'V_trans', str(vTrans))

    return 0


# temp for debuggin in editor
#RunCommand(True)