if r.GetTypeId() == TID: filteredlist.append(r.Id) if vsList: ovname = doc.GetElement(r.OwnerViewId).ViewName if ovname in vsItems: vsItems[ovname].append(r) else: vsItems[ovname] = [r] else: modelItems.append(r) if vsList: for ovname, items in vsItems.items(): print('OWNER VIEW: {0}'.format(ovname)) for r in items: print('\tID: {0}\t{1}'.format(this_script.output.linkify(r.Id), r.GetType().Name.ljust(20) )) print('\n') else: print('SELECTING MODEL ITEMS:') for el in modelItems: print('\tID: {0}\t{1}'.format(this_script.output.linkify(r.Id), r.GetType().Name.ljust(20) )) uidoc.Selection.SetElementIds(List[ElementId](filteredlist)) else: __window__.Close() TaskDialog.Show('pyrevit', 'At least one object must be selected.')
import sys import clr from Autodesk.Revit.DB import Transaction, ElementId, StorageType, FilteredElementCollector, Dimension, FamilyParameter from Autodesk.Revit.UI import TaskDialog, TaskDialogCommonButtons, TaskDialogResult __doc__ = 'This script removes all custom parameters that has not been used '\ 'in dimensions as labels and also resets the value for the other ' \ 'parameters to zero or null.' uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document res = TaskDialog.Show( 'pyRevit', 'Make sure your models are saved and synced. ' 'Hit OK to continue...', TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel) if not res == TaskDialogResult.Ok: sys.exit() if doc.IsFamilyDocument: params = doc.FamilyManager.GetParameters() dims = FilteredElementCollector(doc).OfClass( Dimension).WhereElementIsNotElementType() labelParams = set() for d in dims: try: if isinstance(d.FamilyLabel, FamilyParameter): labelParams.add(d.FamilyLabel.Id.IntegerValue) except:
collPipeSystems = FilteredElementCollector(doc).\ OfCategory(BuiltInCategory.OST_PipingSystem).ToElements() # DS now and late = Duct System collDuctSystems = FilteredElementCollector(doc).\ OfCategory(BuiltInCategory.OST_DuctSystem).WhereElementIsNotElementType().ToElements() DSNameList = [i.Name for i in collDuctSystems] newDialog = TaskDialog("Warning!") newDialog.MainContent = "Найдено " + DSNameList.Count.ToString( ) + " систем воздуховодов.\ \nПродолжить?" buttons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No newDialog.CommonButtons = buttons result = newDialog.Show() if result == TaskDialogResult.No: TaskDialog.Show("Warning!", "Отменено") raise SystemExit vfType = [i for i in FilteredElementCollector(doc).\ OfClass(ViewFamilyType).ToElements() if i.ViewFamily.ToString() == "ThreeDimensional"] vfType = vfType[0].Id #view template ID for 200 try: vt200 = [i for i in FilteredElementCollector(doc).\ OfClass(View).ToElements() if i.IsTemplate and i.Name == "P-A-200"][0].Id except Exception as e:
See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE ''' __window__.Hide() from Autodesk.Revit.DB import Transaction, ViewSheet, Viewport from Autodesk.Revit.UI import TaskDialog from Autodesk.Revit.UI.Selection import ObjectType uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document curview = doc.ActiveView if not isinstance(curview, ViewSheet): TaskDialog.Show('pyRevit', 'You must be on a sheet to use this tool.') __window__.Close() viewports = [] for vpId in curview.GetAllViewports(): viewports.append( doc.GetElement( vpId )) vports = { int(vp.LookupParameter('Detail Number').AsString()):vp for vp in viewports if vp.LookupParameter('Detail Number')} maxNum = max( vports.keys() ) with Transaction(doc, 'Re-number Viewports') as t: t.Start() sel = [] while len(sel) < len(vports): try:
BuiltInParameter.VIEWPORT_SHEET_NUMBER).HasValue), allviews) viewList = [] # print str(datetime.datetime.now()) if len(uidoc.Selection.GetElementIds()) > 0: for v in views: cl_els = FilteredElementCollector( doc, v.Id).WhereElementIsNotElementType().ToElementIds() i = 0 for elId in uidoc.Selection.GetElementIds(): if elId in cl_els: i = +1 viewList.append(v) else: TaskDialog.Show("Try Again", "No element was selected, try again.") __window__.Close() sys.exit() if len(viewList) > 0: print('\n\nSheet views containing the selected elements:') else: TaskDialog.Show("No views were found", "No views on sheets were found with this element") myset = set(viewList) viewList = list(myset) for v in viewList: print('{0}{1}ID:{2}'.format(v.ViewName.ljust(45), str(v.ViewType).ljust(25),
def main(): location = doc.ActiveProjectLocation activeview = uidoc.ActiveView project_position = location.get_ProjectPosition(XYZ.Zero) project_angle = project_position.Angle origin = location.GetTotalTransform().Origin # Search for any 3D view or a Plan view cl = FilteredElementCollector(doc) views = cl.OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() q = TaskDialog.Show( __title__, "Link CAD to current view only?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel) if str(q) == "No": this_view_only = False target_view = None elif str(q) == "Yes": this_view_only = True target_view = activeview else: return rotate = False if not target_view: target_view_project = None target_view_3d = None for v in views: if v.IsTemplate: continue if type(v) == ViewPlan: orientation = v.get_Parameter(BuiltInParameter.PLAN_VIEW_NORTH) if orientation.AsInteger() == 1: target_view = v break else: if not target_view_project: target_view_project = v if type(v) == View3D and not target_view_3d: target_view_3d = v if not target_view: rotate = True if target_view_project: target_view = target_view_project elif target_view_3d: target_view = target_view_3d if not target_view: logger.error( "Please create 3D view or a PlanView in a project to place CAD correctly" ) return path = pick_file( files_filter= "DWG files (*.dwg)|*.dwg|DXF files (*.dxf)|*.dxf|DGN files (*.dgn)|*.dgn|All files (*.*)|*.*" ) if not path: return o = DWGImportOptions() o.AutoCorrectAlmostVHLines = False o.Unit = ImportUnit.Meter o.OrientToView = False o.ReferencePoint = origin o.ThisViewOnly = this_view_only link_func = doc.Link.Overloads[str, DWGImportOptions, View, System.Type.MakeByRefType(ElementId)] t = Transaction(doc) t.Start(__title__) try: status, e_id = link_func( path, o, target_view, ) except Exception as e: logger.error("Unable to import CAD") logger.error(e) status = False # override rotation option if __shiftclick__: q = TaskDialog.Show( __title__, "Is it okay?\nIf not CAD will be rotated", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No | TaskDialogCommonButtons.Cancel) if str(q) == "No": rotate = True elif str(q) == "Yes": rotate = False else: return if status: l = doc.GetElement(e_id) if rotate: if l.Pinned: l.Pinned = False axis = Line.CreateBound(origin, XYZ(origin.X, origin.Y, origin.Z + 1)) ElementTransformUtils.RotateElement(doc, l.Id, axis, -project_angle) l.Pinned = True t.Commit() else: t.RollBack()
run = IN[3] if run: lineStylesName = convertToList(IN[0]) lineStylesWeight = convertToList(IN[1]) lineStylesColour = convertToListOfLists(IN[2], messsageTitle) if lineStylesColour == True: OUT = "Colour data structure error - colours should be input as integer sublists defining the RGB values", [] else: listLacingCheck = False if len(lineStylesName) == len(lineStylesWeight) == len( lineStylesColour): listLacingCheck = True else: TaskDialog.Show( messsageTitle, "bimorph.CreateNewLineStyles:\nLacing error - The number of items in the name, line weight and line colours input lists do not match. Ensure there are an equal number of items in each list and try again", TaskDialogCommonButtons.Ok) OUT = "Lacing error - Data mismatch; ensure an equal number of items are in each input", [] if listLacingCheck: TransactionManager.Instance.EnsureInTransaction(doc) doc.Regenerate() categories = doc.Settings.Categories lineCategory = doc.Settings.Categories.get_Item( BuiltInCategory.OST_Lines) lineSubCategory = lineCategory.SubCategories newLineStyleList = zip(lineStylesName, lineStylesWeight, lineStylesColour)
solidType = "By Curves" except: pass if roomPoly == None: try: solidType = "Can't Create-Solid not tested" roomPoly = roomCurves if tryExtractSolid: roomSolid = get_solid(room) solidType = "By Solid" except: roomPoly = roomCurves solidType = "Can't Create" #if solids not created store all None values #store values based on success of solid creation roomsRegions.append(roomPoly) roomsSolids.append(roomSolid) creationLog.append(solidType) #TransactionManager.Instance.TransactionTaskDone() if msgList <> []: msg = str(msgList) TaskDialog.Show('Test', str(msg)) OUT = [paramList] + [paramValues] + [roomsRegions] + [roomsSolids] + [ progData ] + [roomElements] + [creationLog] + [visData]
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE """ __doc__ = 'Opens the view associated to the selected viewport. You can assign a shortcut to this tool ' \ 'and this is a quick way top open the views when working on sheets.' __window__.Close() from Autodesk.Revit.DB import Viewport from Autodesk.Revit.UI import TaskDialog uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document selection = [doc.GetElement(elId) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds()] # Opens the associated view with the selected viewport on a sheet. if len(selection) > 0 and isinstance(selection[0], Viewport): vp = selection[0] vpid = vp.ViewId view = doc.GetElement(vpid) uidoc.ActiveView = view else: TaskDialog.Show('pyRevit', 'Select a Viewport first')
git_executive = '\"' + op.join(gitDir, 'git.exe') + '\"' print('Installation directory is: {0}'.format(installDir)) print('Portable git package is located at: {0}'.format(gitDir)) if op.exists('{0}\git.exe'.format(gitDir)): try: print('\nUPDATING PYTHON LOADER '.ljust(100, '-')) print( 'pyRevit loader has been cloned to: {0}\n'.format(loaderCloneDir)) git_pull_overwrite(loaderCloneDir) except: print('Error Updating loader repository...The cloned repo might be corrupt or no internet access.\n' \ 'Trying to update the main repository now') try: print('\n\nUPDATING PYTHON SCRIPT LIBRARY '.ljust(100, '-')) print('pyRevit has been cloned to: {0}\n'.format(pyrevitCloneDir)) git_pull_overwrite(pyrevitCloneDir) TaskDialog.Show( 'pyRevit', 'Update completed. reload pyRevit now to see changes...') __window__.Focus() except: TaskDialog.Show('pyRevit', 'Error Updating repository...Please check your internet connection. ' \ 'If the updater still did not work please copy the printed report and ' \ 'contact the developers...') __window__.Focus() else: print('Can not find portable git package.')
Author: Jared Friedman | github.com/jbf1212 This file is shared on www.revitapidocs.com For more information visit http://github.com/gtalarico/revitapidocs License: http://github.com/gtalarico/revitapidocs/blob/master/LICENSE.md """ from Autodesk.Revit.DB import Transaction, Element from Autodesk.Revit.DB import FilteredElementCollector from Autodesk.Revit.UI import TaskDialog from System.Collections.Generic import List uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document # GET ALL ROOMS IN MODEL rooms = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) ub_rooms = [] for r in rooms: if r.Area > 0: pass else: ub_rooms.append(r) # SELECT UNBOUND ROOMS collection = List[ElementId]([r.Id for r in ub_rooms]) selection = uidoc.Selection selection.SetElementIds(collection) TaskDialog.Show('Unbound Rooms', "{} unbound rooms selected". format(len(ub_rooms)))
#TaskDialog.Show("type(id)",id.ToString()) countreal = countreal + 1 if not delel.Category is None: delcategories.append(delel.Category.Name) # TaskDialog.Show("Element that will be deleted",delel.Category.Name) c = Counter(delcategories) delcategoriesstring = '' for q, a in zip(list(c), c.values()): spaces = ' ' * 2 * (4 - len(str(a))) delcategoriesstring += ('{1} {2}{0}'.format(q, a, spaces)) + "\n" #TaskDialog.Show("Element that will be deleted",c) s = Transaction(doc, 'Select Elements') s.Start() if countreal == 1: TaskDialog.Show( "Deleted Elements", "If you delete this " + el.Category.Name + ", no other elements will be deleted.") else: TaskDialog.Show( "Deleted Elements", "If you delete this " + el.Category.Name + ", " + str(countreal) + " elements will be deleted. They have been selected. \n\n" + delcategoriesstring + "\n(This selection may include non-physical elements.)") # elements_to_hide = collector.WhereElementIsNotElementType().Excluding(element_collection).ToElements() uidoc.Selection.SetElementIds(deleteids) s.Commit() elif len(selectedElement) > 1: TaskDialog.Show( "Invalid Selection",
def alert(msg): TaskDialog.Show('pyrevit', msg)
elif view.ViewType == ViewType.DraftingView: viewlist.append(view) ids = [] options = sorted(getNames(viewlist)) if options: selected_fromlist = SelectFromList.show(options) logger.debug('Selected symbols are: {}'.format(selected_fromlist)) if selected_fromlist: if len(selected_fromlist)==1: for item in selected_fromlist: for t in viewlist: if item == t.Name: baseview = t TaskDialog.Show('BaseView', t.Name) else: TaskDialog.Show('pyRevit', 'You must select only one template to grab filters.') sys.exit else: TaskDialog.Show('pyRevit', 'You must select one item') options = sorted(getNames(viewlist)) if options: selected_fromlist = SelectFromList.show(options) logger.debug('Selected symbols are: {}'.format(selected_fromlist)) if selected_fromlist: for item in selected_fromlist: for t in viewlist:
from Autodesk.Revit.DB import Transaction, Element, Family, FamilySymbol, FamilyInstance from Autodesk.Revit.UI import TaskDialog # get family symbol from selection ------------------------------------------------------------------------------------- if not selection.is_empty: selected_comp = selection.first if isinstance(selected_comp, FamilySymbol): logger.debug('Getting family from symbol with id: {}'.format( selected_comp.Id)) fam_symbol = selected_comp.Family elif isinstance(selected_comp, FamilyInstance): logger.debug('Getting family from instance with id: {}'.format( selected_comp.Id)) fam_symbol = selected_comp.Symbol.Family else: TaskDialog.Show( 'pyRevit', 'System families do not have external type definition.') logger.debug( 'Cancelled. System families do not have external type definition.') this_script.exit() else: TaskDialog.Show('pyRevit', 'At least one family instance must be selected.') logger.debug('Cancelled. No elements selected.') this_script.exit() # verify family symbol is ready ---------------------------------------------------------------------------------------- if not fam_symbol: logger.error('Can not load family symbol.') this_script.exit() else: logger.debug('Family symbol aquired: {}'.format(fam_symbol))
def error(msg): TaskDialog.Show('pyRevit', msg) sys.exit(0)
def run(interactive=False): """ :param interactive: show dialogs :return: None """ # Ask user to confirm running of the script if interactive: text = "Run Grid distance check?" a = TaskDialog.Show( __title__, text, TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.Cancel) if str(a) != "Yes": return # Collect all grids in current document grids = get_grids() # Filter linear grids grids_linear = filter(lambda x: not x.IsCurved, grids) # Get list of design options in a document design_options_dict = get_design_options_ids(doc) # If there are design options in a document, group grids if design_options_dict: # list of lists of elements grouped by design options elements_by_design_option = group_by_design_options( grids_linear, design_options_dict) else: elements_by_design_option = [ grids_linear, ] ids_bad_to_override = [] # list of false result ids_orphaned = [] # list of "outliers" for i in range(len(elements_by_design_option)): # if there are design options in a document, show combination index if len(elements_by_design_option) > 1: print("Design options combination %d" % (i + 1)) # get list of grids in current design options combination grids_by_design_option = elements_by_design_option[i] logger.debug(grids_by_design_option) grids_grouped = group_grids(grids_by_design_option, precision=2) # get outliers outliers = find_outlier_grids_distance(grids_grouped) for outliers_pair in outliers: ids_good, ids_bad = outliers_pair if len(ids_bad) == 0: continue # add bad ids to mark them later ids_bad_to_override += ids_bad if len(ids_good) > 0: good_id = ids_good[0] print("Outliers from grid \"%s\" %s:" % (doc.GetElement(good_id).Name, \ linkify(good_id))) else: good_id = None print("Orphaned grids:") for g_id in ids_bad: g_name = doc.GetElement(g_id).Name if good_id: print("\"%s\" ( %s° ) %s " % (g_name, \ curve_angles[g_id] - curve_angles[good_id], linkify(g_id),)) else: print("\"%s\" %s " % ( g_name, linkify(g_id), )) print("\n\n") if type(doc.ActiveView) == ViewPlan and len(ids_bad_to_override) > 0: text = "Check completed\n%d errors found. Mark outliers grids on active plan view \"%s\"?" % ( len(ids_bad_to_override), doc.ActiveView.Name) a = TaskDialog.Show( __title__, text, TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No) if a == "No": return override_gray = OverrideGraphicSettings() \ .SetProjectionLineColor(Color(200, 200, 200)) override_red = OverrideGraphicSettings().SetProjectionLineColor(Color(255, 0, 0)) \ .SetProjectionLineWeight(6) t = Transaction(doc) t.Start("Override graphics") for g in grids: doc.ActiveView.SetElementOverrides(g.Id, override_gray) grids_visible = get_grids(doc.ActiveView.Id, ids=True) for g in ids_bad_to_override: if g not in grids_visible: line = doc.Create.NewDetailCurve(doc.ActiveView, doc.GetElement(g).Curve) doc.ActiveView.SetElementOverrides(line.Id, override_red) doc.ActiveView.SetElementOverrides(g, override_red) t.Commit() if len(ids_bad_to_override) == 0: TaskDialog.Show(__title__, "Check completed\n0 errors")
bbA.Min.Z, bbA.Max.Z, bbB.Min.Z, bbB.Max.Z) output = [] for a in listA: bbA = a.get_BoundingBox(None) if not bbA is None: for b in listB: bbB = b.get_BoundingBox(None) if not bbB is None: if bbIntersect(bbA, bbB): output.append([a, b]) c = 0 if len(selected_ids) > 0: t = Transaction(doc) t.Start(__title__) for x in selected_ids: for y in selected_ids: try: JoinGeometryUtils.JoinGeometry(doc, doc.GetElement(x), doc.GetElement(y)) c += 1 except: pass t.Commit() TaskDialog.Show(__title__, "%d pairs of elements unjoined" % c)
import clr from System.Collections.Generic import * doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument def getNames(z_element): z_elementname = [] for e in z_element: z_elementname.append(e.Name) return z_elementname TaskDialog.Show('Not working', "programming isn't done yet, need a way to save to new file") views = [] baseid = "802532" baseview = doc.GetElement(ElementId(int(baseid))) #TaskDialog.Show("Original View",baseview.Name) collector = FilteredElementCollector(doc) allviews = collector.OfClass(View).ToElements() templatelist = [] viewlist = [] for view in allviews: #if view.ViewType == ViewType.ThreeD: if not (view.IsTemplate) and view.ViewType == ViewType.DraftingView: viewlist.append(view)
See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE """ __doc__ = 'Select a series of tags and this tool will add their associated elements to selection. ' \ 'This is especially useful for isolating elements and their tags.' __window__.Close() from Autodesk.Revit.DB import ElementId, IndependentTag from Autodesk.Revit.DB.Architecture import RoomTag from Autodesk.Revit.UI import TaskDialog from System.Collections.Generic import List uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document selection = list(uidoc.Selection.GetElementIds()) tagged_elements = [] for eltid in selection: elt = doc.GetElement(eltid) if isinstance(elt, IndependentTag): tagged_elements.append(elt.TaggedLocalElementId) if len(tagged_elements) > 0: uidoc.Selection.SetElementIds(List[ElementId](selection + tagged_elements)) else: TaskDialog.Show('pyRevit', 'Please select at least one element tag.')
from System.Collections.Generic import List uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document import clr from Autodesk.Revit.DB import * walls = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElementIds() columns = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_StructuralColumns).WhereElementIsNotElementType( ).ToElementIds() TaskDialog.Show( "Number of Walls and Columns Selected", "Walls - " + str(len(walls)) + " Columns - " + str(len(columns))) results = [] t = Transaction(doc, 'Switch Join Between all Columns and Walls') t.Start() i = 0 for c in columns: cel = doc.GetElement(c) for w in walls: try: wel = doc.GetElement(w) if JoinGeometryUtils.AreElementsJoined(doc, wel, cel): if JoinGeometryUtils.IsCuttingElementInJoin(doc, wel, cel): result = JoinGeometryUtils.SwitchJoinOrder(doc, wel, cel) results.append(result) print result
import clr import numpy as np clr.AddReference('RevitAPIUI') from Autodesk.Revit.DB import * def closest_node(node, nodelist): nodelist = np.asarray(nodelist) deltas = nodelist - node dist_2 = np.einsum('ij,ij->i', deltas, deltas) return np.argmin(dist_2) nodes = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_AnalyticalNodes).WhereElementIsNotElementType( ).ToElements() TaskDialog.Show("Number of nodes selected", "nodes - " + str(len(nodes))) display = "Look at this" for n in nodes: if "ReferencePoint" in n.ToString(): zpoint = n.Position display += str(zpoint.X) + " " + str(zpoint.Y) + " " + str( zpoint.Z) + "\n" #TaskDialog.Show("header",str(n.X) + str(n.Y) + str(n.Z)) display += str(closest_node(n, nodes)) TaskDialog.Show("header", display) sys.exit
def alert(msg): TaskDialog.Show('RevitPythonShell', msg)
def window(): dialog = TaskDialog("Sheet Names to CSV") dialog.MainInstruction = 'Options' dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, 'Sheet Name and Number','') dialog.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, 'Sheet Name Only', '') return dialog.Show()
curview = doc.ActiveView if isinstance(curview, View3D) and curview.IsSectionBoxActive: try: ref = uidoc.Selection.PickObject(ObjectType.Face) el = doc.GetElement(ref.ElementId) face = el.GetGeometryObjectFromReference(ref) box = curview.GetSectionBox() norm = face.ComputeNormal(UV(0, 0)).Normalize() boxNormal = box.Transform.Basis[0].Normalize() angle = norm.AngleTo(boxNormal) axis = XYZ(0, 0, 1.0) origin = XYZ(box.Min.X + (box.Max.X - box.Min.X) / 2, box.Min.Y + (box.Max.Y - box.Min.Y) / 2, 0.0) if norm.Y * boxNormal.X < 0: rotate = Transform.CreateRotationAtPoint(axis, Math.PI / 2 - angle, origin) else: rotate = Transform.CreateRotationAtPoint(axis, angle, origin) box.Transform = box.Transform.Multiply(rotate) t = Transaction(doc, 'Orient Section Box to Face') t.Start() curview.SetSectionBox(box) uidoc.RefreshActiveView() t.Commit() except: pass elif isinstance(curview, View3D) and not curview.IsSectionBoxActive: TaskDialog.Show("pyRevit", "The section box for View3D isn't active.") else: TaskDialog.Show("pyRevit", "You must be on a 3D view for this tool to work.")
vo = pl.load(f) f.close() sb = BoundingBoxXYZ() sb.Min = XYZ(sbox.minx, sbox.miny, sbox.minz) sb.Max = XYZ(sbox.maxx, sbox.maxy, sbox.maxz) vor = ViewOrientation3D(XYZ(vo.eyex, vo.eyey, vo.eyez), XYZ(vo.upx, vo.upy, vo.upz), XYZ(vo.forwardx, vo.forwardy, vo.forwardz)) av = uidoc.ActiveGraphicalView avui = uidoc.GetOpenUIViews()[0] if isinstance(av, View3D): with Transaction(doc, 'Paste Section Box Settings') as t: t.Start() av.SetSectionBox(sb) av.SetOrientation(vor) t.Commit() avui.ZoomToFit() else: TaskDialog.Show( 'pyRevit', 'You must be on a 3D view to paste Section Box settings.') __window__.Close() except: __window__.Show() print( 'CAN NOT FIND ANY VISIBILITY GRAPHICS SETTINGS IN MEMORY:\n{0}'.format( datafile))
the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE ''' __doc__ = 'Uses the Worksharing tooltip to find out the element creator and other info.' __window__.Close() from Autodesk.Revit.DB import WorksharingUtils, WorksharingTooltipInfo from Autodesk.Revit.UI import TaskDialog uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document selection = [ doc.GetElement( elId ) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds() ] if doc.IsWorkshared: if selection and len(selection) == 1: el = selection[0] wti = WorksharingUtils.GetWorksharingTooltipInfo(doc, el.Id) TaskDialog.Show('pyRevit','Creator: {0}\nCurrent Owner: {1}\nLast Changed By: {2}'.format(wti.Creator, wti.Owner, wti.LastChangedBy)) else: TaskDialog.Show('pyRevit','Exactly one element must be selected.') else: TaskDialog.Show('pyRevit','Model is not workshared.')
from Autodesk.Revit.UI import TaskDialog class CopyUseDestination(IDuplicateTypeNamesHandler): def OnDuplicateTypeNamesFound(self, args): return DuplicateTypeAction.UseDestinationTypes # get a list of selected drafting views selection = [ el for el in selection.elements if isinstance(el, View) and el.ViewType == ViewType.DraftingView ] if not len(selection) > 0: TaskDialog.Show('pyRevit', 'At least one Drafting view must be selected.') sys.exit(0) # finding first available legend view baseLegendView = None allViews = FilteredElementCollector(doc).OfClass(View) for v in allViews: if v.ViewType == ViewType.Legend: baseLegendView = v break if not baseLegendView: TaskDialog.Show('pyRevit', 'At least one Legend view must exist in the model.') sys.exit(0)
from System.Collections.Generic import List uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document # selection = [ doc.GetElement( elId ) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds() ] filteredlist = [] viewlist = [] if doc.IsWorkshared: currentviewid = uidoc.ActiveGraphicalView.Id viewlist.append(currentviewid) if isinstance(uidoc.ActiveGraphicalView, ViewSheet): vportids = uidoc.ActiveGraphicalView.GetAllViewports() for vportid in vportids: viewlist.append(doc.GetElement(vportid).ViewId) for view in viewlist: curviewelements = FilteredElementCollector(doc).OwnedByView( view).WhereElementIsNotElementType().ToElements() if len(curviewelements) > 0: for el in curviewelements: wti = WorksharingUtils.GetWorksharingTooltipInfo(doc, el.Id) # wti.Creator, wti.Owner, wti.LastChangedBy if wti.LastChangedBy == __revit__.Application.Username: filteredlist.append(el.Id) uidoc.Selection.SetElementIds(List[ElementId](filteredlist)) else: pass else: TaskDialog.Show('pyRevit', 'Model is not workshared.')
doc = __revit__.ActiveUIDocument.Document from pyrevit import script __doc__ = 'Print all the irregular pipe slopes and element id in selection'\ 'Tolerance at 0.001 ' \ 'clear list 12/12, 0.5/12, 0.25/12, 0.125/12, 0.0625/12' def isclose(a, b, rel_tol=1e-08, abs_tol=1e-03): return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def isnotclose(a, b, rel_tol=1e-08, abs_tol=1e-03): return abs(a-b) >= max(rel_tol * max(abs(a), abs(b)), abs_tol) sel_element = Selection.get_selected_elements(doc) if len(sel_element) == 0: TaskDialog.Show('Warning', 'Please make selection first') else: outprint = script.get_output() pipes = [] for i in sel_element: if i.Category.Name == 'Pipes': pipes.append(i) print('Found ' + str(len(pipes)) + ' pipes') # pipes = FilteredElementCollector(doc).OfClass(Pipe).ToElements() for p in pipes: slope = p.LookupParameter('Slope').AsDouble() if slope != 0.0 and slope < 1.1 and isnotclose(slope, 12/12)and isnotclose(slope, 0.5/12) and isnotclose(slope, 0.25/12)\ and isnotclose(slope, 0.125/12) and isnotclose(slope, 0.0625/12): print(format(outprint.linkify(p.Id))+ ' SLOPE: ' + str(slope*12) + '/foot') print('End')