public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; m_doc = app.ActiveUIDocument.Document; // filter for family instance and (door or window): ElementClassFilter fFamInstClass = new ElementClassFilter( typeof( FamilyInstance ) ); ElementCategoryFilter fDoorCat = new ElementCategoryFilter( BuiltInCategory.OST_Doors ); ElementCategoryFilter fWindowCat = new ElementCategoryFilter( BuiltInCategory.OST_Windows ); LogicalOrFilter fCat = new LogicalOrFilter( fDoorCat, fWindowCat ); LogicalAndFilter f = new LogicalAndFilter( fCat, fFamInstClass ); FilteredElementCollector openings = new FilteredElementCollector( m_doc ); openings.WherePasses( f ); // map with key = host element id and // value = list of hosted element ids: Dictionary<ElementId, List<ElementId>> ids = GetElementIds( openings ); DumpHostedElements( ids ); m_doc = null; return Result.Succeeded; }
public Result OnStartup(UIControlledApplication a) { //Create Ribbon Panel add the UI button on start up RibbonPanel alignViewsPanel = ribbonPanel(a); //Register location updater with Revit. LocationUpdater updater = new LocationUpdater(a.ActiveAddInId); UpdaterRegistry.RegisterUpdater(updater, true); ElementCategoryFilter viewPortFilter = new ElementCategoryFilter(BuiltInCategory.OST_Viewports); ElementCategoryFilter viewFilter = new ElementCategoryFilter(BuiltInCategory.OST_Views); LogicalOrFilter filter = new LogicalOrFilter(viewPortFilter, viewFilter); //Parameter to send to the trigger. ElementClassFilter viewPort = new ElementClassFilter(typeof(Viewport)); ElementId viewPortNumberId = new ElementId(BuiltInParameter.VIEWPORT_DETAIL_NUMBER); //Set trigger UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), viewPort, Element.GetChangeTypeParameter(viewPortNumberId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); //add buttons to ribbon addVRCommandButtons(alignViewsPanel); pushButton_Setting(alignViewsPanel); return Result.Succeeded; }
/// <summary> /// Adds 1 to the mark of every column in the document /// </summary> /// <param name="commandData">the revit command data</param> /// <param name="message">a message to return</param> /// <param name="elements">Elements to display in a failed message dialog</param> /// <returns>Suceeded, Failed or Cancelled</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //we want the 'database' document, which represents the Revit Model itself. Document dbDoc = commandData.Application.ActiveUIDocument.Document; //Use a FilteredElementCollector to get all the columns in the model. FilteredElementCollector collector = new FilteredElementCollector(dbDoc); //for this, we use a Category Filter which finds all elements in the Column category ElementCategoryFilter columnFilter = new ElementCategoryFilter(BuiltInCategory.OST_Columns); //structural columns have a different category ElementCategoryFilter structuralColumnFilter =new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns); //to get elements that match either of these categories, we us a logical 'Or' filter. LogicalOrFilter orFilter = new LogicalOrFilter(columnFilter, structuralColumnFilter); //you can then get these elements as a list. //we also specify WhereElementIsNotElementType() so that we don't get FamilySymbols IList<Element> allColumns = collector.WherePasses(orFilter).WhereElementIsNotElementType().ToElements(); string results = "Updated Marks For : " + Environment.NewLine; //loop through this list and update the mark foreach (Element element in allColumns) { UpdateMark(element); results += element.Id + Environment.NewLine; } TaskDialog.Show("Updated Elements", results); return Result.Succeeded; }
private static void ExtractObjects() { FilteredElementCollector fec = new FilteredElementCollector(_doc); IList<ElementFilter> StruMaterialFilterList = new List<ElementFilter>(); StruMaterialFilterList.Add(new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete)); StruMaterialFilterList.Add(new StructuralMaterialTypeFilter(StructuralMaterialType.PrecastConcrete)); LogicalOrFilter StruMaterialFilter = new LogicalOrFilter(StruMaterialFilterList); _slabs = fec.OfCategory(BuiltInCategory.OST_Floors).OfClass(typeof(Floor)). WherePasses(StruMaterialFilter).Cast<Floor>().ToList(); }
private void docOpen(object sender, DocumentOpenedEventArgs e) { Autodesk.Revit.ApplicationServices.Application app = sender as Autodesk.Revit.ApplicationServices.Application; UIApplication uiApp = new UIApplication(app); Document doc = uiApp.ActiveUIDocument.Document; FilteredElementCollector collector = new FilteredElementCollector(doc); collector.WherePasses(new ElementClassFilter(typeof(FamilyInstance))); var sphereElements = from element in collector where element.Name == "sphere" select element; if (sphereElements.Count() == 0) { TaskDialog.Show("Error", "Sphere family must be loaded"); return; } FamilyInstance sphere = sphereElements.Cast<FamilyInstance>().First<FamilyInstance>(); FilteredElementCollector viewCollector = new FilteredElementCollector(doc); ICollection<Element> views = viewCollector.OfClass(typeof(View3D)).ToElements(); var viewElements = from element in viewCollector where element.Name == "AVF" select element; if (viewElements.Count() == 0) { TaskDialog.Show("Error", "A 3D view named 'AVF' must exist to run this application."); return; } View view = viewElements.Cast<View>().First<View>(); SpatialFieldUpdater updater = new SpatialFieldUpdater(uiApp.ActiveAddInId, sphere.Id, view.Id); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(updater); ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(wallFilter); filterList.Add(familyFilter); filterList.Add(massFilter); LogicalOrFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeGeometry()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); }
private static void ExtractObjects() { FilteredElementCollector Walls = new FilteredElementCollector(_doc); ElementFilter WallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); IList<ElementFilter> StruWallFilterList = new List<ElementFilter>(); StruWallFilterList.Add(new StructuralWallUsageFilter(StructuralWallUsage.Bearing)); StruWallFilterList.Add(new StructuralWallUsageFilter(StructuralWallUsage.Shear)); StruWallFilterList.Add(new StructuralWallUsageFilter(StructuralWallUsage.Combined)); LogicalOrFilter logicOrFilter = new LogicalOrFilter(StruWallFilterList); Walls.WherePasses(WallFilter).WherePasses(logicOrFilter); foreach (Wall wall in Walls) { Material material = _doc.GetElement (wall.WallType.get_Parameter(BuiltInParameter.STRUCTURAL_MATERIAL_PARAM).AsElementId()) as Material; if (material == null) continue; if (material.MaterialCategory == _addiInfo.materialTypes[(byte)PGMaterialType.Masonry]) { _masonryWalls.Add(wall); } } }
/// <summary> /// Get the selected element as the host object, also check if the selected element is expected host object /// </summary> /// <returns>true if get the selected element, otherwise false.</returns> private bool GetHostObject() { List <ElementId> selectedIds = new List <ElementId>(); foreach (Autodesk.Revit.DB.ElementId elemId in m_commandData.Application.ActiveUIDocument.Selection.GetElementIds()) { Autodesk.Revit.DB.Element elem = m_commandData.Application.ActiveUIDocument.Document.GetElement(elemId); selectedIds.Add(elem.Id); } if (selectedIds.Count != 1) { return(false); } // // Construct filters to find expected host object: // . Host should be Beam/Column structural type. // . and it's material type should be Concrete // . and it should be FamilyInstance // // Structural type filters firstly LogicalOrFilter stFilter = new LogicalOrFilter( new ElementStructuralTypeFilter(StructuralType.Beam), new ElementStructuralTypeFilter(StructuralType.Column)); // StructuralMaterialType should be Concrete LogicalAndFilter hostFilter = new LogicalAndFilter(stFilter, new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete)); // // Expected host object FilteredElementCollector collector = new FilteredElementCollector(m_commandData.Application.ActiveUIDocument.Document, selectedIds); m_hostObject = collector .OfClass(typeof(FamilyInstance)) // FamilyInstance .WherePasses(hostFilter) // Filters .FirstElement() as FamilyInstance; return(null != m_hostObject); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; FilteredElementCollector coll = new FilteredElementCollector(doc); // 篩選條件為窗和柱的篩選器 ElementCategoryFilter filter1 = new ElementCategoryFilter(BuiltInCategory.OST_Windows); ElementCategoryFilter filter2 = new ElementCategoryFilter(BuiltInCategory.OST_Columns); // 邏輯篩選器,用以組合兩個或多個篩選器做使用 LogicalOrFilter orfilter = new LogicalOrFilter(filter1, filter2); IList <Element> elemList = coll.WherePasses(orfilter).WhereElementIsNotElementType().ToElements(); // 計算元件數量 int counter = elemList.Count; // 輸出柱元件的品類、族群、與類型 string output = null; foreach (Element elem in elemList) { FamilyInstance familyInstance = elem as FamilyInstance; FamilySymbol familySymbol = familyInstance.Symbol; Family family = familySymbol.Family; output += "品類:" + elem.Category.Name + ",族群:" + family.Name + ",類型:" + elem.Name + "\n"; } // 展示資訊並回傳成功 MessageBox.Show("符合篩選條件的元件共有 " + counter + " 個,有:\n" + output); return(Result.Succeeded); }
/// <summary> /// Resets override on all elements in current view /// </summary> public static void reset() { using (Transaction ResetView = new Transaction(tools.uidoc.Document, "Reset view")) { ResetView.Start(); OverrideGraphicSettings overrideGraphicSettings = new OverrideGraphicSettings(); var selection = tools.uidoc.Selection.GetElementIds(); List <ElementId> collector = new List <ElementId>(); if (selection != null && selection.Count > 0) { foreach (var item in selection) { collector.Add(item); } } else { LogicalOrFilter logicalOrFilter = new LogicalOrFilter(MEPCategories.listCat()); collector = new FilteredElementCollector(tools.doc, tools.doc.ActiveView.Id).WherePasses( logicalOrFilter).WhereElementIsNotElementType().ToElementIds().ToList(); } foreach (var item in collector) { if (tools.doc.GetElement(item) != null) { tools.doc.ActiveView.SetElementOverrides(item, overrideGraphicSettings); } } ResetView.Commit(); } }
/// <summary> /// Checkouts all elements in the document. /// </summary> /// <param name="doc"></param> /// <param name="viewId"></param> /// <param name="onlyInstance"></param> /// <returns></returns> public static List <Element> Checkout(this Document doc, ElementId viewId, bool onlyInstance = true) { if (doc == null) { throw new ArgumentNullException(nameof(doc)); } if (viewId == null) { throw new ArgumentNullException(nameof(viewId)); } var baseCollector = new FilteredElementCollector(doc, viewId); var logicCollector = new LogicalOrFilter(new ElementIsElementTypeFilter(false), new ElementIsElementTypeFilter(true)); var results = baseCollector.WherePasses(logicCollector); if (onlyInstance) { results = results.WhereElementIsNotElementType(); } return(results.ToList()); }
static public List <Room> GetCollidedRooms(Element el) { // Проверка параметров Room у FamilyInstance FamilyInstance fi = el as FamilyInstance; if (fi != null) { Room[] rooms = new Room[] { fi?.Room, fi?.FromRoom, fi?.ToRoom }; if (rooms.Any(x => x != null)) { return(rooms.Where(x => x != null).ToList()); } } BoundingBoxXYZ bb = el.get_BoundingBox(null); BoundingBoxContainsPointFilter filterMin = new BoundingBoxContainsPointFilter(bb.Min); BoundingBoxContainsPointFilter filterMax = new BoundingBoxContainsPointFilter(bb.Max); filterMin.Tolerance = filterMax.Tolerance = 1; ElementFilter filter = new LogicalOrFilter(filterMin, filterMax); return(new FilteredElementCollector(el.Document).OfCategory(BuiltInCategory.OST_Rooms).WherePasses(filter).Cast <Room>().ToList()); }
/// <summary> /// Init ParameterFilterElement by rules /// </summary> /// <param name="name"></param> /// <param name="ids"></param> /// <param name="rules"></param> private void Init(string name, IEnumerable <ElementId> ids, IEnumerable <Autodesk.Revit.DB.FilterRule> rules) { Autodesk.Revit.DB.Document document = DocumentManager.Instance.CurrentDBDocument; TransactionManager.Instance.EnsureInTransaction(document); var elemFilters = new List <ElementFilter>(); foreach (var rule in rules) { var elemParamFilter = new ElementParameterFilter(rule); elemFilters.Add(elemParamFilter); } Autodesk.Revit.DB.ElementFilter eleFilter = new LogicalOrFilter(elemFilters); var elem = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.ParameterFilterElement>(document); if (elem == null) { // ParameterFilterElement..::..Create Method (Document, String, ICollection<ElementId>, IList<FilterRule>) is deprecated in Revit 2019 and will be removed in the next version of Revit. //We suggest you instead use a Create method that takes an ElementFilter as input. elem = Autodesk.Revit.DB.ParameterFilterElement.Create(document, name, ids.ToList(), eleFilter); } else { elem.Name = name; elem.SetCategories(ids.ToList()); //ParameterFilterElement..::..SetRules Method is deprecated in Revit 2019 and will be removed in the next version of Revit. //We suggest you instead use SetElementFilter instead. elem.SetElementFilter(eleFilter); } InternalSetElement(elem); TransactionManager.Instance.TransactionTaskDone(); ElementBinder.SetElementForTrace(this.InternalElement); }
private void StoreDataOfViewType(ViewFamilyType viewType) { try { FilteredElementCollector collector = new FilteredElementCollector(doc); ElementCategoryFilter viewfilter = new ElementCategoryFilter(BuiltInCategory.OST_Views); ElementCategoryFilter sheetfilter = new ElementCategoryFilter(BuiltInCategory.OST_Sheets); LogicalOrFilter orfilter = new LogicalOrFilter(viewfilter, sheetfilter); collector = collector.WherePasses(orfilter).WhereElementIsNotElementType(); var query = from element in collector where element.GetTypeId() == viewType.Id select element; List <Element> elements = query.ToList <Element>(); if (elements.Count > 0) { foreach (Element elem in elements) { Autodesk.Revit.DB.View view = elem as Autodesk.Revit.DB.View; ViewProperties vp = new ViewProperties(view, doc); AddParameterInfo(vp.ViewParameters); if (!viewInstDictionary.ContainsKey(vp.ViewID)) { viewInstDictionary.Add(vp.ViewID, vp); } } } } catch (Exception ex) { MessageBox.Show("Failed to collect selected view Types: " + viewType.Name + " \n" + ex.Message, "ElementDataCollector Error:", MessageBoxButtons.OK, MessageBoxIcon.Warning); } }
private List <Element> GetFilteredElements() { List <ElementFilter> filters = new List <ElementFilter>(); foreach (Category c in checkedListBox.CheckedItems) { filters.Add(new ElementCategoryFilter(c.Id)); } LogicalOrFilter filter = new LogicalOrFilter(filters); string parameter = parameterComboBox.Text; string value = valueComboBox.Text; string condition = comparisonComboBox.Text; List <Element> elements = new List <Element>(); switch (condition) { case "равно": elements = new FilteredElementCollector(doc, activeView.Id) .WherePasses(filter) .Where(x => x.LookupParameter(parameter).AsValueString() == value || x.LookupParameter(parameter).AsString() == value) .ToList(); break; case "не равно": elements = new FilteredElementCollector(doc, activeView.Id) .WherePasses(filter) .Where(x => x.LookupParameter(parameter).AsValueString() != value && x.LookupParameter(parameter).AsString() != value) .ToList(); break; default: break; } return(elements); }
/// <summary> /// Gets element filter for export. /// </summary> /// <param name="document">The Revit document.</param> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="filterView">The view for current view export.</param> /// <param name="forSpatialElements">True to get spatial element filter, false for non spatial elements filter.</param> /// <returns>The element filter.</returns> private static ElementFilter GetExportFilter(Document document, ExporterIFC exporterIFC, Element filterView, bool forSpatialElements) { List <ElementFilter> filters = new List <ElementFilter>(); // Class types & categories ElementFilter classFilter = GetClassFilter(forSpatialElements); // Special handling for family instances and view specific elements if (!forSpatialElements) { ElementFilter familyInstanceFilter = GetFamilyInstanceFilter(exporterIFC); List <ElementFilter> classFilters = new List <ElementFilter>(); classFilters.Add(classFilter); classFilters.Add(familyInstanceFilter); if (ExporterCacheManager.ExportOptionsCache.ExportAnnotations) { ElementFilter ownerViewFilter = GetViewSpecificTypesFilter(exporterIFC); classFilters.Add(ownerViewFilter); } classFilter = new LogicalOrFilter(classFilters); } filters.Add(classFilter); // Design options filters.Add(GetDesignOptionFilter()); // Phases filters.Add(GetPhaseStatusFilter(document, filterView)); return(new LogicalAndFilter(filters)); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var uidoc = uiapp.ActiveUIDocument; var doc = uidoc.Document; var sel = uidoc.Selection; var acview = doc.ActiveView; //filter target columntypes ElementFilter architectureColumnFilter = new ElementCategoryFilter(BuiltInCategory.OST_Columns); ElementFilter structuralColumnFilter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns); ElementFilter orfilter = new LogicalOrFilter(architectureColumnFilter, structuralColumnFilter); var collector = new FilteredElementCollector(doc); var columnstypes = collector.WhereElementIsElementType().WherePasses(orfilter).ToElements(); ColumnTypesForm typesform = ColumnTypesForm.Getinstance(columnstypes.ToList());//new ColumnTypesForm(columnstypes.ToList()); typesform.ShowDialog(RevitWindowHelper.GetRevitWindow()); //get selected familysymbol of combobox in columntypesForm var familysymbol = typesform.symbolCombo.SelectedItem as FamilySymbol; //varient for setting bottom and top /*for learners self modifing*/ var bottomlevel = default(Level); var bottomoffset = default(double); var toplevel = default(Level); var topoffset = default(double); var grids = doc.TCollector <Grid>(); var points = new List <XYZ>(); foreach (var grid in grids) { foreach (var grid1 in grids) { if (grid.Id == grid1.Id) { continue; } var curve1 = grid.Curve; var curve2 = grid1.Curve; var res = new IntersectionResultArray(); var intersecRes = curve1.Intersect(curve2, out res); if (intersecRes != SetComparisonResult.Disjoint) { if (res != null) { points.Add(res.get_Item(0).XYZPoint); } } } } //distinct points on same location points = points.Where((m, i) => points.FindIndex(n => n.IsAlmostEqualTo(m)) == i).ToList(); //MessageBox.Show(points.Count.ToString()); //CreateColumns as intersection point TransactionGroup tsg = new TransactionGroup(doc); tsg.Start("统一创建柱子"); foreach (var point in points) { doc.Invoke(m => { if (!familysymbol.IsActive) { familysymbol.Activate(); } var instance = doc.Create.NewFamilyInstance(point, familysymbol, acview.GenLevel, StructuralType.NonStructural); }, "创建柱子"); } tsg.Assimilate(); return(Result.Succeeded); }
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { try { // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel("Visual Programming"); //MDJ todo - move hard-coded strings out to resource files //Create a push button in the ribbon panel PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", "Dynamo", m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; System.Drawing.Bitmap dynamoIcon = Dynamo.Applications.Properties.Resources.Nodes_32_32; BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; // MDJ = element level events and dyanmic model update // Register sfm updater with Revit //DynamoUpdater updater = new DynamoUpdater(application.ActiveAddInId); //UpdaterRegistry.RegisterUpdater(updater); //// Change Scope = any spatial field element //ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ////ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); //// Change type = element addition //UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), SpatialFieldFilter, //Element.GetChangeTypeAny()); // Element.GetChangeTypeElementAddition() DynamoUpdater updater = new DynamoUpdater(application.ActiveAddInId);//, sphere.Id, view.Id); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) { UpdaterRegistry.RegisterUpdater(updater); } ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); IList <ElementFilter> filterList = new List <ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(massFilter); LogicalOrFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeGeometry()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); return(Result.Succeeded); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(Result.Failed); } }
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { try { //TAF load english_us TODO add a way to localize res = Resource_en_us.ResourceManager; // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel(res.GetString("App_Description")); //MDJ todo - move hard-coded strings out to resource files //Create a push button in the ribbon panel PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", res.GetString("App_Name"), m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; System.Drawing.Bitmap dynamoIcon = Dynamo.Applications.Properties.Resources.Nodes_32_32; BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; // MDJ = element level events and dyanmic model update // MDJ 6-8-12 trying to get new dynamo to watch for user created ref points and re-run definition when they are moved IdlePromise.RegisterIdle(application); updater = new DynamoUpdater(application.ActiveAddInId, application.ControlledApplication); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(updater); ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter refPointFilter = new ElementCategoryFilter(BuiltInCategory.OST_ReferencePoints); ElementClassFilter modelCurveFilter = new ElementClassFilter(typeof(CurveElement)); ElementClassFilter sunFilter = new ElementClassFilter(typeof(SunAndShadowSettings)); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(modelCurveFilter); filterList.Add(refPointFilter); filterList.Add(sunFilter); ElementFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeAny()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); return Result.Succeeded; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); return Result.Failed; } }
// (sic) From Dynamo legacy /// <summary> /// Utility method to create a filtered element collector which collects all elements in a view /// which Dynamo would like to view or on which Dynamo would like to operate. /// </summary> /// <returns></returns> protected static FilteredElementCollector GetVisibleElementFilter() { var fec = new FilteredElementCollector(Document); var filterList = new List<ElementFilter>(); //Autodesk.Revit.DB.Analysis.AnalysisDisplayLegend; //Autodesk.Revit.DB.Analysis.AnalysisDisplayStyle; //Autodesk.Revit.DB.Analysis.MassEnergyAnalyticalModel; //Autodesk.Revit.DB.Analysis.MassLevelData; //Autodesk.Revit.DB.Analysis.MassSurfaceData; //Autodesk.Revit.DB.Analysis.MassZone; //Autodesk.Revit.DB.Analysis.SpatialFieldManager; //Autodesk.Revit.DB.AreaScheme; //Autodesk.Revit.DB.AppearanceAssetElement; var FContinuousRail = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.ContinuousRail)); var FRailing = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.Railing)); var FStairs = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.Stairs)); var FStairsLanding = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsLanding)); //var FStairsPath = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsPath)); //var FStairsRun = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsRun)); var FTopographySurface = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.TopographySurface)); //Autodesk.Revit.DB.AreaScheme; var FAssemblyInstance = new ElementClassFilter(typeof(Autodesk.Revit.DB.AssemblyInstance)); var FBaseArray = new ElementClassFilter(typeof(Autodesk.Revit.DB.BaseArray)); //ElementClassFilter FBasePoint = new ElementClassFilter(typeof(Autodesk.Revit.DB.BasePoint)); var FBeamSystem = new ElementClassFilter(typeof(Autodesk.Revit.DB.BeamSystem)); var FBoundaryConditions = new ElementClassFilter(typeof(Autodesk.Revit.DB.BoundaryConditions)); //ElementClassFilter FCombinableElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.CombinableElement)); //Autodesk.Revit.DB..::..ComponentRepeater //Autodesk.Revit.DB..::..ComponentRepeaterSlot var FConnectorElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.ConnectorElement)); var FControl = new ElementClassFilter(typeof(Autodesk.Revit.DB.Control)); var FCurveElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.CurveElement)); //Autodesk.Revit.DB.DesignOption; //Autodesk.Revit.DB.Dimension; //Autodesk.Revit.DB..::..DisplacementElement var FDividedSurface = new ElementClassFilter(typeof(Autodesk.Revit.DB.DividedSurface)); var FCableTrayConduitRunBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.Electrical.CableTrayConduitRunBase)); //Autodesk.Revit.DB.Electrical.ElectricalDemandFactorDefinition; //Autodesk.Revit.DB.Electrical.ElectricalLoadClassification; //Autodesk.Revit.DB.Electrical.PanelScheduleSheetInstance; //Autodesk.Revit.DB.Electrical.PanelScheduleTemplate; var FElementType = new ElementClassFilter(typeof(Autodesk.Revit.DB.ElementType)); //Autodesk.Revit.DB..::..ElevationMarker //ElementClassFilter FFamilyBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.FamilyBase)); //Autodesk.Revit.DB.FilledRegion; //Autodesk.Revit.DB.FillPatternElement; //Autodesk.Revit.DB.FilterElement; //Autodesk.Revit.DB.GraphicsStyle; //Autodesk.Revit.DB.Grid; //ElementClassFilter FGroup = new ElementClassFilter(typeof(Autodesk.Revit.DB.Group)); var FHostObject = new ElementClassFilter(typeof(Autodesk.Revit.DB.HostObject)); //Autodesk.Revit.DB.IndependentTag; var FInstance = new ElementClassFilter(typeof(Autodesk.Revit.DB.Instance)); //Autodesk.Revit.DB.Level; //Autodesk.Revit.DB.LinePatternElement; //Autodesk.Revit.DB.Material; //Autodesk.Revit.DB.Mechanical.Zone; var FMEPSystem = new ElementClassFilter(typeof(Autodesk.Revit.DB.MEPSystem)); var FModelText = new ElementClassFilter(typeof(Autodesk.Revit.DB.ModelText)); //Autodesk.Revit.DB..::..MultiReferenceAnnotation var FOpening = new ElementClassFilter(typeof(Autodesk.Revit.DB.Opening)); var FPart = new ElementClassFilter(typeof(Autodesk.Revit.DB.Part)); var FPartMaker = new ElementClassFilter(typeof(Autodesk.Revit.DB.PartMaker)); //Autodesk.Revit.DB.Phase; //Autodesk.Revit.DB..::..PhaseFilter //Autodesk.Revit.DB.PrintSetting; //Autodesk.Revit.DB.ProjectInfo; //Autodesk.Revit.DB.PropertyLine; //ElementClassFilter FPropertySetElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.PropertySetElement)); //Autodesk.Revit.DB.PropertySetLibrary; var FReferencePlane = new ElementClassFilter(typeof(Autodesk.Revit.DB.ReferencePlane)); var FReferencePoint = new ElementClassFilter(typeof(Autodesk.Revit.DB.ReferencePoint)); //Autodesk.Revit.DB..::..ScheduleSheetInstance //Autodesk.Revit.DB..::..Segment //ElementClassFilter FSketchBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.SketchBase)); //ElementClassFilter FSketchPlane = new ElementClassFilter(typeof(Autodesk.Revit.DB.SketchPlane)); var FSpatialElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.SpatialElement)); //Autodesk.Revit.DB..::..SpatialElementCalculationLocation //ElementClassFilter FSpatialElementTag = new ElementClassFilter(typeof(Autodesk.Revit.DB.SpatialElementTag)); //Autodesk.Revit.DB.Structure..::..AnalyticalLink //Autodesk.Revit.DB.Structure.AnalyticalModel; var FAreaReinforcement = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.AreaReinforcement)); //Autodesk.Revit.DB.Structure..::..FabricArea //Autodesk.Revit.DB.Structure..::..FabricReinSpanSymbolControl //Autodesk.Revit.DB.Structure..::..FabricSheet var FHub = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Hub)); //Autodesk.Revit.DB.Structure.LoadBase; //Autodesk.Revit.DB.Structure.LoadCase; //Autodesk.Revit.DB.Structure.LoadCombination; //Autodesk.Revit.DB.Structure.LoadNature; //Autodesk.Revit.DB.Structure.LoadUsage; var FPathReinforcement = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.PathReinforcement)); var FRebar = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Rebar)); //Autodesk.Revit.DB.Structure..::..RebarInSystem var FTruss = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Truss)); //Autodesk.Revit.DB.SunAndShadowSettings; //Autodesk.Revit.DB.TextElement; //Autodesk.Revit.DB.View; //Autodesk.Revit.DB..::..Viewport //Autodesk.Revit.DB.ViewSheetSet; //Autodesk.Revit.DB.WorksharingDisplaySettings; filterList.Add(FContinuousRail); filterList.Add(FRailing); filterList.Add(FStairs); filterList.Add(FStairsLanding); filterList.Add(FTopographySurface); filterList.Add(FAssemblyInstance); filterList.Add(FBaseArray); filterList.Add(FBeamSystem); filterList.Add(FBoundaryConditions); filterList.Add(FConnectorElement); filterList.Add(FControl); filterList.Add(FCurveElement); filterList.Add(FDividedSurface); filterList.Add(FCableTrayConduitRunBase); filterList.Add(FHostObject); filterList.Add(FInstance); filterList.Add(FMEPSystem); filterList.Add(FModelText); filterList.Add(FOpening); filterList.Add(FPart); filterList.Add(FPartMaker); filterList.Add(FReferencePlane); filterList.Add(FReferencePoint); filterList.Add(FAreaReinforcement); filterList.Add(FHub); filterList.Add(FPathReinforcement); filterList.Add(FRebar); filterList.Add(FTruss); filterList.Add(FSpatialElement); //ElementCategoryFilter CRailings = new ElementCategoryFilter(BuiltInCategory.OST_StairsRailing); //ElementCategoryFilter CStairs = new ElementCategoryFilter(BuiltInCategory.OST_Stairs); var CRvtLinks = new ElementCategoryFilter(BuiltInCategory.OST_RvtLinks); filterList.Add(CRvtLinks); //List<ElementFilter> ignores = new List<ElementFilter>(); //ElementCategoryFilter CLightFixtureSource = new ElementCategoryFilter(BuiltInCategory.OST_LightingFixtureSource, true); //ignores.Add(CLightFixtureSource); var filters = new LogicalOrFilter(filterList); //LogicalOrFilter exclusions = new LogicalOrFilter(ignores); fec.WherePasses(filters).WhereElementIsNotElementType(); return fec; }
//I was having trouble with FilteredELementCollector to //retrieve "Conduit Fittings", so a got this code that worked for me. //-------------------------------------------------------------------- //Returns a FilteredElementCollector with the connector elements //https://thebuildingcoder.typepad.com/blog/2010/06/retrieve-mep-elements-and-connectors.html //Jeremy Tammik static FilteredElementCollector GetConnectorElements( Document doc, bool include_wires) { // what categories of family instances // are we interested in? BuiltInCategory[] bics = new BuiltInCategory[] { //BuiltInCategory.OST_CableTray, //BuiltInCategory.OST_CableTrayFitting, BuiltInCategory.OST_Conduit, BuiltInCategory.OST_ConduitFitting, //BuiltInCategory.OST_DuctCurves, //BuiltInCategory.OST_DuctFitting, //BuiltInCategory.OST_DuctTerminal, //BuiltInCategory.OST_ElectricalEquipment, //BuiltInCategory.OST_ElectricalFixtures, //BuiltInCategory.OST_LightingDevices, //BuiltInCategory.OST_LightingFixtures, //BuiltInCategory.OST_MechanicalEquipment, //BuiltInCategory.OST_PipeCurves, //BuiltInCategory.OST_PipeFitting, //BuiltInCategory.OST_PlumbingFixtures, //BuiltInCategory.OST_SpecialityEquipment, //BuiltInCategory.OST_Sprinklers, //BuiltInCategory.OST_Wire, }; IList <ElementFilter> a = new List <ElementFilter>(bics.Count()); foreach (BuiltInCategory bic in bics) { a.Add(new ElementCategoryFilter(bic)); } LogicalOrFilter categoryFilter = new LogicalOrFilter(a); LogicalAndFilter familyInstanceFilter = new LogicalAndFilter(categoryFilter, new ElementClassFilter( typeof(FamilyInstance))); IList <ElementFilter> b = new List <ElementFilter>(6); b.Add(new ElementClassFilter(typeof(CableTray))); b.Add(new ElementClassFilter(typeof(Conduit))); b.Add(new ElementClassFilter(typeof(Duct))); b.Add(new ElementClassFilter(typeof(Pipe))); if (include_wires) { b.Add(new ElementClassFilter(typeof(Wire))); } b.Add(familyInstanceFilter); LogicalOrFilter classFilter = new LogicalOrFilter(b); FilteredElementCollector collector = new FilteredElementCollector(doc); collector.WherePasses(classFilter); return(collector); }
/// <summary> /// Find out all useful elements. /// </summary> private void FindElements() { IList<ElementFilter> filters = new List<ElementFilter>(4); filters.Add(new ElementClassFilter(typeof(Level))); filters.Add(new ElementClassFilter(typeof(View))); filters.Add(new ElementClassFilter(typeof(Floor))); filters.Add(new ElementClassFilter(typeof(FloorType))); LogicalOrFilter orFilter = new LogicalOrFilter(filters); FilteredElementCollector collector = new FilteredElementCollector(m_revit.ActiveUIDocument.Document); FilteredElementIterator iterator = collector.WherePasses(orFilter).GetElementIterator(); while (iterator.MoveNext()) { // Find out all levels. Level level = (iterator.Current) as Level; if (null != level) { m_levelList.Add(level.Elevation, level); continue; } // Find out all views. View view = (iterator.Current) as View; if (null != view && !view.IsTemplate) { m_viewList.Add(view); continue; } // Find out all floors. Floor floor = (iterator.Current) as Floor; if (null != floor) { m_floorList.Add(floor); continue; } // Find out all foundation slab types. FloorType floorType = (iterator.Current) as FloorType; if (null == floorType) { continue; } if ("Structural Foundations" == floorType.Category.Name) { m_slabTypeList.Add(floorType); } } }
/// <summary> /// Do some check for the selection elements, includes geometry check. /// If the data doesn't meet our need, Exception will be thrown. /// </summary> private void Assert() { // Reserve all element ids for following iteration List<ElementId> selectedIds = new List<ElementId>(); foreach (Autodesk.Revit.DB.Element elem in m_rvtUIDoc.Selection.Elements) { selectedIds.Add(elem.Id); } if (selectedIds.Count == 0) throw new Exception("Please select a concrete beam or column to create rebar."); // // Construct filter to find expected rebar host // Structural type filters firstly LogicalOrFilter stFilter = new LogicalOrFilter( new ElementStructuralTypeFilter(StructuralType.Beam), new ElementStructuralTypeFilter(StructuralType.Column)); // + StructuralMaterial LogicalAndFilter hostFilter = new LogicalAndFilter(stFilter, new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete)); // Expected rebar host: it should be family instance FilteredElementCollector collector = new FilteredElementCollector(m_rvtUIDoc.Document, selectedIds); FamilyInstance rebarHost = collector.OfClass(typeof(FamilyInstance)).WherePasses(hostFilter).FirstElement() as FamilyInstance; // Make sure the selected beam or column is rectangular. try { m_geometryData = new GeometrySupport(rebarHost); } catch { throw new Exception("Please select a beam or column in rectangular shape."); } m_rebarHost = rebarHost; // Judge the rebar host is a valid host. RebarHostData rebarHostData = RebarHostData.GetRebarHostData(rebarHost); if (rebarHostData == null || !rebarHostData.IsValidHost()) { throw new Exception("The selected element is not a valid rebar host."); } // Make sure the selected beam or column doesn't contain any rebar. if (rebarHostData.GetRebarsInHost().Count > 0) { throw new Exception("Please select a beam or a column which doesn't contain any rebar."); } }
/// <summary> /// Return the element ids of all furniture and /// equipment family instances contained in the /// given room. /// </summary> static List<Element> GetFurniture( Room room ) { BoundingBoxXYZ bb = room.get_BoundingBox( null ); Outline outline = new Outline( bb.Min, bb.Max ); BoundingBoxIntersectsFilter filter = new BoundingBoxIntersectsFilter( outline ); Document doc = room.Document; // Todo: add category filters and other // properties to narrow down the results // what categories of family instances // are we interested in? BuiltInCategory[] bics = new BuiltInCategory[] { BuiltInCategory.OST_Furniture, BuiltInCategory.OST_PlumbingFixtures, BuiltInCategory.OST_SpecialityEquipment }; LogicalOrFilter categoryFilter = new LogicalOrFilter( bics .Select<BuiltInCategory,ElementFilter>( bic => new ElementCategoryFilter( bic ) ) .ToList<ElementFilter>() ); FilteredElementCollector familyInstances = new FilteredElementCollector( doc ) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .OfClass( typeof( FamilyInstance ) ) .WherePasses( categoryFilter ) .WherePasses( filter ); int roomid = room.Id.IntegerValue; List<Element> a = new List<Element>(); foreach( FamilyInstance fi in familyInstances ) { if( null != fi.Room && fi.Room.Id.IntegerValue.Equals( roomid ) ) { Debug.Assert( fi.Location is LocationPoint, "expected all furniture to have a location point" ); a.Add( fi ); } } return a; }
public Autodesk.Revit.UI.Result OnStartup(UIControlledApplication application) { try { // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel("Visual Programming"); //MDJ todo - move hard-coded strings out to resource files //Create a push button in the ribbon panel PushButton pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", "Dynamo", m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; System.Drawing.Bitmap dynamoIcon = Dynamo.Applications.Properties.Resources.Nodes_32_32; BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; // MDJ = element level events and dyanmic model update // Register sfm updater with Revit //DynamoUpdater updater = new DynamoUpdater(application.ActiveAddInId); //UpdaterRegistry.RegisterUpdater(updater); //// Change Scope = any spatial field element //ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ////ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); //// Change type = element addition //UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), SpatialFieldFilter, //Element.GetChangeTypeAny()); // Element.GetChangeTypeElementAddition() DynamoUpdater updater = new DynamoUpdater(application.ActiveAddInId);//, sphere.Id, view.Id); if (!UpdaterRegistry.IsUpdaterRegistered(updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(updater); ElementClassFilter SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); ElementClassFilter familyFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(massFilter); LogicalOrFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeGeometry()); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return Result.Failed; } }
/// <summary> /// Join geometry between overlapping solids. /// </summary> /// <param name="document">The active document</param> /// <returns>The number of geometry combination be joined in this document.</returns> public int Join(Document document) { int combinated = 0; // CombinableElement is of an element type that exists in the API, but not in Revit's native object model. // We use a combination of GenericForm and GeomCombination elements instead to find all CombinableElement. LogicalOrFilter filter = new LogicalOrFilter( new ElementClassFilter(typeof(GenericForm)), new ElementClassFilter(typeof(GeomCombination))); FilteredElementIterator itor = (new FilteredElementCollector(document)).WherePasses(filter).GetElementIterator(); itor.Reset(); while (itor.MoveNext()) { GenericForm gf = itor.Current as GenericForm; if (null != gf && !gf.IsSolid) continue; CombinableElement ce = itor.Current as CombinableElement; if (null == ce) continue; else m_elements.Add(ce); } // Added all solid forms in this document. while (1 < m_elements.Count) { GeomCombination geomCombination = JoinOverlapping(m_elements, document); if (null == geomCombination) { return combinated;//No overlapping. } combinated++; } return combinated; }
// (sic) From Dynamo legacy /// <summary> /// Utility method to create a filtered element collector which collects all elements in a view /// which Dynamo would like to view or on which Dynamo would like to operate. /// </summary> /// <param name="doc"></param> /// <returns></returns> protected static FilteredElementCollector GetVisibleElementFilter() { var fec = new FilteredElementCollector(Document); var filterList = new List <ElementFilter>(); //Autodesk.Revit.DB.Analysis.AnalysisDisplayLegend; //Autodesk.Revit.DB.Analysis.AnalysisDisplayStyle; //Autodesk.Revit.DB.Analysis.MassEnergyAnalyticalModel; //Autodesk.Revit.DB.Analysis.MassLevelData; //Autodesk.Revit.DB.Analysis.MassSurfaceData; //Autodesk.Revit.DB.Analysis.MassZone; //Autodesk.Revit.DB.Analysis.SpatialFieldManager; //Autodesk.Revit.DB.AreaScheme; //Autodesk.Revit.DB.AppearanceAssetElement; var FContinuousRail = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.ContinuousRail)); var FRailing = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.Railing)); var FStairs = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.Stairs)); var FStairsLanding = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsLanding)); //var FStairsPath = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsPath)); //var FStairsRun = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.StairsRun)); var FTopographySurface = new ElementClassFilter(typeof(Autodesk.Revit.DB.Architecture.TopographySurface)); //Autodesk.Revit.DB.AreaScheme; var FAssemblyInstance = new ElementClassFilter(typeof(Autodesk.Revit.DB.AssemblyInstance)); var FBaseArray = new ElementClassFilter(typeof(Autodesk.Revit.DB.BaseArray)); //ElementClassFilter FBasePoint = new ElementClassFilter(typeof(Autodesk.Revit.DB.BasePoint)); var FBeamSystem = new ElementClassFilter(typeof(Autodesk.Revit.DB.BeamSystem)); var FBoundaryConditions = new ElementClassFilter(typeof(Autodesk.Revit.DB.BoundaryConditions)); //ElementClassFilter FCombinableElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.CombinableElement)); //Autodesk.Revit.DB..::..ComponentRepeater //Autodesk.Revit.DB..::..ComponentRepeaterSlot var FConnectorElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.ConnectorElement)); var FControl = new ElementClassFilter(typeof(Autodesk.Revit.DB.Control)); var FCurveElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.CurveElement)); //Autodesk.Revit.DB.DesignOption; //Autodesk.Revit.DB.Dimension; //Autodesk.Revit.DB..::..DisplacementElement var FDividedSurface = new ElementClassFilter(typeof(Autodesk.Revit.DB.DividedSurface)); var FCableTrayConduitRunBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.Electrical.CableTrayConduitRunBase)); //Autodesk.Revit.DB.Electrical.ElectricalDemandFactorDefinition; //Autodesk.Revit.DB.Electrical.ElectricalLoadClassification; //Autodesk.Revit.DB.Electrical.PanelScheduleSheetInstance; //Autodesk.Revit.DB.Electrical.PanelScheduleTemplate; var FElementType = new ElementClassFilter(typeof(Autodesk.Revit.DB.ElementType)); //Autodesk.Revit.DB..::..ElevationMarker //ElementClassFilter FFamilyBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.FamilyBase)); //Autodesk.Revit.DB.FilledRegion; //Autodesk.Revit.DB.FillPatternElement; //Autodesk.Revit.DB.FilterElement; //Autodesk.Revit.DB.GraphicsStyle; //Autodesk.Revit.DB.Grid; //ElementClassFilter FGroup = new ElementClassFilter(typeof(Autodesk.Revit.DB.Group)); var FHostObject = new ElementClassFilter(typeof(Autodesk.Revit.DB.HostObject)); //Autodesk.Revit.DB.IndependentTag; var FInstance = new ElementClassFilter(typeof(Autodesk.Revit.DB.Instance)); //Autodesk.Revit.DB.Level; //Autodesk.Revit.DB.LinePatternElement; //Autodesk.Revit.DB.Material; //Autodesk.Revit.DB.Mechanical.Zone; var FMEPSystem = new ElementClassFilter(typeof(Autodesk.Revit.DB.MEPSystem)); var FModelText = new ElementClassFilter(typeof(Autodesk.Revit.DB.ModelText)); //Autodesk.Revit.DB..::..MultiReferenceAnnotation var FOpening = new ElementClassFilter(typeof(Autodesk.Revit.DB.Opening)); var FPart = new ElementClassFilter(typeof(Autodesk.Revit.DB.Part)); var FPartMaker = new ElementClassFilter(typeof(Autodesk.Revit.DB.PartMaker)); //Autodesk.Revit.DB.Phase; //Autodesk.Revit.DB..::..PhaseFilter //Autodesk.Revit.DB.PrintSetting; //Autodesk.Revit.DB.ProjectInfo; //Autodesk.Revit.DB.PropertyLine; //ElementClassFilter FPropertySetElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.PropertySetElement)); //Autodesk.Revit.DB.PropertySetLibrary; var FReferencePlane = new ElementClassFilter(typeof(Autodesk.Revit.DB.ReferencePlane)); var FReferencePoint = new ElementClassFilter(typeof(Autodesk.Revit.DB.ReferencePoint)); //Autodesk.Revit.DB..::..ScheduleSheetInstance //Autodesk.Revit.DB..::..Segment //ElementClassFilter FSketchBase = new ElementClassFilter(typeof(Autodesk.Revit.DB.SketchBase)); //ElementClassFilter FSketchPlane = new ElementClassFilter(typeof(Autodesk.Revit.DB.SketchPlane)); var FSpatialElement = new ElementClassFilter(typeof(Autodesk.Revit.DB.SpatialElement)); //Autodesk.Revit.DB..::..SpatialElementCalculationLocation //ElementClassFilter FSpatialElementTag = new ElementClassFilter(typeof(Autodesk.Revit.DB.SpatialElementTag)); //Autodesk.Revit.DB.Structure..::..AnalyticalLink //Autodesk.Revit.DB.Structure.AnalyticalModel; var FAreaReinforcement = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.AreaReinforcement)); //Autodesk.Revit.DB.Structure..::..FabricArea //Autodesk.Revit.DB.Structure..::..FabricReinSpanSymbolControl //Autodesk.Revit.DB.Structure..::..FabricSheet var FHub = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Hub)); //Autodesk.Revit.DB.Structure.LoadBase; //Autodesk.Revit.DB.Structure.LoadCase; //Autodesk.Revit.DB.Structure.LoadCombination; //Autodesk.Revit.DB.Structure.LoadNature; //Autodesk.Revit.DB.Structure.LoadUsage; var FPathReinforcement = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.PathReinforcement)); var FRebar = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Rebar)); //Autodesk.Revit.DB.Structure..::..RebarInSystem var FTruss = new ElementClassFilter(typeof(Autodesk.Revit.DB.Structure.Truss)); //Autodesk.Revit.DB.SunAndShadowSettings; //Autodesk.Revit.DB.TextElement; //Autodesk.Revit.DB.View; //Autodesk.Revit.DB..::..Viewport //Autodesk.Revit.DB.ViewSheetSet; //Autodesk.Revit.DB.WorksharingDisplaySettings; filterList.Add(FContinuousRail); filterList.Add(FRailing); filterList.Add(FStairs); filterList.Add(FStairsLanding); filterList.Add(FTopographySurface); filterList.Add(FAssemblyInstance); filterList.Add(FBaseArray); filterList.Add(FBeamSystem); filterList.Add(FBoundaryConditions); filterList.Add(FConnectorElement); filterList.Add(FControl); filterList.Add(FCurveElement); filterList.Add(FDividedSurface); filterList.Add(FCableTrayConduitRunBase); filterList.Add(FHostObject); filterList.Add(FInstance); filterList.Add(FMEPSystem); filterList.Add(FModelText); filterList.Add(FOpening); filterList.Add(FPart); filterList.Add(FPartMaker); filterList.Add(FReferencePlane); filterList.Add(FReferencePoint); filterList.Add(FAreaReinforcement); filterList.Add(FHub); filterList.Add(FPathReinforcement); filterList.Add(FRebar); filterList.Add(FTruss); filterList.Add(FSpatialElement); //ElementCategoryFilter CRailings = new ElementCategoryFilter(BuiltInCategory.OST_StairsRailing); //ElementCategoryFilter CStairs = new ElementCategoryFilter(BuiltInCategory.OST_Stairs); var CRvtLinks = new ElementCategoryFilter(BuiltInCategory.OST_RvtLinks); filterList.Add(CRvtLinks); //List<ElementFilter> ignores = new List<ElementFilter>(); //ElementCategoryFilter CLightFixtureSource = new ElementCategoryFilter(BuiltInCategory.OST_LightingFixtureSource, true); //ignores.Add(CLightFixtureSource); var filters = new LogicalOrFilter(filterList); //LogicalOrFilter exclusions = new LogicalOrFilter(ignores); fec.WherePasses(filters).WhereElementIsNotElementType(); return(fec); }
/// <summary> /// Collect relationship information from Ceiling to Room to be used later to determine whether a Ceiling can be contained in a Room /// </summary> /// <param name="spatialElement">The revit spatial object to process</param> /// <param name="results">The results of the CalculateSpatialElementGeometry call, for caching for later use.</param> /// <returns>True if it found a ceiling, false otherwise.</returns> static private bool GetCeilingSpaceBoundary(SpatialElement spatialElement, out SpatialElementGeometryResults results) { results = null; // Areas don't have a 3D rep, so no ceiling space boundaries. if (spatialElement is Area) return false; // Represents the criteria for boundary elements to be considered bounding Ceiling LogicalOrFilter categoryFilter = new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Ceilings), new ElementCategoryFilter(BuiltInCategory.OST_Ceilings)); try { results = s_SpatialElementGeometryCalculator.CalculateSpatialElementGeometry(spatialElement); } catch { return false; } Solid geometry = results.GetGeometry(); // Go through the boundary faces to identify whether it is bounded by a Ceiling. If it is Ceiling, add into the Cache foreach (Face face in geometry.Faces) { IList<SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face); foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces) { // Get boundary element LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement; // Only considering local file room bounding elements ElementId localElementId = boundaryElementId.HostElementId; // Evaluate if element meets criteria using PassesFilter() if (localElementId != ElementId.InvalidElementId && categoryFilter.PassesFilter(spatialElement.Document, localElementId)) { if (ExporterCacheManager.CeilingSpaceRelCache.ContainsKey(localElementId)) { // The ceiling already exists in the Dictionary, add the Space into list IList<ElementId> roomlist = ExporterCacheManager.CeilingSpaceRelCache[localElementId]; roomlist.Add(spatialElement.Id); } else { // The first time this Ceiling Id appears IList<ElementId> roomlist = new List<ElementId>(); roomlist.Add(spatialElement.Id); ExporterCacheManager.CeilingSpaceRelCache.Add(localElementId, roomlist); } } } } return true; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; // Extract and group the data from Revit in a // dictionary, where the key is the category // name and the value is a list of elements. Stopwatch sw = Stopwatch.StartNew(); Dictionary<string, List<Element>> sortedElements = new Dictionary<string, List<Element>>(); // Iterate over all elements, both symbols and // model elements, and them in the dictionary. ElementFilter f = new LogicalOrFilter( new ElementIsElementTypeFilter( false ), new ElementIsElementTypeFilter( true ) ); FilteredElementCollector collector = new FilteredElementCollector( doc ) .WherePasses( f ); string name; foreach( Element e in collector ) { Category category = e.Category; if( null != category ) { name = category.Name; // If this category was not yet encountered, // add it and create a new container for its // elements. if( !sortedElements.ContainsKey( name ) ) { sortedElements.Add( name, new List<Element>() ); } sortedElements[name].Add( e ); } } // Launch or access Excel via COM Interop: X.Application excel = new X.Application(); if( null == excel ) { LabUtils.ErrorMsg( "Failed to get or start Excel." ); return Result.Failed; } excel.Visible = true; X.Workbook workbook = excel.Workbooks.Add( Missing.Value ); X.Worksheet worksheet; // We cannot delete all work sheets, // Excel requires at least one. // //while( 1 < workbook.Sheets.Count ) //{ // worksheet = workbook.Sheets.get_Item(1) as X.Worksheet; // worksheet.Delete(); //} // Loop through all collected categories and // create a worksheet for each except the first. // We sort the categories and work trough them // from the end, since the worksheet added last // shows up first in the Excel tab. List<string> keys = new List<string>( sortedElements.Keys ); keys.Sort(); keys.Reverse(); bool first = true; int nElements = 0; int nCategories = keys.Count; foreach( string categoryName in keys ) { List<Element> elementSet = sortedElements[categoryName]; // Create and name the worksheet if( first ) { worksheet = workbook.Sheets.get_Item( 1 ) as X.Worksheet; first = false; } else { worksheet = excel.Worksheets.Add( Missing.Value, Missing.Value, Missing.Value, Missing.Value ) as X.Worksheet; } name = ( 31 < categoryName.Length ) ? categoryName.Substring( 0, 31 ) : categoryName; name = name .Replace( ':', '_' ) .Replace( '/', '_' ); worksheet.Name = name; // Determine the names of all parameters // defined for the elements in this set. List<string> paramNames = new List<string>(); foreach( Element e in elementSet ) { ParameterSet parameters = e.Parameters; foreach( Parameter parameter in parameters ) { name = parameter.Definition.Name; if( !paramNames.Contains( name ) ) { paramNames.Add( name ); } } } paramNames.Sort(); // Add the header row in bold. worksheet.Cells[1, 1] = "ID"; worksheet.Cells[1, 2] = "IsType"; int column = 3; foreach( string paramName in paramNames ) { worksheet.Cells[1, column] = paramName; ++column; } var range = worksheet.get_Range( "A1", "Z1" ); range.Font.Bold = true; range.EntireColumn.AutoFit(); int row = 2; foreach( Element e in elementSet ) { // First column is the element id, // second a flag indicating type (symbol) // or not, both displayed as an integer. worksheet.Cells[row, 1] = e.Id.IntegerValue; worksheet.Cells[row, 2] = ( e is ElementType ) ? 1 : 0; column = 3; string paramValue; foreach( string paramName in paramNames ) { paramValue = "*NA*"; //Parameter p = e.get_Parameter( paramName ); // 2014 // Careful! This returns the first best param found. Parameter p = e.LookupParameter( paramName ); // 2015 if( null != p ) { //try //{ paramValue = LabUtils.GetParameterValue( p ); //} //catch( Exception ex ) //{ // Debug.Print( ex.Message ); //} } worksheet.Cells[row, column++] = paramValue; } // column ++nElements; ++row; } // row } // category == worksheet sw.Stop(); TaskDialog.Show( "Parameter Export", string.Format( "{0} categories and a total " + "of {1} elements exported " + "in {2:F2} seconds.", nCategories, nElements, sw.Elapsed.TotalSeconds ) ); return Result.Succeeded; }
public static ElementFilter FiltersToElementFilter(Document document, IEnumerable <Filter> filters, IEnumerable <string> categoryNames) { var parameters = new List <Parameter>(); var orElementFilters = new List <ElementFilter>(); var andElementFilters = new List <ElementFilter>(); var filtersWithParameterNames = filters.Where(x => !string.IsNullOrEmpty(x.ParameterName)); ElementFilter combinedFilter = null; if (filtersWithParameterNames.Count() > 0) { foreach (var filter in filters) { if (string.IsNullOrEmpty(filter.Value)) { continue; } ElementId parameterId; if (GetParameterIdByName(document, filter.ParameterName) is ElementId id) { parameterId = id; } else { continue; } var pvp = new ParameterValueProvider(parameterId); var filterRule = FilterRuleProvider.GetFilterRule(filter.Value, pvp, (StorageType)Enum.Parse(typeof(StorageType), filter.StorageType.ToString()), filter.CompareMethod); var elementFilter = new ElementParameterFilter(filterRule, filter.Operator == OperatorType.Nand || filter.Operator == OperatorType.Nor); if (filter.Operator == OperatorType.And || filter.Operator == OperatorType.Nand) { andElementFilters.Add(elementFilter); } if (filter.Operator == OperatorType.Or || filter.Operator == OperatorType.Nor) { orElementFilters.Add(elementFilter); } } var filterList = new List <ElementFilter>(); ElementFilter orFilter = null; if (orElementFilters.Count > 1) { orFilter = new LogicalOrFilter(orElementFilters); } else if (orElementFilters.Count == 1) { orFilter = orElementFilters.First(); } if (andElementFilters.Count > 1) { var excludeFilter = new LogicalAndFilter(andElementFilters); filterList.Add(excludeFilter); } else if (andElementFilters.Count == 1) { filterList.Add(andElementFilters.First()); } if (filterList.Count > 1) { combinedFilter = new LogicalAndFilter(filterList); } if (filterList.Count == 1) { combinedFilter = filterList.First(); } if (combinedFilter != null && orFilter != null) { combinedFilter = new LogicalAndFilter(combinedFilter, orFilter); } if (filterList.Count == 0 && orFilter != null) { combinedFilter = orFilter; } } ElementFilter categoriesFilter = null; if (categoryNames != null && categoryNames.Count() > 0) { var categoryIds = new List <ElementId>(); foreach (var categoryName in categoryNames) { var category = document.Settings.Categories.get_Item(categoryName); if (category != null) { categoryIds.Add(category.Id); } } var categoryFilters = new List <ElementFilter>(); if (categoryIds.Count > 0) { var categoryRule = new FilterCategoryRule(categoryIds); var categoryFilter = new ElementParameterFilter(categoryRule); categoryFilters.Add(categoryFilter); } if (categoryFilters.Count > 0) { categoriesFilter = new LogicalOrFilter(categoryFilters); } } if (combinedFilter != null && categoriesFilter != null) { combinedFilter = new LogicalAndFilter(combinedFilter, categoriesFilter); } else if (combinedFilter == null && categoriesFilter != null) { combinedFilter = categoriesFilter; } return(combinedFilter); }
/// <summary> /// iterate all the symbols of levels and beams /// </summary> /// <returns>A value that signifies if the initialization was successful for true or failed for false</returns> private bool Initialize() { try { ElementClassFilter levelFilter = new ElementClassFilter(typeof(Level)); ElementClassFilter famFilter = new ElementClassFilter(typeof(Family)); LogicalOrFilter orFilter = new LogicalOrFilter(levelFilter, famFilter); FilteredElementCollector collector = new FilteredElementCollector(m_revit.ActiveUIDocument.Document); FilteredElementIterator i = collector.WherePasses(orFilter).GetElementIterator(); i.Reset(); bool moreElement = i.MoveNext(); while (moreElement) { object o = i.Current; // add level to list Level level = o as Level; if (null != level) { m_levels.Add(new LevelMap(level)); goto nextLoop; } // get Family f = o as Family; if (null == f) { goto nextLoop; } foreach (object symbol in f.Symbols) { FamilySymbol familyType = symbol as FamilySymbol; if (null == familyType) { goto nextLoop; } if (null == familyType.Category) { goto nextLoop; } // add symbols of beams and braces to lists string categoryName = familyType.Category.Name; if ("Structural Framing" == categoryName) { m_beamMaps.Add(new SymbolMap(familyType)); } } nextLoop: moreElement = i.MoveNext(); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return true; }
/// <summary> /// Given the filter in use by a stream returns the document elements that match it. /// </summary> /// <param name="filter"></param> /// <returns></returns> private List <Element> GetSelectionFilterObjects(ISelectionFilter filter) { var doc = CurrentDoc.Document; var selection = new List <Element>(); switch (filter.Name) { case "Category": var catFilter = filter as ListSelectionFilter; var bics = new List <BuiltInCategory>(); var categories = ConnectorRevitUtils.GetCategories(doc); IList <ElementFilter> elementFilters = new List <ElementFilter>(); foreach (var cat in catFilter.Selection) { elementFilters.Add(new ElementCategoryFilter(categories[cat].Id)); } var categoryFilter = new LogicalOrFilter(elementFilters); selection = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .WherePasses(categoryFilter).ToList(); return(selection); case "View": var viewFilter = filter as ListSelectionFilter; var views = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfClass(typeof(View)) .Where(x => viewFilter.Selection.Contains(x.Name)); foreach (var view in views) { var ids = selection.Select(x => x.UniqueId); var viewElements = new FilteredElementCollector(doc, view.Id) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Where(x => !ids.Contains(x.UniqueId)) //exclude elements already added from other views .ToList(); selection.AddRange(viewElements); } return(selection); case "Project Info": var projectInfoFilter = filter as ListSelectionFilter; if (projectInfoFilter.Selection.Contains("Project Info")) { selection.Add(doc.ProjectInformation); } if (projectInfoFilter.Selection.Contains("Views 2D")) { selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Views) .Cast <View>() .Where(x => x.ViewType == ViewType.CeilingPlan || x.ViewType == ViewType.FloorPlan || x.ViewType == ViewType.Elevation || x.ViewType == ViewType.Section) .ToList()); } if (projectInfoFilter.Selection.Contains("Views 3D")) { selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Views) .Cast <View>() .Where(x => x.ViewType == ViewType.ThreeD) .ToList()); } if (projectInfoFilter.Selection.Contains("Levels")) { selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.OST_Levels).ToList()); } if (projectInfoFilter.Selection.Contains("Families & Types")) { //get all the elementtypes of the categories we support var allCategoryFilter = new LogicalOrFilter(ConnectorRevitUtils.GetCategories(doc).Select(x => new ElementCategoryFilter(x.Value.Id)).Cast <ElementFilter>().ToList()); selection.AddRange(new FilteredElementCollector(doc) .WhereElementIsElementType() .WherePasses(allCategoryFilter).ToList()); } return(selection); case "Parameter": try { var propFilter = filter as PropertySelectionFilter; var query = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Where(fi => fi.LookupParameter(propFilter.PropertyName) != null); propFilter.PropertyValue = propFilter.PropertyValue.ToLowerInvariant(); switch (propFilter.PropertyOperator) { case "equals": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)) == propFilter.PropertyValue); break; case "contains": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)).Contains(propFilter.PropertyValue)); break; case "is greater than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) > double.Parse(propFilter.PropertyValue)); break; case "is less than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) < double.Parse(propFilter.PropertyValue)); break; } selection = query.ToList(); } catch (Exception e) { Log.CaptureException(e); } return(selection); } return(selection); }
public Result OnStartup(UIControlledApplication a) { //add the UI button on start up AddButtons(a); //Register sheet updater with Revit RenameViewUpdater updater = new RenameViewUpdater(a.ActiveAddInId); UpdaterRegistry.RegisterUpdater(updater); UpdaterRegistry.SetIsUpdaterOptional(updater.GetUpdaterId(), true); //filter by Class ElementClassFilter sheet = new ElementClassFilter(typeof(ViewSheet)); ElementClassFilter viewPort = new ElementClassFilter(typeof(Viewport)); ElementClassFilter view = new ElementClassFilter(typeof(View)); ElementCategoryFilter viewPortFilter = new ElementCategoryFilter(BuiltInCategory.OST_Viewports); ElementCategoryFilter viewFilter = new ElementCategoryFilter(BuiltInCategory.OST_Views); LogicalOrFilter filter = new LogicalOrFilter(viewPortFilter, viewFilter); //Paramter to send to the trigger ElementId sheetId = new ElementId(BuiltInParameter.SHEET_NUMBER); ElementId viewPortNumberId = new ElementId(BuiltInParameter.VIEWPORT_DETAIL_NUMBER); ElementId viewPortNameId = new ElementId(BuiltInParameter.VIEWPORT_VIEW_NAME); ElementId titleOnSheetId = new ElementId(BuiltInParameter.VIEW_DESCRIPTION); ElementId viewPortSheetNumber = new ElementId(BuiltInParameter.VIEWPORT_SHEET_NUMBER); //Set trigger to send to execute when modified UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), sheet, Element.GetChangeTypeParameter(sheetId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), viewPort, Element.GetChangeTypeParameter(viewPortNumberId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), view, Element.GetChangeTypeParameter(viewPortNameId)); UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), view, Element.GetChangeTypeParameter(titleOnSheetId)); //Set trigger to send when added UpdaterRegistry.AddTrigger(updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); return Result.Succeeded; }
/// <summary> /// Set value(uuid) to Unique ID parameter /// </summary> public void SetValueToUniqueIDParameter() { ElementClassFilter beamClassFilter = new ElementClassFilter(typeof(FamilyInstance)); ElementClassFilter slabClassFilter = new ElementClassFilter(typeof(Floor)); ElementCategoryFilter beamTypeFilter = new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming); ElementCategoryFilter slabTypeFilter = new ElementCategoryFilter(BuiltInCategory.OST_Floors); LogicalAndFilter beamFilter = new LogicalAndFilter(beamClassFilter,beamTypeFilter); LogicalAndFilter slabFilter = new LogicalAndFilter(slabClassFilter,slabTypeFilter); LogicalOrFilter beamandslabFilter = new LogicalOrFilter(beamFilter, slabFilter); IEnumerable<Element> elems = from elem in new FilteredElementCollector(m_revit.ActiveUIDocument.Document).WherePasses(beamandslabFilter).ToElements() let category = elem.Category where category!=null && (category.Name =="Structural Framing" || category.Name == "Floors") select elem; foreach (Element elem in elems) { // Find the parameter which is named "Unique ID" // belongs to a specifically beam or slab ParameterSet attributes = elem.Parameters; IEnumerator iter = attributes.GetEnumerator(); iter.Reset(); while (iter.MoveNext()) { Parameter attribute = iter.Current as Autodesk.Revit.DB.Parameter; Definition information = attribute.Definition; if ((null != information)&&("Unique ID" == information.Name) && (null == attribute.AsString()) ) { // The shared parameter "Unique ID" then be set to a UUID Guid uuid = Guid.NewGuid(); attribute.Set(uuid.ToString()); } } } }
GetFilteredNestedFamilyInstances( string familyFileNameFilter, string typeNameFilter, Document familyDocument, bool caseSensitiveFiltering) { // Following good SOA practices, verify the // incoming data can be worked with. ValidateFamilyDocument(familyDocument); // Throws an exception if not a family doc // The filters can be null List <FamilyInstance> oResult = new List <FamilyInstance>(); FamilyInstance oFamilyInstanceCandidate; FamilySymbol oFamilySymbolCandidate; List <Family> oMatchingNestedFamilies = new List <Family>(); List <FamilyInstance> oAllFamilyInstances = new List <FamilyInstance>(); bool bFamilyFileNameFilterExists = true; bool bTypeNameFilterExists = true; // Set up some fast-to-test boolean values, which will be // used for short-circuit Boolean evaluation later. if (string.IsNullOrEmpty(familyFileNameFilter)) { bFamilyFileNameFilterExists = false; } if (string.IsNullOrEmpty(typeNameFilter)) { bTypeNameFilterExists = false; } // Unfortunately detecting nested families in a family document requires iterating // over all the elements in the document, because the built-in filtering mechanism // doesn't work for this case. However, families typically don't have nearly as many // elements as a whole project, so the performance hit shouldn't be too bad. // Still, the fastest performance should come by iterating over all elements in the given // family document exactly once, keeping subsets of the family instances found for // later testing against the nested family file matches found. ElementClassFilter fFamilyClass = new ElementClassFilter(typeof(Family)); ElementClassFilter fFamInstClass = new ElementClassFilter(typeof(FamilyInstance)); LogicalOrFilter f = new LogicalOrFilter(fFamilyClass, fFamInstClass); FilteredElementCollector collector = new FilteredElementCollector(familyDocument); collector.WherePasses(f); foreach (Element e in collector) { // See if this is a family file nested into the current family document. Family oNestedFamilyFileCandidate = e as Family; if (oNestedFamilyFileCandidate != null) { // Must ask the "Element" version for it's name, because the Family object's // name is always the empty string. if (!bFamilyFileNameFilterExists || FilterMatches(oNestedFamilyFileCandidate.Name, familyFileNameFilter, caseSensitiveFiltering)) { // This is a nested family file, and either no valid family file name filter was // given, or the name of this family file matches the filter. oMatchingNestedFamilies.Add(oNestedFamilyFileCandidate); } } else { // This element is not a nested family file definition, see if it's a // nested family instance. oFamilyInstanceCandidate = e as FamilyInstance; if (oFamilyInstanceCandidate != null) { // Just add the family instance to our "all" collection for later testing // because we may not have yet found all the matching nested family file // definitions. oAllFamilyInstances.Add(oFamilyInstanceCandidate); } } } // End iterating over all the elements in the family document exactly once // See if any matching nested family file definitions were found. Only do any // more work if at least one was found. foreach (Family oMatchingNestedFamilyFile in oMatchingNestedFamilies) { // Count backwards through the all family instances list. As we find // matches on this iteration through the matching nested families, we can // delete them from the candidates list to reduce the number of family // instance candidates to test for later matching nested family files to be tested for (int iCounter = oAllFamilyInstances.Count - 1; iCounter >= 0; iCounter--) { oFamilyInstanceCandidate = oAllFamilyInstances[iCounter]; #if _2010 oFamilySymbolCandidate = oFamilyInstanceCandidate.ObjectType as FamilySymbol; #endif // _2010 ElementId id = oFamilyInstanceCandidate.GetTypeId(); oFamilySymbolCandidate = familyDocument.GetElement(id) as FamilySymbol; if (oFamilySymbolCandidate.Family.UniqueId == oMatchingNestedFamilyFile.UniqueId) { // Only add this family instance to the results if there was no type name // filter, or this family instance's type matches the given filter. if (!bTypeNameFilterExists || FilterMatches(oFamilyInstanceCandidate.Name, typeNameFilter, caseSensitiveFiltering)) { oResult.Add(oFamilyInstanceCandidate); } // No point in testing this one again, // since we know its family definition // has already been processed. oAllFamilyInstances.RemoveAt(iCounter); } } // Next family instance candidate } // End of for each matching nested family file definition found return(oResult); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // Add an EventLogTraceListener object System.Diagnostics.Trace.Listeners.Add( new System.Diagnostics.EventLogTraceListener("Application")); // Lay the hands on the active document UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; // set up a timer Timing myTimer = new Timing(); myTimer.StartTime(); try { CheckNecessarySharedParameters(doc); // Set up a filter ElementCategoryFilter doorsFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); ElementCategoryFilter windowsFilter = new ElementCategoryFilter(BuiltInCategory.OST_Windows); LogicalOrFilter orFilter = new LogicalOrFilter(doorsFilter, windowsFilter); IList <FamilyInstance> doorsAndWindows = new FilteredElementCollector(doc, doc.ActiveView.Id) .OfClass(typeof(FamilyInstance)) .WherePasses(orFilter) .WhereElementIsNotElementType() .Cast <FamilyInstance>() .ToList(); if (doorsAndWindows.Count != 0) { foreach (FamilyInstance fi in doorsAndWindows) { try { ElementId hostId = fi.Host.Id; Wall hostWall = doc.GetElement(hostId) as Wall; if (hostWall == null || hostWall.WallType.Kind == WallKind.Curtain) { continue; } SetHeights(fi); } catch (Exception) { System.Diagnostics.Trace.Write( string.Format("The object which caused failure is : {0}", fi.Name)); continue; } } } return(Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Result.Cancelled); } catch (Exception ex) { TaskDialog.Show("Exception", string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); System.Diagnostics.Trace.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Result.Failed); } finally { myTimer.StopTime(); System.Diagnostics.Trace .Write(string.Format("Time elapsed: {0}s", myTimer.Duration.TotalSeconds)); } }
public static List <IPartition> ToSAM_Partitions(this HostObject hostObject, ConvertSettings convertSettings) { if (hostObject == null) { return(null); } List <IPartition> result = convertSettings?.GetObjects <IPartition>(hostObject.Id); if (result != null) { return(result); } ElementId elementId_Type = hostObject.GetTypeId(); if (elementId_Type == null || elementId_Type == ElementId.InvalidElementId) { return(null); } HostPartitionType hostPartitionType = ((HostObjAttributes)hostObject.Document.GetElement(elementId_Type)).ToSAM_HostPartitionType(convertSettings); if (hostPartitionType == null) { return(null); } List <Face3D> face3Ds = hostObject.Profiles(); if (face3Ds == null || face3Ds.Count == 0) { return(null); } LogicalOrFilter logicalOrFilter = new LogicalOrFilter(new List <ElementFilter>() { new ElementCategoryFilter(BuiltInCategory.OST_Windows), new ElementCategoryFilter(BuiltInCategory.OST_Doors) }); #if Revit2017 IEnumerable <ElementId> elementIds = null; #else IEnumerable <ElementId> elementIds = hostObject.GetDependentElements(logicalOrFilter); #endif if (hostObject is Autodesk.Revit.DB.Wall || hostObject is CurtainSystem) { List <Autodesk.Revit.DB.Panel> panels = Core.Revit.Query.Panels(hostObject as dynamic); if (panels != null && panels.Count > 0) { List <ElementId> elementIds_Temp = panels.ConvertAll(x => x.Id); if (elementIds != null && elementIds.Count() > 0) { elementIds_Temp.AddRange(elementIds); } elementIds = elementIds_Temp; } } result = new List <IPartition>(); foreach (Face3D face3D in face3Ds) { if (face3D == null) { continue; } IHostPartition hostPartition = Analytical.Create.HostPartition(face3D, hostPartitionType); hostPartition.UpdateParameterSets(hostObject); if (elementIds != null && elementIds.Count() > 0) { foreach (ElementId elementId in elementIds) { Element element = hostObject.Document.GetElement(elementId); if (element == null) { continue; } if (!(element is FamilyInstance)) { continue; } IOpening opening = ToSAM_Opening((FamilyInstance)element, convertSettings); if (opening != null) { opening = Analytical.Query.Project(hostPartition, opening); hostPartition.AddOpening(opening); } } } result.Add(hostPartition); } convertSettings?.Add(hostObject.Id, result); return(result); }
public void Execute(UpdaterData data) { Document doc = data.GetDocument(); Autodesk.Revit.ApplicationServices.Application app = doc.Application; View view = doc.GetElement(viewID) as View; FamilyInstance sphere = doc.GetElement(sphereID) as FamilyInstance; LocationPoint sphereLP = sphere.Location as LocationPoint; XYZ sphereXYZ = sphereLP.Point; SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view); if (sfm == null) { sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3); // Three measurement values for each point } sfm.Clear(); FilteredElementCollector collector = new FilteredElementCollector(doc, view.Id); ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); LogicalOrFilter filter = new LogicalOrFilter(wallFilter, massFilter); ICollection <Element> elements = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); foreach (Face face in GetFaces(elements)) { int idx = sfm.AddSpatialFieldPrimitive(face.Reference); List <double> doubleList = new List <double>(); IList <UV> uvPts = new List <UV>(); IList <ValueAtPoint> valList = new List <ValueAtPoint>(); BoundingBoxUV bb = face.GetBoundingBox(); for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15) { for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15) { UV uvPnt = new UV(u, v); uvPts.Add(uvPnt); XYZ faceXYZ = face.Evaluate(uvPnt); // Specify three values for each point doubleList.Add(faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10); valList.Add(new ValueAtPoint(doubleList)); doubleList.Clear(); } } FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts); FieldValues vals = new FieldValues(valList); AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("Schema 1", "Schema 1 Description"); IList <int> registeredResults = new List <int>(); registeredResults = sfm.GetRegisteredResults(); int idx1 = 0; if (registeredResults.Count == 0) { idx1 = sfm.RegisterResult(resultSchema1); } else { idx1 = registeredResults.First(); } sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1); } }
/// <summary> /// Gets element filter for export. /// </summary> /// <param name="document">The Revit document.</param> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="filterView">The view for current view export.</param> /// <param name="forSpatialElements">True to get spatial element filter, false for non spatial elements filter.</param> /// <returns>The element filter.</returns> private static ElementFilter GetExportFilter(Document document, ExporterIFC exporterIFC, Element filterView, bool forSpatialElements) { List<ElementFilter> filters = new List<ElementFilter>(); // Class types & categories ElementFilter classFilter = GetClassFilter(forSpatialElements); // Special handling for family instances and view specific elements if (!forSpatialElements) { ElementFilter familyInstanceFilter = GetFamilyInstanceFilter(exporterIFC); List<ElementFilter> classFilters = new List<ElementFilter>(); classFilters.Add(classFilter); classFilters.Add(familyInstanceFilter); if (ExporterCacheManager.ExportOptionsCache.ExportAnnotations) { ElementFilter ownerViewFilter = GetViewSpecificTypesFilter(exporterIFC); classFilters.Add(ownerViewFilter); } classFilter = new LogicalOrFilter(classFilters); } filters.Add(classFilter); // Design options filters.Add(GetDesignOptionFilter()); // Phases filters.Add(GetPhaseStatusFilter(document, filterView)); return new LogicalAndFilter(filters); }
private static ElementFilter GetVisibleElementFilter() { var filterList = new List <ElementFilter>(); var fContinuousRail = new ElementClassFilter(typeof(ContinuousRail)); var fRailing = new ElementClassFilter(typeof(Railing)); var fStairs = new ElementClassFilter(typeof(Stairs)); var fStairsLanding = new ElementClassFilter(typeof(StairsLanding)); var fTopographySurface = new ElementClassFilter(typeof(TopographySurface)); var fAssemblyInstance = new ElementClassFilter(typeof(AssemblyInstance)); var fBaseArray = new ElementClassFilter(typeof(BaseArray)); var fBeamSystem = new ElementClassFilter(typeof(BeamSystem)); var fBoundaryConditions = new ElementClassFilter(typeof(BoundaryConditions)); var fConnectorElement = new ElementClassFilter(typeof(ConnectorElement)); var fControl = new ElementClassFilter(typeof(Control)); var fCurveElement = new ElementClassFilter(typeof(CurveElement)); var fDividedSurface = new ElementClassFilter(typeof(DividedSurface)); var fCableTrayConduitRunBase = new ElementClassFilter(typeof(CableTrayConduitRunBase)); var fHostObject = new ElementClassFilter(typeof(HostObject)); var fInstance = new ElementClassFilter(typeof(Instance)); var fmepSystem = new ElementClassFilter(typeof(MEPSystem)); var fModelText = new ElementClassFilter(typeof(ModelText)); var fOpening = new ElementClassFilter(typeof(Opening)); var fPart = new ElementClassFilter(typeof(Part)); var fPartMaker = new ElementClassFilter(typeof(PartMaker)); var fReferencePlane = new ElementClassFilter(typeof(ReferencePlane)); var fReferencePoint = new ElementClassFilter(typeof(ReferencePoint)); var fSpatialElement = new ElementClassFilter(typeof(SpatialElement)); var fAreaReinforcement = new ElementClassFilter(typeof(AreaReinforcement)); var fHub = new ElementClassFilter(typeof(Hub)); var fPathReinforcement = new ElementClassFilter(typeof(PathReinforcement)); var fRebar = new ElementClassFilter(typeof(Rebar)); var fTruss = new ElementClassFilter(typeof(Truss)); filterList.Add(fContinuousRail); filterList.Add(fRailing); filterList.Add(fStairs); filterList.Add(fStairsLanding); filterList.Add(fTopographySurface); filterList.Add(fAssemblyInstance); filterList.Add(fBaseArray); filterList.Add(fBeamSystem); filterList.Add(fBoundaryConditions); filterList.Add(fConnectorElement); filterList.Add(fControl); filterList.Add(fCurveElement); filterList.Add(fDividedSurface); filterList.Add(fCableTrayConduitRunBase); filterList.Add(fHostObject); filterList.Add(fInstance); filterList.Add(fmepSystem); filterList.Add(fModelText); filterList.Add(fOpening); filterList.Add(fPart); filterList.Add(fPartMaker); filterList.Add(fReferencePlane); filterList.Add(fReferencePoint); filterList.Add(fAreaReinforcement); filterList.Add(fHub); filterList.Add(fPathReinforcement); filterList.Add(fRebar); filterList.Add(fTruss); filterList.Add(fSpatialElement); var cRvtLinks = new ElementCategoryFilter(BuiltInCategory.OST_RvtLinks); filterList.Add(cRvtLinks); var filters = new LogicalOrFilter(filterList); return(filters); }
public Result OnStartup(UIControlledApplication application) { try { //TAF load english_us TODO add a way to localize res = Resource_en_us.ResourceManager; // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel(res.GetString("App_Description")); //Create a push button in the ribbon panel var pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", res.GetString("App_Name"), m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; Bitmap dynamoIcon = Resources.logo_square_32x32; BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; IdlePromise.RegisterIdle(application); Updater = new DynamoUpdater(application.ActiveAddInId, application.ControlledApplication); if (!UpdaterRegistry.IsUpdaterRegistered(Updater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(Updater); var SpatialFieldFilter = new ElementClassFilter(typeof (SpatialFieldManager)); var familyFilter = new ElementClassFilter(typeof (FamilyInstance)); var refPointFilter = new ElementCategoryFilter(BuiltInCategory.OST_ReferencePoints); var modelCurveFilter = new ElementClassFilter(typeof (CurveElement)); var sunFilter = new ElementClassFilter(typeof (SunAndShadowSettings)); IList<ElementFilter> filterList = new List<ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(modelCurveFilter); filterList.Add(refPointFilter); filterList.Add(sunFilter); ElementFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeAny()); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); env = new ExecutionEnvironment(); return Result.Succeeded; } catch (Exception ex) { MessageBox.Show(ex.ToString()); return Result.Failed; } }
/// <summary> /// Initialize the filter with the accepted element types. /// </summary> /// <param name="elemTypesAllowed">Logical filter containing accepted element types.</param> /// <returns></returns> public StructuralConnectionSelectionFilter(LogicalOrFilter elemTypesAllowed) { _filter = elemTypesAllowed; }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { try { UIApplication uiApp = commandData.Application; UIDocument uidoc = uiApp.ActiveUIDocument; Application app = uiApp.Application; Document doc = uidoc.Document; Stopwatch sw = Stopwatch.StartNew(); // f5 = f1 && f4 // = f1 && (f2 || f3) // = family instance and (door or window) #region Filters and collector definitions ElementClassFilter f1 = new ElementClassFilter( typeof( FamilyInstance ) ); ElementCategoryFilter f2 = new ElementCategoryFilter( BuiltInCategory.OST_Doors ); ElementCategoryFilter f3 = new ElementCategoryFilter( BuiltInCategory.OST_Windows ); LogicalOrFilter f4 = new LogicalOrFilter( f2, f3 ); LogicalAndFilter f5 = new LogicalAndFilter( f1, f4 ); FilteredElementCollector collector = new FilteredElementCollector( doc ); #endregion //#region Filtering with a class filter //List<Element> openingInstances = // collector.WherePasses(f5).ToElements() // as List<Element>; //#endregion //#region Filtering with an anonymous method //List<Element> openings = collector // .WherePasses(f4) // .ToElements() as List<Element>; //List<Element> openingInstances // = openings.FindAll( // e => e is FamilyInstance ); //#endregion #region Filtering with LINQ List<Element> openings = collector .WherePasses( f4 ) .ToElements() as List<Element>; List<Element> openingInstances = ( from instances in openings where instances is FamilyInstance select instances ).ToList<Element>(); #endregion int n = openingInstances.Count; sw.Stop(); Debug.WriteLine( string.Format( "Time to get {0} elements: {1}ms", n, sw.ElapsedMilliseconds ) ); return Result.Succeeded; } catch( Exception ex ) { message = ex.Message + ex.StackTrace; return Result.Failed; } }
//default execute method required by the IExternalCommand class public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { //call to the security check method to check for authentication security = SecurityLNT.Security_Check(); if (security == false) { return(Result.Succeeded); } //get the application data Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; //read the config file SpecificationData configFileData = UtilityMethods.ReadConfig(); //check for discipline if (configFileData.discipline != "PHE") { TaskDialog.Show("Failed!", "Sorry! Plug-in Not intended for your discipline."); return(Result.Succeeded); } //exception handled if (configFileData.offset == -1.0) { MessageBox.Show("Configuration data not found!"); return(Result.Succeeded); } //get all data from the specification file specsData = UtilityMethods.GetAllSpecs(configFileData); //exception handled if (specsData == null) { MessageBox.Show("Specifications not found!"); return(Result.Succeeded); } //open the active document in revit m_document = commandData.Application.ActiveUIDocument; //get the selected element set eleSet = m_document.Selection.Elements; if (eleSet.IsEmpty) { MessageBox.Show("Please select pipes before executing the Add-in!"); return(Result.Succeeded); } //call to method to get the transform required Transform transform = UtilityMethods.GetInverseTransform(m_document.Document, commandData.Application.Application); if (transform == null) { MessageBox.Show("Sorry! Couldn't find a possible transform."); return(Result.Succeeded); } //get family name from config data FamilyName = configFileData.selectedFamily; //check if family exists family = UtilityMethods.FindElementByName(m_document.Document, typeof(Family), FamilyName) as Family; //if existing if (family == null) { MessageBox.Show("Please load the family into the project and re-run the Add-in."); return(Result.Succeeded); } //get the family symbol symbol = UtilityMethods.GetFamilySymbol(family); //exception handled if (family == null) { MessageBox.Show("No family symbol for the family you specified!"); return(Result.Succeeded); } //create a logical filter for all the structural elements LogicalOrFilter filter = UtilityMethods.GetStructuralFilter(); //if no filter is returned if (filter == null) { return(Result.Succeeded); } //get the structural elements from the documents List <Element> structuralElements = new List <Element>(); structuralElements = UtilityMethods.GetStructuralElements(app, filter); if (structuralElements == null) { MessageBox.Show("Sorry! No structural element found"); return(Result.Succeeded); } //list to store all the planar botom faces of the structural elements List <PlanarFace> pFace = new List <PlanarFace>(); //find and add bottom planar faces to the list foreach (Element e in structuralElements) { PlanarFace pf = UtilityMethods.GetBottomFace(e); if (pf != null) { pFace.Add(pf); } } //clear the structural elements list as it is no longer required structuralElements.Clear(); //control variable for removing unwanted elements from the planar faces list int flag = 0; //iterate through all the selected elements foreach (Element ele in eleSet) { //check whether the selected element is of type pipe if (ele is Pipe) { //get the location curve of the pipe pipeCurve = ((LocationCurve)ele.Location).Curve; //if the length of pipe curve obtained is zero skip that pipe if (pipeCurve.Length == 0) { FailedToPlace.Add(ele.Id); continue; } //remove unwanted planes from the list if (flag == 0) { //remove unwanted faces from the list (this works only once) pFace = UtilityMethods.GetPossiblePlanes(pFace, pipeCurve.get_EndPoint(0), transform); flag = -1; } //if no plane is found for intersect to work if (pFace.Count == 0) { MessageBox.Show("Sorry! No structural element found"); return(Result.Succeeded); } //from the specification file, get the spacing corresponding to the pipe diameter spacing = UtilityMethods.GetSpacing(ele, specsData); //check if the spacing returned is -1 if (spacing == -1) { FailedToPlace.Add(ele.Id); continue; } //get the points for placing the family instances points = UtilityMethods.GetPlacementPoints(spacing, pipeCurve, 1000 * configFileData.offset, 1000 * configFileData.minSpacing); //check if the points is null exception if (points == null) { FailedToPlace.Add(ele.Id); continue; } //get the pipe level pipeLevel = ele.Level; //iterate through all the points for placing the family instances foreach (XYZ point in points) { try { //create the instances at each points tempEle = m_document.Document.Create.NewFamilyInstance (point, symbol, ele, pipeLevel, StructuralType.NonStructural); createdElements.Add(tempEle.Id); } catch { FailedToPlace.Add(ele.Id); continue; } //find the rod length required rodLength = UtilityMethods.ReturnLeastZ_Value(m_document.Document, pFace, point, transform); if (rodLength == -1) { FailedToPlace.Add(ele.Id); createdElements.Remove(tempEle.Id); m_document.Document.Delete(tempEle.Id); continue; } //adjust the newly created element properties based on the rodlength, //orientation and dia of pipe if (!UtilityMethods.AdjustElement(m_document.Document, tempEle, point, (Pipe)ele, rodLength, pipeCurve)) { FailedToPlace.Add(ele.Id); createdElements.Remove(tempEle.Id); m_document.Document.Delete(tempEle.Id); continue; } } } } return(Result.Succeeded); } catch (Exception e) { message = e.Message; return(Autodesk.Revit.UI.Result.Failed); } throw new NotImplementedException(); }
/// <summary> /// Example demonstrating truss creation in the Autodesk Revit API. This example constructs /// a "mono" truss aligned with the reference planes in the (already loaded) truss family /// document. /// </summary> private void MakeNewTruss() { // Constants for arranging the angular truss members double webAngle = 35.0; double webAngleRadians = (180 - webAngle) * Math.PI / 180.0; Autodesk.Revit.DB.XYZ angleDirection = new Autodesk.Revit.DB.XYZ(Math.Cos(webAngleRadians), Math.Sin(webAngleRadians), 0); // Look up the reference planes and view in which to sketch ReferencePlane top = null, bottom = null, left = null, right = null, center = null; View level1 = null; List <Autodesk.Revit.DB.Element> elements = new List <Autodesk.Revit.DB.Element>(); ElementClassFilter refPlaneFilter = new ElementClassFilter(typeof(ReferencePlane)); ElementClassFilter viewFilter = new ElementClassFilter(typeof(View)); LogicalOrFilter filter = new LogicalOrFilter(refPlaneFilter, viewFilter); FilteredElementCollector collector = new FilteredElementCollector(m_document); elements.AddRange(collector.WherePasses(filter).ToElements()); foreach (Element e in elements) { // skip view templates because they're invisible invalid for truss creation View view = e as View; if (null != view && view.IsTemplate) { continue; } // switch (e.Name) { case "Top": top = e as ReferencePlane; break; case "Bottom": bottom = e as ReferencePlane; break; case "Right": right = e as ReferencePlane; break; case "Left": left = e as ReferencePlane; break; case "Center": center = e as ReferencePlane; break; case "Level 1": level1 = e as View; break; } } if (top == null || bottom == null || left == null || right == null || center == null || level1 == null) { throw new InvalidOperationException("Could not find prerequisite named reference plane or named view."); } SketchPlane sPlane = level1.SketchPlane; // Extract the geometry of each reference plane Line bottomLine = GetReferencePlaneLine(bottom); Line leftLine = GetReferencePlaneLine(left); Line rightLine = GetReferencePlaneLine(right); Line topLine = GetReferencePlaneLine(top); Line centerLine = GetReferencePlaneLine(center); // Create bottom chord along "bottom" from "left" to "right" Autodesk.Revit.DB.XYZ bottomLeft = GetIntersection(bottomLine, leftLine); Autodesk.Revit.DB.XYZ bottomRight = GetIntersection(bottomLine, rightLine); ModelCurve bottomChord = MakeTrussCurve(bottomLeft, bottomRight, sPlane, TrussCurveType.BottomChord); if (null != bottomChord) { // Add the alignment constraint to the bottom chord. Curve geometryCurve = bottomChord.GeometryCurve; // Lock the bottom chord to bottom reference plan m_familyCreator.NewAlignment(level1, bottom.GetReference(), geometryCurve.Reference); } // Create web connecting top and bottom chords on the right side Autodesk.Revit.DB.XYZ topRight = GetIntersection(topLine, rightLine); ModelCurve rightWeb = MakeTrussCurve(bottomRight, topRight, sPlane, TrussCurveType.Web); if (null != rightWeb) { // Add the alignment constraint to the right web chord. Curve geometryCurve = rightWeb.GeometryCurve; // Lock the right web chord to right reference plan m_familyCreator.NewAlignment(level1, right.GetReference(), geometryCurve.Reference); } // Create top chord diagonally from bottom-left to top-right ModelCurve topChord = MakeTrussCurve(bottomLeft, topRight, sPlane, TrussCurveType.TopChord); if (null != topChord) { // Add the alignment constraint to the top chord. Curve geometryCurve = topChord.GeometryCurve; // Lock the start point of top chord to the Intersection of left and bottom reference plan m_familyCreator.NewAlignment(level1, geometryCurve.GetEndPointReference(0), left.GetReference()); m_familyCreator.NewAlignment(level1, geometryCurve.GetEndPointReference(0), bottom.GetReference()); // Lock the end point of top chord to the Intersection of right and top reference plan m_familyCreator.NewAlignment(level1, geometryCurve.GetEndPointReference(1), top.GetReference()); m_familyCreator.NewAlignment(level1, geometryCurve.GetEndPointReference(1), right.GetReference()); } // Create angled web from midpoint to the narrow end of the truss Autodesk.Revit.DB.XYZ bottomMidPoint = GetIntersection(bottomLine, centerLine); Line webDirection = Line.CreateUnbound(bottomMidPoint, angleDirection); Autodesk.Revit.DB.XYZ endOfWeb = GetIntersection(topChord.GeometryCurve as Line, webDirection); ModelCurve angledWeb = MakeTrussCurve(bottomMidPoint, endOfWeb, sPlane, TrussCurveType.Web); // Add a dimension to force the angle to be stable even when truss length and height are modified Arc dimensionArc = Arc.Create( bottomMidPoint, angledWeb.GeometryCurve.Length / 2, webAngleRadians, Math.PI, Autodesk.Revit.DB.XYZ.BasisX, Autodesk.Revit.DB.XYZ.BasisY); Dimension createdDim = m_familyCreator.NewAngularDimension( level1, dimensionArc, angledWeb.GeometryCurve.Reference, bottomChord.GeometryCurve.Reference); if (null != createdDim) { createdDim.IsLocked = true; } // Create angled web from corner to top of truss Autodesk.Revit.DB.XYZ bottomRight2 = GetIntersection(bottomLine, rightLine); webDirection = Line.CreateUnbound(bottomRight2, angleDirection); endOfWeb = GetIntersection(topChord.GeometryCurve as Line, webDirection); ModelCurve angledWeb2 = MakeTrussCurve(bottomRight, endOfWeb, sPlane, TrussCurveType.Web); // Add a dimension to force the angle to be stable even when truss length and height are modified dimensionArc = Arc.Create( bottomRight, angledWeb2.GeometryCurve.Length / 2, webAngleRadians, Math.PI, Autodesk.Revit.DB.XYZ.BasisX, Autodesk.Revit.DB.XYZ.BasisY); createdDim = m_familyCreator.NewAngularDimension( level1, dimensionArc, angledWeb2.GeometryCurve.Reference, bottomChord.GeometryCurve.Reference); if (null != createdDim) { createdDim.IsLocked = true; } //Connect bottom midpoint to end of the angled web ModelCurve braceWeb = MakeTrussCurve(bottomMidPoint, endOfWeb, sPlane, TrussCurveType.Web); }
/// <summary> /// Returns a list of family instances found in the given family document whose family file /// name matches the given familyFileNameFilter and whose type name matches the given /// typeNameFilter. If no filter values are provided (or they evaluate to the empty string /// when trimmed) then all instances will be evaluated. /// Filtering is done with a simple Contains (substring) check, so wildcards don't work. /// </summary> /// <param name="familyFileNameFilter">The portion of the nested family file name (or exact match) to find</param> /// <param name="typeNameFilter">The portion of the type name (or exact match) to find</param> /// <param name="familyDocument">The family document to search.</param> /// <param name="caseSensitiveFiltering">Whether or not the filter checking is case-sensitive</param> /// <example> /// GetFilteredNestedFamilyInstances("window", "double-hung", document, false); /// </example> /// <remarks> /// Because standard Revit filtering techniques fail when searching for nested families in a /// family document, we have no choice but to iterate over all elements in the family. /// While there usually aren't that many elements at the family level, nonetheless this method /// has been built for MAXIMUM SPEED. /// </remarks> /// <returns> /// A collection of matching nested family file instances. /// </returns> public static List<FamilyInstance> GetFilteredNestedFamilyInstances( string familyFileNameFilter, string typeNameFilter, Document familyDocument, bool caseSensitiveFiltering) { // Following good SOA practices, verify the // incoming data can be worked with. ValidateFamilyDocument( familyDocument ); // Throws an exception if not a family doc // The filters can be null List<FamilyInstance> oResult = new List<FamilyInstance>(); FamilyInstance oFamilyInstanceCandidate; FamilySymbol oFamilySymbolCandidate; List<Family> oMatchingNestedFamilies = new List<Family>(); List<FamilyInstance> oAllFamilyInstances = new List<FamilyInstance>(); bool bFamilyFileNameFilterExists = true; bool bTypeNameFilterExists = true; // Set up some fast-to-test boolean values, which will be // used for short-circuit Boolean evaluation later. if( string.IsNullOrEmpty( familyFileNameFilter ) ) { bFamilyFileNameFilterExists = false; } if( string.IsNullOrEmpty( typeNameFilter ) ) { bTypeNameFilterExists = false; } // Unfortunately detecting nested families in a family document requires iterating // over all the elements in the document, because the built-in filtering mechanism // doesn't work for this case. However, families typically don't have nearly as many // elements as a whole project, so the performance hit shouldn't be too bad. // Still, the fastest performance should come by iterating over all elements in the given // family document exactly once, keeping subsets of the family instances found for // later testing against the nested family file matches found. ElementClassFilter fFamilyClass = new ElementClassFilter( typeof( Family ) ); ElementClassFilter fFamInstClass = new ElementClassFilter( typeof( FamilyInstance ) ); LogicalOrFilter f = new LogicalOrFilter( fFamilyClass, fFamInstClass ); FilteredElementCollector collector = new FilteredElementCollector( familyDocument ); collector.WherePasses( f ); foreach( Element e in collector ) { // See if this is a family file nested into the current family document. Family oNestedFamilyFileCandidate = e as Family; if( oNestedFamilyFileCandidate != null ) { // Must ask the "Element" version for it's name, because the Family object's // name is always the empty string. if( !bFamilyFileNameFilterExists || FilterMatches( oNestedFamilyFileCandidate.Name, familyFileNameFilter, caseSensitiveFiltering ) ) { // This is a nested family file, and either no valid family file name filter was // given, or the name of this family file matches the filter. oMatchingNestedFamilies.Add( oNestedFamilyFileCandidate ); } } else { // This element is not a nested family file definition, see if it's a // nested family instance. oFamilyInstanceCandidate = e as FamilyInstance; if( oFamilyInstanceCandidate != null ) { // Just add the family instance to our "all" collection for later testing // because we may not have yet found all the matching nested family file // definitions. oAllFamilyInstances.Add( oFamilyInstanceCandidate ); } } } // End iterating over all the elements in the family document exactly once // See if any matching nested family file definitions were found. Only do any // more work if at least one was found. foreach( Family oMatchingNestedFamilyFile in oMatchingNestedFamilies ) { // Count backwards through the all family instances list. As we find // matches on this iteration through the matching nested families, we can // delete them from the candidates list to reduce the number of family // instance candidates to test for later matching nested family files to be tested for( int iCounter = oAllFamilyInstances.Count - 1; iCounter >= 0; iCounter-- ) { oFamilyInstanceCandidate = oAllFamilyInstances[iCounter]; #if _2010 oFamilySymbolCandidate = oFamilyInstanceCandidate.ObjectType as FamilySymbol; #endif // _2010 ElementId id = oFamilyInstanceCandidate.GetTypeId(); oFamilySymbolCandidate = familyDocument.GetElement( id ) as FamilySymbol; if( oFamilySymbolCandidate.Family.UniqueId == oMatchingNestedFamilyFile.UniqueId ) { // Only add this family instance to the results if there was no type name // filter, or this family instance's type matches the given filter. if( !bTypeNameFilterExists || FilterMatches( oFamilyInstanceCandidate.Name, typeNameFilter, caseSensitiveFiltering ) ) { oResult.Add( oFamilyInstanceCandidate ); } // No point in testing this one again, // since we know its family definition // has already been processed. oAllFamilyInstances.RemoveAt( iCounter ); } } // Next family instance candidate } // End of for each matching nested family file definition found return oResult; }
public void Execute(UpdaterData data) { Document doc = data.GetDocument(); Autodesk.Revit.ApplicationServices.Application app = doc.Application; View view = doc.get_Element(viewID) as View; FamilyInstance sphere = doc.get_Element(sphereID) as FamilyInstance; LocationPoint sphereLP = sphere.Location as LocationPoint; XYZ sphereXYZ = sphereLP.Point; SpatialFieldManager sfm = SpatialFieldManager.GetSpatialFieldManager(view); if (sfm == null) sfm = SpatialFieldManager.CreateSpatialFieldManager(view, 3); // Three measurement values for each point sfm.Clear(); FilteredElementCollector collector = new FilteredElementCollector(doc,view.Id); ElementCategoryFilter wallFilter = new ElementCategoryFilter(BuiltInCategory.OST_Walls); ElementCategoryFilter massFilter = new ElementCategoryFilter(BuiltInCategory.OST_Mass); LogicalOrFilter filter = new LogicalOrFilter(wallFilter, massFilter); ICollection<Element> elements = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements(); foreach (Face face in GetFaces(elements)) { int idx = sfm.AddSpatialFieldPrimitive(face.Reference); List<double> doubleList = new List<double>(); IList<UV> uvPts = new List<UV>(); IList<ValueAtPoint> valList = new List<ValueAtPoint>(); BoundingBoxUV bb = face.GetBoundingBox(); for (double u = bb.Min.U; u < bb.Max.U; u = u + (bb.Max.U - bb.Min.U) / 15) { for (double v = bb.Min.V; v < bb.Max.V; v = v + (bb.Max.V - bb.Min.V) / 15) { UV uvPnt = new UV(u, v); uvPts.Add(uvPnt); XYZ faceXYZ = face.Evaluate(uvPnt); // Specify three values for each point doubleList.Add(faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(-faceXYZ.DistanceTo(sphereXYZ)); doubleList.Add(faceXYZ.DistanceTo(sphereXYZ) * 10); valList.Add(new ValueAtPoint(doubleList)); doubleList.Clear(); } } FieldDomainPointsByUV pnts = new FieldDomainPointsByUV(uvPts); FieldValues vals = new FieldValues(valList); AnalysisResultSchema resultSchema1 = new AnalysisResultSchema("Schema 1", "Schema 1 Description"); IList<int> registeredResults = new List<int>(); registeredResults = sfm.GetRegisteredResults(); int idx1 = 0; if (registeredResults.Count == 0) { idx1 = sfm.RegisterResult(resultSchema1); } else { idx1 = registeredResults.First(); } sfm.UpdateSpatialFieldPrimitive(idx, pnts, vals, idx1); } }
/// <summary> /// Test whether each room has a roof to bound it. /// </summary> /// <param name="message">Error message to be dumped.</param> /// <param name="elements">Some elements to return.</param> /// <returns></returns> private bool FindRoomBoundingRoofs(ref string message, Autodesk.Revit.DB.ElementSet elements) { // Get all rooms List <Element> rooms = GetRoomsElements(); if (rooms.Count == 0) { message = "Unable to identify any rooms, please create room first!"; return(false); } // Represents the criteria for boundary elements to be considered bounding roofs LogicalOrFilter categoryFilter = new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Roofs), new ElementCategoryFilter(BuiltInCategory.OST_RoofSoffit)); // Calculator for room/space geometry. SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(m_document); // Stores the resulting room->roof relationships Dictionary <Element, List <ElementId> > roomsAndRoofs = new Dictionary <Element, List <ElementId> >(); foreach (Element room in rooms) { // Get room geometry & boundaries SpatialElementGeometryResults results = calculator.CalculateSpatialElementGeometry((SpatialElement)room); // Get solid geometry so we can examine each face Solid geometry = results.GetGeometry(); foreach (Face face in geometry.Faces) { // Get list of roof boundary subfaces for a given face IList <SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face); foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces) { // Get boundary element LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement; // Only considering local file room bounding elements ElementId localElementId = boundaryElementId.HostElementId; // Evaluate if element meets criteria using PassesFilter() if (localElementId != ElementId.InvalidElementId && categoryFilter.PassesFilter(m_document, localElementId)) { // Room already has roofs, add more if (roomsAndRoofs.ContainsKey(room)) { List <ElementId> roofs = roomsAndRoofs[room]; if (!roofs.Contains(localElementId)) { roofs.Add(localElementId); } } // Room found first roof else { List <ElementId> roofs = new List <ElementId>(); roofs.Add(localElementId); roomsAndRoofs.Add(room, roofs); } break; } } } } // Format results if (roomsAndRoofs.Count > 0) { String logs = String.Format("Rooms that have a bounding roof:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (KeyValuePair <Element, List <ElementId> > kvp in roomsAndRoofs) { // remove this room from all rooms list rooms.Remove(kvp.Key); List <ElementId> roofs = kvp.Value; String roofsString; // Single roof boundary if (roofs.Count == 1) { Element roof = m_document.GetElement(roofs[0]); roofsString = String.Format("Roof: Id = {0}, Name = {1}", roof.Id.IntegerValue, roof.Name); } // Multiple roofs else { roofsString = "Roofs ids = " + string.Join(", ", Array.ConvertAll <ElementId, string>(roofs.ToArray(), i => i.ToString())); } // Save results logs = String.Format( " Room: Id = {0}, Name = {1} --> {2}", kvp.Key.Id.IntegerValue, kvp.Key.Name, roofsString); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } // Format the rooms that have no bounding roof Trace.WriteLine("Geometry relationship checking finished..."); if (rooms.Count != 0) { String logs = String.Format("Below rooms don't have bounding roofs:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (Element room in rooms) { elements.Insert(room); logs = String.Format(" Room Id: {0}, Room Name: {1}", room.Id.IntegerValue, room.Name); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } return(true); }
/// <summary> /// Test whether each room has a roof to bound it. /// </summary> /// <param name="message">Error message to be dumped.</param> /// <param name="elements">Some elements to return.</param> /// <returns></returns> private bool FindRoomBoundingRoofs(ref string message, Autodesk.Revit.DB.ElementSet elements) { // Get all rooms List<Element> rooms = GetRoomsElements(); if (rooms.Count == 0) { message = "Unable to identify any rooms, please create room first!"; return false; } // Represents the criteria for boundary elements to be considered bounding roofs LogicalOrFilter categoryFilter = new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Roofs), new ElementCategoryFilter(BuiltInCategory.OST_RoofSoffit)); // Calculator for room/space geometry. SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(m_document); // Stores the resulting room->roof relationships Dictionary<Element, List<ElementId>> roomsAndRoofs = new Dictionary<Element, List<ElementId>>(); foreach (Element room in rooms) { // Get room geometry & boundaries SpatialElementGeometryResults results = calculator.CalculateSpatialElementGeometry((SpatialElement)room); // Get solid geometry so we can examine each face Solid geometry = results.GetGeometry(); foreach (Face face in geometry.Faces) { // Get list of roof boundary subfaces for a given face IList<SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face); foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces) { // Get boundary element LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement; // Only considering local file room bounding elements ElementId localElementId = boundaryElementId.HostElementId; // Evaluate if element meets criteria using PassesFilter() if (localElementId != ElementId.InvalidElementId && categoryFilter.PassesFilter(m_document, localElementId)) { // Room already has roofs, add more if (roomsAndRoofs.ContainsKey(room)) { List<ElementId> roofs = roomsAndRoofs[room]; if (!roofs.Contains(localElementId)) roofs.Add(localElementId); } // Room found first roof else { List<ElementId> roofs = new List<ElementId>(); roofs.Add(localElementId); roomsAndRoofs.Add(room, roofs); } break; } } } } // Format results if (roomsAndRoofs.Count > 0) { String logs = String.Format("Rooms that have a bounding roof:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (KeyValuePair<Element, List<ElementId>> kvp in roomsAndRoofs) { // remove this room from all rooms list rooms.Remove(kvp.Key); List<ElementId> roofs = kvp.Value; String roofsString; // Single roof boundary if (roofs.Count == 1) { Element roof = m_document.get_Element(roofs[0]); roofsString = String.Format("Roof: Id = {0}, Name = {1}", roof.Id.IntegerValue, roof.Name); } // Multiple roofs else { roofsString = "Roofs ids = " + string.Join(", ", Array.ConvertAll<ElementId, string>(roofs.ToArray(), i => i.ToString())); } // Save results logs = String.Format( " Room: Id = {0}, Name = {1} --> {2}", kvp.Key.Id.IntegerValue, kvp.Key.Name, roofsString); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } // Format the rooms that have no bounding roof Trace.WriteLine("Geometry relationship checking finished..."); if (rooms.Count != 0) { String logs = String.Format("Below rooms don't have bounding roofs:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (Element room in rooms) { elements.Insert(room); logs = String.Format(" Room Id: {0}, Room Name: {1}", room.Id.IntegerValue, room.Name); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } return true; }
/// <summary> /// Helper function /// Find a door or window on the given wall. /// If it does, return it. /// </summary> public FamilyInstance FindWindowDoorOnWall(Document rvtDoc, Wall aWall) { // Collect the list of windows and doors // No object relation graph. So going hard way. // List all the door instances var windowDoorCollector = new FilteredElementCollector(rvtDoc); windowDoorCollector.OfClass(typeof(FamilyInstance)); ElementCategoryFilter windowFilter = new ElementCategoryFilter(BuiltInCategory.OST_Windows); ElementCategoryFilter doorFilter = new ElementCategoryFilter(BuiltInCategory.OST_Doors); LogicalOrFilter windowDoorFilter = new LogicalOrFilter(windowFilter, doorFilter); windowDoorCollector.WherePasses(windowDoorFilter); IList<Element> windowDoorList = windowDoorCollector.ToElements(); // This is really bad in a large model! // You might have ten thousand doors and windows. // It would make sense to add a bounding box containment or intersection filter as well. // Check to see if the door or window is on the wall we got. foreach (FamilyInstance e in windowDoorList) { if (e.Host.Id.Equals(aWall.Id)) { return e; } } // If you come here, you did not find window or door on the given wall. return null; }
/// <summary> /// Retrieve all Rooms and Spaces elements from active document. /// </summary> /// <returns>Element list retrieved from current document.</returns> private List<Element> GetRoomsElements() { List<Element> array = new List<Element>(); ElementFilter roomSpaceFilter = new LogicalOrFilter(new RoomFilter(), new SpaceFilter()); FilteredElementCollector collector = new FilteredElementCollector(m_document); array.AddRange(collector.WherePasses(roomSpaceFilter).ToElements()); return array; }
/// <summary> /// Gets element filter to match elements which are owned by a particular view. /// </summary> /// <param name="exporter">The exporter.</param> /// <returns>The element filter.</returns> private static ElementFilter GetOwnerViewFilter(ExporterIFC exporter) { List<ElementFilter> filters = new List<ElementFilter>(); ICollection<ElementId> viewIds = exporter.GetViewIdsToExport(); foreach (ElementId id in viewIds) { filters.Add(new ElementOwnerViewFilter(id)); } filters.Add(new ElementOwnerViewFilter(ElementId.InvalidElementId)); LogicalOrFilter viewFilters = new LogicalOrFilter(filters); return viewFilters; }
/// <summary> /// Gets element filter meeting design option requirements. /// </summary> /// <returns>The element filter.</returns> private static ElementFilter GetDesignOptionFilter() { // We will respect the active design option if we are exporting a specific view. ElementFilter noDesignOptionFilter = new ElementDesignOptionFilter(ElementId.InvalidElementId); ElementFilter primaryOptionsFilter = new PrimaryDesignOptionMemberFilter(); ElementFilter designOptionFilter = new LogicalOrFilter(noDesignOptionFilter, primaryOptionsFilter); View filterView = ExporterCacheManager.ExportOptionsCache.FilterViewForExport; if (filterView != null) { ElementId designOptionId = DesignOption.GetActiveDesignOptionId(ExporterCacheManager.Document); if (designOptionId != ElementId.InvalidElementId) { ElementFilter activeDesignOptionFilter = new ElementDesignOptionFilter(designOptionId); return new LogicalOrFilter(designOptionFilter, activeDesignOptionFilter); } } return designOptionFilter; }
// should be handled by the ModelUpdater class. But there are some // cases where the document modifications handled there do no catch // certain document interactions. Those should be registered here. /// <summary> /// Register some document updaters. Generally, document updaters /// </summary> /// <param name="application"></param> private static void RegisterAdditionalUpdaters(UIControlledApplication application) { var sunUpdater = new SunPathUpdater(application.ActiveAddInId); if (!UpdaterRegistry.IsUpdaterRegistered(sunUpdater.GetUpdaterId())) UpdaterRegistry.RegisterUpdater(sunUpdater); var sunFilter = new ElementClassFilter(typeof(SunAndShadowSettings)); var filterList = new List<ElementFilter> { sunFilter }; ElementFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger( sunUpdater.GetUpdaterId(), filter, Element.GetChangeTypeAny()); Updaters.Add(sunUpdater); }
/// <summary> /// Get the selected element as the host object, also check if the selected element is expected host object /// </summary> /// <returns>true if get the selected element, otherwise false.</returns> private bool GetHostObject() { List<ElementId> selectedIds = new List<ElementId>(); foreach (Autodesk.Revit.DB.Element elem in m_commandData.Application.ActiveUIDocument.Selection.Elements) { selectedIds.Add(elem.Id); } if (selectedIds.Count != 1) return false; // // Construct filters to find expected host object: // . Host should be Beam/Column structural type. // . and it's material type should be Concrete // . and it should be FamilyInstance // // Structural type filters firstly LogicalOrFilter stFilter = new LogicalOrFilter( new ElementStructuralTypeFilter(StructuralType.Beam), new ElementStructuralTypeFilter(StructuralType.Column)); // StructuralMaterialType should be Concrete LogicalAndFilter hostFilter = new LogicalAndFilter(stFilter, new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete)); // // Expected host object FilteredElementCollector collector = new FilteredElementCollector(m_commandData.Application.ActiveUIDocument.Document, selectedIds); m_hostObject = collector .OfClass(typeof(FamilyInstance)) // FamilyInstance .WherePasses(hostFilter) // Filters .FirstElement() as FamilyInstance; return (null != m_hostObject); }
public Result OnStartup(UIControlledApplication application) { try { //TAF load english_us TODO add a way to localize res = Resource_en_us.ResourceManager; // Create new ribbon panel RibbonPanel ribbonPanel = application.CreateRibbonPanel(res.GetString("App_Description")); //Create a push button in the ribbon panel var pushButton = ribbonPanel.AddItem(new PushButtonData("Dynamo", res.GetString("App_Name"), m_AssemblyName, "Dynamo.Applications.DynamoRevit")) as PushButton; Bitmap dynamoIcon = Resources.logo_square_32x32; BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( dynamoIcon.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); pushButton.LargeImage = bitmapSource; pushButton.Image = bitmapSource; IdlePromise.RegisterIdle(application); Updater = new DynamoUpdater(application.ActiveAddInId, application.ControlledApplication); if (!UpdaterRegistry.IsUpdaterRegistered(Updater.GetUpdaterId())) { UpdaterRegistry.RegisterUpdater(Updater); } var SpatialFieldFilter = new ElementClassFilter(typeof(SpatialFieldManager)); var familyFilter = new ElementClassFilter(typeof(FamilyInstance)); var refPointFilter = new ElementCategoryFilter(BuiltInCategory.OST_ReferencePoints); var modelCurveFilter = new ElementClassFilter(typeof(CurveElement)); var sunFilter = new ElementClassFilter(typeof(SunAndShadowSettings)); IList <ElementFilter> filterList = new List <ElementFilter>(); filterList.Add(SpatialFieldFilter); filterList.Add(familyFilter); filterList.Add(modelCurveFilter); filterList.Add(refPointFilter); filterList.Add(sunFilter); ElementFilter filter = new LogicalOrFilter(filterList); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeAny()); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementDeletion()); UpdaterRegistry.AddTrigger(Updater.GetUpdaterId(), filter, Element.GetChangeTypeElementAddition()); env = new ExecutionEnvironment(); return(Result.Succeeded); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(Result.Failed); } }
/// <summary> /// Given the filter in use by a stream returns the document elements that match it /// </summary> /// <returns></returns> private IEnumerable <SpeckleObject> GetSelectionFilterObjects(ISelectionFilter filter, string clientId, string streamId) { var doc = CurrentDoc.Document; IEnumerable <SpeckleObject> objects = new List <SpeckleObject>(); var selectionIds = new List <string>(); if (filter.Name == "Selection") { var selFilter = filter as ElementsSelectionFilter; selectionIds = selFilter.Selection; } else if (filter.Name == "Category") { var catFilter = filter as ListSelectionFilter; var bics = new List <BuiltInCategory>(); var categories = Globals.GetCategories(doc); IList <ElementFilter> elementFilters = new List <ElementFilter>(); foreach (var cat in catFilter.Selection) { elementFilters.Add(new ElementCategoryFilter(categories[cat].Id)); } LogicalOrFilter categoryFilter = new LogicalOrFilter(elementFilters); selectionIds = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .WherePasses(categoryFilter) .Select(x => x.UniqueId).ToList(); } else if (filter.Name == "View") { var viewFilter = filter as ListSelectionFilter; var views = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfClass(typeof(View)) .Where(x => viewFilter.Selection.Contains(x.Name)); foreach (var view in views) { var ids = new FilteredElementCollector(doc, view.Id) .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Select(x => x.UniqueId).ToList(); selectionIds = selectionIds.Union(ids).ToList(); } } else if (filter.Name == "Parameter") { try { var propFilter = filter as PropertySelectionFilter; var query = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WhereElementIsNotElementType() .WhereElementIsViewIndependent() .Where(x => x.IsPhysicalElement()) .Where(fi => fi.LookupParameter(propFilter.PropertyName) != null); propFilter.PropertyValue = propFilter.PropertyValue.ToLowerInvariant(); switch (propFilter.PropertyOperator) { case "equals": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)) == propFilter.PropertyValue); break; case "contains": query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)).Contains(propFilter.PropertyValue)); break; case "is greater than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) > double.Parse(propFilter.PropertyValue)); break; case "is less than": query = query.Where(fi => UnitUtils.ConvertFromInternalUnits( fi.LookupParameter(propFilter.PropertyName).AsDouble(), fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) < double.Parse(propFilter.PropertyValue)); break; default: break; } selectionIds = query.Select(x => x.UniqueId).ToList(); } catch (Exception e) { Console.WriteLine(e); } } // LOCAL STATE management objects = selectionIds.Select(id => { var temp = new SpeckleObject(); temp.Properties["revitUniqueId"] = id; temp.Properties["__type"] = "Sent Object"; return(temp); }); var myStream = LocalState.FirstOrDefault(st => st.StreamId == streamId); myStream.Objects.Clear(); myStream.Objects.AddRange(objects); var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)clientId); myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects)); // Persist state and clients to revit file Queue.Add(new Action(() => { using (Transaction t = new Transaction(CurrentDoc.Document, "Update local storage")) { t.Start(); SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState); SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper); t.Commit(); } })); Executor.Raise(); var plural = objects.Count() == 1 ? "" : "s"; if (objects.Count() != 0) { NotifyUi("update-client", JsonConvert.SerializeObject(new { _id = clientId, expired = true, objects = myClient.objects, //message = $"You have added {objects.Count()} object{plural} to this sender." })); } return(objects); }
/// <summary> /// Retrieve all structural elements that we are /// interested in using to define setout points. /// We are looking at concrete for the moment. /// This includes: columns, framing, floors, /// foundations, ramps, walls. /// </summary> FilteredElementCollector GetStructuralElements( Document doc) { // What categories of family instances // are we interested in? BuiltInCategory[] bics = new BuiltInCategory[] { BuiltInCategory.OST_StructuralColumns, BuiltInCategory.OST_StructuralFraming, BuiltInCategory.OST_StructuralFoundation, BuiltInCategory.OST_Floors, BuiltInCategory.OST_Ramps }; IList <ElementFilter> a = new List <ElementFilter>(bics.Length); foreach (BuiltInCategory bic in bics) { a.Add(new ElementCategoryFilter(bic)); } LogicalOrFilter categoryFilter = new LogicalOrFilter(a); // Filter only for structural family // instances using concrete or precast // concrete structural material: List <ElementFilter> b = new List <ElementFilter>(2); b.Add(new StructuralMaterialTypeFilter( StructuralMaterialType.Concrete)); b.Add(new StructuralMaterialTypeFilter( StructuralMaterialType.PrecastConcrete)); LogicalOrFilter structuralMaterialFilter = new LogicalOrFilter(b); List <ElementFilter> c = new List <ElementFilter>(3); c.Add(new ElementClassFilter( typeof(FamilyInstance))); c.Add(structuralMaterialFilter); c.Add(categoryFilter); LogicalAndFilter familyInstanceFilter = new LogicalAndFilter(c); IList <ElementFilter> d = new List <ElementFilter>(6); d.Add(new ElementClassFilter( typeof(Wall))); d.Add(new ElementClassFilter( typeof(Floor))); //d.Add( new ElementClassFilter( // typeof( ContFooting ) ) ); #if NEED_LOADS d.Add(new ElementClassFilter( typeof(PointLoad))); d.Add(new ElementClassFilter( typeof(LineLoad))); d.Add(new ElementClassFilter( typeof(AreaLoad))); #endif d.Add(familyInstanceFilter); LogicalOrFilter classFilter = new LogicalOrFilter(d); FilteredElementCollector col = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WherePasses(classFilter); return(col); }
public void MarkUntagedFrame2() { UIDocument uidoc = ActiveUIDocument; Document doc = uidoc.Document; BuiltInCategory[] bics = new BuiltInCategory[] { BuiltInCategory.OST_StructuralColumns, BuiltInCategory.OST_StructuralFraming, BuiltInCategory.OST_StructuralFoundation, BuiltInCategory.OST_Floors, BuiltInCategory.OST_Ramps }; IList <ElementFilter> a = new List <ElementFilter>(bics.Length); foreach (BuiltInCategory bic in bics) { a.Add(new ElementCategoryFilter(bic)); } LogicalOrFilter categoryFilter = new LogicalOrFilter(a); ElementClassFilter f1 = new ElementClassFilter(typeof(FamilyInstance)); ElementClassFilter f2 = new ElementClassFilter(typeof(Floor)); LogicalAndFilter f3 = new LogicalAndFilter(categoryFilter, f1); LogicalAndFilter f4 = new LogicalAndFilter(categoryFilter, f2); //StructuralMaterialTypeFilter 會把不是OST_StructuralFraming的物件過濾掉,即使他們的材料也是Concrete!!!! StructuralMaterialTypeFilter f5 = new StructuralMaterialTypeFilter(StructuralMaterialType.Concrete); LogicalOrFilter f6 = new LogicalOrFilter(f3, f4); LogicalAndFilter memberFilter = new LogicalAndFilter(f5, f6); FilteredElementCollector collector = new FilteredElementCollector(doc); collector.WherePasses(memberFilter); List <Element> members = collector.ToList(); String Tag = null; foreach (Element e in members) { Tag = e.get_Parameter(BuiltInParameter.DOOR_NUMBER).AsString(); if (Tag == "" || Tag == null) { HiLighted(e.Id, uidoc, doc); } else { UnHiLighted(e.Id, uidoc, doc); } Tag = null; } }
private static ElementId GetParameterIdByName(Document document, string parameterName) { if (Enum.TryParse(parameterName, out BuiltInParameter bip) && Enum.IsDefined(typeof(BuiltInParameter), bip)) { return(new ElementId(bip)); } var iterator = document.ParameterBindings.ForwardIterator(); while (iterator.MoveNext()) { if (iterator.Key.Name == parameterName) { if (iterator.Key is InternalDefinition internalDefinition) { return(internalDefinition.Id); } else { var extDef = iterator.Key as ExternalDefinition; ElementFilter filter; if (iterator.Current is InstanceBinding instanceBinding) { var categoryFilters = new List <ElementFilter>(); foreach (Category category in instanceBinding.Categories) { categoryFilters.Add(new ElementCategoryFilter(category.Id)); } var categoryFilter = new LogicalOrFilter(categoryFilters); var classFilters = new List <ElementFilter> { new ElementClassFilter(typeof(SpatialElement)), new ElementClassFilter(typeof(FamilyInstance)), new ElementClassFilter(typeof(AssemblyInstance)), new ElementClassFilter(typeof(Group)), }; var classFilter = new LogicalOrFilter(classFilters); filter = new LogicalAndFilter(classFilter, categoryFilter); } else { var typeBinding = iterator.Current as TypeBinding; var categoryFilters = new List <ElementFilter>(); foreach (Category category in typeBinding.Categories) { categoryFilters.Add(new ElementCategoryFilter(category.Id)); } var categoryFilter = new LogicalOrFilter(categoryFilters); var classFilters = new List <ElementFilter> { new ElementClassFilter(typeof(FamilySymbol)), new ElementClassFilter(typeof(AssemblyType)), new ElementClassFilter(typeof(GroupType)), }; var classFilter = new LogicalOrFilter(classFilters); filter = new LogicalAndFilter(classFilter, categoryFilter); } var collector = new FilteredElementCollector(document).WherePasses(filter); foreach (var element in collector) { if (element.GetParameters(parameterName).FirstOrDefault() is Parameter parameter) { return(parameter.Id); } } } } } return(null); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; //IWin32Window revit_window // = new JtWindowHandle( // ComponentManager.ApplicationWindow ); // pre-2020 IWin32Window revit_window = new JtWindowHandle(uiapp.MainWindowHandle); // 2020 if (null == doc) { Util.ErrorMsg("Please run this command in a valid" + " Revit project document."); return(Result.Failed); } // Interactive sheet selection. FrmSelectSheets form = new FrmSelectSheets(doc); if (DialogResult.OK == form.ShowDialog( revit_window)) { List <ViewSheet> sheets = form.GetSelectedSheets(); int n = sheets.Count; string caption = Util.PluralString( n, "Sheet") + " Selected"; string msg = string.Join(", ", sheets.Select <Element, string>( e => Util.SheetDescription(e))) + "."; // Determine all floor plan views displayed // in the selected sheets. Dictionary <View, int> views = new Dictionary <View, int>( new ElementEqualityComparer()); int nFloorPlans = 0; foreach (ViewSheet sheet in sheets) { foreach (View v in sheet.GetAllPlacedViews() .Select <ElementId, View>(id => doc.GetElement(id) as View)) { if (!views.ContainsKey(v)) { if (IsFloorPlan(v)) { ++nFloorPlans; } views.Add(v, 0); } ++views[v]; } } msg += (1 == n) ? "\nIt contains" : "\nThey contain"; n = views.Count; msg += string.Format( " {0} including {1}: ", Util.PluralString(n, "view"), Util.PluralString(nFloorPlans, "floor plan")); msg += string.Join(", ", views.Keys.Select <Element, string>( e => e.Name)) + "."; Util.InfoMsg2(caption, msg, false); // Determine all categories occurring // in the views displayed by the sheets. List <Category> categories = new List <Category>( new CategoryCollector(views.Keys).Keys); // Sort categories alphabetically by name // to display them in selection form. categories.Sort( delegate(Category c1, Category c2) { return(string.Compare(c1.Name, c2.Name)); }); // Interactive category selection. FrmSelectCategories form2 = new FrmSelectCategories(categories); if (DialogResult.OK == form2.ShowDialog( revit_window)) { categories = form2.GetSelectedCategories(); n = categories.Count; caption = Util.PluralString(n, "Category") + " Selected"; msg = string.Join(", ", categories.Select <Category, string>( e => e.Name)) + "."; Util.InfoMsg2(caption, msg, false); // Convert category list to a dictionary for // more effective repeated lookup. // //Dictionary<ElementId, Category> catLookup = // categories.ToDictionary<Category, ElementId>( // c => c.Id ); // // No, much better: set up a reusable element // filter for the categories of interest: ElementFilter categoryFilter = new LogicalOrFilter(categories .Select <Category, ElementCategoryFilter>( c => new ElementCategoryFilter(c.Id)) .ToList <ElementFilter>()); // Instantiate a container for all // cloud data repository content. SheetModelCollections modelCollections = new SheetModelCollections( DbUpload.GetProjectInfo(doc).Id); foreach (ViewSheet sheet in sheets) { // Define preview form caption. caption = "Sheet and Viewport Loops - " + Util.SheetDescription(sheet); // This is currently not used for anything. ListSheetAndViewTransforms(sheet); // Determine the polygon loops representing // the size and location of given sheet and // the viewports it contains. JtLoops sheetViewportLoops = GetSheetViewportLoops( modelCollections, sheet); // Determine graphics for family instances, // their symbols and other BIM parts. GetBimGraphics(modelCollections, sheet, categoryFilter); // Display sheet and viewports with the // geometry retrieved in a temporary GeoSnoop // form generated on the fly for debugging // purposes. Bitmap bmp = GeoSnoop.DisplaySheet( sheet.Id, sheetViewportLoops, modelCollections); GeoSnoop.DisplayImageInForm( revit_window, caption, false, bmp); // Upload data to the cloud database. DbUpload.DbUploadSheet(sheet, sheetViewportLoops, modelCollections); } DbUpdater.SetLastSequence(); } } return(Result.Succeeded); }