Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
0
def getSourceKeys(source, bakename=False):
    if rs.IsUserText(source) == 0:
        print 'no keys'
        return
    if bakename == False:
        return [x for x in rs.GetUserText(source) if "BakeName" not in x]
    else:
        return [x for x in rs.GetUserText(source)]
Ejemplo n.º 4
0
    def set_values_from_Rhino(self, _inputs, _ghenv, _input_num=0):
        """ Will try and pull relevant data for the Recirc loop from the Rhino scene

        Arguments:
            _inputs: (float: curve:)
            _ghenv: (ghenv)
            _input_num: (int) The index (zero based) of the GH Component input to look at
        """
        
        def cleanPipeDimInputs(_diam, _thickness):
            # Clean diam, thickness
            if _diam != None:
                if " (" in _diam: 
                    _diam = float( _diam.split(" (")[0] )
            
            if _thickness != None:
                if " (" in _thickness: 
                    _thickness = float( _thickness.split(" (")[0] )
            
            return _diam, _thickness
        
        # First, see if I can pull any data from the Rhino scene?
        # Otherwise, if its just a number, use that as the length
        lengths, diams, insul_thks, insul_lambdas, refectives = [], [], [], [], []
        for i, input in enumerate( _inputs ):
            try:
                lengths.append( float(convert_value_to_metric( input, 'M' )) )
            except AttributeError as e:
                try:
                    rhinoGuid = _ghenv.Component.Params.Input[_input_num].VolatileData[0][i].ReferenceID
                    rh_obj = Rhino.RhinoDoc.ActiveDoc.Objects.Find( rhinoGuid )
                    
                    length = float(rh_obj.CurveGeometry.GetLength())
                    
                    k = rs.GetUserText(rh_obj, 'insulation_conductivity')
                    r = rs.GetUserText(rh_obj, 'insulation_reflective')
                    t = rs.GetUserText(rh_obj, 'insulation_thickness')
                    d = rs.GetUserText(rh_obj, 'pipe_diameter')
                    d, t = cleanPipeDimInputs(d, t)
                    
                    lengths.append(length)
                    diams.append(d)
                    insul_thks.append(t)
                    insul_lambdas.append(k)
                    refectives.append(r)
                except Exception as e:
                    msg = str(e)
                    msg += "\nSorry, I am not sure what to do with the input: {} in 'pipe_geom_'?\n"\
                        "Please input either a Curve or a number/numbers representing the pipe segments.".format(input)
                    _ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, msg )

        if lengths: self.lengths = lengths
        if diams: self.diams = diams
        if insul_thks: self.insul_thicknesses = insul_thks
        if insul_lambdas: self.insul_conductivities = insul_lambdas
        if refectives: self.insul_reflectives = refectives
Ejemplo n.º 5
0
def setObjDict(obj):
    rs.SetUserText(obj, 'objdict')
    objkeys = [ x for x in rs.GetUserText(obj) if "BakeName" not in x ]
    # objkeys = rs.GetUserText()
    # keys = 'level grade elevation'
    # keys = keys.split()
    objvals = map(lambda x: rs.GetUserText(obj, x), objkeys)
    # vals = [idx, grade, str(x[1])]
    # objdict = dict(zip(objkeys, objvals))
    # rs.SetUserText(obj, 'objdict')
    rs.SetUserText(obj, 'objdict', dict(zip(objkeys, objvals)))
Ejemplo n.º 6
0
def makeDetail(keys, objs):
    if not objs: return
    for obj in objs:
        for key in keys:
            cur_keys = rs.GetUserText(obj)
            if key not in cur_keys:
                rs.SetUserText(obj, key, "0", False)
            else:
                val = rs.GetUserText(obj, key)
                if len(val) < 1 or val == " ":
                    rs.SetUserText(obj, key, "0", False)
Ejemplo n.º 7
0
 def __init__(self, obj):
     self.obj = obj
     self.selected = 0
     self.id = obj
     attrs = rs.GetUserText(obj)
     attrs = [i.name for i in ATTRS if i.isEditable]
     for attr in attrs:
         setattr(self, attr, rs.GetUserText(str(obj), attr))
     self.setDims()
     objRef = Rhino.DocObjects.ObjRef(self.id)
     obj = objRef.Object()
     index = obj.Attributes.LayerIndex
     self.Layer = scriptcontext.doc.Layers[index].Name
Ejemplo n.º 8
0
def getWindowUserText(_in):
    with idf2ph_rhDoc():
        windowDataFromRhino = {}

        if rs.IsUserText(_in):
            print 'Pulling data from Rhino model for Window: {}'.format(
                rs.ObjectName(_in))
            # Get the User-Text data from the Rhino Scene
            for eachKey in rs.GetUserText(_in):
                windowDataFromRhino[eachKey] = rs.GetUserText(_in, eachKey)
            return windowDataFromRhino
        else:
            return None
Ejemplo n.º 9
0
def getAllUserText(_GUID):
    """ Takes in an objects GUID and returns the full dictionary of

    Attribute UserText Key and Value pairs. Cleans up a bit as well.

    

    Arguments:

        _GUID: the Rhino GUID of the surface object to try and read from

    Returns:

        dict: a dictionary object with all the keys / values found in the Object's UserText

    """

    dict = {}

    if not _GUID.GetType() == System.Guid:

        remark = "Unable to get parameter data for the surface? If trying to pull data\n"\

        "from Rhino, be sure the '_srfc' input Type Hint is set to 'Guid'\n"\

        "For now, using default values for all surface parameter values."

        ghenv.Component.AddRuntimeMessage(ghK.GH_RuntimeMessageLevel.Remark,
                                          remark)

        return dict

    with idf2ph_rhDoc():

        dict['Object Name'] = rs.ObjectName(_GUID)  # Always get the name

        for eachKey in rs.GetUserText(_GUID):

            if 'Object Name' not in eachKey:

                val = rs.GetUserText(_GUID, eachKey)

                if val != 'None':

                    dict[eachKey] = val

                else:

                    dict[eachKey] = None

    return dict
Ejemplo n.º 10
0
def get_tfa_surface_data_from_Rhino(_guid):  
   
    geom = rs.coercegeometry(_guid)
    nm = rs.ObjectName(_guid)

    params = {}
    param_keys = rs.GetUserText(_guid)
    
    for k in param_keys:
        params[k] =rs.GetUserText(_guid, k)
    
    if 'Object Name' in params.keys():
        params['Object Name'] = nm

    return (geom, params)
Ejemplo n.º 11
0
def getAttrs(_in, _key):
    results = []
    for each in _in:
        if _key == 'Object Name':
            results.append(rs.ObjectName(each))

        else:

            if rs.IsUserText(each):
                for eachKey in rs.GetUserText(each):
                    if _key in eachKey:
                        results.append(rs.GetUserText(each, _key))
                        break

    if len(set(results)) > 1:
        return '<varies>'
    def GetExistingValues(self):
        for k, v in self.fieldsDict.items():
            val = rs.GetUserText(self.obj, k)
            eto_field = v[0]
            try: 
                v1, v2 = val.split("::")
                if isinstance(eto_field, self.textField):
                    eto_field.Text = v1
                elif isinstance(eto_field, self.toggleButton):
                    if v1:
                        v1 = True if v1 == "True" else False
                        print("V!",v1, bool(v1))
                        eto_field.Checked = v1
                        eto_field.Text = str(v1)
                    else:
                        eto_field.Checked = True
                        eto_field.Text = 'True'
                v[1].Checked = int(v2)

            except AttributeError:
                if val:
                    v[0].Text = val
                else:
                    v[0].Text = 'default'
                v[1].Checked = False
Ejemplo n.º 13
0
def getSegmentId(id):
    segmentId = rs.GetUserText(id, "SegmentId")

    if segmentId:
      return int(segmentId)
    else:
      return
Ejemplo n.º 14
0
def blkObjs(blkid):
    blockName = rs.BlockInstanceName(blkid)
    objref = rs.coercerhinoobject(blkid)
    idef = objref.InstanceDefinition
    idefIndex = idef.Index

    lvl = levels[rs.GetUserText(blkid, 'level')]
    height = float(lvl['height'])
    xform = rs.BlockInstanceXform(blkid)
    objects = rs.BlockObjects(blockName)
    # masses = map(lambda x: massFromSrf(x, height), objects)
    # newblk = rs.AddBlock(masses, (0,0,0), name=name, delete_input=True)

    # objects.extend(masses)

    newGeometry = []
    newAttributes = []
    for object in objects:
        newGeometry.append(rs.coercegeometry(object))
        ref = Rhino.DocObjects.ObjRef(object)
        attr = ref.Object().Attributes
        attr.SetUserString('blkname', blockName)
        newAttributes.append(attr)

    InstanceDefinitionTable = sc.doc.ActiveDoc.InstanceDefinitions
    InstanceDefinitionTable.ModifyGeometry(idefIndex, newGeometry,
                                           newAttributes)
    # rs.TransformObjects(masses, xform)
    rs.DeleteObjects(masses)
Ejemplo n.º 15
0
 def get_UserText_with_default(_obj, _key, _default=None):
     """ Why doesn't rs.GetUserText() do this by Default already? Sheesh...."""
     result = rs.GetUserText(_obj, _key)
     if result:
         return result
     else:
         return _default
Ejemplo n.º 16
0
    def _get_surface_U_value(self, _srfcGUID):
        """Takes in a single Surface GUID and returns its U-Value Param
        
        Will look at the UserText of the surface to get the EP Construction
        Name and then the Document UserText library to get the U-Value of tha
        Construction Type. 
        
        Returns 0.5 W/m2k as default on any errors.
        
        Args:
            self:
            _srfcGUID (GUID): A single GUID value
        Returns:
            srfcUvalue (float): The Surface's UserText Param for 'U-Value' if found
        """

        srfcConstructionName = rs.GetUserText(_srfcGUID, 'EPConstruction')
        if srfcConstructionName:
            constParams = rs.GetDocumentUserText('PHPP_lib_Assmbly_' +
                                                 srfcConstructionName)

            for k in rs.GetDocumentUserText():
                if 'PHPP_lib_Assmbly' not in k:
                    continue
                try:
                    d = json.loads(rs.GetDocumentUserText(k))
                    if d.get('Name', None) == srfcConstructionName:
                        constParams = rs.GetDocumentUserText(k)
                        break
                except:
                    constParams = None
            else:
                constParams = None

            if constParams:
                constParams = json.loads(constParams)
                srfcUvalue = constParams.get('uValue', 1)
            else:
                warning = (
                    'Warning: Could not find a construction type in the',
                    'Rhino Document UserText with the name "{}?"'.format(
                        srfcConstructionName.upper()),
                    'Check your Document UserText library to make sure that you have',
                    'your most recent assembly library file loaded?',
                    'For now applying a U-Value of 0.5 w/m2k (R11 hr-sf-F/Btu)  for this surface.'
                )
                self.ghenv.Component.AddRuntimeMessage(
                    ghK.GH_RuntimeMessageLevel.Warning, warning)
                srfcUvalue = 0.5
        else:
            warning = 'Warning: could not find a construction type in the\n'\
            'UserText for one or more surfaces? Are you sure you assigned a\n'\
            '"EPConstruction" parameter to the Floor Surface being input?\n'\
            'For now applying a U-Value of 0.5 w/m2k (R11 hr-sf-F/Btu) for this surface.'
            self.ghenv.Component.AddRuntimeMessage(
                ghK.GH_RuntimeMessageLevel.Warning, warning)
            srfcUvalue = 0.5

        return srfcUvalue
Ejemplo n.º 17
0
def translateToGcode(id):
    path = rs.ConvertCurveToPolyline(id)
    points = rs.CurvePoints(path)
    rs.DeleteObject(path)

    feedrate = int(rs.GetUserText(id, "Feedrate"))

    for pointId in points:
Ejemplo n.º 18
0
def setClass(obj):
    classKeys = 'units public'
    func = rs.GetUserText(obj, "func")
    if func in classKeys:
        classValue = func
    else:
        classValue = "na"
    rs.SetUserText(obj, "class", classValue)
Ejemplo n.º 19
0
def UserDataInput():
    obj = rs.GetObject("Select Object")

    Keylist = rs.GetUserText(obj, )

    UserDataList = []
    for n in Keylist:
        b = rs.GetUserText(obj, n)
        UserDataList.append(b)

    newlist = []
    newlist = rs.PropertyListBox(Keylist, UserDataList, "User Data",
                                 "User Data Key List")

    if newlist:
        for c in range(len(Keylist)):
            rs.SetUserText(obj, Keylist[c], newlist[c])
Ejemplo n.º 20
0
def get_user_text(obj, key, default_value=None, fn=None):
    if not obj:
        return default_value
    val = rs.GetUserText(obj.Id, key)
    if not val:
        return default_value
    if not fn:
        return val
    return fn(val)
Ejemplo n.º 21
0
def groupByBB(objs):
    pairs = map(objBBPtPair, objs)

    for bb in groupbb:
        lvl = rs.GetUserText(bb, 'level')
        for pair in pairs:
            result = rs.PointInPlanarClosedCurve(pair[1], bb)
            if result == 1:
                rs.SetUserText(pair[0], "level", lvl)
Ejemplo n.º 22
0
def func(obj):
    obj = alignNormal(obj)
    width = wallthickness / 2
    lvl = levels[rs.GetUserText(obj, 'level')]
    height = float(lvl['height'])
    # height = float(rs.GetUserText(obj, "height"))
    # lvl = rs.GetUserText(obj, 'level')
    walls = wallByBrep(obj, height, width, -width)
    [trp.copySourceData(wall, obj) for wall in walls]
Ejemplo n.º 23
0
def createKVByVal(obj, skeys, svals, classkey, classvals):
    objsval = rs.GetUserText(obj, skeys)
    svals = svals.split()
    classvals = classvals.split()
    if objsval not in svals:
        objclass = classvals[1]
    else:
        objclass = classvals[0]
    rs.SetUserText(obj, classkey, objclass)
Ejemplo n.º 24
0
def del_noattr_plt():
    # get all objects in plots layer
    plot_objs = rs.ObjectsByLayer(relevant_layers_dict["plots"])

    for plot_obj in plot_objs:
        if rs.IsCurve(plot_obj) and rs.IsCurveClosed(plot_obj):
            some_attrib = rs.GetUserText(plot_obj, plot_attribs_list[0])
            if some_attrib == None:
                rs.DeleteObject(plot_obj)
Ejemplo n.º 25
0
    def get_params_from_rhino(self, _in):
        """Got and find any param values in the geometry in the RH Scene 
        Args:
            _in (Rhino.Geometry.Curve): The Rhino Curve object to look at
        Returns:
            (tuple) length, width, thickness, lambda
        """

        with LBT2PH.helpers.context_rh_doc(self.ghdoc):
            try:
                l = float(ghc.Length(_in))
                w = float(rs.GetUserText(_in, 'ductWidth'))
                t = float(rs.GetUserText(_in, 'insulThickness'))
                c = float(rs.GetUserText(_in, 'insulConductivity'))
            except Exception as e:
                print('Error getting values from Rhino Scene\n{}'.format(e))
                return None, None, None, None

        return l, w, t, c
Ejemplo n.º 26
0
def massFromSrf(obj):
    lvl = levels[rs.GetUserText(obj, 'level')]
    height = float(lvl['height'])
    startpt = trp.objBBPts(obj)[0]
    endpt = (startpt.X, startpt.Y, startpt.Z + height)
    curve = rs.AddLine(startpt, endpt)
    mass = rs.ExtrudeSurface(obj, curve)
    trp.copySourceLayer(mass, obj)
    trp.copySourceData(mass, obj)
    rs.DeleteObject(curve)
    return mass
Ejemplo n.º 27
0
def layerChangeEvent(sender, e):
    toolpaths = rs.LayerChildren("Toolpaths")
    layerId = ""

    for toolpath in toolpaths:
        layerId = rs.LayerId(toolpath)

        for textDotId in rs.ObjectsByType(8192):
            toolpathName = rs.TextDotText(textDotId)

            if rs.GetUserText(textDotId, "LayerId") == layerId:
                newToolpathName = toolpath.split("::")[1]
                print "Renaming ", toolpathName, " to ", newToolpathName
                rs.TextDotText(textDotId, newToolpathName)
Ejemplo n.º 28
0
def DesignHistory():
    print "Design Option History"
    block = rs.GetObject("Select Design Option Block",
                         rs.filter.instance,
                         preselect=True)
    history = rs.GetUserText(block, 'Design Option History')
    names = history.split("<--")
    message = ''
    for i in range(len(names)):
        message += names[i]
        if i != len(names) - 1:
            message += '\n' + ('\t' * (i + 1)) + '|——'

    print message
Ejemplo n.º 29
0
def getAttrs(_in, _key, _defaultVal):
    # Takes in a list of Objects (_in) and the key to search for in
    # User-Text. Returns '<varies>' if more than one value is found for the key
    results = []
    for each in _in:
        if _key == 'Object Name':
            results.append(rs.ObjectName(each))
            # Get the objects Name
        else:
            # Get the User text info
            if rs.IsUserText(each):
                for eachKey in rs.GetUserText(each):
                    if _key in eachKey:
                        results.append(rs.GetUserText(each, _key))
                        break

    if len(set(results)) > 1:
        return '<varies>'
    else:
        try:
            return results[0]
        except:
            return _defaultVal
Ejemplo n.º 30
0
def add_attr_plt():
    # get objects by layer
    building_objs = rs.ObjectsByLayer(relevant_layers_dict["buildings"])
    plot_objs = rs.ObjectsByLayer(relevant_layers_dict["plots"])

    # read attribure labels (first row)
    attribute_labels_list = []
    with open(proc_attributes_path, "r") as input_handle:
        rdr = csv.reader(input_handle)
        attribute_labels_list = next(rdr)

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

            #building_center_pt = rs.CurveAreaCentroid(building_obj)[0]
            building_center_pt = crv.GetBoundingBox(True).Center

            for plot_obj in plot_objs:
                if rs.PointInPlanarClosedCurve(building_center_pt, plot_obj):
                    for attr_label in set(attribute_labels_list).intersection(
                            plot_attribs_list):  #todo: intersection redundant

                        # get building attribute
                        plot_attr_val = int(
                            rs.GetUserText(building_obj, attr_label))

                        # if NUM_APTS_C already set, add to it
                        num_of_apts_label = "NUM_APTS_C"
                        if attr_label == num_of_apts_label:
                            num_of_apts_val = rs.GetUserText(
                                plot_obj, num_of_apts_label)
                            if num_of_apts_val != None:
                                plot_attr_val += int(num_of_apts_val)

                        rs.SetUserText(plot_obj, attr_label, plot_attr_val)