def LevelChangePreselected(selected_ids, target_level_id): errors = [] changed = [] t = Transaction(doc, 'Change level to 0') t.Start() for e_id in selected_ids: el = doc.GetElement(e_id) try: levelID = el.LevelId # Initial level of object, assigned on element creation if levelID.IntegerValue < 0: continue LevelToElement = doc.GetElement(levelID) LevElev = LevelToElement.get_Parameter( BuiltInParameter.LEVEL_ELEV).AsValueString().replace(" ", "") offset = el.get_Parameter( BuiltInParameter.INSTANCE_FREE_HOST_OFFSET_PARAM) if not offset: offset = el.get_Parameter( BuiltInParameter.FAMILY_BASE_LEVEL_OFFSET_PARAM) if not offset: offset = el.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET) if not offset: offset = el.get_Parameter(BuiltInParameter.ROOM_LOWER_OFFSET) print(offset.AsValueString()) finalElev = float(LevElev) + float(offset.AsValueString().replace( " ", "")) print(offset.AsValueString(), finalElev) offset.SetValueString(str(finalElev)) baselevel = el.get_Parameter(BuiltInParameter.FAMILY_LEVEL_PARAM) if not baselevel: baselevel = el.get_Parameter( BuiltInParameter.WALL_BASE_CONSTRAINT) # if baselevel: # baseoffset = el.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET) # finalOffset = float(LevElev) + float(offset.AsValueString().replace(" ", "")) baselevel.Set(target_level_id) changed.append(str(e_id.IntegerValue)) except Exception as e: try: print("%s %s - %s" % (str(e_id.IntegerValue), str(el.GetType()), str(e))) except: print("%s - %s" % (str(e_id.IntegerValue), str(e))) errors.append(str(e_id.IntegerValue)) t.Commit() return errors, changed
def get_styles(): fromStyleLine = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element, 'Pick a line with the style to be replaced.')) fromStyle = fromStyleLine.LineStyle toStyleLine = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element, 'Pick a line with the interfacetypes style.')) toStyle = toStyleLine.LineStyle return fromStyle, toStyle
def pick_and_match_dim_overrides(src_dim_id): src_dim = doc.GetElement(src_dim_id) while True: try: dest_dim = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element, 'Pick dimensions to match their overrides.')) if isinstance(dest_dim, Dimension): with Transaction(doc, 'Match Dimension Overrides') as t: t.Start() setup_dim_overrides_per_config(src_dim, dest_dim) t.Commit() except: break
def remove_all_external_links(): """Remove All External Links""" def confirm_removal(link_el): return isinstance(link_el, RevitLinkType) or isinstance( link_el, CADLinkType) print_header('REMOVE ALL EXTERNAL LINKS') if doc.PathName: modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath( doc.PathName) try: transData = TransmissionData.ReadTransmissionData(modelPath) externalReferences = transData.GetAllExternalFileReferenceIds() xref_links = [doc.GetElement(x) for x in externalReferences] except: logger.warning( 'Model must be saved for external links to be removed.') return remove_action('Remove All External Links', 'External Link', xref_links, validity_func=confirm_removal) else: logger.warning('Model must be saved for external links to be removed.')
def process_options(element_list): # find all relevant parameters param_sets = [] for el in element_list: shared_params = set() # find element parameters for param in el.ParametersMap: if is_calculable_param(param): pdef = param.Definition shared_params.add(ParamDef(pdef.Name, pdef.ParameterType)) # find element type parameters el_type = doc.GetElement(el.GetTypeId()) if el_type and el_type.Id != ElementId.InvalidElementId: for type_param in el_type.ParametersMap: if is_calculable_param(type_param): pdef = type_param.Definition shared_params.add(ParamDef(pdef.Name, pdef.ParameterType)) param_sets.append(shared_params) # make a list of options from discovered parameters all_shared_params = param_sets[0] for param_set in param_sets[1:]: all_shared_params = all_shared_params.intersection(param_set) return {'{} <{}>'.format(x.name, x.type):x for x in all_shared_params}
def calc_param_total(element_list, param_name): sum_total = 0.0 def _add_total(total, param): if param.StorageType == StorageType.Double: total += param.AsDouble() elif param.StorageType == StorageType.Integer: total += param.AsInteger() return total for el in element_list: param = el.LookupParameter(param_name) if not param: el_type = doc.GetElement(el.GetTypeId()) type_param = el_type.LookupParameter(param_name) if not type_param: logger.error('Elemend with ID: {} ' 'does not have parameter: {}.'.format(el.Id, param_name)) else: sum_total = _add_total(sum_total, type_param) else: sum_total = _add_total(sum_total, param) return sum_total
def __init__(self, xaml_file_name, rvt_elements): # cleanup selection (pick only acceptable curves) self.selected_lines = self._cleanup_selection(rvt_elements) self.active_view = doc.GetElement(self.selected_lines[0].OwnerViewId) # create pattern maker window and process options WPFWindow.__init__(self, xaml_file_name) self.dottypes_cb.ItemsSource = patmaker.DOT_TYPES self.dottypes_cb.SelectedIndex = 0 self.pat_name_tb.Focus()
def pick_and_match_styles(src_style): while True: try: dest_element = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element, 'Pick objects to change their graphic overrides.')) curview = doc.ActiveView with Transaction(doc, 'Match Graphics Overrides') as t: t.Start() curview.SetElementOverrides(dest_element.Id, src_style) t.Commit() except: break
def copy_sheet_viewports(activedoc, source_sheet, dest_doc, dest_sheet): existing_views = [ dest_doc.GetElement(x).ViewId for x in dest_sheet.GetAllViewports() ] for vport_id in source_sheet.GetAllViewports(): vport = activedoc.GetElement(vport_id) vport_view = activedoc.GetElement(vport.ViewId) print('\t\tCopying/updating view: {}'.format(vport_view.ViewName)) new_view = copy_view(activedoc, vport_view, dest_doc) if new_view: if new_view.Id not in existing_views: print('\t\t\tPlacing copied view on sheet.') t = Transaction(dest_doc, 'Place View on Sheet') t.Start() new_vport = Viewport.Create(dest_doc, dest_sheet.Id, new_view.Id, vport.GetBoxCenter()) t.Commit() else: print('\t\t\tView already exists on the sheet.')
def process_sets(element_list): el_sets = DefaultOrderedDict(list) # add all elements as first set, for totals of all elements el_sets['All Selected Elements'].extend(element_list) # separate elements into sets based on their type for el in element_list: if hasattr(el ,'LineStyle'): el_sets[el.LineStyle.Name].append(el) else: tname = Element.Name.GetValue(doc.GetElement(el.GetTypeId())) el_sets[tname].append(el) return el_sets
def _calc_param_total(param_name): total = 0.0 for el in selection.elements: param = el.LookupParameter(param_name) if not param: el_type = doc.GetElement(el.GetTypeId()) type_param = el_type.LookupParameter(param_name) if not type_param: print('Elemend with ID: {} does not have {} parameter.'.format( el.Id, param_name)) else: total = _add_total(total, type_param) else: total = _add_total(total, param) return total
def __init__(self, view_id): self.element = doc.GetElement(view_id) if not self._valid_view(): raise Exception() title = self.element.LookupParameter('Title on Sheet').AsString() self.name = title if title else self.element.ViewName self.refs = [] self._update_refs(all_ref_els) # self._update_refs(self.element.GetReferenceCallouts()) # self._update_refs(self.element.GetReferenceSections()) # self._update_refs(self.element.GetReferenceElevations()) self.sheet_num = self.element.LookupParameter( 'Sheet Number').AsString() self.sheet_name = self.element.LookupParameter('Sheet Name').AsString() self.ref_det = self.element.LookupParameter('Detail Number').AsString()
def listconstraints(selelement): print('THIS OBJECT ID: {0}'.format(selelement.Id)) clconst = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Constraints).WhereElementIsNotElementType() constlst = set() for cnst in clconst: refs = [(x.ElementId, x) for x in cnst.References] elids = [x[0] for x in refs] if selelement.Id in elids: constlst.add(cnst) print("CONST TYPE: {0} # OF REFs: {1} CONST ID: {2}".format(cnst.GetType().Name.ljust(28), str(cnst.References.Size).ljust(24), cnst.Id)) for t in refs: ref = t[1] elid = t[0] if elid == selelement.Id: elid = str(elid) + ' (this)' print(" {0} LINKED OBJ CATEGORY: {1} ID: {2}".format(ref.ElementReferenceType.ToString().ljust(35), doc.GetElement( ref.ElementId).Category.Name.ljust(20), elid)) print('\n') print('\n')
BuiltInCategory.OST_Rooms).WhereElementIsNotElementType( ).ToElementIds() allelements = [] allelements.extend(rooms) allelements.extend(roomtags) element_to_isolate = List[ElementId](allelements) elif selected_switch == 'Model Groups': elements = FilteredElementCollector( doc, curview.Id).WhereElementIsNotElementType().ToElementIds() modelgroups = [] expanded = [] for elid in elements: el = doc.GetElement(elid) if isinstance(el, Group) and not el.ViewSpecific: modelgroups.append(elid) members = el.GetMemberIds() expanded.extend(list(members)) expanded.extend(modelgroups) element_to_isolate = List[ElementId](expanded) elif selected_switch == 'Painted Elements': set = [] elements = FilteredElementCollector( doc, curview.Id).WhereElementIsNotElementType().ToElementIds() for elId in elements: el = doc.GetElement(elId) if len(list(el.GetMaterialIds(True))) > 0:
def members(self): return [doc.GetElement(x) for x in self.group.GetMemberIds()]
for idx, sub_grp in enumerate(groupnode): last = idx == count -1 if last: sub_grp_trunk = trunk + inset + ' ' sub_grp_branch = trunk + inset + '└──' else: sub_grp_trunk = trunk + inset + '│' sub_grp_branch = trunk + inset + '├──' print_tree(sub_grp, level + 1, sub_grp_trunk, sub_grp_branch) # inspect the selection and find first parents parent_groups = [] if not selection.is_empty: for element in selection.elements: if hasattr(element, 'GroupId'): firstparent = element while firstparent.GroupId != ElementId.InvalidElementId: firstparent = doc.GetElement(firstparent.GroupId) if isinstance(firstparent, Group): parent_groups.append(GroupNode(firstparent)) # print group structure for all discovered parent groups for parent_grp in parent_groups: print_tree(parent_grp, 0) print('\n\n')
def _find_all_revisions(self): self._revisions = set([cloud.RevisionId for cloud in self._clouds]) self._rev_numbers = set([ doc.GetElement(rev_id).RevisionNumber for rev_id in self._revisions ])
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory this_script.output.print_md('**LIST OF REVISIONS:**') cl = FilteredElementCollector(doc) revs = cl.OfCategory( BuiltInCategory.OST_Revisions).WhereElementIsNotElementType() for rev in revs: print('{0}\tREV#: {1}\tDATE: {2}\tTYPE:{3}\tDESC: {4}'.format( rev.SequenceNumber, str(rev.RevisionNumber).ljust(5), str(rev.RevisionDate).ljust(10), str(rev.NumberType.ToString()).ljust(15), rev.Description)) this_script.output.print_md('*****\n\n\n###REVISED SHEETS:\n') sheetsnotsorted = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToElements() sheets = sorted(sheetsnotsorted, key=lambda x: x.SheetNumber) for sht in sheets: revs = sht.GetAllRevisionIds() if len(revs) > 0: print('{}\t{}\t{}'.format( this_script.output.linkify(sht.Id), sht.LookupParameter('Sheet Number').AsString(), sht.LookupParameter('Sheet Name').AsString())) for rev in revs: rev = doc.GetElement(rev) print('\tREV#: {0}\t\tDATE: {1}\t\tDESC:{2}'.format( rev.RevisionNumber, rev.RevisionDate, rev.Description))
return view_name in self.refs def is_sheeted(self): return self.sheet_num != '' print 'Collecting all view references in all view...' for view in views: try: rv = ReferencingView(view.Id) all_views.append(rv) except: pass print '{} views processed...'.format(len(all_views)) for selid in selection: vp = doc.GetElement(selid) if isinstance(vp, Viewport): v = doc.GetElement(vp.ViewId) title = v.LookupParameter('Title on Sheet').AsString() print '\n\nVIEW NAME: {}\n Referenced by:'.format( title if title else v.ViewName) for r_view in all_views: if r_view.is_sheeted() and r_view.is_referring_to(v.ViewName): print('\t\t{} : {}/{} : {}'.format( this_script.output.linkify(r_view.element.Id), r_view.ref_det, r_view.sheet_num, r_view.name))
# noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import BuiltInCategory, WorksharingUtils clouded_views = defaultdict(list) rev_clouds = Fec(doc).OfCategory(BuiltInCategory.OST_RevisionClouds ).WhereElementIsNotElementType().ToElements() notification = """ Note that legends with revision clouds will not trigger the sheet index of the sheet they are placed on!""" for rev_cloud in rev_clouds: rev_view_id = rev_cloud.OwnerViewId rev_view = doc.GetElement(rev_view_id) if rev_view.ViewType.ToString() == "Legend": clouded_views[rev_view_id].append(rev_cloud) this_script.output.print_md("####LEGENDS WITH REVISION CLOUDS:") this_script.output.print_md('By: [{}]({})'.format(__author__, __contact__)) for view_id in clouded_views: view = doc.GetElement(view_id) this_script.output.print_md("{1} **Legend: {0}**".format( view.Name, this_script.output.linkify(view_id))) for rev_cloud in clouded_views[view_id]: rev_cloud_id = rev_cloud.Id rev_date = doc.GetElement(rev_cloud.RevisionId).RevisionDate rev_creator = WorksharingUtils.GetWorksharingTooltipInfo(
return self.type_name == other.type_name def __hash__(self): return hash(self.type_name) def __lt__(self, other): if self.sort_alphabetically or other.sort_alphabetically: return self.type_name < other.type_name else: return self.number_list < other.number_list # collect all symbols already loaded ----------------------------------------------------------------------------------- loaded_symbols = set() for sym_id in fam_symbol.GetFamilySymbolIds(): fam_sym = doc.GetElement(sym_id) fam_sym_name = Element.Name.GetValue(fam_sym) sortable_sym = SmartSortableFamilyType(fam_sym_name) logger.debug('Loaded Type: {}'.format(sortable_sym)) loaded_symbols.add(sortable_sym) # get family document and verify the file exists ----------------------------------------------------------------------- fam_doc = doc.EditFamily(fam_symbol) fam_doc_path = fam_doc.PathName if not op.exists(fam_doc_path): TaskDialog.Show( 'pyRevit', 'Can not file original family file at\n{}'.format(fam_doc_path)) logger.debug( 'Can not file original family file at {}'.format(fam_doc_path)) this_script.exit()
"""Lists views that have a template assigned to them.""" from scriptutils import this_script from revitutils import doc, uidoc from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, View cl_views = FilteredElementCollector(doc) views = cl_views.OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() for v in views: vtid = v.ViewTemplateId vt = doc.GetElement(vtid) if vt: phasep = v.LookupParameter('Phase') print('TYPE: {1} ID: {2} TEMPLATE: {3} PHASE:{4} {0}'.format( v.ViewName, str(v.ViewType).ljust(20), this_script.output.linkify(v.Id), str(v.IsTemplate).ljust(10), phasep.AsValueString().ljust(25) if phasep else '---'.ljust(25)))
from collections import defaultdict from scriptutils import this_script from revitutils import doc, uidoc clr.AddReference('RevitAPI') # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.UI import TaskDialog this_script.output.print_md("####LIST ALL ELEMENTS ON SELECTED LEVEL(S):") this_script.output.print_md('By: [{}]({})'.format(__author__, __contact__)) all_elements = Fec(doc).WhereElementIsNotElementType().ToElements() selection = [doc.GetElement(elId) for elId in uidoc.Selection.GetElementIds()] levels = [] for el in selection: if el.Category.Name == 'Levels': levels.append(el) if not levels: TaskDialog.Show('pyRevit', 'At least one Level element must be selected.') else: all_count = all_elements.Count print('\n' + str(all_count) + ' Elements found in project.') for element in levels: element_categories = defaultdict(list) level = element
def _update_refs(self, el_list): for elid in el_list: el = doc.GetElement(elid) if el.OwnerViewId == self.element.Id: self.refs.append(el.Name)
param_name = param.Definition.Name if not param.IsReadOnly and param_name not in exclude_params: if param_name in value_dict.keys(): param_value = value_dict[param_name] try: logger.debug('Setting param: {} to value: {}'.format( param_name, param_value)) param.Set(param_value) except: logger.debug('Param: {} Value is not settable: {}'.format( param_name, param_value)) with Transaction(doc, 'Change Element Types') as t: t.Start() src_element = selection.utils.pick_element( 'Pick object with source element type') if src_element: src_type = src_element.GetTypeId() for dest_element in selection.elements: logger.debug('Converting: {} | {}'.format(dest_element.Id, dest_element)) value_dict = get_param_values(dest_element) new_element = dest_element.ChangeTypeId(src_type) if new_element != ElementId.InvalidElementId: set_param_values(doc.GetElement(new_element), value_dict) else: set_param_values(dest_element, value_dict) t.Commit()
print('Hello22'.format()) rvt_uidoc = __revit__.ActiveUIDocument this_sel = rvt_uidoc.Selection this_sel = selection print(this_sel) print(dir(this_sel)) #print(this_sel.ToString()) elIDS = rvt_uidoc.Selection.GetElementIds() print(elIDS) mech_eq_ID = elIDS[0] print(mech_eq_ID) print(type(mech_eq_ID)) mech_eq_el = doc.GetElement(mech_eq_ID) #print(mech_eq_el) #print(dir(mech_eq_el)) #for i in dir(mech_eq_el): # print(i) print("*********") #room_attr = mech_eq_el.Room #print(room_attr) #print(type(room_attr)) def get_room(phase, ele): phase = list(doc.Phases)[1] room = mech_eq_el.Room[phase] #print(room.Name.ToString()) this_number = room.Number
if selection.is_empty: if isinstance(curview, ViewSheet): sheetlist.append(curview) else: for sel_view in selection: if isinstance(sel_view, ViewSheet): sheetlist.append(sel_view) if not sheetlist: TaskDialog.Show( 'pyrevit', 'You must have at least one sheet selected or active view must be a sheet.' ) sys.exit() with Action('Pin all viewports'): for sheet in sheetlist: count = 0 alreadypinnedcount = 0 for vportid in sheet.GetAllViewports(): vport = doc.GetElement(vportid) if not vport.Pinned: vport.Pinned = True count += 1 else: alreadypinnedcount += 1 print('Pinned {} viewports on sheet: {} - {}' '\n({} viewports were already pinned)'.format( count, sheet.SheetNumber, sheet.Name, alreadypinnedcount))
for v in views: try: filters = v.GetFilters() for flid in filters: usedFiltersSet.add(flid.IntegerValue) except: continue unusedFilters = allFilters - usedFiltersSet if unusedFilters: print('{} Filters have not been used and will be purged.'.format( len(unusedFilters))) t = Transaction(doc, 'Purge Unused Filters') t.Start() for flid in unusedFilters: fl = doc.GetElement(ElementId(flid)) print('Purging Filter: {0}\t{1}'.format(fl.Id, fl.Name)) try: doc.Delete(ElementId(flid)) except Exception as del_err: logger.error('Error purging filter: {} | {}'.format( fl.Name, del_err)) t.Commit() else: print('All filters are in use. No purging in necessary.')
detail_lines = defaultdict(int) all_lines = Fec(doc).OfCategory(BuiltInCategory.OST_Lines).WhereElementIsNotElementType().ToElements() for line in all_lines: if line.CurveElementType.ToString() == "DetailCurve": view_id_int = line.OwnerViewId.IntegerValue detail_lines[view_id_int] += 1 this_script.output.print_md("####LINE COUNT IN CURRENT VIEW:") this_script.output.print_md('By: [{}]({})'.format(__author__, __contact__)) for line_count, view_id_int in sorted(zip(detail_lines.values(), detail_lines.keys()), reverse=True): view_id = ElementId(view_id_int) view_creator = WorksharingUtils.GetWorksharingTooltipInfo(doc, view_id).Creator try: view_name = doc.GetElement(view_id).ViewName except: view_name = "<no view name available>" this_script.output.print_md("\n**{0} Lines in view:** {3}\n" \ "View id:{1}\n" \ "View creator: {2}\n".format(line_count, this_script.output.linkify(view_id), view_creator, view_name)) print("\n" + str(sum(detail_lines.values())) + " Lines in " + str(len(detail_lines)) + " Views.")
views = Fec(doc).OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() for v in views: if not v.IsTemplate: if v.ViewType == ViewType.DraftingView: dviews.append(v) elif v.ViewType == ViewType.Legend: lviews.append(v) else: mviews.append(v) sheets = Fec(doc).OfCategory( BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToElements() for sht in sheets: vp_ids = [doc.GetElement(x).ViewId for x in sht.GetAllViewports()] all_sheeted_view_ids.extend(vp_ids) this_script.output.print_md('### DRAFTING VIEWS NOT ON ANY SHEETS') for v in dviews: if v.Id in all_sheeted_view_ids: continue else: print('TYPE: {1}\t\tID: {2}\t\t{0}'.format( v.ViewName, v.ViewType, this_script.output.linkify(v.Id))) this_script.output.print_md('### MODEL VIEWS NOT ON ANY SHEETS') for v in mviews: if v.Id in all_sheeted_view_ids: continue else: