Ejemplo n.º 1
0
 def __init__(self):
     self.param_id = DB.ElementId(DB.BuiltInParameter.UNIFORMAT_CODE)
     self.AssembleCode = ""
     self.ClassName = ""
     self.unit = ''
     #KEYNOTE_PARAM
     self.param_id_Keynote = DB.ElementId(DB.BuiltInParameter.KEYNOTE_PARAM)
Ejemplo n.º 2
0
def compare_elmnt_sets(elementset_a,
                       elementset_b,
                       compare_types=False,
                       diff_results=None):
    dict_a = element_hash_dict(elementset_a, compare_types, diff_results)
    hash_list_a = sorted(dict_a.values())

    dict_b = element_hash_dict(elementset_b, compare_types, diff_results)
    hash_list_b = sorted(dict_b.values())

    if hash_list_a == hash_list_b:
        return True

    elif diff_results:
        rdict_a = reverse_dict(dict_a)
        rdict_b = reverse_dict(dict_b)
        for el_hash in set(hash_list_a) ^ set(hash_list_b):
            if el_hash in rdict_a:
                for el_id in rdict_a[el_hash]:
                    diff_results.diff_elements.append(DB.ElementId(el_id))

            if el_hash in rdict_b:
                for el_id in rdict_b[el_hash]:
                    diff_results.diff_elements.append(DB.ElementId(el_id))

    return False
Ejemplo n.º 3
0
 def overkill(self, doc=None):
     bounded_curve_ids = set()
     if doc and len(self.points) > 2:
         # extend the root curve to cover the full cgroup
         root_curve = doc.GetElement(DB.ElementId(self.dir_cid))
         min_dpoint = self.min_point
         max_dpoint = self.max_point
         # create new geometry
         curve_z = root_curve.GeometryCurve.GetEndPoint(0).Z
         min_point = DB.XYZ(min_dpoint.x, min_dpoint.y, curve_z)
         max_point = DB.XYZ(max_dpoint.x, max_dpoint.y, curve_z)
         reset_dir_curve = False
         try:
             geom_curve = DB.Line.CreateBound(min_point, max_point)
             root_curve.SetGeometryCurve(geom_curve, overrideJoins=True)
             reset_dir_curve = True
         except Exception as set_ex:
             logger.debug('Failed re-setting root curve | %s', set_ex)
         # now delete the overlapping lines
         if reset_dir_curve:
             bounded_curve_ids = \
                 {x.cid for x in self.points if x.cid != self.dir_cid}
             if bounded_curve_ids:
                 bounded_curve_ids = \
                     [DB.ElementId(x) for x in bounded_curve_ids]
                 doc.Delete(List[DB.ElementId](bounded_curve_ids))
     return len(bounded_curve_ids)
Ejemplo n.º 4
0
def match_prop(dest_inst, dest_type, src_props):
    """Match given properties on target instance or type"""
    for pkv in src_props:
        logger.debug("Applying %s", pkv.name)

        # determine target
        target = dest_type if pkv.istype else dest_inst
        # ensure target is valid if it is type
        if pkv.istype and not target:
            logger.warning("Element type is not accessible.")
            continue
        logger.debug("Target is %s", target)

        # find parameter
        dparam = target.LookupParameter(pkv.name)
        if dparam and pkv.datatype == dparam.StorageType:
            try:
                if dparam.StorageType == DB.StorageType.Integer:
                    dparam.Set(pkv.value or 0)
                elif dparam.StorageType == DB.StorageType.Double:
                    dparam.Set(pkv.value or 0.0)
                elif dparam.StorageType == DB.StorageType.ElementId:
                    dparam.Set(DB.ElementId(pkv.value))
                else:
                    dparam.Set(pkv.value or "")
            except Exception as setex:
                logger.warning(
                    "Error applying value to: %s | %s",
                    pkv.name, setex)
                continue
        else:
            logger.debug("Parameter \"%s\"not found on target.", pkv.name)
Ejemplo n.º 5
0
    def update_commit_history(self):
        commit_cfg = pkgcfg.CommitConfigs()
        # process package commits
        for commit_pt in [x for x in self.commit_history.commit_points
                          if x.cptype == CommitPointTypes.Package]:
            pkg_param = self.revit_sheet.LookupParameter(commit_pt.target)
            if pkg_param:
                commit = self.get_commit_at_point(commit_pt)
                pkg_param.Set(commit_cfg.get_commit_value(commit.commit_type))
            else:
                mlogger.error('Package parameter "%s" does not exist for %s:%s',
                              commit_pt.target, self.number, self.name)

        # process revisions
        all_revs = []
        sheet_revs = []
        for commit_pt in [x for x in self.commit_history.commit_points
                          if x.cptype == CommitPointTypes.Revision]:
            commit = self.get_commit_at_point(commit_pt)
            revision = revit.doc.GetElement(DB.ElementId(commit_pt.target))
            all_revs.append(revision)
            if commit.commit_type == CommitTypes.Revised \
                    and not commit.read_only:
                sheet_revs.append(revision)
        revit.update.update_sheet_revisions(all_revs,
                                            [self.revit_sheet], state=False)
        revit.update.update_sheet_revisions(sheet_revs,
                                            [self.revit_sheet])
Ejemplo n.º 6
0
def update_sheet_revisions(revisions, sheets, state=True, doc=None):
    doc or HOST_APP.doc

    # get revisions if not set
    revisions = revisions or query.get_revisions()
    if type(revisions) is not list:
        revisions = [revisions]
    # get sheets if not available
    sheets = sheets or query.get_sheets()

    cloudedsheets = []
    updated_sheets = []
    for s in sheets:
        for r in revisions:
            revs = set([x.IntegerValue for x in s.GetAllRevisionIds()])
            addrevs = set(
                [x.IntegerValue for x in s.GetAdditionalRevisionIds()])
            cloudrevs = revs - addrevs
            if r.Id.IntegerValue in cloudrevs:
                cloudedsheets.append(s)
                continue

            if state:
                addrevs.add(r.Id.IntegerValue)
            elif r.Id.IntegerValue in addrevs:
                addrevs.remove(r.Id.IntegerValue)

            rev_elids = [DB.ElementId(x) for x in addrevs]
            s.SetAdditionalRevisionIds(List[DB.ElementId](rev_elids))
            updated_sheets.append(s)

    return updated_sheets
Ejemplo n.º 7
0
def update_sheet_revisions(revisions, sheets=None, state=True, doc=None):
    doc = doc or DOCS.doc
    # make sure revisions is a list
    if not isinstance(revisions, list):
        revisions = [revisions]

    updated_sheets = []
    if revisions:
        # get sheets if not available
        for sheet in sheets or query.get_sheets(doc=doc):
            addrevs = set([x.IntegerValue
                           for x in sheet.GetAdditionalRevisionIds()])
            for rev in revisions:
                # skip issued revisions
                if not rev.Issued:
                    if state:
                        addrevs.add(rev.Id.IntegerValue)
                    elif rev.Id.IntegerValue in addrevs:
                        addrevs.remove(rev.Id.IntegerValue)

            rev_elids = [DB.ElementId(x) for x in addrevs]
            sheet.SetAdditionalRevisionIds(List[DB.ElementId](rev_elids))
            updated_sheets.append(sheet)

    return updated_sheets
Ejemplo n.º 8
0
def iterate(mode, step_size=1):
    if op.exists(index_datafile):
        with open(index_datafile, 'r') as f:
            idx = pickle.load(f)

        if mode == '-':
            idx = idx - step_size
        else:
            idx = idx + step_size
    else:
        idx = 0

    try:
        with open(datafile, 'r') as df:
            cursel = pickle.load(df)

        if idx < 0:
            idx = abs(idx / len(cursel)) * len(cursel) + idx
        elif idx >= len(cursel):
            idx = idx - abs(idx / len(cursel)) * len(cursel)

        selection.set_to([DB.ElementId(int(list(cursel)[idx]))])

        with open(index_datafile, 'w') as f:
            pickle.dump(idx, f)

    except Exception as io_err:
        logger.error('Error read/write to: {} | {}'.format(datafile, io_err))
Ejemplo n.º 9
0
def CreateMesh(GeometricalObjects):
    ds = DB.DirectShape.CreateElement(doc, DB.ElementId(Category))
    ds.ApplicationId = "Application id"
    ds.ApplicationDataId = "Geometry object id"

    ds.SetShape(GeometricalObjects)
    print("Id:{id} 创建成功".format(id=ds.Id))
Ejemplo n.º 10
0
def filter_rule(para, param_equality, value):
    param_id = DB.ElementId(para)
    param_prov = DB.ParameterValueProvider(param_id)

    value_rule = DB.FilterDoubleRule(param_prov, param_equality(), value,
                                     1e-3 / 0.3048)  # tolerance of 1 mm
    param_filter = DB.ElementParameterFilter(value_rule)
    return param_filter
Ejemplo n.º 11
0
 def MakeSolid(self):
     solid = self.RoomSolid()
     new = List[DB.GeometryObject]()
     new.Add(solid)
     categoryId = DB.ElementId(DB.BuiltInCategory.OST_GenericModel)
     with revit.Transaction("CreateElement"):
         ds = DB.DirectShape.CreateElement(doc, categoryId)
         ds.SetShape(new)
         ds.Name = "MyShape"
Ejemplo n.º 12
0
 def controlled_by_template(view):
     if view.ViewTemplateId != DB.ElementId.InvalidElementId:
         view_template = view.Document.GetElement(view.ViewTemplateId)
         non_controlled_params = view_template \
             .GetNonControlledTemplateParameterIds()
         # check if filters are controlled by template
         if DB.ElementId(int(DB.BuiltInParameter.VIS_GRAPHICS_FILTERS)) \
                 not in non_controlled_params:
             return True
     return False
Ejemplo n.º 13
0
def get_fam_types(family_name):
    fam_bip_id = DB.ElementId(DB.BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM)
    fam_bip_provider = DB.ParameterValueProvider(fam_bip_id)
    fam_filter_rule = DB.FilterStringRule(fam_bip_provider, DB.FilterStringEquals(), family_name, True)
    fam_filter = DB.ElementParameterFilter(fam_filter_rule)

    collector = DB.FilteredElementCollector(revit.doc) \
        .WherePasses(fam_filter) \
        .WhereElementIsElementType()

    return collector
Ejemplo n.º 14
0
def model_has_family(family_name, doc=None):
    bip_id = DB.ElementId(DB.BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM)
    param_value_provider = DB.ParameterValueProvider(bip_id)
    value_rule = DB.FilterStringRule(param_value_provider,
                                     DB.FilterStringEquals(), family_name,
                                     True)
    symbol_name_filter = DB.ElementParameterFilter(value_rule)
    collector = DB.FilteredElementCollector(doc or HOST_APP.doc)\
                  .WherePasses(symbol_name_filter)

    return hasattr(collector, 'Count') and collector.Count > 0
Ejemplo n.º 15
0
def get_viewport_types(doc=revit.doc):
    # get viewport types using a parameter filter
    bip_id = DB.ElementId(DB.BuiltInParameter.VIEWPORT_ATTR_SHOW_LABEL)
    bip_provider = DB.ParameterValueProvider(bip_id)
    rule = DB.FilterIntegerRule(bip_provider, DB.FilterNumericGreaterOrEqual(), 0)
    param_filter = DB.ElementParameterFilter(rule)

    collector = DB.FilteredElementCollector(doc) \
        .WherePasses(param_filter) \
        .WhereElementIsElementType()\
        .ToElements()

    return collector
Ejemplo n.º 16
0
def get_vp_by_name(name, doc=revit.doc):
    #
    bip_id = DB.ElementId(DB.BuiltInParameter.VIEWPORT_ATTR_SHOW_LABEL)
    bip_provider = DB.ParameterValueProvider(bip_id)
    rule = DB.FilterIntegerRule(bip_provider, DB.FilterNumericGreaterOrEqual(), 0)
    param_filter = DB.ElementParameterFilter(rule)

    type_bip_id = DB.ElementId(DB.BuiltInParameter.ALL_MODEL_TYPE_NAME)
    type_bip_provider = DB.ParameterValueProvider(type_bip_id)
    type_filter_rule = DB.FilterStringRule(type_bip_provider, DB.FilterStringEquals(), name, True)
    type_filter = DB.ElementParameterFilter(type_filter_rule)

    and_filter = DB.LogicalAndFilter(param_filter, type_filter)



    collector = DB.FilteredElementCollector(doc) \
        .WherePasses(and_filter) \
        .WhereElementIsElementType()\
        .FirstElement()

    return collector
Ejemplo n.º 17
0
def create_key_schedule(category,
                        key_name,
                        sched_name,
                        fields=None,
                        records=None,
                        doc=None):
    """Create a key schedule for given category and fill with given data."""
    # verify input
    doc = doc or revit.doc
    fields = fields or []
    records = records or []
    # create the key schedule view
    new_key_sched = \
        DB.ViewSchedule.CreateKeySchedule(doc, category.Id)
    # set name and key parameter name
    new_key_sched.Name = sched_name
    new_key_sched.KeyScheduleParameterName = key_name
    # set the schedulable fields
    for sched_field in new_key_sched.Definition.GetSchedulableFields():
        sched_fieldname = sched_field.GetName(doc)
        for field in fields:
            if sched_fieldname == field:
                try:
                    new_key_sched.Definition.AddField(sched_field)
                except Exception:
                    logger.debug('Failed adding field: %s', sched_fieldname)
    # fill with data
    if records:
        # create records first
        create_schedule_record(new_key_sched, count=len(records))
        # now grab the records and update their param values
        # iterate over elements and records
        # FIXME: collect new elements only
        for keysched_el, record_data in zip(
                revit.query.get_all_elements_in_view(new_key_sched), records):
            logger.debug('Processing record: %s', record_data)
            for idx, field_name in enumerate(fields):
                if record_data[idx]:
                    p = keysched_el.LookupParameter(field_name)
                    if p and not p.SetValueString(record_data[idx]):
                        if p.StorageType == DB.StorageType.Integer:
                            p.Set(int(record_data[idx]))
                        elif p.StorageType == DB.StorageType.Double:
                            p.Set(float(record_data[idx]))
                        elif p.StorageType == DB.StorageType.String:
                            p.Set(record_data[idx])
                        elif p.StorageType == DB.StorageType.ElementId:
                            p.Set(DB.ElementId(int(record_data[idx])))
    return new_key_sched
Ejemplo n.º 18
0
    def FloorFinishType(self):
        try:
            WallFinishName = self.Room.get_Parameter(
                DB.BuiltInParameter.ROOM_FINISH_FLOOR)
            param_id = DB.ElementId(DB.BuiltInParameter.SYMBOL_NAME_PARAM)
            parameter_filter = db.ParameterFilter(
                param_id, equals=WallFinishName.AsString())
            FloorType = db.Collector(of_category='OST_Floors',
                                     parameter_filter=parameter_filter,
                                     is_type=True).get_first(wrapped=False)
            return FloorType

        except Exception as e:
            print("{Room}不能获取建筑楼面类型:{Problem}".format(Room=self.RoomName,
                                                      Problem=e))
Ejemplo n.º 19
0
    def _get_element_ids(mixed_list):
        element_id_list = []

        if not isinstance(mixed_list, list):
            mixed_list = [mixed_list]

        for item in mixed_list:
            if isinstance(item, DB.ElementId):
                element_id_list.append(item)
            elif isinstance(item, DB.Element):
                element_id_list.append(item.Id)
            elif type(item) == int:
                element_id_list.append(DB.ElementId(item))

        return element_id_list
Ejemplo n.º 20
0
def get_biparam_stringequals_filter(bip_paramvalue_dict):
    filters = []
    for bip, fvalue in bip_paramvalue_dict.items():
        bip_id = DB.ElementId(bip)
        bip_valueprovider = DB.ParameterValueProvider(bip_id)
        bip_valuerule = DB.FilterStringRule(bip_valueprovider,
                                            DB.FilterStringEquals(), fvalue,
                                            True)
        filters.append(bip_valuerule)

    if filters:
        return DB.ElementParameterFilter(
            framework.List[DB.FilterRule](filters))
    else:
        raise PyRevitException('Error creating filters.')
Ejemplo n.º 21
0
def verify_element_id(parameter_set, value):
    logger.debug("verify_element_id")
    if parameter_set.StorageType != DB.StorageType.ElementId:
        raise Exception("verify_element_id: parameter_set.StorageType is not ElementId")
    doc = parameter_set.Element.Document
    try:
        element_id = value if isinstance(value, DB.ElementId) else DB.ElementId(int(value))
    except:
        raise Exception("verify_element_id: unable to create element id")
    element = doc.GetElement(element_id)
    if not element:
        raise Exception("verify_element_id: element not found")
    logger.debug("element: %s" % str(element))
    if not isinstance(element, DB.FamilyType):
        raise Exception("verify_element_id: element is not a family type")
Ejemplo n.º 22
0
def ensure_element_ids(mixed_list):
    element_id_list = []

    if not isinstance(mixed_list, list):
        mixed_list = [mixed_list]

    for item in mixed_list:
        if isinstance(item, DB.ElementId):
            element_id_list.append(item)
        elif isinstance(item, DB.Element):
            element_id_list.append(item.Id)
        elif hasattr(item, 'Id') and isinstance(item.Id, DB.ElementId):
            element_id_list.append(item.Id)
        elif isinstance(item, int):
            element_id_list.append(DB.ElementId(item))

    return element_id_list
Ejemplo n.º 23
0
def remove_rev_from_sheets(revision_element, sheets=None):
    if not sheets:
        # collect data
        sheets = DB.FilteredElementCollector(revit.doc)\
                   .OfCategory(DB.BuiltInCategory.OST_Sheets)\
                   .WhereElementIsNotElementType()\
                   .ToElements()

    cloudedsheets = []
    affectedsheets = []
    with revit.Transaction('Remove Revision from Sheets'):
        for s in sheets:
            revs = set([x.IntegerValue for x in s.GetAllRevisionIds()])
            addrevs = set([x.IntegerValue
                           for x in s.GetAdditionalRevisionIds()])
            cloudrevs = revs - addrevs
            if revision_element.Id.IntegerValue in cloudrevs:
                cloudedsheets.append(s)
                continue
            elif len(addrevs) > 0:
                addrevs.remove(revision_element.Id.IntegerValue)
                revelids = [DB.ElementId(x) for x in addrevs]
                s.SetAdditionalRevisionIds(List[DB.ElementId](revelids))
                affectedsheets.append(s)

    if len(affectedsheets) > 0:
        print('SELECTED REVISION REMOVED FROM THESE SHEETS:')
        print('-' * 100)
        for s in affectedsheets:
            snum = s.LookupParameter('Sheet Number').AsString().rjust(10)
            sname = s.LookupParameter('Sheet Name').AsString().ljust(50)
            print('NUMBER: {0}   NAME:{1}'.format(snum, sname))

    if len(cloudedsheets) > 0:
        print('SELECTED REVISION IS CLOUDED ON THESE SHEETS '
              'AND CAN NOT BE REMOVED.')
        print('-' * 100)

        for s in cloudedsheets:
            snum = s.LookupParameter('Sheet Number').AsString().rjust(10)
            sname = s.LookupParameter('Sheet Name').AsString().ljust(50)
            print('NUMBER: {0}   NAME:{1}'.format(snum, sname))
Ejemplo n.º 24
0
    def WallFinishType(self):
        try:
            WallFinishName = self.WrapedRoom.parameters[
                ParameterName.Room_Wall_Finish].value
            param_id = DB.ElementId(DB.BuiltInParameter.SYMBOL_NAME_PARAM)
            parameter_filter = db.ParameterFilter(param_id,
                                                  equals=WallFinishName)
            WallType = db.Collector(of_category='OST_Walls',
                                    parameter_filter=parameter_filter,
                                    is_type=True).get_first()

            WallType = WallType.unwrap()
            return WallType

        except Exception as e:
            print("{roomname} 没有设置墙体类型,使用默认墙体".format(roomname=self.RoomName))
            defaultWallTypeId = doc.GetDefaultElementTypeId(
                DB.ElementTypeGroup.WallType)
            WallType = doc.GetElement(defaultWallTypeId)
            return WallType
Ejemplo n.º 25
0
    def WallFinishType(self):
        try:
            WallFinishName = self.WrapedRoom.parameters['Wall Finish'].value
            param_id = DB.ElementId(DB.BuiltInParameter.SYMBOL_NAME_PARAM)
            parameter_filter = db.ParameterFilter(param_id,
                                                  equals=WallFinishName)
            WallType = db.Collector(of_category='OST_Walls',
                                    parameter_filter=parameter_filter,
                                    is_type=True).get_first()

            return WallType

        except Exception as e:
            print(
                "{roomname} is not set WallFinishType,We use Default Wall Type defaultType"
                .format(roomname=self.RoomName))
        finally:
            defaultWallTypeId = doc.GetDefaultElementTypeId(
                DB.ElementTypeGroup.WallType)
            WallType = doc.GetElement(defaultWallTypeId)
            return WallType
Ejemplo n.º 26
0
def create_schedule_records(schedule, fields, records):
    """Create records in given schedule"""
    # create records first
    create_schedule_record(schedule, count=len(records))
    # now grab the records and update their param values
    # iterate over elements and records
    for keysched_el, record_data in zip(
            revit.query.get_all_elements_in_view(schedule), records):
        logger.debug('Processing record: %s', record_data)
        for idx, field_name in enumerate(fields):
            if record_data[idx]:
                p = keysched_el.LookupParameter(field_name)
                if p and not p.SetValueString(record_data[idx]):
                    if p.StorageType == DB.StorageType.Integer:
                        p.Set(int(record_data[idx]))
                    elif p.StorageType == DB.StorageType.Double:
                        p.Set(float(record_data[idx]))
                    elif p.StorageType == DB.StorageType.String:
                        p.Set(record_data[idx])
                    elif p.StorageType == DB.StorageType.ElementId:
                        p.Set(DB.ElementId(int(record_data[idx])))
Ejemplo n.º 27
0
def find_ins_wall(width):
    # which parameter to look at
    parameter_value_provider = DB.ParameterValueProvider(
        DB.ElementId(DB.BuiltInParameter.WALL_ATTR_WIDTH_PARAM))
    # construct filter rule
    width_rule = DB.FilterDoubleRule(parameter_value_provider,
                                     DB.FilterNumericEquals(), width, 10e-10)
    # using slow parameter filter
    width_filter = DB.ElementParameterFilter(width_rule)
    # filter wall types of same width as insulation layer
    width_wall_types = DB.FilteredElementCollector(revit.doc) \
        .OfCategory(DB.BuiltInCategory.OST_Walls) \
        .WhereElementIsElementType() \
        .WherePasses(width_filter) \
        .ToElements()
    # iterate through wall types to find one that have one layer of insulation
    for wt in width_wall_types:
        compound_str = wt.GetCompoundStructure()
        num = compound_str.LayerCount
        if num == 1 and str(compound_str.GetLayerFunction(0)) == "Insulation":
            return wt
Ejemplo n.º 28
0
def SolidRoom(Room):
    roomName = Room.Id.ToString()
    solid = GetElementSolid(Room)

    build = FlipSolidNormal(solid[0])

    newSolid = build.meshSolid().GetGeometricalObjects()
    new = List[DB.GeometryObject]()
    new.Add(newSolid[0])

    directShapeLibrary = DB.DirectShapeLibrary.GetDirectShapeLibrary(doc)
    directShapeType = DB.DirectShapeType.Create(
        doc, roomName, DB.ElementId(DB.BuiltInCategory.OST_Mass))
    directShapeType.SetShape(new)

    directShapeType.Parameter[DB.BuiltInParameter.UNIFORMAT_CODE].Set(
        "14-90.03")

    directShapeLibrary.AddDefinitionType(roomName, directShapeType.Id)

    ds = DB.DirectShape.CreateElementInstance(doc, directShapeType.Id,
                                              directShapeType.Category.Id,
                                              roomName, DB.Transform.Identity)
    #ds.SetTypeId(directShapeType.Id)
    ds.Parameter[DB.BuiltInParameter.ALL_MODEL_MARK].Set("Room:" + roomName)
    ds.Name = roomName

    wrapedNewRoom = db.Element(ds)

    wrapedNewRoom.parameters['Area'] = round(CovertToM2(Room.Area), 1)

    wrapedNewRoom.parameters['Price'] = Room.Area * 10000

    wrapedNewRoom.parameters['BAT_Area'] = db.Element(
        Room).parameters['BAT_Area'].value

    wrapedNewRoom.parameters['InterWallType'] = Room.Parameter[
        DB.BuiltInParameter.ROOM_FINISH_WALL].AsString()

    print("done")
Ejemplo n.º 29
0
def iterate(mode, step_size=1):
    """Iterate over elements in memorized selection"""
    index_datafile = \
        script.get_document_data_file("SelListPrevNextIndex", "pym")
    datafile = \
        script.get_document_data_file("SelList", "pym")

    selection = revit.get_selection()

    if op.exists(index_datafile):
        with open(index_datafile, 'r') as f:
            idx = pickle.load(f)

        if mode == '-':
            idx = idx - step_size
        else:
            idx = idx + step_size
    else:
        idx = 0

    if op.exists(datafile):
        try:
            with open(datafile, 'r') as df:
                cursel = pickle.load(df)

            if cursel:
                if idx < 0:
                    idx = abs(idx / len(cursel)) * len(cursel) + idx
                elif idx >= len(cursel):
                    idx = idx - abs(idx / len(cursel)) * len(cursel)

                selection.set_to([DB.ElementId(int(list(cursel)[idx]))])

                with open(index_datafile, 'w') as f:
                    pickle.dump(idx, f)
        except Exception as io_err:
            logger.error('Error read/write to: %s | %s', datafile, io_err)
Ejemplo n.º 30
0
#getting selection from user
# __context__ = 'Selection'

doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument
curview = doc.ActiveView  # gets current view

if isinstance(curview, DB.ViewSheet):
    forms.alert("You're on a Sheet. Activate a model view please.",
                exitscript=True)

length_feet = float(forms.ask_for_string(
    "Enter length in meters")) / 0.3048  # sometimes revit interprets 1 > 1.0
target_parameter = DB.BuiltInParameter.CURVE_ELEM_LENGTH  # FAMILY_TOP_LEVEL_PARAM, FAMILY_BASE_LEVEL_PARAM
param_id = DB.ElementId(target_parameter)
param_prov = DB.ParameterValueProvider(param_id)
param_equality = DB.FilterNumericEquals()  # equality class

value_rule = DB.FilterDoubleRule(param_prov, param_equality, length_feet,
                                 1e-3 / 0.3048)  # tolerance of 1 mm
param_filter = DB.ElementParameterFilter(value_rule)

same_cat_elements = \
        DB.FilteredElementCollector(doc,curview.Id)\
          .OfCategory(DB.BuiltInCategory.OST_Walls)\
          .WhereElementIsNotElementType()\
          .WherePasses(param_filter)\
          .ToElements()

filered_elements = []