コード例 #1
0
ファイル: Panels.cs プロジェクト: HoareLea/SAM_Revit
        public static List <Panel> ToSAM_Panels(this Document document, IEnumerable <ElementId> elementIds, ConvertSettings convertSettings)
        {
            if (document == null)
            {
                return(null);
            }

            LogicalOrFilter logicalOrFilter = null;

            logicalOrFilter = new LogicalOrFilter((new List <BuiltInCategory> {
                BuiltInCategory.OST_Walls, BuiltInCategory.OST_Floors, BuiltInCategory.OST_Roofs
            }).ConvertAll(x => (ElementFilter)(new ElementCategoryFilter(x))));
            FilteredElementCollector filteredElementCollector = null;

            if (elementIds != null && elementIds.Count() > 0)
            {
                filteredElementCollector = new FilteredElementCollector(document, new List <ElementId>(elementIds));
            }
            else
            {
                filteredElementCollector = new FilteredElementCollector(document);
            }

            IEnumerable <HostObject> hostObjects = filteredElementCollector.WherePasses(logicalOrFilter).OfClass(typeof(HostObject)).WhereElementIsNotElementType().Cast <HostObject>();

            if (hostObjects == null || hostObjects.Count() == 0)
            {
                return(null);
            }

            List <Panel> result = new List <Panel>();

            foreach (HostObject hostObject in hostObjects)
            {
                List <Panel> panels = hostObject.ToSAM(convertSettings);
                if (panels != null && panels.Count > 0)
                {
                    result.AddRange(panels);
                }
            }

            logicalOrFilter = new LogicalOrFilter((new List <BuiltInCategory> {
                BuiltInCategory.OST_MEPSpaceSeparationLines, BuiltInCategory.OST_RoomSeparationLines
            }).ConvertAll(x => (ElementFilter)(new ElementCategoryFilter(x))));
            IEnumerable <ModelCurve> modelCurves = new FilteredElementCollector(document).WherePasses(logicalOrFilter).WhereElementIsNotElementType()?.ToList().FindAll(x => x is ModelCurve).Cast <ModelCurve>();

            if (modelCurves != null && modelCurves.Count() != 0)
            {
                foreach (ModelCurve modelCurve in modelCurves)
                {
                    List <Panel> panels = modelCurve.ToSAM_Panels(convertSettings);
                    if (panels != null && panels.Count > 0)
                    {
                        result.AddRange(panels);
                    }
                }
            }

            return(result);
        }
        private void ListViewItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            int eL = -1;

            try
            {
                UIDocument uidoc = commandData.Application.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                Window0506_LoadAndPlaceFamilies.ListView_Class myListView_Class = myWindow1.myWindow3.myListView.SelectedItem as Window0506_LoadAndPlaceFamilies.ListView_Class;

                IEnumerable <Element> myIEnumerableElement = new FilteredElementCollector(doc).WherePasses(new ElementClassFilter(typeof(Family))).Where(x => x.Name == myListView_Class.String_Name);

                if (myIEnumerableElement.Count() == 0)
                {
                    MessageBox.Show(myListView_Class.String_Name + Environment.NewLine + Environment.NewLine + "Is not present in model" + Environment.NewLine + "...please click the 'Load all families' button below");
                    return;
                }
                FamilySymbol myFamilySymbol_Carrier = doc.GetElement(((Family)myIEnumerableElement.First()).GetFamilySymbolIds().First()) as FamilySymbol;

                myWindow1.myEE06_PlaceAFamily_OnDoubleClick.myFamilySymbol = myFamilySymbol_Carrier;
                myWindow1.myExternalEvent_EE06_PlaceAFamily_OnDoubleClick.Raise();
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("ListViewItem_PreviewMouseDoubleClick, error line:" + eL + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
コード例 #3
0
        public void solidBeamFinder(Document doc, XYZ startOfInterest, double solidHeight, out List <ElementId> beamIds)
        {
            beamIds = new List <ElementId>();
            double radius = 0.1;

            XYZ arcCenter = new XYZ(startOfInterest.X, startOfInterest.Y, startOfInterest.Z);

            //Build a solid cylinder
            // Create a vertical half-circle loop in the frame location.
            List <CurveLoop> curveloops = new List <CurveLoop>();
            CurveLoop        circle     = new CurveLoop();

            circle.Append(Arc.Create(arcCenter, radius, 0, Math.PI, XYZ.BasisX, XYZ.BasisY));
            circle.Append(Arc.Create(arcCenter, radius, Math.PI, 2 * Math.PI, XYZ.BasisX, XYZ.BasisY));
            curveloops.Add(circle);

            Solid cylinder = GeometryCreationUtilities.CreateExtrusionGeometry(curveloops, XYZ.BasisZ, (solidHeight));
            //PaintSolid(commandData, cylinder, 5);
            //Find beam
            IEnumerable <Element> beams = new FilteredElementCollector(doc)
                                          .OfClass(typeof(FamilyInstance))
                                          .OfCategory(BuiltInCategory.OST_StructuralFraming)
                                          .WherePasses(new ElementIntersectsSolidFilter(cylinder));

            if (beams.Count() > 0)
            {
                foreach (Element e in beams)
                {
                    beamIds.Add(e.Id);
                }
            }
        }
コード例 #4
0
 public static void AddItemsInComboBox(FilteredElementCollector lst, Type typ, IList <System.Windows.Forms.ComboBox> CBoxs)
 {
     if (null == lst || lst.Count() < 1)
     {
         TaskDialog.Show(typ.Name, "No " + typ.Name + " Found ! . . ." + "\n Please Create " + typ.Name);
     }
     else
     {
         foreach (System.Windows.Forms.ComboBox CBox in CBoxs)
         {
             foreach (object item in lst)
             {
                 if (typ == typeof(RebarCoverType))
                 {
                     CBox.Items.Add(((RebarCoverType)item).Name + " < " + Converter.Feet2Inch(((RebarCoverType)item)
                                                                                              .CoverDistance, 2) + " >");
                 }
                 else if (typ == typeof(RebarBarType))
                 {
                     CBox.Items.Add(((RebarBarType)item).Name);
                 }
                 else if (typ == typeof(RebarHookType))
                 {
                     CBox.Items.Add(((RebarHookType)item).Name);
                 }
                 else if (typ == typeof(RebarShape))
                 {
                     CBox.Items.Add(((RebarShape)item).Name);
                 }
             }
             CBox.SelectedIndex = 0;
         }
     }
 }
コード例 #5
0
        public ModifyValueForm(Document document)
        {
            InitializeComponent();

            _document = document;

            //读取所有类别
            foreach (Category category in _document.Settings.Categories)
            {
                if (category.Id.IntegerValue < 0)
                {
                    FilteredElementCollector cate_Type = new FilteredElementCollector(_document).OfCategory((BuiltInCategory)category.Id.IntegerValue).WhereElementIsElementType();
                    FilteredElementCollector cate_Ins  = new FilteredElementCollector(_document).OfCategory((BuiltInCategory)category.Id.IntegerValue).WhereElementIsNotElementType();
                    if (cate_Type.Count() == 0 && cate_Ins.Count() == 0)
                    {
                        continue;
                    }

                    categories.Add(category);
                }
            }
            categories.Sort((x, y) => x.Name.CompareTo(y.Name));

            Sel_Category.ItemsSource  = categories;
            Sel_Parameter.ItemsSource = parameters;
            View_Objects.ItemsSource  = viewObjects;
        }
コード例 #6
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            // 找到与选择图元相交的solid
            Reference       reference   = uidoc.Selection.PickObject(ObjectType.Element, "选择要检查与其他图元相交的图元");
            Element         element     = doc.GetElement(reference);
            GeometryElement geomElement = element.get_Geometry(new Options());
            Solid           solid       = null;

            foreach (GeometryObject geomObj in geomElement)
            {
                solid = geomObj as Solid;
                if (solid != null)
                {
                    break;
                }
            }

            FilteredElementCollector collector = new FilteredElementCollector(doc);

            collector.OfClass(typeof(FamilyInstance));
            collector.WherePasses(new ElementIntersectsSolidFilter(solid)); // 应用相交过滤器

            TaskDialog.Show("Revit", collector.Count() + " 个图元与相中的图元相交(" + element.Category.Name + " id:" + element.Id.ToString() + ")");

            return(Result.Succeeded);
        }
コード例 #7
0
            public static IList <string> FilteredElementCollector2IList(FilteredElementCollector lst, Type typ)
            {
                IList <string> ItemList = new List <string>();

                if (null == lst || lst.Count() < 1)
                {
                    TaskDialog.Show(typ.Name, "No " + typ.Name + " Found ! . . ." + "\n Please Create " + typ.Name);
                    return(null);
                }
                else
                {
                    foreach (object item in lst)
                    {
                        if (typ == typeof(RebarCoverType))
                        {
                            ItemList.Add(((RebarCoverType)item).Name + " < " + Converter.Feet2Inch(((RebarCoverType)item)
                                                                                                   .CoverDistance, 2) + " >");
                        }
                        else if (typ == typeof(RebarBarType))
                        {
                            ItemList.Add(((RebarBarType)item).Name);
                        }
                        else if (typ == typeof(RebarHookType))
                        {
                            ItemList.Add(((RebarHookType)item).Name);
                        }
                    }
                    return(ItemList);
                }
            }
コード例 #8
0
ファイル: Form1.cs プロジェクト: danllarom/Revit_SetPathMode
        public Form1(Document Doc)
        {
            doc = Doc;
            InitializeComponent();
            FilteredElementCollector collector1 = new FilteredElementCollector(doc);

            collector1.OfCategory(BuiltInCategory.OST_ElectricalCircuit);

            int elementos = collector1.Count();

            string[]  circuitos = new string[elementos];
            Element[] elem      = new Element[elementos];
            int       i         = 0;

            foreach (Element elem2 in collector1)
            {
                circuitos[i] = elem2.LookupParameter("Panel").AsString() + " - " + elem2.Name.ToString() + " (" + elem2.LookupParameter("Load Name").AsString() + ")";
                elem[i]      = elem2;
                i            = i + 1;
            }

            circuitos1 = circuitos;
            elem1      = elem;
            checkedListBox1.Items.AddRange(circuitos);
            checkedListBox1.CheckOnClick = true;
        }
コード例 #9
0
        private void my14ReferenceIntersector_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UIDocument uidoc = commandData.Application.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                List <Element> myListElement = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).Where(x => x.Name == "Nerf Gun").ToList();

                if (myListElement.Count() == 0)
                {
                    MessageBox.Show("Please place a nerf gun in the model, (previous button)");
                    return;
                }

                uidoc.Selection.SetElementIds(new List <ElementId>()
                {
                    myListElement.Last().Id
                });

                myExternalEvent_EE14_Draw3D_IntersectorLines.Raise();
            }

            #region catch and finally
            catch (Exception ex)
            {
                _952_PRLoogleClassLibrary.DatabaseMethods.writeDebug("my14ReferenceIntersector_Click" + Environment.NewLine + ex.Message + Environment.NewLine + ex.InnerException, true);
            }
            finally
            {
            }
            #endregion
        }
コード例 #10
0
 public static void CollectData(this Document doc)
 {
     using (TransactionGroup tg = new TransactionGroup(doc, "Output Xml and Update Data"))
     {
         tg.Start();
         using (Transaction t = new Transaction(doc, "Add Parameters:"))
         {
             t.Start();
             foreach (Param p in Parameters)
             {
                 doc.AddParam(p);
             }
             t.Commit();
         }
         using (Transaction t = new Transaction(doc, "Collect Project Data"))
         {
             t.Start();
             var fams   = new FilteredElementCollector(doc).OfClass(typeof(Family)).Count();
             var insts  = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance)).Count();
             var mats   = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Materials).Count();
             var Sheets = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets).ToElementIds().ToList();
             var Views  = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views).ToElementIds().ToList();
             var vos    = Views.Where(x => !Viewport.CanAddViewToSheet(doc, Sheets.FirstOrDefault(), x)).Count();
             doc.SetParam(ProjectParams.Families, fams.ToString());
             doc.SetParam(ProjectParams.FamilyInstances, insts.ToString());
             doc.SetParam(ProjectParams.Materials, mats.ToString());
             doc.SetParam(ProjectParams.Sheets, Sheets.Count().ToString());
             doc.SetParam(ProjectParams.Views, Views.Count().ToString());
             doc.SetParam(ProjectParams.ViwesOnSheets, vos.ToString());
             t.Commit();
         }
         tg.Commit();
     }
 }
コード例 #11
0
        // Получение уникальных типоразмеров елементов по заданной категории на активном виде
        private List <ElementType> GetUniquElementTypeByCategory(Document doc, Category category)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id);

            collector.OfCategoryId(category.Id).ToElements();

            if (collector.Count() > 0)
            {
                List <ElementId> elementTypeIds = new List <ElementId>();
                foreach (Element element in collector)
                {
                    elementTypeIds.Add(element.GetTypeId());
                }

                List <ElementType> elementTypes = new List <ElementType>();
                foreach (ElementId elementTypeId in elementTypeIds.Distinct().ToList <ElementId>())
                {
                    elementTypes.Add(doc.GetElement(elementTypeId) as ElementType);
                }
                return(elementTypes);
            }
            else
            {
                throw new ArgumentException();
            }
        }
コード例 #12
0
        // Select all Grid in a view

        public void selectAllGridsInView()
        {
            UIDocument uiDoc = this.ActiveUIDocument;
            Document   doc   = uiDoc.Document;

            // Element FIlter



            ElementFilter myElementFilter = new ElementClassFilter(typeof(Grid));

            FilteredElementCollector myCollector = new FilteredElementCollector(doc, doc.ActiveView.Id).WherePasses(myElementFilter);

            TaskDialog.Show("abc", "number of grids in view: " + myCollector.Count());

            List <Grid> myListRefGridCollector = new List <Grid>();

            List <Level> myListLevelCollector = new List <Level>();

            foreach (var elem in myCollector)
            {
                if (elem is Grid)
                {
                    Grid myGrid = elem as Grid;
                    myListRefGridCollector.Add(myGrid);
                }

                if (elem is Level)
                {
                    Level myLevel = elem as Level;
                    myListLevelCollector.Add(myLevel);
                }
            }
        }
コード例 #13
0
        //Build solid
        public void incrementIntercetor(Document doc, XYZ startOfInterest, Parameter zOffsetVar, out ElementId columnId, out ElementId beamId)
        {
            columnId = null;
            beamId   = null;

            double radius  = 0;
            double limit   = 0.75;
            double zOffset = zOffsetVar.AsDouble();
            //lower arc center
            double centerZ   = (startOfInterest.Z + zOffset) - 0.25;
            XYZ    arcCenter = new XYZ(startOfInterest.X, startOfInterest.Y, centerZ);

            //Build a solid cylinder
            for (radius = .125; radius < limit; radius = radius + 0.1)
            {
                // Create a vertical half-circle loop in the frame location.
                List <CurveLoop> curveloops = new List <CurveLoop>();
                CurveLoop        circle     = new CurveLoop();
                circle.Append(Arc.Create(arcCenter, radius, 0, Math.PI, XYZ.BasisX, XYZ.BasisY));
                circle.Append(Arc.Create(arcCenter, radius, Math.PI, 2 * Math.PI, XYZ.BasisX, XYZ.BasisY));
                curveloops.Add(circle);

                Solid cylinder = GeometryCreationUtilities.CreateExtrusionGeometry(curveloops, XYZ.BasisZ, (0.25));
                //PaintSolid(commandData, cylinder, 5);
                //Find column
                IEnumerable <Element> columns = new FilteredElementCollector(doc)
                                                .OfClass(typeof(FamilyInstance))
                                                .OfCategory(BuiltInCategory.OST_StructuralColumns)
                                                .WherePasses(new ElementIntersectsSolidFilter(cylinder));

                if (columns.Count() > 0)
                {
                    foreach (Element e in columns)
                    {
                        FamilyInstance fi = e as FamilyInstance;
                        FamilySymbol   fs = fi.Symbol;
                        columnId = e.Id;
                    }
                    break;
                }

                //Find beam
                IEnumerable <Element> beams = new FilteredElementCollector(doc)
                                              .OfClass(typeof(FamilyInstance))
                                              .OfCategory(BuiltInCategory.OST_StructuralFraming)
                                              .WherePasses(new ElementIntersectsSolidFilter(cylinder));

                if (beams.Count() > 0)
                {
                    foreach (Element e in beams)
                    {
                        FamilyInstance fi = e as FamilyInstance;
                        FamilySymbol   fs = fi.Symbol;
                        beamId = e.Id;
                    }
                    break;
                }
            }
            //End of loop
        }
コード例 #14
0
        public void deleteLinePatterns(Document doc)
        {
            var collector = new FilteredElementCollector(doc)
                .OfClass(typeof(LinePatternElement)).Where(i => i.Name.StartsWith("IMPORT")).ToList();

            List<ElementId> ids = new List<ElementId>();
            for (int i = 0; i < collector.Count(); i++)
            {
                ids.Add(collector[i].Id);
            }

            using (Transaction t = new Transaction(doc, "Remove Pattern"))
            {
                t.Start();
                try
                {
                    doc.Delete(ids);
                }
                catch (Exception)
                {
                    t.RollBack();
                    return;
                }
                t.Commit();
            }
        }
コード例 #15
0
        public static void AddOverride(Document doc, View view,
                                       ElementId pattern, List <List <string> > category_cols)
        {
            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("SetViewtx");
                foreach (List <string> category_ovr in category_cols)
                {
                    try
                    {
                        OverrideCat ov = new OverrideCat(doc, pattern, category_ovr);
                        FilteredElementCollector col
                            = new FilteredElementCollector(doc, view.Id)
                              .WhereElementIsNotElementType()
                              .OfCategory(ov.builtincategory);

                        if (col.Count() > 0)
                        {
                            foreach (Element e in col)
                            {
                                view.SetElementOverrides(e.Id, ov.overrides);
                            }
                        }
                    }
                    catch (Exception) { }
                }
                tx.Commit();
            }
        }
コード例 #16
0
        public static List <Panel> ToSAM_Panels(this Document document, ConvertSettings convertSettings)
        {
            LogicalOrFilter logicalOrFilter = new LogicalOrFilter((new List <BuiltInCategory> {
                BuiltInCategory.OST_Walls, BuiltInCategory.OST_Floors, BuiltInCategory.OST_Roofs
            }).ConvertAll(x => (ElementFilter)(new ElementCategoryFilter(x))));

            IEnumerable <HostObject> hostObjects = new FilteredElementCollector(document).WherePasses(logicalOrFilter).OfClass(typeof(HostObject)).WhereElementIsNotElementType().Cast <HostObject>();

            if (hostObjects == null || hostObjects.Count() == 0)
            {
                return(null);
            }

            List <Panel> result = new List <Panel>();

            foreach (HostObject hostObject in hostObjects)
            {
                List <Panel> panelList = hostObject.ToSAM(convertSettings);
                if (panelList != null && panelList.Count > 0)
                {
                    result.AddRange(panelList);
                }
            }

            return(result);
        }
コード例 #17
0
        public static List <ElementId> getAllRoomsInView(ElementId curLevel, Document m_doc)
        {
            FilteredElementCollector m_col = new FilteredElementCollector(m_doc);

            m_col.OfClass(typeof(SpatialElement)).ToElements();

            //loop through room and find rooms for specified level
            List <ElementId> roomList = new List <ElementId>();

            if (m_col.Count() > 0)
            {
                foreach (SpatialElement e in m_col)
                {
                    Debug.Print(e.GetType().ToString());

                    try {
                        roomList.Add(e.Id);
                    } catch (Exception ex) {
                        Debug.Print(ex.Message);
                    }

                    //				If curRoom.LevelId = curLevel Then
                    //roomList.Add(curRoom)
                    //				End If
                }
            }

            return(roomList);
        }
コード例 #18
0
        public static List <Category> GetNotEmptyCategories(List <Document> documents, Categories categories)
        {
            ElementCategoryFilter f1 = new ElementCategoryFilter(BuiltInCategory.OST_Rooms, true);
            ElementCategoryFilter f2 = new ElementCategoryFilter(BuiltInCategory.OST_PipeSegments, true);
            ElementCategoryFilter f3 = new ElementCategoryFilter(BuiltInCategory.OST_Materials, true);

            List <ElementFilter> filters = new List <ElementFilter>()
            {
                f1, f2, f3
            };
            LogicalAndFilter filter = new LogicalAndFilter(filters);


            List <Category> categoryList = new List <Category>();

            foreach (Document d in documents)
            {
                foreach (Category c in categories)
                {
                    BuiltInCategory bCat = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), c.Id.ToString());
                    if (c.CategoryType == CategoryType.Model)
                    {
                        FilteredElementCollector coll = new FilteredElementCollector(d).OfCategoryId(c.Id).WhereElementIsNotElementType().WherePasses(filter);
                        if (coll.Count() > 1)
                        {
                            categoryList.Add(c);
                        }
                    }
                }
            }
            return(categoryList.Distinct(new DistinctItemComparer()).ToList());
        }
コード例 #19
0
        /// <summary>
        /// Detects the collision or clash between two elements. By analyzing the geometry intersection of an element (Element A) against other element (Element B)
        /// </summary>
        /// <param name="doc">Active revit document</param>
        /// <param name="geometryElement">Geometry element from which the intersection will be verified (Element B)</param>
        /// <param name="element">Element to verify the presence of intersection (Element A)</param>
        /// <returns>A Boolean flag that indicates whether or not there is a clash between elements. True = Clash detected. False = No clash detected</returns>
        public static bool getClashWithSolid(Document doc, GeometryElement geometryElement, Element element)
        {
            // Elements list, This list contains the Id's of element A
            List <ElementId> elementsList = new List <ElementId>();

            elementsList.Add(element.Id);

            bool clashOutputFlag = false;

            //Look for each solid in linked model
            foreach (GeometryObject geomObj in geometryElement)
            {
                // If solid is present we perform a solid intersection filter.
                // and later, perform a filter iteration with the element to clash (Element A vs Element B)
                if (geomObj is Solid)
                {
                    Solid solidObject = geomObj as Solid;
                    ElementIntersectsSolidFilter elementIntersectsSolidFilter = new ElementIntersectsSolidFilter(solidObject);
                    FilteredElementCollector     collector = new FilteredElementCollector(doc, elementsList).WherePasses(elementIntersectsSolidFilter);

                    // If collector count is zero, this means that Solid intersection can't be possible with the given element (ie: Fabrication Parts).
                    if (collector.Count() == 0 && !fabparts.Contains(element.Category.Id))
                    {
                        BoundingBoxXYZ bbox    = geometryElement.GetBoundingBox();
                        Outline        outline = new Outline(bbox.Min, bbox.Max);
                        BoundingBoxIntersectsFilter bbFilter = new BoundingBoxIntersectsFilter(outline);
                        collector = new FilteredElementCollector(doc, elementsList).WherePasses(bbFilter);
                    }

                    foreach (var item in collector)
                    {
                        clashOutputFlag = true;
                        break;
                    }
                }

                // If a Geometry instance is present. We implement a BoundingBox intersect filter over the Geometry of element A
                // and later, perform a Filter iteration with the element to clash (Element A vs Element B)
                if (geomObj is GeometryInstance)
                {
                    BoundingBoxXYZ bbox    = geometryElement.GetBoundingBox();
                    Outline        outline = new Outline(bbox.Min, bbox.Max);
                    BoundingBoxIntersectsFilter bbFilter  = new BoundingBoxIntersectsFilter(outline);
                    FilteredElementCollector    collector = new FilteredElementCollector(doc, elementsList).WherePasses(bbFilter);
                    foreach (var item in collector)
                    {
                        clashOutputFlag = true;
                        break;
                    }
                }

                if (!clashOutputFlag)
                {
                    break;
                }
            }

            return(clashOutputFlag);
        }
コード例 #20
0
        public static FilteredElementCollector ColumnCollector(Document doc)
        {
            FilteredElementCollector columnCollector = new FilteredElementCollector(doc);

            columnCollector.OfCategory(BuiltInCategory.OST_StructuralColumns).OfClass(typeof(FamilyInstance));
            TaskDialog.Show("REVIT", columnCollector.Count().ToString());
            return(columnCollector);
        }
コード例 #21
0
        public static FilteredElementCollector WindowsCollector(Document doc)
        {
            FilteredElementCollector doorCollector = new FilteredElementCollector(doc);

            doorCollector.OfCategory(BuiltInCategory.OST_Windows).OfClass(typeof(FamilyInstance));
            TaskDialog.Show("REVIT", doorCollector.Count().ToString());
            return(doorCollector);
        }
コード例 #22
0
        public static int CountDWGs(UIApplication uiapp)
        {
            UIDocument uidoc             = uiapp.ActiveUIDocument;
            Document   doc               = uidoc.Document;
            FilteredElementCollector col = new FilteredElementCollector(doc).OfClass(typeof(ImportInstance));

            return(col.Count());
        }
コード例 #23
0
        public static FilteredElementCollector EletricalQCollector(Document doc)
        {
            FilteredElementCollector qiaojiaCollector = new FilteredElementCollector(doc);

            qiaojiaCollector.OfCategory(BuiltInCategory.OST_CableTray).OfClass(typeof(CableTray));
            TaskDialog.Show("REVIT", qiaojiaCollector.Count().ToString());
            return(qiaojiaCollector);
        }
コード例 #24
0
        public static FilteredElementCollector PipeCollector(Document doc)
        {
            FilteredElementCollector pipeCollector = new FilteredElementCollector(doc);

            pipeCollector.OfCategory(BuiltInCategory.OST_PipeCurves).OfClass(typeof(Pipe));
            TaskDialog.Show("REVIT", pipeCollector.Count().ToString());
            return(pipeCollector);
        }
コード例 #25
0
        public static FilteredElementCollector DuctCollector(Document doc)
        {
            FilteredElementCollector ductCollector = new FilteredElementCollector(doc);

            ductCollector.OfCategory(BuiltInCategory.OST_DuctCurves).OfClass(typeof(Duct));
            TaskDialog.Show("REVIT", ductCollector.Count().ToString());
            return(ductCollector);
        }
コード例 #26
0
ファイル: Command.cs プロジェクト: xiongbigbear/DomainManager
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var doc  = commandData.Application.ActiveUIDocument.Document;
            var ctor = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance));

            JsonConvert.SerializeObject("ss");
            MessageBox.Show(ctor.Count().ToString());
            return(Result.Succeeded);
        }
コード例 #27
0
        private Message ExportAll(Document doc)
        {
            IEnumerable <string> families = new FilteredElementCollector(doc).
                                            OfClass(typeof(FamilySymbol)).
                                            Select(e => e.Id.ToString());

            int success = 0;
            int failure = 0;

            Debug("EXPORTING " + families.Count() + " FAMILIES");

            foreach (string id in families)
            {
                try
                {
                    Message response = this.Command_Export.Execute(doc, new Message
                    {
                        Type  = "EXPORT",
                        Reply = null,
                        Data  = JsonConvert.SerializeObject(new
                        {
                            Id = id // "56182"
                        })
                    });

                    if (response.Type == "ERROR")
                    {
                        throw new Exception(response.Data);
                    }

                    Debug(response.Data);
                    success++;
                }
                catch (Exception e)
                {
                    Debug($"Error 2 {id} {e.ToString()}");
                    failure++;
                }
            }

            Debug("EXPORT RESULTS " + JsonConvert.SerializeObject(new
            {
                Successes = success,
                Failures  = failure
            }));

            return(new Message
            {
                Type = "EXPORT_RESULTS",
                Data = JsonConvert.SerializeObject(new
                {
                    Successes = success,
                    Failures = failure
                })
            });
        }
コード例 #28
0
        /// <summary>
        /// 功能初始化过滤器把房间所有的梁给收集起来
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public static FilteredElementCollector BeamCollector(Document doc)
        {
            //初始化梁收集器
            FilteredElementCollector beamCollector = new FilteredElementCollector(doc);

            //给梁收集器加上一个过滤器
            beamCollector.OfCategory(BuiltInCategory.OST_StructuralFraming).OfClass(typeof(FamilyInstance));
            TaskDialog.Show("REVIT", beamCollector.Count().ToString());
            return(beamCollector);
        }
コード例 #29
0
        public static bool LoadFamily(Document doc, string filePath, string _family_name)
        {
            Family family = null;

            FilteredElementCollector a = new FilteredElementCollector(doc).OfClass(typeof(Family));

            int n = a.Count <Element>(e => e.Name.Equals(_family_name));

            bool isLaoded = doc.LoadFamily(filePath, new MyFamilyLoadOptions(), out family);

            return(isLaoded);
        }
コード例 #30
0
ファイル: PBracedFrame.cs プロジェクト: ycruan/P58_Loss
        private static int DFS(IList <ElementId> columnIds, IList <ElementId> beamIds, out int num_IndividualColumn)
        {
            num_IndividualColumn = 0;
            List <Element>       columns    = (new FilteredElementCollector(_doc, columnIds)).OfClass(typeof(FamilyInstance)).ToList();
            List <Element>       beams      = (new FilteredElementCollector(_doc, beamIds)).OfClass(typeof(FamilyInstance)).ToList();
            int                  k          = 0;
            LinkedList <Element> open       = new LinkedList <Element>();
            HashSet <ElementId>  discovered = new HashSet <ElementId>();

            foreach (Element column in columns)
            {
                if (!discovered.Contains(column.Id))
                {
                    ++k;
                    open.AddFirst(column);
                    discovered.Add(column.Id);
                    while (open.Count != 0)
                    {
                        Element e = open.First();
                        open.RemoveFirst();
                        BoundingBoxXYZ bbXYZ    = e.get_BoundingBox(_doc.ActiveView);
                        XYZ            deltaXYZ = new XYZ(ErrorCTRL_BB, ErrorCTRL_BB, _maxBB.Max.Z);
                        BoundingBoxIntersectsFilter bbFilter = new BoundingBoxIntersectsFilter(new Outline(bbXYZ.Min - deltaXYZ, bbXYZ.Max + deltaXYZ));
                        FilteredElementCollector    fec      = null;
                        if (((FamilyInstance)e).StructuralUsage == StructuralInstanceUsage.Column)
                        {
                            fec = new FilteredElementCollector(_doc, beamIds);
                            fec.WherePasses(bbFilter);
                            if (fec.Count() == 0)
                            {
                                ++num_IndividualColumn;
                                --k;
                            }
                        }
                        else
                        {
                            fec = new FilteredElementCollector(_doc, columnIds);
                            fec.WherePasses(bbFilter);
                        }

                        foreach (Element intersectedEle in fec)
                        {
                            if (!discovered.Contains(intersectedEle.Id))
                            {
                                open.AddFirst(intersectedEle);
                                discovered.Add(intersectedEle.Id);
                            }
                        }
                    }
                }
            }
            return(k);
        }
コード例 #31
0
ファイル: PBracedFrame.cs プロジェクト: Xiang-Zeng/P58_Loss
        private static int DFS(IList<ElementId> columnIds, IList<ElementId> beamIds, out int num_IndividualColumn)
        {
            num_IndividualColumn = 0;
            List<Element> columns = (new FilteredElementCollector(_doc, columnIds)).OfClass(typeof(FamilyInstance)).ToList();
            List<Element> beams = (new FilteredElementCollector(_doc, beamIds)).OfClass(typeof(FamilyInstance)).ToList();
            int k = 0;
            LinkedList<Element> open = new LinkedList<Element>();
            HashSet<ElementId> discovered = new HashSet<ElementId>();
            foreach(Element column in columns)
            {
                if (!discovered.Contains(column.Id))
                {
                    ++k;
                    open.AddFirst(column);
                    discovered.Add(column.Id);
                    while (open.Count != 0)
                    {
                        Element e = open.First();
                        open.RemoveFirst();
                        BoundingBoxXYZ bbXYZ = e.get_BoundingBox(_doc.ActiveView);
                        XYZ deltaXYZ = new XYZ(ErrorCTRL_BB, ErrorCTRL_BB, _maxBB.Max.Z);
                        BoundingBoxIntersectsFilter bbFilter = new BoundingBoxIntersectsFilter(new Outline(bbXYZ.Min - deltaXYZ, bbXYZ.Max + deltaXYZ));
                        FilteredElementCollector fec = null;
                        if (((FamilyInstance)e).StructuralUsage == StructuralInstanceUsage.Column)
                        {
                            fec = new FilteredElementCollector(_doc, beamIds);
                            fec.WherePasses(bbFilter);
                            if (fec.Count() == 0)
                            {
                                ++num_IndividualColumn;
                                --k;
                            }
                        }
                        else
                        {
                            fec = new FilteredElementCollector(_doc, columnIds);
                            fec.WherePasses(bbFilter);
                        }

                        foreach (Element intersectedEle in fec)
                        {
                            if (!discovered.Contains(intersectedEle.Id))
                            {
                                open.AddFirst(intersectedEle);
                                discovered.Add(intersectedEle.Id);
                            }
                        }
                    }
                }
            }
            return k;
        }
コード例 #32
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                var doc = commandData.Application.ActiveUIDocument.Document;

                var sheetSets = new FilteredElementCollector(doc).OfClass(typeof(ViewSheetSet));

                var result = "Total of " + sheetSets.Count().ToString() + " sheet sets in this project.\n\n";

                var stopWatch = new Stopwatch();
                stopWatch.Start();

                foreach (var elem in sheetSets)
                {
                    var set = elem as ViewSheetSet;

                    result += set.Name;

                    // getting the Views property takes around 1.5 seconds on the given sample.rvt file.
                    var views = set.Views;

                    result += " has " + views.Size.ToString() + " views.\n";
                }

                result += "\nOperation completed in " + Math.Round(stopWatch.ElapsedMilliseconds / 1000.0, 3) + " seconds.\n"
                          + "Average of " + stopWatch.ElapsedMilliseconds / sheetSets.Count() + " ms per loop iteration.";

                stopWatch.Stop();

                MessageBox.Show(result);
                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(Result.Failed);
            }
        }
コード例 #33
0
        /// <summary>
        /// Purge all graphic styles whose name contains 
        /// the given substring. Watch out what you do!
        /// If your substring is empty, this might delete 
        /// all graphic styles in the entire project!
        /// </summary>
        void PurgeGraphicStyles( 
            Document doc,
            string name_substring)
        {
            FilteredElementCollector graphic_styles
            = new FilteredElementCollector( doc )
              .OfClass( typeof( GraphicsStyle ) );

              int n1 = graphic_styles.Count<Element>();

              IEnumerable<Element> red_line_styles
            = graphic_styles.Where<Element>( e
              => e.Name.Contains( name_substring ) );

              int n2 = red_line_styles.Count<Element>();

              if( 0 < n2 )
              {
            using( Transaction tx = new Transaction( doc ) )
            {
              tx.Start( "Delete Line Styles" );

              doc.Delete( red_line_styles
            .Select<Element, ElementId>( e => e.Id )
            .ToArray<ElementId>() );

              tx.Commit();

              TaskDialog.Show( "Purge line styles",
            string.Format(
              "Deleted {0} graphic style{1} named '*{2}*' "
              + "from {3} total graohic styles.",
              n2, ( 1 == n2 ? "" : "s" ),
              name_substring, n1 ) );
            }
              }
        }
コード例 #34
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string messages,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              Document doc = app.ActiveUIDocument.Document;

              Transaction tx = new Transaction( doc, "Test" );
              tx.Start();

              // use the view filter

              FilteredElementCollector collector
            = new FilteredElementCollector(
              doc, doc.ActiveView.Id );

              // use the parameter filter.
              // get the phase id "New construction"

              ElementId idPhase = GetPhaseId(
            "New Construction", doc );

              ParameterValueProvider provider
            = new ParameterValueProvider(
              new ElementId( (int)
            BuiltInParameter.PHASE_CREATED ) );

              FilterNumericRuleEvaluator evaluator
            = new FilterNumericEquals();

              FilterElementIdRule rule
            = new FilterElementIdRule(
              provider, evaluator, idPhase );

              ElementParameterFilter parafilter
            = new ElementParameterFilter( rule );

              collector.WherePasses( parafilter );

              TaskDialog.Show( "Element Count",
            "There are " + collector.Count().ToString()
            + " elements in the current view created"
            + " with phase New Construction" );

              tx.Commit();

              return Result.Succeeded;
        }
    public static Result ExportBatch(
      FilteredElementCollector doors,
      Guid paramGuid,
      string project_id,
      uint timestamp,
      ref string message )
    {
      // Loop through the selected doors and export 
      // their shared parameter value in one single 
      // batch call.

      int n = doors.Count<Element>();

      List<FireRating.DoorData> doorData 
        = new List<FireRating.DoorData>( n );
      
      HttpStatusCode sc;
      string jsonResponse, errorMessage;
      Result rc = Result.Succeeded;

      foreach( Element e in doors )
      {
        //Util.Log( e.Id.IntegerValue.ToString() );

        doorData.Add( new DoorData( e,
          project_id, paramGuid, timestamp ) );

        //Util.Log( jsonResponse );
      }

      string query = "doors/project/" + project_id;

      string content = Util.Delete( query );

      sc = Util.PostBatch( out jsonResponse,
        out errorMessage, "doors", doorData );

      if( 0 == (int) sc )
      {
        message = errorMessage;
        rc = Result.Failed;
      }
      return rc;
    }
    public static Result ExportMain(
      bool useBatch,
      ExternalCommandData commandData,
      ref string message )
    {
      UIApplication uiapp = commandData.Application;
      Application app = uiapp.Application;
      Document doc = uiapp.ActiveUIDocument.Document;

      // Get shared parameter GUID.

      Guid paramGuid;
      if( !Util.GetSharedParamGuid( app, out paramGuid ) )
      {
        message = "Shared parameter GUID not found.";
        return Result.Failed;
      }

      // Determine custom project identifier.

      string project_id = Util.GetProjectIdentifier( doc );

      // Determine timestamp.

      uint timestamp = Util.UnixTimestamp();

      // Loop through all elements of the given target
      // category and export the shared parameter value 
      // specified by paramGuid for each.

      //FilteredElementCollector collector
      //  = Util.GetTargetInstances( doc,
      //    Cmd_1_CreateAndBindSharedParameter.Target );

      FilteredElementCollector collector
        = new FilteredElementCollector( doc )
          .OfClass( typeof( FamilyInstance ) )
          .OfCategory( BuiltInCategory.OST_Doors );

      int n = collector.Count<Element>();

      Util.Log( string.Format( 
        "Exporting {0} element{1} {2}.", 
        n, Util.PluralSuffix( n ),
        (useBatch ? "in batch" : "one by one" ) ) );

      Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();

      Result rc = useBatch
        ? ExportBatch( collector, paramGuid, 
          project_id, timestamp, ref message )
        : ExportOneByOne( collector, paramGuid, 
          project_id, timestamp, ref message );

      stopwatch.Stop();

      Util.Log( string.Format(
        "{0} milliseconds to export {1} element{2}: {3}.",
        stopwatch.ElapsedMilliseconds, 
        n, Util.PluralSuffix( n ), rc ) );

      return rc;
    }
コード例 #37
0
ファイル: RevitWindow.xaml.cs プロジェクト: GeorgDangl/BCFier
        //<summary>
        //Generate a VisualizationInfo of the current view
        //</summary>
        //<returns></returns>
        private VisualizationInfo GenerateViewpoint()
        {
            try
              {
            var uidoc = uiapp.ActiveUIDocument;
            var doc = uidoc.Document;

            var v = new VisualizationInfo();

            //Corners of the active UI view
            var topLeft = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
            var bottomRight = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

            //It's a 2D view
            //not supported by BCF, but I store it under a custom
            //fields using 2D coordinates and sheet id
            if (uidoc.ActiveView.ViewType != ViewType.ThreeD)
            {
              v.SheetCamera = new SheetCamera
              {
            SheetID = uidoc.ActiveView.Id.IntegerValue,
            TopLeft = new Point { X = topLeft.X, Y = topLeft.Y, Z = topLeft.Z },
            BottomRight = new Point { X = bottomRight.X, Y = bottomRight.Y, Z = bottomRight.Z }
              };
            }
            //It's a 3d view
            else
            {
              var viewCenter = new XYZ();
              var view3D = (View3D)uidoc.ActiveView;
              double zoomValue = 1;
              // it is a orthogonal view
              if (!view3D.IsPerspective)
              {
            double x = (topLeft.X + bottomRight.X) / 2;
            double y = (topLeft.Y + bottomRight.Y) / 2;
            double z = (topLeft.Z + bottomRight.Z) / 2;
            //center of the UI view
            viewCenter = new XYZ(x, y, z);

            //vector going from BR to TL
            XYZ diagVector = topLeft.Subtract(bottomRight);
            //lenght of the vector
            double dist = topLeft.DistanceTo(bottomRight) / 2;

            //ViewToWorldScale value
            zoomValue = dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)).ToMeters();

            // **** CUSTOM VALUE FOR TEKLA **** //
            // calculated sperimentally, not sure why but it works
            //if (UserSettings.Get("optTekla") == "1")
            //  zoomValue = zoomValue * 2.5;
            // **** CUSTOM VALUE FOR TEKLA **** //

            ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
            uidoc.ActiveView.UpDirection, false);

            XYZ c = t.EyePosition;
            XYZ vi = t.ForwardDirection;
            XYZ up = t.UpDirection;

            v.OrthogonalCamera = new OrthogonalCamera
            {
              CameraViewPoint =
              {
                X = c.X.ToMeters(),
                Y = c.Y.ToMeters(),
                Z = c.Z.ToMeters()
              },
              CameraUpVector =
              {
                X = up.X.ToMeters(),
                Y = up.Y.ToMeters(),
                Z = up.Z.ToMeters()
              },
              CameraDirection =
              {
                X = vi.X.ToMeters() * -1,
                Y = vi.Y.ToMeters() * -1,
                Z = vi.Z.ToMeters() * -1
              },
              ViewToWorldScale = zoomValue
            };
              }
              // it is a perspective view
              else
              {
            viewCenter = uidoc.ActiveView.Origin;
            //revit default value
            zoomValue = 45;

            ViewOrientation3D t = RevitUtils.ConvertBasePoint(doc, viewCenter, uidoc.ActiveView.ViewDirection,
             uidoc.ActiveView.UpDirection, false);

            XYZ c = t.EyePosition;
            XYZ vi = t.ForwardDirection;
            XYZ up = t.UpDirection;

            v.PerspectiveCamera = new PerspectiveCamera
            {
              CameraViewPoint =
              {
                X = c.X.ToMeters(),
                Y = c.Y.ToMeters(),
                Z = c.Z.ToMeters()
              },
              CameraUpVector =
              {
                X = up.X.ToMeters(),
                Y = up.Y.ToMeters(),
                Z = up.Z.ToMeters()
              },
              CameraDirection =
              {
                X = vi.X.ToMeters() * -1,
                Y = vi.Y.ToMeters() * -1,
                Z = vi.Z.ToMeters() * -1
              },
              FieldOfView = zoomValue
            };
              }

            }
            //COMPONENTS PART
            string versionName = doc.Application.VersionName;
            v.Components = new List<Component>();

            var visibleElems = new FilteredElementCollector(doc, doc.ActiveView.Id)
              .WhereElementIsNotElementType()
              .WhereElementIsViewIndependent()
            .ToElementIds();
            var hiddenElems = new FilteredElementCollector(doc)
              .WhereElementIsNotElementType()
              .WhereElementIsViewIndependent()
              .Where(x => x.IsHidden(doc.ActiveView)
            || !doc.ActiveView.IsElementVisibleInTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate, x.Id)).ToList();//would need to check how much this is affecting performance

            var selectedElems = uidoc.Selection.GetElementIds();

            //include only hidden elements and selected in the BCF
            if (visibleElems.Count() > hiddenElems.Count())
            {
            foreach (var elem in hiddenElems)
            {
              v.Components.Add(new Component
            {
              OriginatingSystem = versionName,
              IfcGuid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem.Id)),
              Visible = false,
              Selected = false,
              AuthoringToolId = elem.Id.IntegerValue.ToString()
            });
            }
            foreach (var elem in selectedElems)
            {
              v.Components.Add(new Component
              {
            OriginatingSystem = versionName,
            IfcGuid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
            Visible = true,
            Selected = true,
            AuthoringToolId = elem.IntegerValue.ToString()
              });
            }
            }
            //include only visigle elements
            //all the others are hidden
            else
            {
              foreach (var elem in visibleElems)
              {
            v.Components.Add(new Component
            {
              OriginatingSystem = versionName,
              IfcGuid = IfcGuid.ToIfcGuid(ExportUtils.GetExportId(doc, elem)),
              Visible = true,
              Selected = selectedElems.Contains(elem),
              AuthoringToolId = elem.IntegerValue.ToString()
            });
              }
            }
            return v;

              }
              catch (System.Exception ex1)
              {
            TaskDialog.Show("Error generating viewpoint", "exception: " + ex1);
              }
              return null;
        }
コード例 #38
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
              Application app = uiapp.Application;
              Document doc = uiapp.ActiveUIDocument.Document;
              Categories categories = doc.Settings.Categories;

              int nCategories = categories.Size;

              Debug.Print(
            "{0} categories and their parents obtained "
            + "from the Categories collection:",
            nCategories );

              foreach( Category c in categories )
              {
            Category p = c.Parent;

            Debug.Print( "  {0} ({1}), parent {2}",
              c.Name, c.Id.IntegerValue,
              ( null == p ? "<none>" : p.Name ) );
              }

              Array bics = Enum.GetValues(
            typeof( BuiltInCategory ) );

              int nBics = bics.Length;

              Debug.Print( "{0} built-in categories and the "
            + "corresponding document ones:", nBics );

              Category cat;
              string s;

              List<BuiltInCategory> bics_null
            = new List<BuiltInCategory>();

              List<BuiltInCategory> bics_exception
            = new List<BuiltInCategory>();

              foreach( BuiltInCategory bic in bics )
              {
            try
            {
              cat = categories.get_Item( bic );

              if( null == cat )
              {
            bics_null.Add( bic );
            s = "<null>";
              }
              else
              {
            s = string.Format( "{0} ({1})",
              cat.Name, cat.Id.IntegerValue );
              }
            }
            catch( Exception ex )
            {
              bics_exception.Add( bic );

              s = ex.GetType().Name + " " + ex.Message;
            }
            Debug.Print( "  {0} --> {1}",
              bic.ToString(), s );
              }

              int nBicsNull = bics_null.Count;
              int nBicsException = bics_exception.Count;

            #if ACCESS_HIDDEN_CATEGORIES_THROUGH_FILTERED_ELEMENT_COLLECTOR
              // Trying to use OfClass( typeof( Category ) )
              // throws an ArgumentException exception saying
              // "Input type Category is not a recognized
              // Revit API type".

              IEnumerable<Category> cats
            = new FilteredElementCollector( doc )
              .WhereElementIsNotElementType()
              .WhereElementIsViewIndependent()
              .Cast<Category>();

              // Unable to cast object of type
              // 'Autodesk.Revit.DB.Element' to type
              // 'Autodesk.Revit.DB.Category':

              int nCategoriesFiltered = cats.Count<Category>();

              Debug.Print(
            "{0} categories obtained from a filtered "
            + "element collector:",
            nCategoriesFiltered );

              foreach( Category c in cats )
              {
            Debug.Print( "  {0}", c.Name );
              }
            #endif // ACCESS_HIDDEN_CATEGORIES_THROUGH_FILTERED_ELEMENT_COLLECTOR

              TaskDialog dlg = new TaskDialog(
            "Hidden Built-in Categories" );

              s = string.Format(
            "{0} categories obtained from the Categories collection;\r\n"
            + "{1} built-in categories;\r\n"
            + "{2} built-in categories retrieve null result;\r\n"
            + "{3} built-in categories throw an exception:\r\n",
            nCategories, nBics, nBicsNull, nBicsException );

              Debug.Print( s );

              dlg.MainInstruction = s;

              s = bics_exception
            .Aggregate<BuiltInCategory, string>(
              string.Empty,
              ( a, bic ) => a + "\n" + bic.ToString() );

              Debug.Print( s );

              dlg.MainContent = s;

              dlg.Show();

              return Result.Succeeded;
        }
コード例 #39
0
ファイル: PBracedFrame.cs プロジェクト: Xiang-Zeng/P58_Loss
        private static bool TryGetFGCode(out string FGCode)
        {
            FGCode = "";
            int ds_type = _addiInfo.defaultSet[(byte)DefaultSet.BracedFrame_FrameType];
            int ds_crossSection = _addiInfo.defaultSet[(byte)DefaultSet.BracedFrame_CrossSection];
            if((ds_type == 0 && 5 <= ds_crossSection) || (ds_type == 1 && ds_crossSection <= 4))
            {
                _abandonWriter.WriteAbandonment(null, AbandonmentTable.BracedFrame_TypeCrossConflict);
                return false;
            }
            else
            {
                int ds_brace = 0;
                int ds_plf = 0;
                if (_Braces.Count != 0)
                {
                    int numOverlap = 0;
                    int numColumn = 0;
                    FamilyInstance brace = (FamilyInstance)_Braces.First();
                    Curve curve = (brace.Location as LocationCurve).Curve;
                    XYZ p0 = curve.GetEndPoint(0);
                    XYZ p1 = curve.GetEndPoint(1);
                    XYZ deltaXYZ = new XYZ(ErrorCTRL_Overlap, ErrorCTRL_Overlap, ErrorCTRL_Overlap);
                    BoundingBoxIntersectsFilter bbFilter = new BoundingBoxIntersectsFilter(
                        new Outline(brace.get_BoundingBox(_doc.ActiveView).Min - deltaXYZ, brace.get_BoundingBox(_doc.ActiveView).Max + deltaXYZ));
                    FilteredElementCollector fec = new FilteredElementCollector(_doc);
                    fec.WherePasses(bbFilter).WherePasses(new ElementStructuralTypeFilter(StructuralType.Brace));
                    foreach (Element brace2 in fec)
                    {
                        if (brace2.Id != brace.Id)
                        {
                            Curve curve2 = (brace2.Location as LocationCurve).Curve;
                            XYZ p2_0 = curve2.GetEndPoint(0);
                            XYZ p2_1 = curve2.GetEndPoint(1);
                            if (IsTheSamePoint(p2_0, p0) || IsTheSamePoint(p2_0, p1)) ++numOverlap;
                            if (IsTheSamePoint(p2_1, p0) || IsTheSamePoint(p2_1, p1)) ++numOverlap;
                            break;
                        }
                    }
                    fec = new FilteredElementCollector(_doc);
                    fec.WherePasses(bbFilter).WherePasses(new ElementStructuralTypeFilter(StructuralType.Column));
                    numColumn = fec.Count();
                    if (numOverlap == 1 && numColumn == 1) ds_brace = 1;    //Chevron
                    else if (numOverlap == 2) ds_brace = 3;                 //X
                    else ds_brace = 2;                                      //single

                    try
                    {
                        IList<Parameter> paras = brace.Symbol.GetParameters("A");
                        double area = paras.First().AsDouble();
                        if (area == 0.0) throw new Exception();
                        else
                        {
                            double plf = area * density_steel;
                            if (plf <= 40.0) ds_plf = 0;
                            else if (100.0 <= plf) ds_plf = 2;
                            else ds_plf = 1;
                        }
                    }
                    catch
                    {
                        ds_plf = _addiInfo.defaultSet[(byte)DefaultSet.BracedFrame_PLF];
                    }

                }
                else
                {
                    ds_brace = _addiInfo.defaultSet[(byte)DefaultSet.BracedFrame_Brace];
                    ds_plf = _addiInfo.defaultSet[(byte)DefaultSet.BracedFrame_PLF];
                }
                if (ds_crossSection != 8)
                {
                    FGCode = "B1033.0";
                    FGCode += ds_crossSection.ToString() + ds_brace.ToString() + ConstSet.Alphabet[ds_plf];
                }
                else
                {
                    FGCode = "B1033.1";
                    if (ds_brace == 3)
                    {
                        _abandonWriter.WriteAbandonment(null, AbandonmentTable.BracedFrame_BRBwXBrace);
                        return false;
                    }
                    else
                    {
                        FGCode += (ds_brace - 1).ToString() + "1" + ConstSet.Alphabet[ds_plf];
                    }
                }
                return true;
            }
        }
コード例 #40
0
ファイル: ProximityDetection.cs プロジェクト: AMEE/revit
        /// <summary>
        /// Find columns in wall
        /// </summary>
        /// <param name="walls">The walls to be detected</param>
        /// <returns>The detection result</returns>
        public XElement findColumnsInWall(IEnumerable<Wall> walls)
        {
            // create a node that place all walls.
             XElement wallsNode = new XElement("Walls", new XAttribute("Name", "Walls"));

             try
             {
            foreach (Wall wall in walls)
            {
               XElement wallNode = new XElement("Wall", new XAttribute("Name", wall.Name));

               // Iterate to find columns and structural columns
               FilteredElementCollector collector = new FilteredElementCollector(m_doc);
               List<BuiltInCategory> columnCategories = new List<BuiltInCategory>();
               columnCategories.Add(BuiltInCategory.OST_Columns);
               columnCategories.Add(BuiltInCategory.OST_StructuralColumns);
               collector.WherePasses(new ElementMulticategoryFilter(columnCategories));

               // Apply element intersection filter
               ElementIntersectsElementFilter testElementIntersectsElementFilter =
                  new ElementIntersectsElementFilter(wall);

               collector.WherePasses(testElementIntersectsElementFilter);

               XElement columnsNode = new XElement("columns",
                  new XAttribute("Count", collector.Count().ToString()));

               foreach (Element column in collector)
               {
                  columnsNode.Add(new XElement("column", new XAttribute("Name", column.Name)));
               }

               wallNode.Add(columnsNode);
               wallsNode.Add(wallNode);
            }
             }
             catch (Exception ex)
             {
            wallsNode.Add(new XElement("Error", new XAttribute("Exception", ex.ToString())));
             }

             // return the whole walls Node
             return wallsNode;
        }
コード例 #41
0
ファイル: PBracedFrame.cs プロジェクト: Xiang-Zeng/P58_Loss
 private static void Process()
 {
     if (_StruColumns.Count() * _StruBeams.Count() == 0) return;
     string FGCode;
     if (!TryGetFGCode(out FGCode)) return;
     int floorNum = MyLevel.GetLevelNum() - 1;
     int[] num = new int[floorNum];
     int totalNum = 0;
     for (int i = 0; i < floorNum; ++i)
     {
         int n, m, k;
         double lowerLevel = _myLevel.GetElevation(i);
         double upperLevel = _myLevel.GetElevation(i + 1);
         double deltaHi = upperLevel - lowerLevel;
         double columnLL = lowerLevel + deltaHi * 0.3;
         double columnUL = upperLevel - deltaHi * 0.3;
         XYZ columnBottom = new XYZ(_maxBB.Min.X, _maxBB.Min.Y, columnLL);
         XYZ columnTop = new XYZ(_maxBB.Max.X, _maxBB.Max.Y, columnUL);
         BoundingBoxIntersectsFilter columnBBFilter = new BoundingBoxIntersectsFilter(new Outline(columnBottom, columnTop));
         FilteredElementCollector columnFec = new FilteredElementCollector(_doc, _StruColumns);
         columnFec.WherePasses(columnBBFilter);
         double beamLL = lowerLevel + deltaHi * 0.7;
         double beamUL = upperLevel + deltaHi * 0.3;
         XYZ beamBottom = new XYZ(_maxBB.Min.X, _maxBB.Min.Y, beamLL);
         XYZ beamTop = new XYZ(_maxBB.Max.X, _maxBB.Max.Y, beamUL);
         BoundingBoxIntersectsFilter beamBBFilter = new BoundingBoxIntersectsFilter(new Outline(beamBottom, beamTop));
         FilteredElementCollector beamFec = new FilteredElementCollector(_doc, _StruBeams);
         beamFec.WherePasses(beamBBFilter);
         if (columnFec.Count() * beamFec.Count() == 0) continue;
         GetNMK(columnFec.ToElementIds().ToList(), beamFec.ToElementIds().ToList(), out n, out m, out k);
         num[i] = m - n + k;
         totalNum += num[i];
     }
     if (totalNum != 0)
     {
         PGItem pgItem = new PGItem();
         pgItem.Code = FGCode;
         pgItem.direction = Direction.Undefined;
         pgItem.PGName = "支撑刚架";
         pgItem.PinYinSuffix = "ZhiChengGangJia";
         pgItem.Price = _addiInfo.prices[(byte)PGComponents.BracedFrame];
         if (pgItem.Price == 0.0) pgItem.IfDefinePrice = false;
         else pgItem.IfDefinePrice = true;
         for (int i = 0; i < floorNum; ++i)
         {
             pgItem.Num[i] = num[i];
         }
         _PGItems.Add(pgItem);
     }
 }
コード例 #42
0
ファイル: CreateExtension.cs プロジェクト: samuto/Grevit
        public static Element Create(this Grevit.Types.Filter filter)
        {
            List<ElementId> categories = new List<ElementId>();

            Dictionary<string,ElementId> parameters = new Dictionary<string,ElementId>();

            foreach (Category category in GrevitBuildModel.document.Settings.Categories)
            {
                if (filter.categories.Contains(category.Name) || filter.categories.Count == 0) categories.Add(category.Id);

                FilteredElementCollector collector = new FilteredElementCollector(GrevitBuildModel.document).OfCategoryId(category.Id);
                if (collector.Count() > 0)
                {
                    foreach (Autodesk.Revit.DB.Parameter parameter in collector.FirstElement().Parameters)
                        if (!parameters.ContainsKey(parameter.Definition.Name)) parameters.Add(parameter.Definition.Name, parameter.Id);
                }
            }




            ParameterFilterElement parameterFilter = null;

            FilteredElementCollector collect = new FilteredElementCollector(GrevitBuildModel.document).OfClass(typeof(ParameterFilterElement));
            foreach (ParameterFilterElement existingFilter in collect.ToElements())
            {
                if (existingFilter.Name == filter.name)
                {
                    existingFilter.ClearRules();
                    parameterFilter = existingFilter;
                }
            }

            if (parameterFilter == null) parameterFilter = ParameterFilterElement.Create(GrevitBuildModel.document, filter.name, categories);


            View view = (View)Utilities.GetElementByName(GrevitBuildModel.document, typeof(View), filter.view);
            view.AddFilter(parameterFilter.Id);
           

            #region Apply Rules

            List<FilterRule> filterRules = new List<FilterRule>();

            foreach (Grevit.Types.Rule rule in filter.Rules)
            {
                if (parameters.ContainsKey(rule.name))
                {
                    FilterRule filterRule = rule.ToRevitRule(parameters[rule.name]);
                    if (filterRule != null) filterRules.Add(filterRule);
                }
            }

            parameterFilter.SetRules(filterRules);

            #endregion

            #region Apply Overrides

            OverrideGraphicSettings filterSettings = new OverrideGraphicSettings();

            // Apply Colors
            if (filter.CutFillColor != null) filterSettings.SetCutFillColor(filter.CutFillColor.ToRevitColor());
            if (filter.ProjectionFillColor != null) filterSettings.SetProjectionFillColor(filter.ProjectionFillColor.ToRevitColor());
            if (filter.CutLineColor != null) filterSettings.SetCutLineColor(filter.CutLineColor.ToRevitColor());
            if (filter.ProjectionLineColor != null) filterSettings.SetProjectionLineColor(filter.ProjectionLineColor.ToRevitColor());

            // Apply Lineweight
            if (filter.CutLineWeight != -1) filterSettings.SetCutLineWeight(filter.CutLineWeight);
            if (filter.ProjectionLineWeight != -1) filterSettings.SetProjectionLineWeight(filter.ProjectionLineWeight);

            // Apply Patterns          
            if (filter.CutFillPattern != null)
            {
                FillPatternElement pattern = (FillPatternElement)Utilities.GetElementByName(GrevitBuildModel.document, typeof(FillPatternElement), filter.CutFillPattern);
                filterSettings.SetCutFillPatternId(pattern.Id);
            }

            if (filter.ProjectionFillPattern != null)
            {
                FillPatternElement pattern = (FillPatternElement)Utilities.GetElementByName(GrevitBuildModel.document, typeof(FillPatternElement), filter.ProjectionFillPattern);
                filterSettings.SetProjectionFillPatternId(pattern.Id);
            }

            if (filter.CutLinePattern != null)
            {
                LinePatternElement pattern = (LinePatternElement)Utilities.GetElementByName(GrevitBuildModel.document, typeof(LinePatternElement), filter.CutLinePattern);
                filterSettings.SetCutLinePatternId(pattern.Id);
            }

            if (filter.ProjectionLinePattern != null)
            {
                LinePatternElement pattern = (LinePatternElement)Utilities.GetElementByName(GrevitBuildModel.document, typeof(LinePatternElement), filter.ProjectionLinePattern);
                filterSettings.SetProjectionLinePatternId(pattern.Id);
            }

            view.SetFilterOverrides(parameterFilter.Id, filterSettings);

            #endregion

            return parameterFilter;
        }
コード例 #43
0
ファイル: Command.cs プロジェクト: kmorin/STF-Exporter
        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;
            _app = app;
            _doc = doc;

            // Set project units to Meters then back after
            // This is how DIALux reads the data from the STF File.

            Units pUnit = doc.GetUnits();
            FormatOptions formatOptions = pUnit.GetFormatOptions(UnitType.UT_Length);

            //DisplayUnitType curUnitType = pUnit.GetDisplayUnitType();
            DisplayUnitType curUnitType = formatOptions.DisplayUnits;

            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("STF EXPORT");
                const DisplayUnitType meters = DisplayUnitType.DUT_METERS;
                formatOptions.DisplayUnits = meters;
                // Comment out, different in 2014
                //formatOptions.Units = meters;
                //formatOptions.Rounding = 0.0000000001;]

                formatOptions.Accuracy = 0.0000000001;
                // Fix decimal symbol for int'l versions (set back again after finish)
                if (pUnit.DecimalSymbol == DecimalSymbol.Comma)
                {
                    intlVersion = true;
                    //TESTING
                    //TaskDialog.Show("INTL", "You have an internationalized version of Revit!");
                    formatOptions.UseDigitGrouping = false;
                    pUnit.DecimalSymbol = DecimalSymbol.Dot;
                }

                try
                {
                    // Filter for only active view.
                    ElementLevelFilter filter = new ElementLevelFilter(doc.ActiveView.GenLevel.Id);

                    FilteredElementCollector fec = new FilteredElementCollector(doc, doc.ActiveView.Id)
                        .OfCategory(BuiltInCategory.OST_MEPSpaces)
                        .WherePasses(filter);

                    int numOfRooms = fec.Count();
                    writer += "[VERSION]\n"
                              + "STFF=" + stfVersionNum + "\n"
                              + "Progname=Revit\n"
                              + "Progvers=" + app.VersionNumber + "\n"
                              + "[Project]\n"
                              + "Name=" + _doc.ProjectInformation.Name + "\n"
                              + "Date=" + DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" +
                              DateTime.Now.Day.ToString() + "\n"
                              + "Operator=" + app.Username + "\n"
                              + "NrRooms=" + numOfRooms + "\n";

                    for (int i = 1; i < numOfRooms + 1; i++)
                    {
                        string _dialuxRoomName = "Room" + i.ToString() + "=ROOM.R" + i.ToString();
                        writer += _dialuxRoomName + "\n";
                    }

                    int increment = 1;

                    // Space writer
                    try
                    {
                        foreach (Element e in fec)
                        {
                            Space s = e as Space;
                            string roomRNum = "ROOM.R" + increment.ToString();
                            writer += "[" + roomRNum + "]\n";
                            SpaceInfoWriter(s.Id, roomRNum);
                            increment++;
                        }

                        // Write out Luminaires to bottom
                        writeLumenairs();

                        // Reset back to original units
                        formatOptions.DisplayUnits = curUnitType;
                        if (intlVersion)
                            pUnit.DecimalSymbol = DecimalSymbol.Comma;

                        tx.Commit();

                        SaveFileDialog dialog = new SaveFileDialog
                        {
                            FileName = doc.ProjectInformation.Name,
                            Filter = "STF File | *.stf",
                            FilterIndex = 2,
                            RestoreDirectory = true
                        };

                        if (dialog.ShowDialog() == DialogResult.OK)
                        {
                            StreamWriter sw = new StreamWriter(dialog.FileName);
                            string[] ar = writer.Split('\n');
                            for (int i = 0; i < ar.Length; i++)
                            {
                                sw.WriteLine(ar[i]);
                            }
                            sw.Close();
                        }

                        return Result.Succeeded;
                    }
                    catch (IndexOutOfRangeException)
                    {
                        return Result.Failed;
                    }
                }
                catch (NullReferenceException)
                {
                    TaskDialog.Show("Incorrect View", "Cannot find Spaces to export.\nMake sure you are in a Floorplan or Ceiling Plan view and Spaces are visible.");
                    return Result.Failed;
                }
            }
        }
コード例 #44
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              UIDocument uidoc = app.ActiveUIDocument;
              Document doc = uidoc.Document;

              // Get all Group Types of Model Family:

              FilteredElementCollector modelGroupTypes
            = new FilteredElementCollector( doc );

              modelGroupTypes.OfClass( typeof( GroupType ) );
              modelGroupTypes.OfCategory( BuiltInCategory.OST_IOSModelGroups );

              if( 0 == modelGroupTypes.Count() )
              {
            message = "No model group types found in model.";
            return Result.Failed;
              }

              FilteredElementCollector groups;
              groups = new FilteredElementCollector( doc );
              groups.OfClass( typeof( Group ) );

              foreach( Group g in groups )
              {
            // Offer simple message box to swap the type
            // (one-by-one, stop if user confirms the change)

            foreach( GroupType gt in modelGroupTypes )
            {
              string msg = "Swap OLD Type=" + g.GroupType.Name
            + " with NEW Type=" + gt.Name
            + " for Group Id=" + g.Id.IntegerValue.ToString() + "?";

              TaskDialogResult r = LabUtils.QuestionCancelMsg( msg );

              switch( r )
              {
            case TaskDialogResult.Yes:
              using( Transaction tx = new Transaction( doc ) )
              {
                tx.Start( "Swap Group Type" );
                g.GroupType = gt;
                tx.Commit();
              }
              LabUtils.InfoMsg( "Group type successfully swapped." );
              return Result.Succeeded;

            case TaskDialogResult.Cancel:
              LabUtils.InfoMsg( "Command cancelled." );
              return Result.Cancelled;

            // else continue...
              }
            }
              }

              /*
              //
              // cannot modify group members after creation:
              //
              Element e = null;
              ElementArray els = new ElementArray();
              els.Append( e );
              Group g = new Group();
              g.Members = els; // Property or indexer 'Autodesk.Revit.Elements.Group.Members' cannot be assigned to -- it is read only
              Element e2 = null;
              els.Append( e2 );
              g.Members = els;
              */

              return Result.Succeeded;
        }
コード例 #45
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication app = commandData.Application;
              Document doc = app.ActiveUIDocument.Document;

              FilteredElementCollector rooms
            = new FilteredElementCollector( doc );

              //
              // this is one way of obtaining rooms ... but see below for a better solution:
              //
              //rooms.OfClass( typeof( Room ) ); // Input type is of an element type that exists in the API, but not in Revit's native object model. Try using Autodesk.Revit.DB.Enclosure instead, and then postprocessing the results to find the elements of interest.
              //rooms.OfClass( typeof( Enclosure ) ); // this works but returns all Enclosure elements

              RoomFilter filter = new RoomFilter();
              rooms.WherePasses( filter );

              if( 0 == rooms.Count() )
              {
            LabUtils.InfoMsg( "There are no rooms in this model." );
              }
              else
              {
            List<string> a = new List<string>();

            /*
            foreach( Enclosure e in rooms ) // todo: remove this
            {
              Room room = e as Room; // todo: remove this
              if( null != room ) // todo: remove this
              {
            */

            foreach( Room room in rooms )
            {
              string roomName = room.Name;
              string roomNumber = room.Number;

              string s = "Room Id=" + room.Id.IntegerValue.ToString()
            + " Name=" + roomName + " Number=" + roomNumber + "\n";

              // Loop all boundaries of this room

              //BoundarySegmentArrayArray boundaries = room.Boundary; // 2011

              IList<IList<BoundarySegment>> boundaries // 2012
            = room.GetBoundarySegments( // 2012
              new SpatialElementBoundaryOptions() ); // 2012; passing in a null value throws an exception

              // Check to ensure room has boundary

              if( null != boundaries )
              {
            int iB = 0;
            //foreach( BoundarySegmentArray boundary in boundaries ) // 2011
            foreach( IList<BoundarySegment> boundary in boundaries ) // 2012
            {
              ++iB;
              s += "  Boundary " + iB + ":\n";
              int iSeg = 0;
              foreach( BoundarySegment segment in boundary )
              {
                ++iSeg;

                // Segment's curve
                Curve crv = segment.GetCurve();

                if( crv is Line )
                {
                  Line line = crv as Line;
                  XYZ ptS = line.GetEndPoint( 0 );
                  XYZ ptE = line.GetEndPoint( 1 );
                  s += "    Segment " + iSeg + " is a LINE: "
                    + LabUtils.PointString( ptS ) + " ; "
                    + LabUtils.PointString( ptE ) + "\n";
                }
                else if( crv is Arc )
                {
                  Arc arc = crv as Arc;
                  XYZ ptS = arc.GetEndPoint( 0 );
                  XYZ ptE = arc.GetEndPoint( 1 );
                  double r = arc.Radius;
                  s += "    Segment " + iSeg + " is an ARC:"
                    + LabUtils.PointString( ptS ) + " ; "
                    + LabUtils.PointString( ptE ) + " ; R="
                    + LabUtils.RealString( r ) + "\n";
                }
              }
            }
            a.Add( s );
              }
              LabUtils.InfoMsg( "{0} room{1} in the model{2}", a );
            }
              }
              return Result.Failed;
        }
コード例 #46
0
        /// <summary>
        /// Retrieve all family instances intersecting a
        /// given BIM element, e.g. all columns 
        /// intersecting a wall.
        /// </summary>
        void GetInstancesIntersectingElement( Element e )
        {
            #region Joe's code
            #if JOE_CODE
            // Find intersections between family instances and a selected element

            Reference Reference = uidoc.Selection.PickObject(
            ObjectType.Element, "Select element that will "
            + "be checked for intersection with all family "
            + "instances" );

            Element e = doc.GetElement( reference );

            GeometryElement geomElement = e.get_Geometry(
            new Options() );

            Solid solid = null;
            foreach( GeometryObject geomObj in geomElement )
            {
            solid = geomObj as Solid;
            if( solid = !null ) break;
            }

            FilteredElementCollector collector
            = new FilteredElementCollector( doc )
              .OfClass( typeof( FamilyInstance ) )
              .WherePasses( new ElementIntersectsSolidFilter(
            solid ) );

            TaskDialog.Show( "Revit", collector.Count() +
            "Family instances intersect with selected element ("
            + element.Category.Name + "ID:" + element.Id + ")" );
            #endif // JOE_CODE
              #endregion // Joe's code

              // Test this in these SDK sample models:
              // C:\a\lib\revit\2015\SDK\Samples\FindReferencesByDirection\FindColumns\FindColumns-Basic.rvt
              // C:\a\lib\revit\2015\SDK\Samples\FindReferencesByDirection\FindColumns\FindColumns-TestCases.rvt

              Document doc = e.Document;

              Solid solid = e.get_Geometry( new Options() )
            .OfType<Solid>()
            .Where<Solid>( s => null != s && !s.Edges.IsEmpty )
            .FirstOrDefault();

              FilteredElementCollector intersectingInstances
            = new FilteredElementCollector( doc )
              .OfClass( typeof( FamilyInstance ) )
              .WherePasses( new ElementIntersectsSolidFilter(
            solid ) );

              int n1 = intersectingInstances.Count<Element>();

              intersectingInstances
            = new FilteredElementCollector( doc )
              .OfClass( typeof( FamilyInstance ) )
              .WherePasses( new ElementIntersectsElementFilter(
            e ) );

              int n = intersectingInstances.Count<Element>();

              Debug.Assert( n.Equals( n1 ),
            "expected solid intersection to equal element intersection" );

              string result = string.Format(
            "{0} family instance{1} intersect{2} the "
            + "selected element {3}{4}",
            n, Util.PluralSuffix( n ),
            ( 1 == n ? "s" : "" ),
            Util.ElementDescription( e ),
            Util.DotOrColon( n ) );

              string id_list = 0 == n
            ? string.Empty
            : string.Join( ", ",
            intersectingInstances
              .Select<Element, string>(
                x => x.Id.IntegerValue.ToString() ) )
              + ".";

              Util.InfoMsg2( result, id_list );
        }
        /// <summary>
        /// Retrieve all beam family instances 
        /// intersecting two columns, cf.
        /// http://forums.autodesk.com/t5/revit-api/check-to-see-if-beam-exists/m-p/6223562
        /// </summary>
        FilteredElementCollector GetBeamsIntersectingTwoColumns(
            Element column1,
            Element column2)
        {
            Document doc = column1.Document;

              if( column2.Document.GetHashCode() != doc.GetHashCode() )
              {
            throw new ArgumentException(
              "Expected two columns from same document." );
              }

              FilteredElementCollector intersectingStructuralFramingElements
            = new FilteredElementCollector( doc )
              .OfClass( typeof( FamilyInstance ) )
              .OfCategory( BuiltInCategory.OST_StructuralFraming )
              .WherePasses( new ElementIntersectsElementFilter( column1 ) )
              .WherePasses( new ElementIntersectsElementFilter( column2 ) );

              int n = intersectingStructuralFramingElements.Count<Element>();

              string result = string.Format(
            "{0} structural framing family instance{1} "
            + "intersect{2} the two beams{3}",
            n, Util.PluralSuffix( n ),
            ( 1 == n ? "s" : "" ),
            Util.DotOrColon( n ) );

              string id_list = 0 == n
            ? string.Empty
            : string.Join( ", ",
            intersectingStructuralFramingElements
              .Select<Element, string>(
                x => x.Id.IntegerValue.ToString() ) )
              + ".";

              Util.InfoMsg2( result, id_list );

              return intersectingStructuralFramingElements;
        }
コード例 #48
0
    /// <summary>
    /// List the family types 
    /// </summary>
    public void ListFamilyTypes()
    {
      // (1) Get a list of family types available in the current rvt project. 
      // 
      // For system family types, there is a designated 
      // properties that allows us to directly access to the types. 
      // e.g., _doc.WallTypes 

      //WallTypeSet wallTypes = _doc.WallTypes; // 2013


      FilteredElementCollector wallTypes
        = new FilteredElementCollector(_doc) // 2014
          .OfClass(typeof(WallType));
      int n = wallTypes.Count();

      string s = string.Empty;
      //int n = 0;

      foreach (WallType wType in wallTypes)
      {
        s += "\r\n" + wType.Kind.ToString() + " : " + wType.Name;
        //++n;
      }
      TaskDialog.Show(n.ToString()
        + " Wall Types:",
        s);

      // (1.1) Same idea applies to other system family, such as Floors, Roofs. 

      //FloorTypeSet floorTypes = _doc.FloorTypes;

      FilteredElementCollector floorTypes
      = new FilteredElementCollector(_doc) // 2014
        .OfClass(typeof(FloorType));

      s = string.Empty;

      foreach (FloorType fType in floorTypes)
      {
        // Family name is not in the property for 
        // floor, so use BuiltInParameter here. 

        Parameter param = fType.get_Parameter(
          BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM);

        if (param != null)
        {
          s += param.AsString();
        }
        s += " : " + fType.Name + "\r\n";
      }
      TaskDialog.Show(
        floorTypes.Count().ToString() + " floor types (by rvtDoc.FloorTypes): ",
        s);

      // (1.2a) Another approach is to use a filter. here is an example with wall type. 

      var wallTypeCollector1 = new FilteredElementCollector(_doc);
      wallTypeCollector1.WherePasses(new ElementClassFilter(typeof(WallType)));
      IList<Element> wallTypes1 = wallTypeCollector1.ToElements();

      // Using a helper function to display the result here. See code below. 

      ShowElementList(wallTypes1, "Wall Types (by Filter): ");

      // (1.2b) The following are the same as two lines above. 
      // These alternative forms are provided for convenience. 
      // Using OfClass() 
      // 
      //FilteredElementCollector wallTypeCollector2 = new FilteredElementCollector(_doc);
      //wallTypeCollector2.OfClass(typeof(WallType)); 

      // (1.2c) The following are the same as above for convenience. 
      // Using short cut this time. 
      // 
      //FilteredElementCollector wallTypeCollector3 = new FilteredElementCollector(_doc).OfClass(typeof(WallType)); 

      // 
      // (2) Listing for component family types. 
      // 
      // For component family, it is slightly different. 
      // There is no designate property in the document class. 
      // You always need to use a filtering. e.g., for doors and windows. 
      // Remember for component family, you will need to check element type and category. 

      var doorTypeCollector = new FilteredElementCollector(_doc);
      doorTypeCollector.OfClass(typeof(FamilySymbol));
      doorTypeCollector.OfCategory(BuiltInCategory.OST_Doors);
      IList<Element> doorTypes = doorTypeCollector.ToElements();

      ShowElementList(doorTypes, "Door Types (by Filter): ");
    }
コード例 #49
0
ファイル: PBracedFrame.cs プロジェクト: Xiang-Zeng/P58_Loss
 //floor starts from 0
 private static void GetNMK(IList<ElementId> columnIds, IList<ElementId> beamIds, out int n, out int m, out int k)
 {
     int num_IndividualColumn;
     k = DFS(columnIds, beamIds, out num_IndividualColumn);
     FilteredElementCollector beamFec = new FilteredElementCollector(_doc, beamIds);
     beamFec.OfClass(typeof(FamilyInstance));
     n = columnIds.Count() - num_IndividualColumn;
     m = beamFec.Count();
     foreach (Element beam in beamFec)
     {
         BoundingBoxXYZ beamBB = beam.get_BoundingBox(_doc.ActiveView);
         XYZ deltaXYZ = new XYZ(ErrorCTRL_BB, ErrorCTRL_BB, ErrorCTRL_BB);
         BoundingBoxIntersectsFilter beamBBFilter = new BoundingBoxIntersectsFilter(new Outline(beamBB.Min - deltaXYZ, beamBB.Max + deltaXYZ));
         FilteredElementCollector fec = new FilteredElementCollector(_doc, columnIds);
         int delta = fec.WherePasses(beamBBFilter).Count() - 2;
         if (delta < 0) delta = -1;      //net of cantilever beam or illegal unsupported beam
         m += delta;
     }
 }
コード例 #50
-1
ファイル: Class1.cs プロジェクト: ipeerbhai/RevitLogistics
    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        Tracelog("Addin Start");

        //Get application and document objects
        UIApplication UIApp = commandData.Application;
        UIDocument UIDoc = UIApp.ActiveUIDocument;
        Application app = UIApp.Application;
        Document doc = UIDoc.Document;

        // Get all doors.
        FilteredElementCollector collectorForDoors = new FilteredElementCollector(doc);
        collectorForDoors.OfCategory(BuiltInCategory.OST_Doors).OfClass(typeof(FamilyInstance));

        // Iterate the collector and show the information
        if ( collectorForDoors.Count<Element>() > 0 )
        {
            // I have a valid collection to iterate
            foreach(Element ele in collectorForDoors)
            {
                TaskDialog.Show(ele.Category.Name, ele.Name);
            }
        }
        else
        {
            // No collection found.
            Tracelog("No collection found");
        }

        return (Result.Succeeded);
    }