Example #1
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiApp = commandData.Application;
            UIDocument    uiDoc = uiApp.ActiveUIDocument;
            Document      doc   = uiApp.ActiveUIDocument.Document;
            Application   app   = uiApp.Application;

            Selection selection = uiDoc.Selection;

            Transaction ts = new Transaction(doc, "cut");

            ts.Start();

            IList <Element> _elements = uiDoc.Selection.PickElementsByRectangle(new WallFilter(), "请框选所有需要剪切的墙、板、柱");

            foreach (var element1 in _elements)
            {
                var collector2          = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming).OfClass(typeof(FamilyInstance));
                var pipeIntersectFilter = new ElementIntersectsElementFilter(element1);

                List <FamilyInstance> pipes = collector2.WherePasses(pipeIntersectFilter).ToList().ConvertAll(x => x as FamilyInstance);

                foreach (var pipe in pipes)
                {
                    InstanceVoidCutUtils.AddInstanceVoidCut(doc, element1, pipe);
                }
                //new BoundingBoxIsInsideFilter();
            }

            ts.Commit();
            return(Result.Succeeded);
        }
Example #2
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uiApp = commandData.Application;
            var app   = commandData.Application.Application;
            var uiDoc = commandData.Application.ActiveUIDocument;
            var doc   = commandData.Application.ActiveUIDocument.Document;

            var elementIds = uiDoc.Selection.PickObjects(ObjectType.Element, new VLClassFilter(typeof(Pipe)), "选择要添加的构件").Select(c => c.ElementId);

            if (elementIds.Count() == 0)
            {
                return(Result.Cancelled);
            }

            List <Element> pickedElements = elementIds.Select(c => doc.GetElement(c)).ToList();

            foreach (var pickedElement in pickedElements)
            {
                ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(pickedElement);
                var conflict     = pickedElements.Where(c => filter.PassesFilter(c)).ToList();
                var conflictIds  = conflict.Select(c => c.Id);
                var conflictIds2 = string.Join(",", conflictIds);
            }
            return(Result.Succeeded);
        }
Example #3
0
        //回傳有碰到ele的牆或版
        public IList <Element> GetElementIntersectsElements(Element ele, String elementType)
        {
            Document doc = ele.Document;
            //--去除ele本身過濾器
            List <ElementId> excludedElementID = new List <ElementId>();

            excludedElementID.Add(ele.Id);
            ExclusionFilter excludedFilter = new ExclusionFilter(excludedElementID);
            //--圖元相交過濾器
            ElementIntersectsElementFilter intersectFilter = new ElementIntersectsElementFilter(ele);
            //--建立圖元過濾器
            FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id);

            switch (elementType)
            {
            case "floor":
                collector.OfClass(typeof(Floor)).WhereElementIsNotElementType().WherePasses(excludedFilter).WherePasses(intersectFilter);
                break;

            case "wall":
                collector.OfClass(typeof(Wall)).WhereElementIsNotElementType().WherePasses(intersectFilter);
                break;

            default:
                MessageBox.Show("依照設定參數回傳有碰到ele的牆或版錯誤", "錯誤訊息");
                break;
            }

            IList <Element> intersectElement = collector.ToElements();

            return(intersectElement);
        }
Example #4
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            Transaction trans = new Transaction(doc, "ExComm");

            trans.Start();

            Selection select = uidoc.Selection;
            Reference r      = select.PickObject(ObjectType.Element, "选择需要检查的墙");
            Element   column = doc.GetElement(r);
            FilteredElementCollector collect = new FilteredElementCollector(doc);

            //ElementIntersectFilter冲突检查
            ElementIntersectsElementFilter iFilter = new ElementIntersectsElementFilter(column, false);

            collect.WherePasses(iFilter);
            List <ElementId> excludes = new List <ElementId>();

            excludes.Add(column.Id);
            collect.Excluding(excludes);
            List <ElementId> ids = new List <ElementId>();

            select.SetElementIds(ids);

            foreach (Element elem in collect)
            {
                ids.Add(elem.Id);
            }
            select.SetElementIds(ids);
            trans.Commit();

            return(Result.Succeeded);
        }
Example #5
0
        /// <summary> 找到与某Element的几何实体相交的Elements </summary>
        public void FindIntersectWallsByElement()
        {
            Transaction trans = new Transaction(Doc, "ExComm");

            trans.Start();

            // 选择一个柱子
            Selection sel    = UIDoc.Selection;
            Reference ref1   = sel.PickObject(ObjectType.Element, "Please pick a column");
            Element   column = Doc.GetElement(ref1);

            // 应用过滤器,在整个文档中搜索与指定Element相交的Element
            FilteredElementCollector       collector     = new FilteredElementCollector(Doc);
            ElementIntersectsElementFilter elementFilter = new ElementIntersectsElementFilter(column, false);

            collector.WherePasses(elementFilter);

            // 排除柱子本身
            List <ElementId> excludes = new List <ElementId>();

            excludes.Add(column.Id);
            collector.Excluding(excludes);

            //将最终的相交结果选中
            List <ElementId> selEle = new List <ElementId>();

            foreach (Element elem in collector)
            {
                selEle.Add(elem.Id);
            }
            sel.SetElementIds(selEle);

            trans.Commit();
        }
Example #6
0
        public static List <global::Revit.Elements.Element> GetIntersectingElementsOfCategory(global::Revit.Elements.Element element,
                                                                                              global::Revit.Elements.Category category)
        {
            //the current document
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //get built in category from user viewable category
            BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());
            //the intersection filter
            ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(element.InternalElement);
            //build a collector
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            //collect the elements that fall in that category
            IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList =
                collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();
            //build a new list for the intersecting elements to be added to
            List <global::Revit.Elements.Element> intersectingElements = new List <global::Revit.Elements.Element>();

            //add each user recognizable element to the list
            foreach (Autodesk.Revit.DB.Element internalElement in intersectingElementsInternaList)
            {
                intersectingElements.Add(internalElement.ToDSType(true));
            }

            return(intersectingElements);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref String message,
            ElementSet elements)
        {
            UIApplication app   = commandData.Application;
            UIDocument    uidoc = app.ActiveUIDocument;
            Document      doc   = uidoc.Document;

            bool test_strange_intersect_result = true;

            if (test_strange_intersect_result)
            {
                TestIntersect(doc);
                return(Result.Succeeded);
            }

            Element e = Util.SelectSingleElement(
                uidoc, "a junction box");

            BoundingBoxXYZ bb = e.get_BoundingBox(null);

            Outline outLne = new Outline(bb.Min, bb.Max);

            // Use a quick bounding box filter - axis aligned

            ElementQuickFilter fbb
                = new BoundingBoxIntersectsFilter(outLne);

            FilteredElementCollector conduits
                = new FilteredElementCollector(doc)
                  .OfClass(typeof(Conduit))
                  .WherePasses(fbb);

            // How many elements did we find?

            int nbb = conduits.GetElementCount();

            // Use a slow intersection filter - exact results

            ElementSlowFilter intersect_junction
                = new ElementIntersectsElementFilter(e);

            conduits = new FilteredElementCollector(doc)
                       .OfClass(typeof(Conduit))
                       .WherePasses(intersect_junction);

            // How many elements did we find?

            int nintersect = conduits.GetElementCount();

            Debug.Assert(nintersect <= nbb,
                         "expected element intersection to be stricter"
                         + "than bounding box containment");

            return(Result.Succeeded);
        }
Example #8
0
        /// <summary>
        /// 判断当前创建出来的那个实体是否与其他单元相交,如果相交,则在原实体中剪除相交的部分,如果没有相交,则直接返回原实体集合(集合中的元素个数与原 originalSolids 集合中元素个数相同)。
        /// </summary>
        /// <param name="directShape"></param>
        /// <param name="originalSolids"> directShape 所对应的实体,由于 ExecuteBooleanOperationModifyingOriginalSolid 函数中的 OriginalSolid
        /// 不能是直接从Revit的Element中得到的,所以要将前面通过轮廓拉伸出来的实体作为参数传入。</param>
        /// <param name="hasIntersect"></param>剪切后的实体的体积有可能不大于 0 啊
        /// <returns> 返回的集合中的元素个数与原 originalSolids 集合中元素个数相同。剪切后的实体的体积有可能不大于 0 .</returns>
        private IList <Solid> ExcludeIntersect(DirectShape directShape, IList <Solid> originalSolids, out bool hasIntersect)
        {
            // 应用过滤器,在整个文档中搜索与指定Element相交的Element
            FilteredElementCollector       collector     = new FilteredElementCollector(directShape.Document);
            ElementIntersectsElementFilter elementFilter = new ElementIntersectsElementFilter(element: directShape, inverted: false);

            collector.WherePasses(elementFilter);

            // 排除面层本身
            collector.Excluding(new ElementId[] { directShape.Id });

            if (!collector.Any())
            {
                // 说明没有相交的部分
                hasIntersect = false;
                return(originalSolids);
            }

            hasIntersect = true;

            // 将与其相交的实体进行剪切操作
            bool promptWhileError = false;

            foreach (Element interSectElem in collector)
            {
                var interSectSolids = GeoHelper.GetSolidsInModel(interSectElem, GeoHelper.SolidVolumnConstraint.Positive).Keys;  // 与面层对象相交的 Element 中所有的实体
                for (int i = 0; i < originalSolids.Count; i++)
                {
                    Solid originalS = originalSolids[i];

                    foreach (Solid interSectS in interSectSolids)
                    {
                        try
                        {
                            //  在原实体中减去相交的部分
                            BooleanOperationsUtils.ExecuteBooleanOperationModifyingOriginalSolid(originalS, interSectS, BooleanOperationsType.Difference);
                        }
                        catch (Exception ex)
                        {
                            if (promptWhileError)
                            {
                                // 在剪切时如果不能剪切,则不剪切。
                                DialogResult res = MessageBox.Show("实体剪切时出现错误,可能的原因是面层与模型中的其他实体有细微交叉," +
                                                                   "以致剪切后的实体出现细小锯齿。\n\r (忽略此细微交叉对于面层算量并无明显影响)。" +
                                                                   " \n\r 点击“是”以忽略并继续,点击“否”不再提示。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button2);

                                promptWhileError = (res != DialogResult.No);
                            }
                        }
                    }
                    // 剪切后的实体的体积有可能不大于 0 啊
                    originalSolids[i] = originalS;  // 将剪切完成后的 Solid 再赋值回集合中
                }
            }
            return(originalSolids);
        }
Example #9
0
        public static bool IsElementIntersect(Document doc, Element elem1, Element elem2)
        {
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            var elemInterSectFilter = new ElementIntersectsElementFilter(elem1, false);
            collector.WherePasses(elemInterSectFilter);
            var elems = collector.ToElements();

            MessageBox.Show(elems.Count.ToString());
            return elems.Contains(elem2);
        }
Example #10
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument            uidoc           = commandData.Application.ActiveUIDocument;
            Document              doc             = uidoc.Document;
            var                   columnCollecter = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns).OfClass(typeof(FamilyInstance));
            List <FamilyInstance> columnlist      = columnCollecter.ToList().ConvertAll(x => x as FamilyInstance);

            foreach (FamilyInstance column in columnlist)
            {
                var columnIntersectsFilter   = new ElementIntersectsElementFilter(column);
                var filteredElementCollector = new FilteredElementCollector(doc);
                //文档中过滤出所有和柱相交的元素集合
                List <Element> columnsIntersectList = filteredElementCollector.WherePasses(columnIntersectsFilter).ToList();

                var coulmnIntersectList = from elem in columnsIntersectList
                                          where elem.Category.Id == new ElementId(-2001320)                                             //梁
                                          ||
                                          elem.Category.Id == new ElementId(-2001330)                                                   //柱
                                          ||
                                          elem.Category.Id == new ElementId(-2000011) && (elem as Wall).WallType.Kind == WallKind.Basic //基本墙
                                          ||
                                          elem.Category.Id == new ElementId(-2000032)                                                   //板
                                          select elem;
                foreach (Element elem in columnsIntersectList)
                {
                    Transaction ts = new Transaction(doc);
                    ts.Start("cut");
                    if (JoinGeometryUtils.AreElementsJoined(doc, column, elem) == false)
                    {
                        try
                        {
                            JoinGeometryUtils.JoinGeometry(doc, elem, column);
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        if (JoinGeometryUtils.IsCuttingElementInJoin(doc, column, elem) == false)
                        {
                            JoinGeometryUtils.SwitchJoinOrder(doc, column, elem);
                        }
                    }
                    ts.Commit();
                }
            }
            return(Result.Succeeded);
        }
Example #11
0
        static internal void JoinBeamToWalls(FamilyInstance targetBeam, Document doc)
        {
            ElementIntersectsElementFilter elementFilter = new ElementIntersectsElementFilter(targetBeam);

            IList <Element> WallsIntersectingBeam = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls)
                                                    .OfClass(typeof(Wall)).WhereElementIsNotElementType().WherePasses(elementFilter).ToList();

            foreach (Element currentWall in WallsIntersectingBeam)
            {
                try
                {
                    JoinGeometryUtils.JoinGeometry(doc, targetBeam, currentWall);
                }
                catch
                {
                }
            }
        }
Example #12
0
        /// <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);
        }
Example #13
0
        static internal bool checkMaxDistanceBetweenSupports(FamilyInstance targetBeam, Document doc, out double maxDistBetweenSupport)
        {
            ElementIntersectsElementFilter intesectFilter = new ElementIntersectsElementFilter(targetBeam);

            IList <Element> intersectingColumns = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns)
                                                  .WhereElementIsNotElementType().WherePasses(intesectFilter).ToList();

            //XYZ pointOfInterest = new XYZ(-99999, 99999, -99999);
            XYZ pointOfInterest = (targetBeam.Location as LocationCurve).Curve.GetEndPoint(0);

            intersectingColumns = intersectingColumns.Where(c => (c is FamilyInstance)).OrderBy(c =>
            {
                FamilyInstance fi = c as FamilyInstance;
                if (!fi.IsSlantedColumn)
                {
                    return((fi.Location as LocationPoint).Point.DistanceTo(pointOfInterest));
                }
                else
                {
                    return((fi.Location as LocationCurve).Curve.Distance(pointOfInterest));
                }
            }).ToList();

            maxDistBetweenSupport = double.NegativeInfinity;
            if (intersectingColumns.Count > 0)
            {
                for (int i = 0; i < (intersectingColumns.Count - 1); i++)
                {
                    XYZ firstPoint  = IntersectPointBetweenBeamAndColumn(targetBeam, intersectingColumns[i]);
                    XYZ secondPoint = IntersectPointBetweenBeamAndColumn(targetBeam, intersectingColumns[i + 1]);

                    double currentDistance = firstPoint.DistanceTo(secondPoint);

                    if (currentDistance > maxDistBetweenSupport)
                    {
                        maxDistBetweenSupport = currentDistance;
                    }
                }
                return(true);
            }

            return(false);
        }
Example #14
0
        public static Dictionary <string, object> IntersectionByElementCategoryFromLink(Revit.Elements.Category category, Document document = null, bool refresh = false)
        {
            List <Revit.Elements.Element>         elList = new List <Revit.Elements.Element>();
            List <List <Revit.Elements.Element> > inList = new List <List <Revit.Elements.Element> >();
            string executed = "";

            if (refresh)
            {
                BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString(), true);
                Document        doc       = DocumentManager.Instance.CurrentDBDocument;
                //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
                //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument;

                ElementCategoryFilter    filter    = new ElementCategoryFilter(myCatEnum);
                FilteredElementCollector collector = new FilteredElementCollector(doc).WherePasses(filter).WhereElementIsNotElementType();

                foreach (Autodesk.Revit.DB.Element e in collector)
                {
                    List <Revit.Elements.Element> intersList = new List <Revit.Elements.Element>();
                    DynaFunctions f = new DynaFunctions();

                    ElementIntersectsElementFilter interFiler = new ElementIntersectsElementFilter(e);
                    FilteredElementCollector       interElem  = new FilteredElementCollector(document).WherePasses(interFiler).WhereElementIsNotElementType();
                    if (interElem.GetElementCount() > 0)
                    {
                        elList.Add(doc.GetElement(e.Id).ToDSType(true));
                        foreach (Autodesk.Revit.DB.Element el in interElem)
                        {
                            intersList.Add(document.GetElement(el.Id).ToDSType(true));
                        }
                        inList.Add(intersList);
                    }
                }
            }
            return(new Dictionary <string, object>
            {
                { "Elements", elList },
                { "Intersections", inList },
                { "Executed", executed }
            });
        }
Example #15
0
        public static List <global::Revit.Elements.Element> IntersectingElementsInRoom(global::Revit.Elements.Room room, global::Revit.Elements.Category category)
        {
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;

            Autodesk.DesignScript.Geometry.Solid roomSolid = Autodesk.DesignScript.Geometry.Solid.ByUnion(room.Solids);

            //get built in category from user viewable category
            BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());

            //start the transaction
            TransactionManager.Instance.EnsureInTransaction(doc);
            //builds an id collection for later deletion
            ICollection <ElementId> idCollection = new List <ElementId>();

            global::Revit.Elements.DirectShape directShape = global::Revit.Elements.DirectShape.ByGeometry(roomSolid, global::Revit.Elements.Category.ByName("Generic Models"), global::Revit.Elements.DirectShape.DynamoPreviewMaterial, "DirectShape");
            idCollection.Add(directShape.InternalElement.Id);
            TransactionManager.Instance.TransactionTaskDone();
            doc.Regenerate();
            ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(directShape.InternalElement);
            //build a collector
            FilteredElementCollector          collector = new FilteredElementCollector(doc);
            IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList = collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();
            //build a list to output geometry
            List <global::Revit.Elements.Element> intersectingElements = new List <global::Revit.Elements.Element>();

            //append the intersecting elements to the output list
            foreach (Autodesk.Revit.DB.Element thing in intersectingElementsInternaList)
            {
                intersectingElements.Add(thing.ToDSType(true));
            }
            //delete the direct shapes as we do not need them any longer
            TransactionManager.Instance.EnsureInTransaction(doc);
            foreach (ElementId id in idCollection)
            {
                doc.Delete(id);
            }
            TransactionManager.Instance.TransactionTaskDone();

            return(intersectingElements);
        }
Example #16
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument  uiDoc = commandData.Application.ActiveUIDocument;
            Document    doc   = uiDoc.Document;
            Transaction tran  = new Transaction(doc, "ExCom");

            tran.Start();
            Selection select = uiDoc.Selection;
            Reference r      = select.PickObject(ObjectType.Element, "选择需要检查的墙");
            Element   column = doc.GetElement(r);
            FilteredElementCollector collector = new FilteredElementCollector(doc);
            //使用ElementIntersectFilter冲突检查
            ElementIntersectsElementFilter iFilter = new ElementIntersectsElementFilter(column, false);

            collector.WherePasses(iFilter);
            List <ElementId> excludes = new List <ElementId> {
                column.Id
            };

            collector.Excluding(excludes);
            List <ElementId> ids = new List <ElementId>();

            select.SetElementIds(ids);
            foreach (Element element in collector)
            {
                ids.Add(element.Id);
            }
            select.SetElementIds(ids);
            tran.Commit();
            CurveLoop curs   = null;
            ElementId rId    = null;
            ElementId leveId = null;
            Railing   rail   = Railing.Create(doc, curs, rId, leveId);

            return(Result.Succeeded);
        }
Example #17
0
        internal void SetConflictElements(List <AvoidElement> elementsToAvoid, List <ValuedConflictNode> conflictNodes)
        {
            ConflictElements = new List <ConflictElement>();
            ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(MEPCurve);
            var elementsConflicted = elementsToAvoid.Where(c => filter.PassesFilter(c.MEPCurve)).ToList();

            foreach (var elementConflicted in elementsConflicted)
            {
                var conflictLocation = GetConflictPoint(elementConflicted.MEPCurve);
                if (conflictLocation != null)
                {
                    var conflictElement = new ConflictElement(this, conflictLocation, elementConflicted);
                    ConflictElements.Add(conflictElement);
                    if (conflictNodes.FirstOrDefault(c => c.ConflictLocation.VL_XYEqualTo(conflictLocation) && (c.ValueNode1.OrientAvoidElement == this || c.ValueNode2.OrientAvoidElement == this)) == null)
                    {
                        conflictNodes.Add(new ValuedConflictNode(this, conflictLocation, elementConflicted));
                    }
                }
            }
            SortConflictElements();

            ////TEST
            //var conflictIds = string.Join(",", elementsConflicted.Select(c => c.MEPElement.Id));
        }
Example #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="category"></param>
        /// <param name="refresh"></param>
        /// <returns></returns>
        public static List <List <Autodesk.DesignScript.Geometry.Solid> > IntersectionSolidsByCategory(Revit.Elements.Category category, Document document = null, bool refresh = false)
        {
            List <Revit.Elements.Element>         elList = new List <Revit.Elements.Element>();
            List <List <Revit.Elements.Element> > inList = new List <List <Revit.Elements.Element> >();

            List <List <Autodesk.DesignScript.Geometry.Solid> > interGeoms = new List <List <Autodesk.DesignScript.Geometry.Solid> >();


            if (refresh)
            {
                BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString(), true);
                Document        doc       = DocumentManager.Instance.CurrentDBDocument;

                //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
                //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument;

                ElementCategoryFilter    filter    = new ElementCategoryFilter(myCatEnum);
                ElementCategoryFilter    exclude   = new ElementCategoryFilter(BuiltInCategory.OST_GenericModel);
                FilteredElementCollector excluded  = new FilteredElementCollector(doc).WherePasses(exclude);
                FilteredElementCollector collector = new FilteredElementCollector(doc).WherePasses(filter).WhereElementIsNotElementType();
                collector.Excluding(excluded.ToElementIds());


                foreach (Autodesk.Revit.DB.Element e in collector)
                {
                    DynaFunctions f = new DynaFunctions();

                    ElementIntersectsElementFilter interFiler = new ElementIntersectsElementFilter(e);
                    FilteredElementCollector       interElem  = new FilteredElementCollector(document).WherePasses(interFiler).WhereElementIsNotElementType();
                    if (interElem.GetElementCount() > 0)
                    {
                        List <Autodesk.Revit.DB.Solid> elGeoms = new List <Autodesk.Revit.DB.Solid>();
                        GeometryElement geomEl = e.get_Geometry(new Options());
                        foreach (GeometryObject geomObj in geomEl)
                        {
                            elGeoms.Add(geomObj as Autodesk.Revit.DB.Solid);
                        }
                        List <Autodesk.Revit.DB.Solid> iS = new List <Autodesk.Revit.DB.Solid>();
                        List <Autodesk.DesignScript.Geometry.Solid> iSS = new List <Autodesk.DesignScript.Geometry.Solid>();
                        foreach (Autodesk.Revit.DB.Element el in interElem)
                        {
                            GeometryElement intEl = el.get_Geometry(new Options());
                            foreach (GeometryObject intObj in intEl)
                            {
                                iS.Add(intObj as Autodesk.Revit.DB.Solid);
                            }
                        }
                        foreach (Autodesk.Revit.DB.Solid s0 in elGeoms)
                        {
                            foreach (Autodesk.Revit.DB.Solid s1 in iS)
                            {
                                Autodesk.Revit.DB.Solid i = BooleanOperationsUtils.ExecuteBooleanOperation(s0, s1, BooleanOperationsType.Intersect);
                                if (i != null)
                                {
                                    Autodesk.Revit.DB.Solid bbox = f.CreateSolidFromBoundingBox(i);
                                    iSS.Add(Revit.GeometryConversion.RevitToProtoSolid.ToProtoType(i));
                                }
                            }
                        }
                        interGeoms.Add(iSS);
                    }
                }
            }
            return(interGeoms);
        }
Example #19
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="category"></param>
        /// <param name="refresh"></param>
        /// <returns></returns>
        public static List <List <Autodesk.DesignScript.Geometry.Point> > IntersectionPointsByCategory(Revit.Elements.Category category, Document document = null, bool refresh = false)
        {
            List <Revit.Elements.Element>         elList = new List <Revit.Elements.Element>();
            List <List <Revit.Elements.Element> > inList = new List <List <Revit.Elements.Element> >();

            List <List <Autodesk.DesignScript.Geometry.Point> > cPoints = new List <List <Autodesk.DesignScript.Geometry.Point> >();

            if (refresh)
            {
                BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString(), true);
                Document        doc       = DocumentManager.Instance.CurrentDBDocument;

                //UIApplication uiapp = DocumentManager.Instance.CurrentUIApplication;
                //Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
                //UIDocument uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument;

                ElementCategoryFilter    filter    = new ElementCategoryFilter(myCatEnum);
                ElementCategoryFilter    exclude   = new ElementCategoryFilter(BuiltInCategory.OST_GenericModel);
                FilteredElementCollector excluded  = new FilteredElementCollector(doc).WherePasses(exclude);
                FilteredElementCollector collector = new FilteredElementCollector(doc).WherePasses(filter).WhereElementIsNotElementType();
                collector.Excluding(excluded.ToElementIds());

                foreach (Autodesk.Revit.DB.Element e in collector)
                {
                    DynaFunctions f = new DynaFunctions();


                    ElementIntersectsElementFilter interFiler = new ElementIntersectsElementFilter(e);
                    FilteredElementCollector       interElem  = new FilteredElementCollector(document).WherePasses(interFiler).WhereElementIsNotElementType();
                    if (interElem.GetElementCount() > 0)
                    {
                        List <Autodesk.Revit.DB.Solid> elGeoms = new List <Autodesk.Revit.DB.Solid>();
                        GeometryElement geomEl = e.get_Geometry(new Options());
                        foreach (GeometryObject geomObj in geomEl)
                        {
                            elGeoms.Add(geomObj as Autodesk.Revit.DB.Solid);
                        }

                        elList.Add(doc.GetElement(e.Id).ToDSType(true));
                        List <Autodesk.Revit.DB.Solid> iS = new List <Autodesk.Revit.DB.Solid>();
                        List <Autodesk.DesignScript.Geometry.Point> cPoint = new List <Autodesk.DesignScript.Geometry.Point>();
                        List <Autodesk.DesignScript.Geometry.Solid> iSS    = new List <Autodesk.DesignScript.Geometry.Solid>();
                        foreach (Autodesk.Revit.DB.Element el in interElem)
                        {
                            GeometryElement intEl = el.get_Geometry(new Options());
                            foreach (GeometryObject intObj in intEl)
                            {
                                iS.Add(intObj as Autodesk.Revit.DB.Solid);
                            }
                        }
                        foreach (Autodesk.Revit.DB.Solid s0 in elGeoms)
                        {
                            foreach (Autodesk.Revit.DB.Solid s1 in iS)
                            {
                                Autodesk.Revit.DB.Solid i = BooleanOperationsUtils.ExecuteBooleanOperation(s0, s1, BooleanOperationsType.Intersect);
                                if (i != null)
                                {
                                    iSS.Add(Revit.GeometryConversion.RevitToProtoSolid.ToProtoType(i));
                                    DisplayUnitType dt = doc.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;

                                    XYZ coord = new XYZ(f.convertToUnit(i.ComputeCentroid().X, dt), f.convertToUnit(i.ComputeCentroid().Y, dt), f.convertToUnit(i.ComputeCentroid().Z, dt));
                                    //XYZ coord = new XYZ(i.ComputeCentroid().X, i.ComputeCentroid().Y, i.ComputeCentroid().Z);
                                    Autodesk.DesignScript.Geometry.Point p = Autodesk.DesignScript.Geometry.Point.ByCoordinates(coord.X, coord.Y, coord.Z);
                                    cPoint.Add(p);
                                }
                            }
                        }
                        cPoints.Add(cPoint);
                    }
                }
            }
            return(cPoints);
        }
Example #20
0
        static internal void CheckForDuplicatesAndIntersectingBeams(FamilyInstance targetBeam, Document doc)
        {
            //We will check if theres another beam here:
            IList <ElementId> listOfElementsThatWillBeDeleted = new List <ElementId>();
            Options           op = new Options()
            {
                ComputeReferences = false, IncludeNonVisibleObjects = false, DetailLevel = ViewDetailLevel.Coarse
            };
            GeometryElement beamGeometryElement = targetBeam.get_Geometry(op);

            BoundingBoxXYZ beamBoundingBox = beamGeometryElement.GetBoundingBox();

            Outline beam3dVolume = new Outline(beamBoundingBox.Min, beamBoundingBox.Max);

            BoundingBoxIntersectsFilter    Intersect       = new BoundingBoxIntersectsFilter(beam3dVolume, Utils.ConvertM.cmToFeet(-3));
            ElementIntersectsElementFilter IntersectElemen = new ElementIntersectsElementFilter(targetBeam);
            IList <Element> beamThatIntersects             = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming)
                                                             .WherePasses(Intersect).WherePasses(IntersectElemen).ToList();

            if (beamThatIntersects.Count > 0)
            {
                Curve targetBeamCurve    = (targetBeam.Location as LocationCurve).Curve;
                Line  targetBeamBeamLine = targetBeamCurve as Line;
                //double newUpperBeamCurveLength = newUpperBeamCurve.ApproximateLength;
                if (targetBeamBeamLine != null)
                {
                    XYZ targetBeamCurveDirection = targetBeamBeamLine.Direction;
                    foreach (Element beamElement in beamThatIntersects)
                    {
                        Curve beamElementLocationCurve = (beamElement.Location as LocationCurve).Curve;
                        Line  beamElementLocationLine  = beamElementLocationCurve as Line;

                        if (beamElementLocationLine == null)
                        {
                            continue;
                        }

                        XYZ beamElementLocationCurveDirection = beamElementLocationLine.Direction;
                        //double beamElementLocationCurveLength = beamElementLocationCurve.ApproximateLength;
                        double angleBetweenBeams = beamElementLocationCurveDirection.AngleTo(targetBeamCurveDirection);
                        //compare the angles
                        if ((angleBetweenBeams < 0.1) || (Math.Abs(angleBetweenBeams - Math.PI) < 0.1))
                        {
                            if (beamElement.Id != targetBeam.Id)
                            {
                                if (targetBeamBeamLine.ApproximateLength >= beamElementLocationLine.ApproximateLength)
                                {
                                    listOfElementsThatWillBeDeleted.Add(beamElement.Id);
                                }
                                else
                                {
                                    listOfElementsThatWillBeDeleted.Add(targetBeam.Id);
                                }
                            }
                        }
                    }
                }
                else
                {
                    //if is a curved beam
                    foreach (Element beamElement in beamThatIntersects)
                    {
                        Curve beamElementLocationCurve = (beamElement.Location as LocationCurve).Curve;
                        if (((beamElementLocationCurve as Line) == null) && (targetBeamBeamLine == null))
                        {
                            //Here we need to check the length and some other things to compare better
                            //We need to implement a better code here

                            if (beamElement.Id != targetBeam.Id)
                            {
                                listOfElementsThatWillBeDeleted.Add(beamElement.Id);
                            }
                        }
                    }
                }
                doc.Delete(listOfElementsThatWillBeDeleted);
            }
        }
Example #21
0
        public void Execute(UpdaterData data)
        {
            //Func<ICollection<ElementId>, string> toString = ids => ids.Aggregate("", (ss, id) => ss + "," + id).TrimStart(',');
            //var sb = new StringBuilder();
            //sb.AppendLine("added:" + toString(data.GetAddedElementIds()));
            //sb.AppendLine("modified:" + toString(data.GetModifiedElementIds()));
            //sb.AppendLine("deleted:" + toString(data.GetDeletedElementIds()));
            //TaskDialog.Show("Changes", sb.ToString());
            Document    doc = data.GetDocument();
            Application app = doc.Application;

            foreach (ElementId id in data.GetAddedElementIds())
            {
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                //  TaskDialog.Show("ElevationWatcher Updater", string.Format("New elevation view '{0}'", data.GetAddedElementIds()));
                ElementIntersectsElementFilter EIEF = new ElementIntersectsElementFilter(doc.GetElement(id));

                //collector.WherePasses(EIEF);
                //ICollection<Element> allLoads = collector.ToElements();
                List <Element> Collisions = new List <Element>();

                IList <Element> elems = collector.OfCategory(BuiltInCategory.OST_RvtLinks).OfClass(typeof(RevitLinkType)).ToElements();
                foreach (Element e in elems)
                {
                    RevitLinkType linkType = e as RevitLinkType;

                    String s = String.Empty;



                    foreach (Document linkedDoc in app.Documents)

                    {
                        //   TaskDialog.Show("Collision tracker", string.Format("A {0}  // {1}", linkedDoc.Title + ".rvt", linkType.Name));

                        if (linkedDoc.Title + ".rvt" == (linkType.Name))
                        {
                            FilteredElementCollector collLinked = new FilteredElementCollector(linkedDoc);

                            collLinked.WherePasses(EIEF);

                            // Collisions=collLinked.ToElements();


                            //  TaskDialog.Show("Collision tracker", string.Format(" {0} ", Collisions.Count));

                            foreach (Element el in collLinked.ToElements())
                            {
                                Collisions.Add(el);
                                TaskDialog.Show("ElevationWatcher Updater", string.Format("El Name: {0}  File: {1}", el.Name, linkedDoc.Title));
                            }
                        }
                    }
                }

                FilteredElementCollector _collector = new FilteredElementCollector(doc);
                _collector.WherePasses(EIEF);
                foreach (Element el in _collector.ToElements())
                {
                    Collisions.Add(el);
                }

                if (Collisions.Count > 0)
                {
                    TaskDialog.Show("Collision tracker", string.Format("This path have '{0}' collisions.", Collisions.Count));
                }
            }
        }
Example #22
0
        private void JoinOrUnJoinElements(bool join)
        {
            if (uidoc != null)
            {
                if (joinSelectUI.currentFirstElementList != null && joinSelectUI.currentSecondElementList != null)
                {
                    bool secondElementsWasEmpty = false;
                    // if we the second elements were not selected, use the first list
                    if (joinSelectUI.currentFirstElementList.Count == 0)
                    {
                        return;
                    }

                    if (joinSelectUI.currentSecondElementList.Count == 0)
                    {
                        secondElementsWasEmpty = true;
                        joinSelectUI.currentSecondElementList = joinSelectUI.currentFirstElementList.ToList();
                    }

                    string transactionName = join ? Properties.Messages.ElementJoinSelect_JoinTransaction : Properties.Messages.ElementJoinSelect_UnJoinTransaction;

                    using (Transaction t = new Transaction(uidoc.Document, transactionName))
                    {
                        t.Start();

                        FailureHandlingOptions joinFailOp = t.GetFailureHandlingOptions();
                        joinFailOp.SetFailuresPreprocessor(new JoinFailurAdvHandler());
                        t.SetFailureHandlingOptions(joinFailOp);

                        foreach (Element currentElementToJoin in joinSelectUI.currentFirstElementList)
                        {
                            BoundingBoxXYZ bBox = currentElementToJoin.get_BoundingBox(null);
                            bBox.Enabled = true;
                            Outline outLine = new Outline(bBox.Min, bBox.Max);

                            BoundingBoxIntersectsFilter    bbIntersects    = new BoundingBoxIntersectsFilter(outLine, Utils.ConvertM.cmToFeet(3));
                            ElementIntersectsElementFilter intersectFilter = new ElementIntersectsElementFilter(currentElementToJoin);

                            foreach (Element currentElementToBeJoined in joinSelectUI.currentSecondElementList)
                            {
                                if (join)
                                {
                                    if (currentElementToJoin.Id == currentElementToBeJoined.Id)
                                    {
                                        continue;
                                    }

                                    if (!bbIntersects.PassesFilter(currentElementToBeJoined))
                                    {
                                        continue;
                                    }

                                    if (currentElementToJoin.Category.Id != currentElementToBeJoined.Category.Id)
                                    {
                                        if (!intersectFilter.PassesFilter(currentElementToBeJoined))
                                        {
                                            continue;
                                        }
                                    }

                                    if (!JoinGeometryUtils.AreElementsJoined(uidoc.Document, currentElementToJoin, currentElementToBeJoined))
                                    {
                                        try
                                        {
                                            JoinGeometryUtils.JoinGeometry(uidoc.Document, currentElementToJoin, currentElementToBeJoined);
                                        }
                                        catch (Exception e)
                                        {
                                            System.Diagnostics.Debug.Print(e.Message);
                                        }
                                    }
                                }
                                else
                                {
                                    if (JoinGeometryUtils.AreElementsJoined(uidoc.Document, currentElementToJoin, currentElementToBeJoined))
                                    {
                                        try
                                        {
                                            JoinGeometryUtils.UnjoinGeometry(uidoc.Document, currentElementToJoin, currentElementToBeJoined);
                                        }
                                        catch (Exception e)
                                        {
                                            System.Diagnostics.Debug.Print(e.Message);
                                        }
                                    }
                                }
                            }
                        }

                        if (secondElementsWasEmpty)
                        {
                            joinSelectUI.currentSecondElementList = new List <Element>();
                        }

                        t.Commit();
                    }
                }
            }
        }
Example #23
0
        private ElementId FindHost(XYZ location, int hostType, Document doc)
        {
            ElementId host = null;
            FilteredElementCollector collector = new FilteredElementCollector(doc);

            // Subtransaction to insert a family and use it to check for intersctions.
            // The family is then moved around to check for the host of each new object being created
            // After the element creation process is over the object and it's parent family are deleted form the project.
            using (SubTransaction subTrans = new SubTransaction(doc))
            {
                subTrans.Start();

                if (hostFinder == null)
                {
                    // check if the point family exists
                    string path = typeof(LyrebirdService).Assembly.Location.Replace("LMNA.Lyrebird.Revit2015.dll", "IntersectionPoint.rfa");
                    if (!System.IO.File.Exists(path))
                    {
                        // save the file from this assembly and load it into project
                        //string directory = System.IO.Path.GetDirectoryName(path);
                        System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                        WriteResource(assembly, "IntersectionPoint.rfa", path);
                    }

                    // Load the family and place an instance of it.
                    Family insertPoint = null;
                    
                    try
                    {
                        if (System.IO.File.Exists(path))
                        {
                            doc.LoadFamily(path, out insertPoint);
                        }
                        else
                        {
                            TaskDialog.Show("Error", "Could not find family to load");
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine("Error", ex.Message); ;
                    }
                    
                    if (insertPoint != null)
                    {
                        FamilySymbol ips = null;
                        foreach (ElementId fsid in insertPoint.GetFamilySymbolIds())
                        {
                            ips = doc.GetElement(fsid) as FamilySymbol;
                        }

                        // Create an instance
                        hostFinder = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc, ips);
                        System.IO.File.Delete(path);
                    }
                    else
                    {
                        TaskDialog.Show("test", "InsertPoint family is still null, loading didn't work.");
                    }
                }

                IList<ElementId> placePointIds = new List<ElementId>();
                placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(hostFinder);
                try
                {
                    ReferencePoint rp = doc.GetElement(placePointIds[0]) as ReferencePoint;
                    XYZ movedPt;
                    if (hostType == 1 || hostType == 3)
                    {
                        movedPt = new XYZ(location.X, location.Y, location.Z + 0.00328);
                    }
                    else
                    {
                        movedPt = new XYZ(location.X, location.Y, location.Z - 0.00328);
                    }

                    if (rp != null)
                    {
                        XYZ vector = movedPt.Subtract(rp.Position);
                        ElementTransformUtils.MoveElement(doc, rp.Id, vector);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }

                Element elem = hostFinder as Element;
                if (elem != null)
                {
                    // Find the host element
                    if (hostType == 1)
                    {
                        // find a wall
                        collector.OfCategory(BuiltInCategory.OST_Walls);
                        collector.OfClass(typeof(Wall));

                        ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem);
                        collector.WherePasses(intersectionFilter);
                        foreach (Element e in collector)
                        {
                            host = e.Id;
                        }

                    }
                    else if (hostType == 2)
                    {
                        // Find a floor
                        collector.OfCategory(BuiltInCategory.OST_Floors);
                        collector.OfClass(typeof(Floor));

                        ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem);
                        collector.WherePasses(intersectionFilter);

                        foreach (Element e in collector)
                        {
                            host = e.Id;
                        }
                    }
                    else if (hostType == 3)
                    {
                        // find a ceiling
                        collector.OfCategory(BuiltInCategory.OST_Ceilings);
                        collector.OfClass(typeof(Ceiling));

                        ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem);
                        collector.WherePasses(intersectionFilter);

                        foreach (Element e in collector)
                        {
                            host = e.Id;
                        }
                    }
                    else if (hostType == 4)
                    {
                        // find a roof
                        collector.OfCategory(BuiltInCategory.OST_Roofs);
                        collector.OfClass(typeof(RoofBase));

                        ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem);
                        collector.WherePasses(intersectionFilter);

                        foreach (Element e in collector)
                        {
                            host = e.Id;
                        }
                    }
                }
                subTrans.Commit();

                // Delete the family file

            }

            return host;
        }
Example #24
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            Selection  sel   = uidoc.Selection;

            try
            {
                //IList<Level> projectLevelList = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).OfClass(typeof(Level))
                //    .Cast<Level>().OrderBy(l => l.Elevation).ToList();

                IList <LevelInfo> projectLevelList = Utils.GetInformation.GetAllLevelsInfo(doc);

                ElementsJoinUIAdvanced currentUI = new ElementsJoinUIAdvanced(projectLevelList);
                currentUI.ShowDialog();

                if (currentUI.DialogResult == false)
                {
                    return(Result.Cancelled);
                }

                string firstCatName = (currentUI.comboFirstCategory.SelectedItem as ComboBoxItem).Content.ToString();
                string seconCatName = (currentUI.comboSecondCategory.SelectedItem as ComboBoxItem).Content.ToString();

                BuiltInCategory firstCat  = checkCategory(currentUI.comboFirstCategory.SelectedIndex);
                BuiltInCategory secondCat = checkCategory(currentUI.comboSecondCategory.SelectedIndex);

                if (firstCat == BuiltInCategory.INVALID || secondCat == BuiltInCategory.INVALID)
                {
                    return(Result.Cancelled);
                }

                Level lowerLevel = null;
                Level upperLevel = null;

                Element lowerLevelElement = null;
                Element upperLevelElement = null;

                if (currentUI.selectedLowerLevel != 0 && currentUI.selectedLowerLevel != -1)
                {
                    lowerLevelElement = doc.GetElement(new ElementId(currentUI.selectedLowerLevel));
                }

                if (currentUI.selectedUpperLevel != 0 && currentUI.selectedUpperLevel != -1)
                {
                    upperLevelElement = doc.GetElement(new ElementId(currentUI.selectedUpperLevel));
                }

                if (lowerLevelElement != null)
                {
                    lowerLevel = lowerLevelElement as Level;
                }

                if (upperLevelElement != null)
                {
                    upperLevel = GetNextLevel(upperLevelElement as Level);
                }


                IList <Element>   ElementsToJoin    = GetElementsOnLevels(doc, firstCat, lowerLevel, upperLevel);
                IList <ElementId> elementsIdsToJoin = new List <ElementId>();

                foreach (Element currentElement in ElementsToJoin)
                {
                    elementsIdsToJoin.Add(currentElement.Id);
                }

                IList <Element> elementsIntersecting = new List <Element>();

                using (Transaction t = new Transaction(doc, Properties.Messages.ElementJoin_JoinTransaction))
                {
                    t.Start();

                    FailureHandlingOptions joinFailOp = t.GetFailureHandlingOptions();
                    joinFailOp.SetFailuresPreprocessor(new JoinFailurAdvHandler());
                    t.SetFailureHandlingOptions(joinFailOp);

                    IList <Element>   elementsIToBeJoin   = GetElementsOnLevels(doc, secondCat, lowerLevel, upperLevel);
                    IList <ElementId> elementsIdsToBeJoin = new List <ElementId>();

                    foreach (Element currentElement in elementsIToBeJoin)
                    {
                        elementsIdsToBeJoin.Add(currentElement.Id);
                    }

                    foreach (Element currentElementToJoin in ElementsToJoin)
                    {
                        BoundingBoxXYZ bBox = currentElementToJoin.get_BoundingBox(null);
                        bBox.Enabled = true;
                        Outline outlineToJoin = new Outline(bBox.Min, bBox.Max);

                        BoundingBoxIntersectsFilter bbIntersects = new BoundingBoxIntersectsFilter(outlineToJoin, Utils.ConvertM.cmToFeet(0.5));

                        elementsIntersecting = new FilteredElementCollector(doc, elementsIdsToBeJoin).OfCategory(secondCat).WherePasses(bbIntersects).ToElements();

                        ElementIntersectsElementFilter intersectFilter = new ElementIntersectsElementFilter(currentElementToJoin);

                        foreach (Element currentElementToBeJoined in elementsIntersecting)
                        {
                            if (currentUI.join)
                            {
                                if (currentElementToJoin.Id == currentElementToBeJoined.Id)
                                {
                                    continue;
                                }

                                if (currentElementToJoin.Category.Id != currentElementToBeJoined.Category.Id)
                                {
                                    if (!intersectFilter.PassesFilter(currentElementToBeJoined))
                                    {
                                        continue;
                                    }
                                }



                                if (!JoinGeometryUtils.AreElementsJoined(doc, currentElementToJoin, currentElementToBeJoined))
                                {
                                    try
                                    {
                                        JoinGeometryUtils.JoinGeometry(doc, currentElementToJoin, currentElementToBeJoined);
                                    }
                                    catch (Exception e)
                                    {
                                        System.Diagnostics.Debug.Print(e.Message);
                                    }
                                }
                            }
                            else
                            {
                                if (JoinGeometryUtils.AreElementsJoined(doc, currentElementToJoin, currentElementToBeJoined))
                                {
                                    try
                                    {
                                        JoinGeometryUtils.UnjoinGeometry(doc, currentElementToJoin, currentElementToBeJoined);
                                    }
                                    catch (Exception e)
                                    {
                                        System.Diagnostics.Debug.Print(e.Message);
                                    }
                                }
                            }
                        }
                    }
                    t.Commit();
                }
            }
            catch (Exception excep)
            {
                ExceptionManager eManager = new ExceptionManager(excep);
            }

            return(Result.Succeeded);
        }
Example #25
0
        public static List <global::Revit.Elements.Element> GetIntersectingElementsOfCategoryLinkOption(global::Revit.Elements.Element element,
                                                                                                        global::Revit.Elements.Category category, [DefaultArgument("Rhythm.Revit.Elements.Element.GetNull()")] global::Revit.Elements.Element sourceInstance)
        {
            //the current document
            Autodesk.Revit.DB.Document doc = DocumentManager.Instance.CurrentDBDocument;
            //get built in category from user viewable category
            BuiltInCategory myCatEnum = (BuiltInCategory)Enum.Parse(typeof(BuiltInCategory), category.Id.ToString());
            //build a new list for the intersecting elements to be added to
            List <global::Revit.Elements.Element> intersectingElements = new List <global::Revit.Elements.Element>();

            if (sourceInstance != null)
            {
                Autodesk.Revit.DB.RevitLinkInstance internalInstance =
                    (Autodesk.Revit.DB.RevitLinkInstance)sourceInstance.InternalElement;
                //get the element's geometry.
                GeometryElement geomElement = element.InternalElement.get_Geometry(new Options());
                //transform the solid to where the eff the link is.
                GeometryElement transformedElement = geomElement.GetTransformed(internalInstance.GetTransform());
                //make a solid filter.
                Solid solid = null;
                foreach (GeometryObject geomObj in transformedElement)
                {
                    solid = geomObj as Solid;
                    if (solid != null)
                    {
                        break;
                    }
                }
                //the intersection filter
                ElementIntersectsSolidFilter filter = new ElementIntersectsSolidFilter(solid);
                //build a collector
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                //collect the elements that fall in that category
                IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList =
                    collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();

                //add each user recognizable element to the list
                foreach (Autodesk.Revit.DB.Element internalElement in intersectingElementsInternaList)
                {
                    intersectingElements.Add(internalElement.ToDSType(true));
                }
            }
            else
            {
                //the intersection filter
                ElementIntersectsElementFilter filter = new ElementIntersectsElementFilter(element.InternalElement);
                //build a collector
                FilteredElementCollector collector = new FilteredElementCollector(doc);
                //collect the elements that fall in that category
                IList <Autodesk.Revit.DB.Element> intersectingElementsInternaList =
                    collector.OfCategory(myCatEnum).WhereElementIsNotElementType().WherePasses(filter).ToElements();

                //add each user recognizable element to the list
                foreach (Autodesk.Revit.DB.Element internalElement in intersectingElementsInternaList)
                {
                    intersectingElements.Add(internalElement.ToDSType(true));
                }
            }

            return(intersectingElements);
        }
Example #26
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            UIApplication uiApp = commandData.Application;
            UIDocument    uiDoc = uiApp.ActiveUIDocument;
            Document      doc   = uiApp.ActiveUIDocument.Document;
            Application   app   = uiApp.Application;

            Selection selection = uiDoc.Selection;

            Transaction ts = new Transaction(doc, "cut");

            ts.Start();

            //Reference refWall = selection.PickObject(ObjectType.Element, "choise");
            //Element elem_1 = doc.GetElement(refWall);

            //Reference refPipe = selection.PickObject(ObjectType.Element, "choise");
            //Element elem_2 = doc.GetElement(refPipe);

            ////SolidSolidCutUtils.RemoveCutBetweenSolids(doc, elem_1, elem_2);
            //InstanceVoidCutUtils.AddInstanceVoidCut(doc, elem_1, elem_2);


            //SolidSolidCutUtils.AddCutBetweenSolids(doc, elem_1, elem_2);
            //JoinGeometryUtils.JoinGeometry(doc, e1, e2);

            //FilteredElementCollector collector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType();

            IList <Element> _elements = uiDoc.Selection.PickElementsByRectangle(new WallFilter(), "请框选所有需要剪切管道的墙");

            foreach (var awall in _elements)
            {
                //FilteredElementCollector collector2 = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_PipeAccessory).WhereElementIsNotElementType();
                var collector2          = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_PipeAccessory).OfClass(typeof(FamilyInstance));
                var pipeIntersectFilter = new ElementIntersectsElementFilter(awall);
                //在所有Pipe中过滤出和每一个墙相交的Pipe然后组成集合
                List <FamilyInstance> pipes = collector2.WherePasses(pipeIntersectFilter).ToList().ConvertAll(x => x as FamilyInstance);

                foreach (var pipe in pipes)
                {
                    InstanceVoidCutUtils.AddInstanceVoidCut(doc, awall, pipe);
                }
            }

            //try
            //{
            //  foreach (var element in selection.GetElementIds())
            //  {

            //    InstanceVoidCutUtils.AddInstanceVoidCut(doc, beam, cuttingInstance);
            //  }
            //}

            //catch (Exception e)
            //{
            //  message = e.Message;
            //  return Result.Failed;
            //}

            //TaskDialog.Show("Hello", "Hello Revit!");
            ts.Commit();
            return(Result.Succeeded);
        }
Example #27
0
        /// <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;
        }