def load_family(folder_path='Insert Path Here', file_name='Insert File Name Here'): 'Loads a family into the Revit project with path and file name.' family_path = os.path.join(folder_path, file_name) if os.path.exists(family_path) is False: return 'Path does not exist.' family_loaded = clr.Reference[Autodesk.Revit.DB.Family]() t = Transaction(doc) t.Start('Load Family') loaded = doc.LoadFamily(family_path, FamilyLoadOptions(), family_loaded) if loaded: family = family_loaded.Value symbols = [] for family_symbol_id in family.GetFamilySymbolIds(): family_symbol = doc.GetElement(family_symbol_id) symbols.append(family_symbol) for s in symbols: try: s.Activate() except: pass t.Commit() return symbols else: t.Commit() return 'Family already exists in project.'
def DeleteExcessLineStyles(doc, list, start_time, limit): lineStyle = doc.Settings.Categories.get_Item( BuiltInCategory.OST_Lines).SubCategories standard = {} for i in lineStyle: # individual transactions t = Transaction(doc, 'Delete Excess Line Styles') t.Start() if not i.Name in list and i.Name[ 0] != '<' and i.Id.IntegerValue > 0 and time.time( ) - start_time < limit: try: if i.Name[0:5] == prefix: standard[i.Name] = i else: print('Deleting Line Style ' + i.Name) doc.Delete(i.Id) except: print('Failed to Delete ' + i.Name) t.Commit() sel_delete = forms.SelectFromList.show(standard.keys(), button_name='Select Item', multiselect=True) for s in sel_delete: if time.time() - start_time < limit: t = Transaction(doc, 'Delete Excess Line Styles') t.Start() print('Deleting Line Style ' + standard[s].Name) doc.Delete(standard[s].Id) t.Commit()
def check_for_selected_code(self, selected_code): if len(selected_code) == 0: self.sublabel_no_selection.Text = "Please select an Assembly Code First!" if len(selected_code) > 0: self.sublabel.Text = "Number of Assembly Codes Selected: " + str( len(selected_code)) ids = list() for i, v in id_assembly_dict.iteritems(): if len(v) > 1: for code in selected_code: if v[0] == code: ids.append(i.Id) self.sublabel_objects.Text = "Number of Objects Current Selection: " + str( len(ids)) #Hide Reset Active View t = Transaction(doc, 'Reset HideIsolate') t.Start() view.TemporaryViewModes.DeactivateAllModes() t.Commit() idElements = List[ElementId](ids) #Hide Isolate Objects in Active View t = Transaction(doc, 'Filter Elements') t.Start() view.IsolateElementsTemporary(idElements) t.Commit()
def check_empty_assembly_code(self, selected_code): self.sublabel_no_selection.Text = "" ids = list() element_instances = [] for i, v in id_empty_dict.iteritems(): if len(v) == 0: element_instances.append(i.Id) ids.append(i.Id) self.sublabel_objects.Text = "Number of Objects Current Selection: " + str( len(ids)) assembly_codes_selected = '-' self.sublabel.Text = "Number of Assembly Codes Selected: " + str( assembly_codes_selected) #Hide Reset Active View t = Transaction(doc, 'Reset HideIsolate') t.Start() view.TemporaryViewModes.DeactivateAllModes() t.Commit() idElements = List[ElementId](ids) #Hide Isolate Objects in Active View t = Transaction(doc, 'Filter Elements') t.Start() view.IsolateElementsTemporary(idElements) t.Commit()
def createobj(type): # get Drafting View named "xForm" for object creation and Selection. fecv = DB.FilteredElementCollector(doc).OfClass(DB.ViewDrafting) \ .WhereElementIsNotElementType().ToElements() dv = [i for i in fecv if i.ViewName.Equals("xForm")] draftview = dv[0] if dv else None if not draftview: t = Transaction(doc, "xForm") t.Start() fec = DB.FilteredElementCollector(doc).OfClass( DB.ViewFamilyType).ToElements() viewdrafttype = [ i for i in fec if i.ViewFamily.Equals(DB.ViewFamily.Drafting) ][0] draftview = DB.ViewDrafting.Create(doc, viewdrafttype.Id) draftview.Name = "xForm" t.Commit() print draftview.Name # Get line of linestyle = type fec = FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Lines) \ .ToElements() detailc = [ i for i in fec if i.CurveElementType.Equals(DB.CurveElementType.DetailCurve) ] li = [i for i in detailc if i.LineStyle.Id.Equals(type.Id)] line = li[0] if li else None if not line: print "line not found" try: t = Transaction(doc, "Draw Line") t.Start() linee = DB.Line.CreateBound(XYZ.Zero, XYZ(0, 10, 0)) line = doc.Create.NewDetailCurve(draftview, linee) print type line.LineStyle = type t.Commit() except: import traceback print traceback.format_exc() if line and draftview: # Select it/Add it to Selection listId = List[ElementId]() listId.Add(line.Id) uidoc.Selection.SetElementIds(listId) # Start CreateSimilar Command. try: revitcomid = UI.RevitCommandId.LookupPostableCommandId( UI.PostableCommand.CreateSimilar) if revitcomid: uiapp.PostCommand(revitcomid) except: import traceback print traceback.format_exc()
def firstrun(): # get Drafting View named "xForm" for object creation and Selection. fecv = DB.FilteredElementCollector(doc).OfClass(DB.ViewDrafting) \ .WhereElementIsNotElementType().ToElements() dv = [i for i in fecv if i.ViewName.Equals("xForm")] draftview = dv[0] if dv else None #print "no draftview, create one", draftview if not draftview: t = Transaction(doc, "xForm") t.Start() fec = DB.FilteredElementCollector(doc).OfClass( DB.ViewFamilyType).ToElements() viewdrafttype = [ i for i in fec if i.ViewFamily.Equals(DB.ViewFamily.Drafting) ][0] draftview = DB.ViewDrafting.Create(doc, viewdrafttype.Id) draftview.Name = "xForm" t.Commit() #print draftview, draftview.Name lines = FilteredElementCollector(doc, draftview.Id) \ .OfCategory(DB.BuiltInCategory.OST_Lines) \ .ToElements() if not lines: #print "NO line" t = Transaction(doc, "Draw Line") t.Start() linee = DB.Line.CreateBound(XYZ.Zero, XYZ(0, 10, 0)) singleline = doc.Create.NewDetailCurve(draftview, linee) t.Commit() lines = List[Element]() lines.Add(singleline) lstyles = sorted([(doc.GetElement(i).Name, doc.GetElement(i)) for i in lines[0].GetLineStyleIds()]) #print len(lstyles), len(lines) if not len(lstyles) == len(lines): t = Transaction(doc, "Create Lines with Linestyles") t.Start() [doc.Delete(i.Id) for i in lines] for i in range(len(lstyles)): linee = DB.Line.CreateBound(XYZ(i * 2, 0, 0), XYZ(i * 2, 10, 0)) line = doc.Create.NewDetailCurve(draftview, linee) line.LineStyle = lstyles[i][1] t.Commit() return lstyles
def firstrun(): # get Drafting View named "xForm" for object creation and Selection. fecv = DB.FilteredElementCollector(doc).OfClass(DB.ViewDrafting) \ .WhereElementIsNotElementType().ToElements() dv = [i for i in fecv if i.ViewName.Equals("xForm")] draftview = dv[0] if dv else None if not draftview: t = Transaction(doc, "xForm") t.Start() fec = DB.FilteredElementCollector(doc).OfClass( DB.ViewFamilyType).ToElements() viewdrafttype = [ i for i in fec if i.ViewFamily.Equals(DB.ViewFamily.Drafting) ][0] draftview = DB.ViewDrafting.Create(doc, viewdrafttype.Id) draftview.Name = "xForm" draftview.Scale = 100 t.Commit() #print draftview, draftview.Name notes = FilteredElementCollector(doc, draftview.Id).OfClass(TextNote) \ .WhereElementIsNotElementType() \ .ToElements() notetypes = sorted( DB.FilteredElementCollector(doc).OfClass(DB.TextNoteType).ToElements(), key=lambda x: x.get_Parameter(DB.BuiltInParameter.SYMBOL_NAME_PARAM ).AsString()) if not notes or not len(notes) == len(notetypes): # TextNote Create( Document document, ElementId viewId, XYZ position, string text, ElementId typeId ) t = Transaction(doc, "Create TextNotes of all TextTypes in DraftingView") t.Start() if not len(notes) == len(notetypes): [doc.Delete(i.Id) for i in notes] for i, j in enumerate(notetypes): text = j.get_Parameter( DB.BuiltInParameter.SYMBOL_NAME_PARAM).AsString() textnote = DB.TextNote.Create(doc, draftview.Id, XYZ(0, -i * 3.5, 0), text, j.Id) t.Commit() return [(i.get_Parameter(DB.BuiltInParameter.SYMBOL_NAME_PARAM).AsString(), i) for i in notetypes] # Tupel
def delete_elements(type): t = Transaction(doc, "Delete selection") t.Start() for elid in uidoc.Selection.GetElementIds(): #print elid doc.Delete(elid) t.Commit()
def btnDeleteFilters_Click(self, sender, args): selected_Filters_Name = self.lbFiltersName.SelectedItems #cant use global? selected_Filters = map(lambda f: filter_source[filter_names.index(f)], selected_Filters_Name) #cant use global? if not selected_Filters: warningDialog.MainContent = "No Filter is selected!" warningDialog.DefaultButton = UI.TaskDialogResult.Cancel warningDialog.Show() else: warningDialog.MainContent = "{} will be deleted.\n Are you sure?".\ format(map(lambda x: x,\ selected_Filters_Name)) warningDialog.CommonButtons = UI.TaskDialogCommonButtons.Yes\ | UI.TaskDialogCommonButtons.No warnDialog = warningDialog.Show() if warnDialog == UI.TaskDialogResult.Yes: trans = Transaction(doc, "Delete Filters") trans.Start() map(lambda x: viewInstance.RemoveFilter(x), selected_Filters) trans.Commit() #Update Filters List view_Instance_Name_ = self.cbbViewName.SelectedItem if view_Instance_Name_ in view_Source_Name: filter_Source_ = view_Source[view_Source_Name.\ index(view_Instance_Name_)].GetFilters() self.lbFiltersName.ItemsSource = map(lambda i: doc.GetElement(i).Name,\ filter_Source_)
class Action: def __init__(self, name=None): self.transaction = Transaction(doc, name if name else DEFAULT_TRANSACTION_NAME) def __enter__(self): self.transaction.Start() return self.transaction def __exit__(self, exception, exception_value, traceback): if exception: self.transaction.RollBack() logger.error('Error in Transaction Context. Rolling back changes. | {}:{}'.format(exception, exception_value)) else: try: self.transaction.Commit() except Exception as errmsg: self.transaction.RollBack() logger.error('Error in Transaction Commit. Rolling back changes. | {}'.format(errmsg)) @staticmethod def carryout(name): from functools import wraps def wrap(f): @wraps(f) def wrapped_f(*args, **kwargs): with Action(name): return_value = f(*args, **kwargs) return return_value return wrapped_f return wrap
def Execute(self, app): if start_increase.GetValue()['Да'] or end_increase.GetValue()['Да']: t = Transaction(doc, 'Добавить учащение') t.Start() rebar = RB_Rebar(selection[0]) path_length = rebar.ArrayLength normale = rebar.Normal start_space = rebar.rebar.MaxSpacing reb_count = int(ceil(path_length / start_space)) biv = (path_length - (reb_count - 1) * start_space) rebars = List[ElementId]() rebars.Add(rebar.rebar.Id) if end_increase.GetValue()['Да'] and start_increase.GetValue( )['Да']: biv = biv / 2 if biv > to_feet(20): rebar.SetAsNumberWithSpacing(reb_count, start_space) if start_increase.GetValue()['Да']: rebar.translate(normale * biv) tr = rebar.copy_by_normal_length(normale * -biv) tr.SetAsSingle() rebars.Add(tr.rebar.Id) if end_increase.GetValue()['Да']: tr = rebar.copy_by_normal_length( normale * (start_space * (reb_count - 1) + biv)) tr.SetAsSingle() rebars.Add(tr.rebar.Id) __revit__.ActiveUIDocument.Selection.SetElementIds(rebars) t.Commit() FORM.Close()
def create_gird(scoord, ecoord, name_gird ): # context-like objects that guard any # changes made to a Revit model t = Transaction(doc, "Create grids") # Starts the transaction. t.Start() # create line reference line_ref = Line.CreateBound(scoord, ecoord) # create gird grid_ins = Grid.Create(doc, line_ref) # retrieve name for gird name = grid_ins.get_Parameter(BuiltInParameter.DATUM_TEXT) # set name for gird name.Set(name_gird) # Commits all changes made # to the model during the transaction. t.Commit()
def link_method_ifc(): files_filter = "IFC files (*.ifc)|*.ifc" files = pick_files(files_filter) for f in files: t = Transaction(doc) t.Start(__title__) f_cache = f + ".rvt" recreate = not os.path.exists(f_cache) logger.debug("Recreate ifc %s = %s" % (f, recreate)) # try: o = RevitLinkOptions(False) # create empty doc if recreate: doc_ifc = HOST_APP.app.OpenIFCDocument(f) save_options = SaveAsOptions() save_options.OverwriteExistingFile = True doc_ifc.SaveAs(f_cache, save_options) doc_ifc.Close() link_load_results = RevitLinkType.CreateFromIFC(doc, f, f_cache, False, o) # TODO log results http://www.revitapidocs.com/2019/11b095e1-24d9-91b9-ae2e-004f67c94d6e.htm logger.debug(link_load_results.LoadResult) instance = RevitLinkInstance.Create(doc, link_load_results.ElementId) status = True # except Exception as e: # logger.error("Unable to import IFC") # logger.error(e) # status = False # instance = None if status: instance.Pinned = True t.Commit() else: t.RollBack()
def button_title(self, sender, e): t = Transaction(doc, __title__) t.Start() for TN in self.selected_text_notes: TN.Text = str(TN.Text).title() t.Commit()
def run(self, sender, args): text_find = self.text_find text_replace = self.text_replace count_changed = 0 t = Transaction(doc, __title__) t.Start() for e in self.selection: definition = self.parameter_to_set.Definition param = e.get_Parameter(definition) param_before = param.AsString() param_after = param_before.replace(text_find, text_replace) if param_before != param_after: count_changed += 1 self.parameter_value_set(param, param_after) if count_changed: t.Commit() TaskDialog.Show( __title__, "%d of %d elements updated" % ( count_changed, len(self.selection), )) else: t.RollBack() TaskDialog.Show(__title__, "Nothing was updated")
def button_find_replace(self, sender, e): t = Transaction(doc, __title__) t.Start() for TN in self.selected_text_notes: TN.Text = self.prefix + str(TN.Text).replace( self.find, self.replace) + self.suffix t.Commit()
def run(self, sender, args): # print(dir(self)) if not(self.parameter_to_sort and self.parameter_to_sort != "" and self.parameter_to_set and self.parameter_to_set != ""): forms.alert("Error! All the parameters should be set") return result = self.sort(self.selection, self.parameter_to_sort, self.is_reversed) i = self.start_from text_format = self.text_format zeros = self.leading_zeros t = Transaction(doc, __title__) t.Start() for r in result: e = r[0] definition = self.parameter_to_set.Definition param = e.get_Parameter(definition) if zeros: _i = str(i).zfill(zeros) else: _i = str(i) self.parameter_value_set(param, _i, text_format) i += 1 t.Commit() my_config.start_from = i # selection_doc.set self.selection try: self.write_config() except: pass logger.debug("run - set_to", map(lambda e: e[0].Id.IntegerValue, result)) selection_pyr.set_to(map(lambda e: e[0].Id, result)) self.Close()
def createsheets(sheetlist): message = [] dic_sheetGuid = {} t = Transaction(doc, "Create SheetViews from EXCEL") try: t.Start() for j in sheetlist: try: tibl = dic_tibl[j[2]] except: mess1 = 'Error: TitleBlock1 "{}" not found'.format(j[2]) message.append(mess1) continue a = DB.ViewSheet.Create(doc, tibl.Id) # ViewSheet Class, Create Method a.SheetNumber = j[0] a.ViewName = j[1] dic_sheetGuid[a.SheetNumber] = str(a.UniqueId) #create TitleBlock2 instance try: tibl_2 = dic_tibl[j[3]] newtitleblock = doc.Create.NewFamilyInstance( XYZ(0, 0, 0), tibl_2, a) mess2 = '; TitleBlock2: {}'.format(str(j[3])) except: mess2 = '; TitleBlock2: not found' pass message.append('--> {}-{}, TiBl1: {}'.format( a.SheetNumber, a.ViewName, j[2]) + mess2) t.Commit() except: t.RollBack() import traceback print(traceback.format_exc()) return (message, dic_sheetGuid)
def parameterupdate(exel_datalist): #Create a list from FECsheets matching ex_row_paralist in Project # using SheetNR for Equality Check, do this with FEC? sheetviews = [] excel_data = [] for i in exel_datalist: if i[0] and i[1] and i[5]: for j in FECsheet: if j.SheetNumber == i[0]: sheetviews.append(j) excel_data.append(i) #GUID BuiltInParameter --------------------------- sheet_issuedate = DB.BuiltInParameter.SHEET_ISSUE_DATE sheet_drawnby = DB.BuiltInParameter.SHEET_DRAWN_BY mess = [] t = Transaction(doc, "update sheet parameters") t.Start() for i, j in zip(sheetviews, excel_data): try: date = getnsetBIP(i, sheet_issuedate, j[5]) drawnby = getnsetBIP(i, sheet_drawnby, j[6]) man_massstab = getnsetSharedPara(i, "man_Massstab", j[7]) pbrowser = getnsetSharedPara(i, "PBrowser", j[4]) mess2 = ' {}-{} --> PBrowser: {}, issue_date: {}, drawnby: {}, M: {}'.format( i.SheetNumber, i.Name, pbrowser, date, drawnby, man_massstab) mess.append(mess2) except: error = 'Error ' mess.append(error) import traceback print("\n", traceback.format_exc()) continue t.Commit() return mess
def link_method_ifc(): files_filter = "IFC files (*.ifc)|*.ifc" files = pick_files(files_filter) for f in files: t = Transaction(doc) t.Start(__title__) f_cache = f + ".rvt" recreate = not os.path.exists(f_cache) logger.debug("Recreate ifc %s = %s" % (f, recreate)) # try: o = RevitLinkOptions(False) # create empty doc if recreate: new_doc = doc.Application.NewProjectDocument(UnitSystem.Metric) new_doc.SaveAs(f_cache) new_doc.Close(False) link_load_results = RevitLinkType.CreateFromIFC( doc, f, f_cache, recreate, o) # TODO log results http://www.revitapidocs.com/2019/11b095e1-24d9-91b9-ae2e-004f67c94d6e.htm logger.debug(link_load_results.LoadResult) instance = RevitLinkInstance.Create(doc, link_load_results.ElementId) status = True # except Exception as e: # logger.error("Unable to import IFC") # logger.error(e) # status = False # instance = None if status: instance.Pinned = True t.Commit() else: t.RollBack()
def createSharedPara(_paramName_string,_groupNameinSPfile_string, \ _paramtype_enum, _builtInCat_enum,_paramGroupinProperty_enum): # open SharedParameterFile file = uiapp.Application.OpenSharedParameterFile() # get GroupName in SharedParameter file, if not exist create new Group group = file.Groups.get_Item(_groupNameinSPfile_string) if group == None: group = file.Groups.Create(_groupNameinSPfile_string) # Create NewCategorySet() catset = app.Create.NewCategorySet() # Insert Category Objects in CatSet <Autodesk.Revit.DB.Category object catset.Insert(doc.Settings.Categories.get_Item(_builtInCat_enum)) # returns True # create an instance binding object with categoryset inst_bind = app.Create.NewInstanceBinding(catset) #ExternalDefinitionCreationOptions Class excpects ( paraname as string, paratype object) # An option class used for creating a new shared parameter definition, ED_opt1 = ExternalDefinitionCreationOptions(_paramName_string, _paramtype_enum) ED_opt1.Visible = True # True is the default value #Create Parameter Definition Object #Test if paraName is in SharedParam file , get Para Name Definition from file, else Create new Name if group.Definitions.Contains(group.Definitions.Item[_paramName_string]): _exdef1 = group.Definitions.Item[_paramName_string] # create parameter definition object from Para in file else: # _def = group.Definitions.Create(_paramName, _paramtype_enum, _visible) _exdef1 = group.Definitions.Create(ED_opt1) #Create para Definition object wit Ext #Create Parameter by inserting the Para Definition in the ParameterBindigs_Map try: t = Transaction(doc, "Parameter Creation") t.Start() bind_Map = doc.ParameterBindings.Insert(_exdef1, inst_bind, _paramGroupinProperty_enum) t.Commit() except: import traceback print(traceback.format_exc())
def link_method_rvt(): files_filter = "RVT files (*.rvt)|*.rvt" files = pick_files(files_filter) for f in files: t = Transaction(doc) t.Start(__title__) try: mp = ModelPathUtils.ConvertUserVisiblePathToModelPath(f) o = RevitLinkOptions(False) linkType = RevitLinkType.Create(doc, mp, o) instance = RevitLinkInstance.Create(doc, linkType.ElementId) status = True except Exception as e: logger.error("Unable to import RVT") logger.error(e) status = False instance = None if status: instance.Pinned = True t.Commit() else: t.RollBack()
def SetParameterInstance(ElementInstance, ParameterName, ParameterValue): ElementInstance = ElementInstance.Symbol Parameter = ElementInstance.LookupParameter(ParameterName) t = Transaction(doc, "Set parameter") t.Start() Parameter.Set(ParameterValue) t.Commit()
def addFilter(): try: t = Transaction(doc, "AddFilterToView") t.Start() [doc.ActiveView.AddFilter(i.Id) for i in response3] t.Commit() except Exceptions.OperationCanceledException: pass
def removeFilter(): try: t = Transaction(doc, "RemoveFilterFromView") t.Start() [doc.ActiveView.RemoveFilter(i.Id) for i in response3] t.Commit() except Exceptions.OperationCanceledException: pass
def set_param_from_symbol(FamilySymbol, ParameterName, ParameterValue): """ set param from symbol """ Parameter = FamilySymbol.LookupParameter(ParameterName) t = Transaction(doc, "Set parameter") t.Start() Parameter.Set(ParameterValue) t.Commit()
def AppendPrefixtoLines(doc, start_time, limit): lineStyles = doc.Settings.Categories.get_Item( BuiltInCategory.OST_Lines).SubCategories names = {} styleName = [] for i in lineStyles: if not i.Name[0:len(prefix)] == prefix and not i.Id.IntegerValue < 0: names[i.Name] = i styleName.append(i.Name) sel_styleName = forms.SelectFromList.show(styleName, button_name='Select Item', multiselect=True) sel_style = [] for i in sel_styleName: sel_style.append(names[i]) # Non-Standard Line Changer for i in sel_style: t = Transaction(doc, 'Add PA prefix to Name') t.Start() if time.time() - start_time < limit: weight = i.GetLineWeight(GraphicsStyleType.Projection).ToString() pattern = doc.GetElement( i.GetLinePatternId(GraphicsStyleType.Projection)) if pattern is None: patternName = 'Solid' else: patternName = pattern.Name uniqueParam = weight + patternName categories = doc.Settings.Categories lineCat = doc.Settings.Categories.get_Item( BuiltInCategory.OST_Lines) count = 0 if not prefix + i.Name in styleName: newName = prefix + i.Name else: newName = prefix + i.Name + '-1' newLineStyleCat = categories.NewSubcategory(lineCat, newName) doc.Regenerate() newLineStyleCat.SetLineWeight(int(weight), GraphicsStyleType.Projection) newLineStyleCat.LineColor = i.LineColor try: newLineStyleCat.SetLinePatternId(pattern.Id, GraphicsStyleType.Projection) except: pass # Add new Line style to dictionary print('Appended Prefix to ' + i.Name + ' to ' '\'' + newName + '\'') try: SetLineStyle(doc, i, newLineStyleCat) doc.Delete(i.Id) except: print( 'Fail to set line, maybe it contains prohibited characters.' ) t.Commit()
def main(ALIGN): """ ADD DOCS """ align_axis = Align.axis[ALIGN] align_method = Align.method[ALIGN] logger.info('Align Class: {}'.format(ALIGN)) logger.debug('Align Axis: {}'.format(align_axis)) logger.debug('Align Methid: {}'.format(align_method)) elements = get_selected_elements() point_collection = PointCollection() for element in elements: point_element = get_location(element, align_method) if point_element: point_element.element = element point_collection.points.append(point_element) point_collection.sort_points(align_axis) qty_items = len(point_collection) min_target = getattr(point_collection, 'min') max_target = getattr(point_collection, 'max') delta = getattr(max_target, align_axis) - getattr(min_target, align_axis) steps = get_division_steps(delta, qty_items) target_locations = [ getattr(min_target, align_axis) + step for step in steps ] logger.debug('Min Location Target is: {}'.format(min_target)) logger.debug('Max Location Target is: {}'.format(max_target)) logger.debug('delta is: {}'.format(str(delta))) logger.debug('steps: {}'.format(steps)) logger.debug('targer_locations: {}'.format(target_locations)) t = Transaction(doc, 'Smart Align - Distribute') t.Start() for point_element, target_location in zip(point_collection, target_locations): current_location = getattr(point_element, align_axis) delta = current_location - target_location delta_vector = PointElement(0, 0, 0) setattr(delta_vector, align_axis, -delta) translation = XYZ(*delta_vector.as_tuple) move_element(point_element.element, translation) logger.debug('current: {}'.format(current_location)) logger.debug('target: {}'.format(target_location)) logger.debug('delta: {}'.format(delta)) logger.debug('delta_vector: {}'.format(delta_vector)) logger.debug('Translation: {}'.format(str(translation))) logger.info('Done.') t.Commit()
def rename_scope_boxes(doc): scope_boxes = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_VolumeOfInterest) tr = Transaction(doc, 'Rename scope boxes') tr.Start() for box in scope_boxes: new_name = box.Name.rstrip(' Scope Box') box.get_Parameter(BuiltInParameter.VOLUME_OF_INTEREST_NAME).Set(new_name) print(new_name) tr.Commit()
def setViewFilter(): try: t = Transaction(doc, "Test") t.Start() [doc.ActiveView.SetFilterVisibility(i.item, i.state) for i in response2] t.Commit() except Exceptions.OperationCanceledException: pass