public void CanUnjoinTwoElements() { var wall1 = ElementSelector.ByElementId(184176, true); var wall2 = ElementSelector.ByElementId(207960, true); var floor = ElementSelector.ByElementId(208259, true); var doc = DocumentManager.Instance.CurrentDBDocument; string expectedNotJoinedExceptionMessages = Revit.Properties.Resources.NotJoinedElements; // Are joined bool originalWall1AndWall2JoinedValue = JoinGeometryUtils.AreElementsJoined(doc, wall1.InternalElement, wall2.InternalElement); Assert.AreEqual(true, originalWall1AndWall2JoinedValue); // Are not joined bool originalWall2AndFloorJoinedValue = JoinGeometryUtils.AreElementsJoined(doc, wall2.InternalElement, floor.InternalElement); Assert.AreEqual(false, originalWall2AndFloorJoinedValue); wall1.UnjoinGeometry(wall2); bool newWall1AndWall2JoinedValue = wall1.AreJoined(wall2); // Are joined should have changed Assert.AreNotEqual(newWall1AndWall2JoinedValue, originalWall1AndWall2JoinedValue); // Should throw InvalidOperationException var ex = Assert.Throws <InvalidOperationException>(() => wall2.UnjoinGeometry(floor)); Assert.AreEqual(ex.Message, expectedNotJoinedExceptionMessages); }
public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI. ExternalCommandData commandData, ref string message, ElementSet elements) { Tracer.Listeners.Add(new System.Diagnostics.EventLogTraceListener("Application")); Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { IList <Wall> walls = new FilteredElementCollector(doc) .OfClass(typeof(Wall)) .WhereElementIsNotElementType() .Cast <Wall>() .ToList(); Tracer.Write("All the walls in the project: " + walls.Count); foreach (Wall wall in walls) { IList <Element> intrudingWalls = GetWallsIntersectBoundingBox(doc, wall); Tracer.Write(string.Format("Wall {0} is intersected by {1} walls", wall.Id.ToString(), intrudingWalls.Count)); using (Transaction t = new Transaction(doc, "Join walls")) { t.Start(); foreach (Element elem in intrudingWalls) { if (((Wall)elem).WallType.Kind == WallKind.Curtain) { continue; } try { if (!JoinGeometryUtils.AreElementsJoined(doc, wall, elem)) { JoinGeometryUtils.JoinGeometry(doc, wall, elem); } } catch (Exception ex) { Tracer.Write(string.Format("{0}\nWall: {1} cannot be joined to {2}", ex.Message, wall.Id.ToString(), elem.Id.ToString())); continue; } } t.Commit(); } } return(Autodesk.Revit.UI.Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Autodesk.Revit.UI.Result.Cancelled); } catch (Exception ex) { Tracer.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Autodesk.Revit.UI.Result.Failed); } }
private void WallJoinColumns(Document doc, List <Wall> wallList) { foreach (Wall wal in wallList) { Solid walSd = bc.AllSolid_Of_Element(wal)[0]; ElementIntersectsSolidFilter sdFilter = new ElementIntersectsSolidFilter(walSd); IList <Element> joinElemList = new FilteredElementCollector(doc).WherePasses(sdFilter).ToElements(); Transaction transJoin = new Transaction(doc, "连接"); transJoin.Start(); foreach (Element e in joinElemList) { //排除掉自己本身 if (e.Id.IntegerValue == wal.Id.IntegerValue) { continue; } //是板梁柱的话 if (e is Floor || e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralFraming || e.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns) { SubTransaction subTrans = new SubTransaction(doc); subTrans.Start(); if (JoinGeometryUtils.AreElementsJoined(doc, e, wal) == false) { JoinGeometryUtils.JoinGeometry(doc, e, wal); } subTrans.Commit(); if (JoinGeometryUtils.IsCuttingElementInJoin(doc, e, wal) == false) { JoinGeometryUtils.SwitchJoinOrder(doc, e, wal); } } } transJoin.Commit(); } }
public JoinedGeometryCtrl(List <Element> _elems) { this.elements = _elems; var count = _elems.Count; var doc = _elems.First().Document; for (int i = 0; i < count - 1; i++) { var e1 = _elems[i]; for (int j = i + 1; j < count; j++) { var e2 = _elems[j]; if (JoinGeometryUtils.AreElementsJoined(doc, e1, e2)) { if (joinMap.ContainsKey(e1.Id) == false) { joinMap[e1.Id] = new List <ElementId>() { e2.Id }; } else { joinMap[e1.Id].Add(e2.Id); } } } } }
private void joiningLining(Document doc, Floor myCuttingFloor) { Element element = myCuttingFloor as Element; 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.WherePasses(new ElementIntersectsSolidFilter(solid)); // Apply intersection filter to find matches //TaskDialog.Show("Revit", collector.Count() + " family instances intersect with the selected element (" + element.Category.Name + " id:" + element.Id.ToString() + ")"); List <ElementId> myListInter = new List <ElementId>(); foreach (Element myE in collector) { if (myE.Id != element.Id) { myListInter.Add(myE.Id); } } // Joint try { using (Transaction trans = new Transaction(doc, "Join Floor")) { trans.Start(); foreach (ElementId myEId in myListInter) { if (!JoinGeometryUtils.AreElementsJoined(doc, doc.GetElement(myEId), element)) { JoinGeometryUtils.JoinGeometry(doc, doc.GetElement(myEId), element); //JoinGeometryUtils.UnjoinGeometry(doc, doc.GetElement(myEId), element); } } trans.Commit(); } } catch (Exception e) { TaskDialog.Show("Error", e.Message); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { //Get UIdocument UIDocument uidoc = commandData.Application.ActiveUIDocument; //Get Document Document doc = uidoc.Document; try { //Get elements of Category var eles = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralColumns) .WhereElementIsNotElementType() .ToElements(); using (var tran = new Transaction(doc, "Calculator Formwork Area for Element")) { tran.Start(); foreach (var ele in eles) { //Get BoundingBox from Element BoundingBoxXYZ boundingBox = ele.get_BoundingBox(null); //Get Outline Outline outline = new Outline(boundingBox.Min, boundingBox.Max); BoundingBoxIntersectsFilter filter = new BoundingBoxIntersectsFilter(outline); //BoundingBoxIntersectsFilter invertFilter = new BoundingBoxIntersectsFilter(outline,true); var eleIntersect = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .WherePasses(filter) .ToElements(); foreach (var item in eleIntersect) { var joined = JoinGeometryUtils.AreElementsJoined(doc, ele, item); if (joined == true) { JoinGeometryUtils.UnjoinGeometry(doc, ele, item); //JoinGeometryUtils.JoinGeometry(doc, ele, item); //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item); } JoinGeometryUtils.JoinGeometry(doc, ele, item); //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item); } } tran.Commit(); } return(Result.Succeeded); } catch (Exception exception) { message = exception.Message; return(Result.Failed); } }
/// <summary> /// 返回被剪切的梁集合 /// </summary> /// <param name="beamList">梁集合</param> /// /// <param name="doc">项目文档</param> public static List <FamilyInstance> JoinBeamToBeam(List <FamilyInstance> beamList, Document doc) { using (Transaction trans = new Transaction(doc, "梁连接")) { //存储被剪切(包含即剪切其它梁又被其他梁剪切)的梁实例 List <FamilyInstance> joinBeamList = new List <FamilyInstance>(); //存储已经与其它构件处理过连接关系的构件 List <FamilyInstance> hasJoinBeamList = new List <FamilyInstance>(); //遍历梁的集合 foreach (FamilyInstance fi1 in beamList) { trans.Start(); foreach (FamilyInstance fi2 in beamList) { //排除已经处理过连接关系的构件 if (hasJoinBeamList.Count != 0 && hasJoinBeamList.Where(m => m.Id.IntegerValue == fi2.Id.IntegerValue).Count() != 0) { continue; } //排除构件本身 if (fi2.Id.IntegerValue == fi1.Id.IntegerValue) { continue; } //比较构件高低 double h1 = fi1.Symbol.LookupParameter("h").AsDouble() * 304.8; double h2 = fi2.Symbol.LookupParameter("h").AsDouble() * 304.8; FamilyInstance f1 = h1 >= h2 ? fi1 : fi2; FamilyInstance f2 = h1 >= h2 ? fi2 : fi1; if (JoinGeometryUtils.AreElementsJoined(doc, f1, f2)) { bool b = JoinGeometryUtils.IsCuttingElementInJoin(doc, f1, f2); //梁高大剪切梁高小的 if (b == false) { SubTransaction sbTrans = new SubTransaction(doc); sbTrans.Start(); JoinGeometryUtils.SwitchJoinOrder(doc, f1, f2); sbTrans.Commit(); } if (joinBeamList.Count == 0 || joinBeamList.Where(m => m.Id.IntegerValue == f2.Id.IntegerValue).Count() == 0) { joinBeamList.Add(f2); } } } hasJoinBeamList.Add(fi1); trans.Commit(); } return(joinBeamList); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Application app = commandData.Application.Application; UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; ICollection<ElementId> elementIds = new List<ElementId>(); if (uidoc.Selection.GetElementIds().Count>0) { elementIds = uidoc.Selection.GetElementIds(); } else { try { elementIds = uidoc.Selection.PickObjects(ObjectType.Element, new FloorSelectFilter(), "Pick floors").Select(q => q.ElementId).ToList(); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { message = "Command cancelled, Click finish in top left corner to complete the command"; return Result.Cancelled; } } using (Transaction t1 = new Transaction(doc, "Switch join order")) { t1.Start(); foreach(ElementId floorId in elementIds) { Floor floor = doc.GetElement(floorId) as Floor; BoundingBoxXYZ boundingBox = floor.get_BoundingBox(doc.ActiveView); BoundingBoxIntersectsFilter bbFilter = new BoundingBoxIntersectsFilter(new Outline(boundingBox.Min, boundingBox.Max)); FilteredElementCollector columnCollector = new FilteredElementCollector(doc, doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_StructuralColumns).WherePasses(bbFilter); foreach (Element column in columnCollector) { if (JoinGeometryUtils.AreElementsJoined(doc, floor, column)) { if(JoinGeometryUtils.IsCuttingElementInJoin(doc, floor, column)) { JoinGeometryUtils.SwitchJoinOrder(doc, floor, column); } } } } t1.Commit(); } return Result.Succeeded; }
public static void joinGeoByTwoCategories(Document doc, BuiltInCategory firstCategory, BuiltInCategory secondCategory) { FilteredElementCollector coll = new FilteredElementCollector(doc); // 篩選條件牆的篩選器 ElementCategoryFilter filterFirstCategory = new ElementCategoryFilter(firstCategory); IList <Element> FirstCategoryElements = coll.WherePasses(filterFirstCategory) .WhereElementIsNotElementType().ToElements(); //因為元件接合要做寫入改動,因此要將它放入交易 //針對所有元件作自動接合 foreach (Element firstElement in FirstCategoryElements) { BoundingBoxXYZ bbx = firstElement.get_BoundingBox(null); //從第一元件取得「邊界長方體」(包覆元件邊界的長方體,如果元件本身是長方體,就會完全包覆) //OutLine是一條線,此處等於直接拿包覆長方體的對角線來定義它 Outline outline = new Outline(bbx.Min, bbx.Max);//Min及Max各是一個點,都能存取XYZ座標 BoundingBoxIntersectsFilter filterIntersection = new BoundingBoxIntersectsFilter(outline); //這個過濾器會取得「所有和這個BoundingBox相交的BoundingBox,並且傳回其所代表之元件」 ElementCategoryFilter filterSecondCategory = new ElementCategoryFilter(secondCategory); //然後在相交元件當中,我只想先處理第一類別與第二類別的相交,所以需要再一個篩選器 LogicalAndFilter andfilter = new LogicalAndFilter(filterIntersection, filterSecondCategory); //用交集篩選器將它們組合起來 IList <Element> adjacents = new FilteredElementCollector(doc).WherePasses(andfilter). WhereElementIsNotElementType().ToElements(); //以上一行選取所有和第一元件相鄰,而且屬於第二類別的元件,把整個doc放進Collector後再濾出通過篩選器的元件 foreach (Element secondElement in adjacents) { //MessageBox.Show(secondElement.Id + "\n" + secondElement.Category.Name); //debug Transaction trans = new Transaction(doc); try { trans.Start("join"); //開始交易(接合) if (JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement) == true) //如果兩個元件已接合 { JoinGeometryUtils.UnjoinGeometry(doc, firstElement, secondElement); //先解除接合,因為我假設它不是我要的結果 } //以上那個動作有點近似我們在Revit裡頭除了「接合」、「取消接合」以外,也可以「改變接合順序」 JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); //再重新接合,但原本就處於未接合的元件也會被接合 } catch (Exception ex) { //MessageBox.Show(ex.ToString()); } finally //這裡刻意讓finally陳述句登場,只是強調無論如何都要做交易的commit { trans.Commit(); } } //end inner foreach } //end outer foreach } //end fun
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); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication application = commandData.get_Application(); Document document = application.get_ActiveUIDocument().get_Document(); Selection selection = application.get_ActiveUIDocument().get_Selection(); ICollection <ElementId> elementIds = selection.GetElementIds(); if (elementIds.Count != 0) { List <Element> list = Method.GeometryFilter(document, elementIds); int num = 0; if (list.Count > 1) { Combinations <Element> combinations = new Combinations <Element>(list, 2, GenerateOption.WithoutRepetition); Transaction val = new Transaction(document); val.Start("Merger Element"); FailureHandlingOptions failureHandlingOptions = val.GetFailureHandlingOptions(); MyFailuresPreProcessor myFailuresPreProcessor = new MyFailuresPreProcessor(); failureHandlingOptions.SetFailuresPreprocessor(myFailuresPreProcessor); val.SetFailureHandlingOptions(failureHandlingOptions); foreach (List <Element> item in combinations) { if (!JoinGeometryUtils.AreElementsJoined(document, item[0], item[1])) { try { JoinGeometryUtils.JoinGeometry(document, item[0], item[1]); num++; } catch { } } } MessageBox.Show(num.ToString() + " Pairs Elements Successfully Join.", "ElementMerger"); val.Commit(); } else if (list.Count == 1) { TaskDialog.Show("ElementMerger", "Only One Element Selected"); } } else { TaskDialog.Show("ElementMerger", "None Element Selected"); } return(0); }
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; // code try { FilteredElementCollector collectorColums = new FilteredElementCollector(doc); List <Element> listColumns = collectorColums.OfCategory(BuiltInCategory.OST_StructuralColumns) .WhereElementIsNotElementType().ToElements().ToList(); FilteredElementCollector collectorBeams = new FilteredElementCollector(doc); List <Element> listBeams = collectorBeams.OfCategory(BuiltInCategory.OST_StructuralFraming) .WhereElementIsNotElementType().ToElements().ToList(); Transaction tran = new Transaction(doc); tran.Start("Switch Beam PRT Column"); int count = 0; foreach (Element column in listColumns) { foreach (Element beam in listBeams) { if (JoinGeometryUtils.AreElementsJoined(doc, column, beam)) { if (!JoinGeometryUtils.IsCuttingElementInJoin(doc, beam, column)) { JoinGeometryUtils.SwitchJoinOrder(doc, beam, column); count++; } } } } tran.Commit(); MessageBox.Show($"Auto switch {count} pairs of beam column done!"); } catch (Exception ex) { } return(Result.Succeeded); }
public void CanUnjoinListOfElements() { var wall1 = ElementSelector.ByElementId(184176, true); var wall2 = ElementSelector.ByElementId(207960, true); var floor = ElementSelector.ByElementId(208259, true); var doc = DocumentManager.Instance.CurrentDBDocument; // Are joined bool originalWall1AndWall2JoinedValue = JoinGeometryUtils.AreElementsJoined(doc, wall1.InternalElement, wall2.InternalElement); Assert.AreEqual(true, originalWall1AndWall2JoinedValue); // Are joined bool originalWall1AndFloorJoinedValue = JoinGeometryUtils.AreElementsJoined(doc, wall1.InternalElement, floor.InternalElement); Assert.AreEqual(true, originalWall1AndFloorJoinedValue); // Are not joined bool originalWall2AndFloorJoinedValue = JoinGeometryUtils.AreElementsJoined(doc, wall2.InternalElement, floor.InternalElement); Assert.AreEqual(false, originalWall2AndFloorJoinedValue); var elementList = new List <Element>() { wall1, wall2, floor }; Element.UnjoinAllGeometry(elementList); bool newWall1AndWall2JoinedValue = wall1.AreJoined(wall2); bool newWall1AndFloorJoinedValue = wall1.AreJoined(floor); bool newWall2AndFloorJoinedValue = wall2.AreJoined(floor); // Are joined should have changed Assert.AreNotEqual(newWall1AndWall2JoinedValue, originalWall1AndWall2JoinedValue); // Are joined should have changed Assert.AreNotEqual(newWall1AndFloorJoinedValue, originalWall1AndFloorJoinedValue); // Are joined should be the same Assert.AreEqual(newWall2AndFloorJoinedValue, originalWall2AndFloorJoinedValue); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uidoc = commandData.Application.ActiveUIDocument; var doc = uidoc.Document; var eles = new FilteredElementCollector(doc).OfCategory((BuiltInCategory.OST_StructuralColumns)) .WhereElementIsNotElementType() .ToElements(); using (var tran = new Transaction(doc, "Join Floor and Column")) { tran.Start(); foreach (var ele in eles) { var boundingBox = ele.get_BoundingBox(null); var outline = new Outline(boundingBox.Min, boundingBox.Max); var filter = new BoundingBoxIntersectsFilter(outline); var collectors = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsNotElementType() .WherePasses(filter) .ToElements(); foreach (var item in collectors) { //Options options = new Options(); //options.ComputeReferences = true; //options.DetailLevel = ViewDetailLevel.Fine; //GeometryElement geoElement = item.get_Geometry(options); bool joined = JoinGeometryUtils.AreElementsJoined(doc, ele, item); if (joined == true) { JoinGeometryUtils.UnjoinGeometry(doc, ele, item); } JoinGeometryUtils.JoinGeometry(doc, ele, item); //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item); } } tran.Commit(); } return(Result.Succeeded); }
public static void FixInstanceFaceProblem(Element _host) { var doc = _host.Document; var anyWall = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfClass(typeof(Wall)) .FirstOrDefault(x => ((Wall)x).WallType.Kind == WallKind.Basic && x.SameDesignOption(_host)); if (anyWall == null) { return; } else if (JoinGeometryUtils.AreElementsJoined(doc, _host, anyWall) == false) { try { JoinGeometryUtils.JoinGeometry(doc, anyWall, _host); JoinGeometryUtils.UnjoinGeometry(doc, anyWall, _host); } catch { } } }
//---------------------------------------------------------- public void Join_Element(Document doc, Element element) { try { BoundingBoxXYZ bb = element.get_BoundingBox(doc.ActiveView); Outline outline = new Outline(bb.Min, bb.Max); BoundingBoxIntersectsFilter bbfilter = new BoundingBoxIntersectsFilter(outline); FilteredElementCollector collectors = new FilteredElementCollector(doc, doc.ActiveView.Id); ICollection <ElementId> idsExclude = new List <ElementId>(); idsExclude.Add(element.Id); var collector = collectors.Excluding(idsExclude).WherePasses(bbfilter).ToElements(); foreach (Element ele in collector) { if (JoinGeometryUtils.AreElementsJoined(doc, element, ele) == false && ele.Category.AllowsBoundParameters == true && ele.Category.CategoryType.ToString() == "Model") { JoinGeometryUtils.JoinGeometry(doc, element, ele); } } } catch (Exception ex) { //MessageBox.Show(ex.Message); } }
public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI. ExternalCommandData commandData, ref string message, ElementSet elements) { Tracer.Listeners.Add(new System.Diagnostics.EventLogTraceListener("Application")); Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; try { // Set the minimum wall width double minWallWidth = UnitUtils .ConvertToInternalUnits(400, DisplayUnitType.DUT_MILLIMETERS); // 400mm // Select all walls wider than 400 mm ElementParameterFilter widthFilter = new ElementParameterFilter(ParameterFilterRuleFactory .CreateGreaterOrEqualRule(new ElementId(BuiltInParameter.WALL_ATTR_WIDTH_PARAM), minWallWidth, 0.1)); IList <Wall> walls = new FilteredElementCollector(doc) .OfClass(typeof(Wall)) .WhereElementIsNotElementType() .WherePasses(widthFilter) .Cast <Wall>() .ToList(); Tracer.Write("The number of walls in the project: " + walls.Count); using (Transaction t = new Transaction(doc, "Join walls")) { FailureHandlingOptions handlingOptions = t.GetFailureHandlingOptions(); handlingOptions.SetFailuresPreprocessor(new AllWarningSwallower()); t.SetFailureHandlingOptions(handlingOptions); t.Start(); foreach (Wall wall in walls) { IList <Element> intrudingWalls = GetWallsIntersectBoundingBox(doc, wall, minWallWidth); Tracer.Write(string.Format("Wall {0} is intersected by {1} walls", wall.Id.ToString(), intrudingWalls.Count)); foreach (Element elem in intrudingWalls) { if (//((Wall)elem).WallType.Width < minWallWidth || ((Wall)elem).WallType.Kind == WallKind.Curtain) { continue; } try { if (!JoinGeometryUtils.AreElementsJoined(doc, wall, elem)) { JoinGeometryUtils.JoinGeometry(doc, wall, elem); } } catch (Exception ex) { Tracer.Write(string.Format("{0}\nWall: {1} cannot be joined to {2}", ex.Message, wall.Id.ToString(), elem.Id.ToString())); continue; } } } t.Commit(); } return(Autodesk.Revit.UI.Result.Succeeded); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { return(Autodesk.Revit.UI.Result.Cancelled); } catch (Exception ex) { Tracer.Write(string.Format("{0}\n{1}", ex.Message, ex.StackTrace)); return(Autodesk.Revit.UI.Result.Failed); } }
/// <summary> /// 处理碰撞 /// </summary> /// <param name="doc"></param> /// <param name="hostELemID"></param> /// <param name="sd"></param> /// <returns></returns> public static Solid SolidHandle(Document doc, ElementId hostELemID, Solid sd) { //TODO:这里是取得该物体是否剪切别的物体 Element hostElem = doc.GetElement(hostELemID); //碰撞集合 List <Element> elembeCutList = JoinGeometryUtils.GetJoinedElements(doc, hostElem).Where(m => { if (JoinGeometryUtils.AreElementsJoined(doc, doc.GetElement(m), hostElem)) { //if (JoinGeometryUtils.IsCuttingElementInJoin(doc, hostElem, doc.GetElement(m))) //{ return(true); //} } return(false); }).ToList().ConvertAll(m => doc.GetElement(m)); //对于与梁进行碰撞的Solid的处理 if (hostElem.Category.Id == new ElementId(BuiltInCategory.OST_StructuralFraming)) { try { elembeCutList = elembeCutList.Where(m => m.Category .Id == new ElementId(BuiltInCategory.OST_StructuralFraming) || m.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns).ToList(); } catch { SWF.MessageBox.Show(hostELemID + ""); } } else if (hostElem is Floor) { elembeCutList = elembeCutList.Where(m => m.Category.Id == new ElementId(BuiltInCategory.OST_StructuralFraming) || m.Category.Id == new ElementId(BuiltInCategory.OST_StructuralColumns) || m.Category.Id == new ElementId(BuiltInCategory.OST_Walls)) .ToList(); } else if (hostElem.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns) { elembeCutList = elembeCutList.Where(m => m is Wall && m.Name.Contains("DW")).ToList(); } else if (hostElem is Wall) { Curve walCurve = (hostElem.Location as LocationCurve).Curve; XYZ startPoint = walCurve.GetEndPoint(0); XYZ endPoint = walCurve.GetEndPoint(1); startPoint = new XYZ(startPoint.X, startPoint.Y, 0); endPoint = new XYZ(endPoint.X, endPoint.Y, 0); List <Element> walElemList = bc.FilterElementList <Wall>(doc).Where(m => { if (hostElem.Id == m.Id) { return(false); } if (!hostElem.Name.Contains("DW")) { return(false); } if (hostElem.LevelId != m.LevelId) { return(false); } Curve mc = (m.Location as LocationCurve).Curve; XYZ sp = mc.GetEndPoint(0); XYZ ep = mc.GetEndPoint(1); sp = new XYZ(sp.X, sp.Y, 0); ep = new XYZ(ep.X, ep.Y, 0); if (sp.IsAlmostEqualTo(startPoint) || sp.IsAlmostEqualTo(endPoint) || ep.IsAlmostEqualTo(endPoint) || ep.IsAlmostEqualTo(startPoint)) { return(true); } return(false); }).ToList(); elembeCutList = elembeCutList.Where(m => m.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralColumns || (m is Wall && m.Name.Contains("DW"))).ToList(); elembeCutList.AddRange(walElemList); } Solid lastSolid = sd; foreach (Element e in elembeCutList) { Solid sdcut = AllSolid_Of_Element(e)[0]; try { lastSolid = BooleanOperationsUtils.ExecuteBooleanOperation(lastSolid, sdcut, BooleanOperationsType.Difference); }//可能由于几何体太过复杂导致Bool失败 catch { } } return(lastSolid); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; Selection sel = commandData.Application.ActiveUIDocument.Selection; if (sel.GetElementIds().Count != 1) { message = "Выберите одну стену"; return(Result.Failed); } Wall wall = doc.GetElement(sel.GetElementIds().First()) as Wall; if (wall == null) { message = "Выберите стену"; return(Result.Failed); } List <FamilyInstance> holesInWall = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_GenericModel) .OfClass(typeof(FamilyInstance)) .Cast <FamilyInstance>() .Where(i => i.Symbol.FamilyName.StartsWith("231")) .Where(i => JoinGeometryUtils.AreElementsJoined(doc, wall, i)) .ToList(); List <FamilyInstance> doorsInWall = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_Windows) .OfClass(typeof(FamilyInstance)) .Cast <FamilyInstance>() .Where(i => i.Symbol.FamilyName.StartsWith("231")) .Where(i => i.Host.Id == wall.Id) .ToList(); using (Transaction t = new Transaction(doc)) { t.Start("Отсоединяю отверстия"); //Отсоединяю отверстия foreach (FamilyInstance hole in holesInWall) { JoinGeometryUtils.UnjoinGeometry(doc, wall, hole); } doc.Regenerate(); if (doorsInWall.Count > 0) //есть дверь или проем в стене, меняю её размеры { FamilyInstance door = doorsInWall.First(); //меняю размер двери Parameter widthParam = door.LookupParameter("Рзм.Ширина"); double width = widthParam.AsDouble(); double width2 = width + 0.01; widthParam.Set(width2); doc.Regenerate(); widthParam.Set(width); } else //нет двери, значит меняю высоту стены { Parameter offsetParam = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET); double baseOffset = offsetParam.AsDouble(); double baseOffset2 = baseOffset - 0.01; offsetParam.Set(baseOffset2); doc.Regenerate(); offsetParam.Set(baseOffset); } doc.Regenerate(); //присоединяю отверстия обратно foreach (FamilyInstance hole in holesInWall) { JoinGeometryUtils.JoinGeometry(doc, hole, wall); } t.Commit(); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Debug.Listeners.Clear(); Debug.Listeners.Add(new RbsLogger.Logger("JoinByOrder")); Document doc = commandData.Application.ActiveUIDocument.Document; Selection sel = commandData.Application.ActiveUIDocument.Selection; ICollection <ElementId> ids = sel.GetElementIds(); if (ids.Count == 0) { message = "Выберите элементы для соединения"; return(Result.Failed); } if (ids.Count > 100) { TaskDialog dialog = new TaskDialog("Предупреждение"); dialog.MainInstruction = "Выделено большое количество элементов (" + ids.Count.ToString() + "), их соединение может привести к снижение быстродействия модели. Продолжить?"; dialog.CommonButtons = TaskDialogCommonButtons.Ok | TaskDialogCommonButtons.Cancel; if (dialog.Show() != TaskDialogResult.Ok) { return(Result.Cancelled); } } List <Element> elems = new List <Element>(); foreach (ElementId id in ids) { Element elem = doc.GetElement(id); elems.Add(elem); } List <MyCategory> uniqCats = elems .Select(i => (BuiltInCategory)i.Category.Id.IntegerValue) .Distinct() .Select(i => new MyCategory(doc, i)) .ToList(); FormSetJoinOrder form = new FormSetJoinOrder(uniqCats); if (form.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return(Result.Cancelled); } Dictionary <BuiltInCategory, int> categoriesPriority = form.Cats.ToDictionary(i => i._category, j => j.priority); int counter = 0; using (Transaction t = new Transaction(doc)) { t.Start("Соединение " + elems.Count.ToString() + " элементов"); foreach (Element elem1 in elems) { foreach (Element elem2 in elems) { if (elem2.Equals(elem1)) { continue; } bool alreadyJoined = JoinGeometryUtils.AreElementsJoined(doc, elem1, elem2); bool isIntersects = Intersection.CheckElementsIsIntersect(doc, elem1, elem2); if (!isIntersects && !alreadyJoined) { continue; } try { JoinGeometryUtils.JoinGeometry(doc, elem1, elem2); } catch { } bool isElemJoined = JoinGeometryUtils.AreElementsJoined(doc, elem1, elem2); if (!isElemJoined) { continue; } bool isFirstElemMain = JoinGeometryUtils.IsCuttingElementInJoin(doc, elem1, elem2); int firstElemPriority = categoriesPriority[(BuiltInCategory)elem1.Category.Id.IntegerValue]; int secondElemPriority = categoriesPriority[(BuiltInCategory)elem2.Category.Id.IntegerValue]; if (isFirstElemMain && firstElemPriority > secondElemPriority) { JoinGeometryUtils.SwitchJoinOrder(doc, elem1, elem2); counter++; } } } doc.Regenerate(); t.Commit(); } if (counter == 0) { message = "Все соединения уже соответствуют заданному приоритету"; return(Result.Cancelled); } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Debug.Listeners.Clear(); Debug.Listeners.Add(new RbsLogger.Logger("AutoJoin")); UIApplication uiApp = commandData.Application; Document doc = commandData.Application.ActiveUIDocument.Document; Autodesk.Revit.ApplicationServices.Application app = commandData.Application.Application; //Выбрать элементы для соединения Selection sel = commandData.Application.ActiveUIDocument.Selection; ICollection <ElementId> ids = sel.GetElementIds(); Debug.WriteLine("Selected elems: " + ids.Count.ToString()); if (ids.Count == 0) { message = "Выберите элементы для соединения"; return(Result.Failed); } List <Element> elems = new List <Element>(); foreach (ElementId id in ids) { Element elem = doc.GetElement(id); elems.Add(elem); } bool isExecute = false; //каждый элемент в списке соединить с каждым элементом из списка using (Transaction t = new Transaction(doc)) { t.Start("Соединение " + elems.Count.ToString() + " элементов"); foreach (Element elem1 in elems) { Debug.WriteLine("Join elem id " + elem1.Id.IntegerValue.ToString() + " with... "); foreach (Element elem2 in elems) { //если этот тот же элемент - пропустить if (elem2.Equals(elem1)) { continue; } Debug.WriteLine(" id " + elem2.Id.IntegerValue.ToString()); //если элементы уже ранее соединены - пропустить bool alreadyJoined = JoinGeometryUtils.AreElementsJoined(doc, elem1, elem2); if (alreadyJoined) { Debug.WriteLine("Elements are already joined"); continue; } //проверить, пересекаются ли элементы, если не пересекаются - пропустить bool isIntersects = Intersection.CheckElementsIsIntersect(doc, elem1, elem2); if (!isIntersects) { Debug.WriteLine("Elements dont have intersection"); continue; } //соединить элементы try { JoinGeometryUtils.JoinGeometry(doc, elem1, elem2); isExecute = true; Debug.WriteLine("Joined succesfully!"); } catch (Exception ex) { Debug.WriteLine("Exception: " + ex.Message); } } } t.Commit(); } if (!isExecute) { message = "Элементы не имеют пересечений или уже соединены"; return(Result.Cancelled); } Debug.WriteLine("AutoJoin success"); return(Result.Succeeded); }
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); }
public void Test() { UIDocument uidoc = this.ActiveUIDocument; Document doc = uidoc.Document; // 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 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.WherePasses(new ElementIntersectsSolidFilter(solid)); // Apply intersection filter to find matches //TaskDialog.Show("Revit", collector.Count() + " family instances intersect with the selected element (" + element.Category.Name + " id:" + element.Id.ToString() + ")"); List <ElementId> myListInter = new List <ElementId>(); foreach (Element myE in collector) { if (myE.Id != element.Id) { myListInter.Add(myE.Id); } } // uidoc.Selection.SetElementIds(myListInter); // Joint try { using (Transaction trans = new Transaction(doc, "Join Floor")) { trans.Start(); foreach (ElementId myEId in myListInter) { if (!JoinGeometryUtils.AreElementsJoined(doc, doc.GetElement(myEId), element)) { JoinGeometryUtils.JoinGeometry(doc, doc.GetElement(myEId), element); //JoinGeometryUtils.UnjoinGeometry(doc, doc.GetElement(myEId), element); } } trans.Commit(); } } catch (Exception) { throw; } }
private void Button1_Click(object sender, EventArgs e) { //Code here string comboA = comboBox1.SelectedItem.ToString(); string comboB = comboBox2.SelectedItem.ToString(); if (comboA == comboB) { MessageBox.Show("Please select diffirent combo above"); return; } bool checkJoin = radioButton1.Checked; bool checkUnJoin = radioButton2.Checked; bool checkSwitchJoin = radioButton3.Checked; // Get data for combo A,B List <Element> listA = new List <Element>(); List <Element> listB = new List <Element>(); FilteredElementCollector collectorA = new FilteredElementCollector(doc); switch (comboA) { case "Beam": listA = collectorA.OfCategory(BuiltInCategory.OST_StructuralFraming) .WhereElementIsNotElementType().ToElements().ToList(); break; case "Column": listA = collectorA.OfCategory(BuiltInCategory.OST_StructuralColumns) .WhereElementIsNotElementType().ToElements().ToList(); break; case "Deck": listA = collectorA.OfCategory(BuiltInCategory.OST_Floors) .WhereElementIsNotElementType().ToElements().ToList(); break; } FilteredElementCollector collectorB = new FilteredElementCollector(doc); switch (comboB) { case "Beam": listB = collectorB.OfCategory(BuiltInCategory.OST_StructuralFraming) .WhereElementIsNotElementType().ToElements().ToList(); break; case "Column": listB = collectorB.OfCategory(BuiltInCategory.OST_StructuralColumns) .WhereElementIsNotElementType().ToElements().ToList(); break; case "Deck": listB = collectorB.OfCategory(BuiltInCategory.OST_Floors) .WhereElementIsNotElementType().ToElements().ToList(); break; } if (checkJoin) { Transaction tran = new Transaction(doc); tran.Start($"Auto Join {comboA} to {comboB}"); int count = 0; foreach (Element a in listA) { foreach (Element b in listB) { try { JoinGeometryUtils.JoinGeometry(doc, a, b); count++; } catch (Exception ex) { } } } tran.Commit(); MessageBox.Show($"Auto join {count} pairs of {comboA} {comboB} done!"); } else if (checkUnJoin) { Transaction tran = new Transaction(doc); tran.Start($"Auto UnJoin {comboA} to {comboB}"); int count = 0; foreach (Element a in listA) { foreach (Element b in listB) { try { JoinGeometryUtils.UnjoinGeometry(doc, a, b); count++; } catch (Exception ex) { } } } tran.Commit(); MessageBox.Show($"Auto Unjoin {count} pairs of {comboA} {comboB} done!"); } else if (checkSwitchJoin) { Transaction tran = new Transaction(doc); tran.Start("Switch Beam PRT Column"); int count = 0; foreach (Element a in listA) { foreach (Element b in listB) { if (JoinGeometryUtils.AreElementsJoined(doc, a, b)) { if (!JoinGeometryUtils.IsCuttingElementInJoin(doc, a, b)) { JoinGeometryUtils.SwitchJoinOrder(doc, a, b); count++; } else { JoinGeometryUtils.SwitchJoinOrder(doc, b, a); count++; } } } } tran.Commit(); MessageBox.Show($"Auto switch {count} pairs of {comboA} {comboB} done!"); } else { MessageBox.Show("Please select mode before run."); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { try { Document doc = commandData.Application.ActiveUIDocument.Document; List <FailureMessage> messages = doc.GetWarnings().ToList(); Dictionary <int, List <ElementId> > elemsDictToUnjoin = new Dictionary <int, List <ElementId> >(); int indexUnjoin = 0; foreach (FailureMessage mess in messages) { String description = mess.GetDescriptionText(); if (description.Contains("Выделенные элементы объединены, но они не пересекаются")) { indexUnjoin++; List <ElementId> failingElems = mess.GetFailingElements().ToList(); elemsDictToUnjoin.Add(indexUnjoin, failingElems); } } int max = elemsDictToUnjoin.Keys.Count(); string format = "{0} из " + max.ToString() + " элементов обработано"; using (Progress_Single pb = new Progress_Single("Отсоединение элементов", format, max)) { using (Transaction t = new Transaction(doc)) { t.Start("Отсоединение элементов"); int counterUnj = 0; int faultCounterUnj = 0; Print("Начинаю отсоединение элементов. Может занять продолжительное время ↑", KPLN_Loader.Preferences.MessageType.Header); foreach (int key in elemsDictToUnjoin.Keys) { pb.Increment(); List <ElementId> unjElems = elemsDictToUnjoin[key]; Element elem1 = doc.GetElement(unjElems[0]); Element elem2 = doc.GetElement(unjElems[1]); if (JoinGeometryUtils.AreElementsJoined(doc, elem1, elem2)) { try { JoinGeometryUtils.UnjoinGeometry(doc, elem1, elem2); doc.Regenerate(); } catch (Exception e) { PrintError(e); } if (JoinGeometryUtils.AreElementsJoined(doc, elem1, elem2)) { Print(string.Format("Не удалось отсоединить элементы: {0} id:{1} и {2} id:{3}", elem1.Name, elem1.Id.IntegerValue, elem2.Name, elem2.Id.IntegerValue ), KPLN_Loader.Preferences.MessageType.System_Regular); faultCounterUnj++; } else { counterUnj++; } } } Print(string.Format("Обработано конфликтов: {0}", counterUnj), KPLN_Loader.Preferences.MessageType.System_OK); Print(string.Format("Не удалось обработать конфликтов: {0}", faultCounterUnj), KPLN_Loader.Preferences.MessageType.System_OK); t.Commit(); } } return(Result.Succeeded); } catch (Exception e) { PrintError(e, "Произошла ошибка во время запуска скрипта"); return(Result.Failed); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uidoc = commandData.Application.ActiveUIDocument; var doc = uidoc.Document; var categories = Enum.GetNames(typeof(BuiltInCategory)); var viewmodel = new AutoJoinDialogViewModel(categories.OrderBy(s => s).ToArray()); var window = new AutoJoinDialog(viewmodel); window.ShowDialog(); if (window.DialogResult == true) { Enum.TryParse(viewmodel.Category1, out BuiltInCategory category1); Enum.TryParse(viewmodel.Category2, out BuiltInCategory category2); var eles = new FilteredElementCollector(doc).OfCategory(category1) .WhereElementIsNotElementType() .ToElements(); using (var tran = new Transaction(doc, "Join Floor and Column")) { tran.Start(); foreach (var ele in eles) { var boundingBox = ele.get_BoundingBox(null); var outline = new Outline(boundingBox.Min, boundingBox.Max); var filter = new BoundingBoxIntersectsFilter(outline); var collectors = new FilteredElementCollector(doc).OfCategory(category2) .WhereElementIsNotElementType() .WherePasses(filter) .ToElements(); foreach (var item in collectors) { //Options options = new Options(); //options.ComputeReferences = true; //options.DetailLevel = ViewDetailLevel.Fine; //GeometryElement geoElement = item.get_Geometry(options); bool joined = JoinGeometryUtils.AreElementsJoined(doc, ele, item); if (joined == true) { JoinGeometryUtils.UnjoinGeometry(doc, ele, item); JoinGeometryUtils.JoinGeometry(doc, ele, item); } else { JoinGeometryUtils.JoinGeometry(doc, ele, item); } //JoinGeometryUtils.SwitchJoinOrder(doc, ele, item); } } tran.Commit(); } } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { // 柱 -> 梁 -> 版 -> 牆 String column = "結構柱"; String beam = "結構構架"; String beamsystem = "結構樑系統"; String board = "樓板"; UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; ICollection <ElementId> elemids = uidoc.Selection.GetElementIds(); MessageBox.Show("You select " + elemids.Count.ToString()); string msg = ""; Transaction trans = new Transaction(doc); foreach (ElementId fid in elemids) { Element firstElement = doc.GetElement(fid); BoundingBoxXYZ bbx = firstElement.get_BoundingBox(null); Outline outline = new Outline(bbx.Min, bbx.Max); BoundingBoxIntersectsFilter invertFilter = new BoundingBoxIntersectsFilter(outline, false); IList <Element> noIntersects = new FilteredElementCollector(doc).WherePasses(invertFilter).ToElements(); foreach (Element secondElement in noIntersects) { try { /* * string floorofirstelement = "1"; * string floorofsecondelement = "2"; * foreach(Parameter pf in firstElement.Parameters) * { * if(pf.Definition.Name == "底部約束" || pf.Definition.Name == "基準樓層" || pf.Definition.Name == "參考樓層") * { * floorofirstelement = pf.AsString(); * break; * } * } * foreach (Parameter pf in secondElement.Parameters) * { * if (pf.Definition.Name == "底部約束" || pf.Definition.Name == "基準樓層" || pf.Definition.Name == "參考樓層") * { * floorofsecondelement = pf.AsString(); * break; * } * } * if(floorofirstelement != floorofsecondelement) * { * continue; * }*/ String fn = firstElement.Category.Name; String sn = secondElement.Category.Name; msg += "<" + fn + "," + sn + ">"; trans.Start("join"); if (fn == column) { if (sn != column) { try { if (!JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement)) { JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); } } catch (Exception e) { //MessageBox.Show("1"+e.ToString()); } } } else if (fn == beam) { if (sn != beam && sn != column) { try { if (!JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement)) { JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); } } catch (Exception e) { //MessageBox.Show("2"+e.ToString()); } } } else if (fn == board) { if (sn != board && sn != column && sn != beam) { try { if (!JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement)) { JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); } } catch (Exception e) { // MessageBox.Show("3" + e.ToString()); } } } else { //MessageBox.Show(msg); } trans.Commit(); } catch (Exception e) { } } /*foreach (Element sid in noIntersects) * { * * // if (fid.IntegerValue != sid.IntegerValue) * // { * //Element secondElement = doc.GetElement(sid); * Element secondElement = sid; * String fn = firstElement.Category.Name; * String sn = secondElement.Category.Name; * trans.Start("join"); * if (fn == column) * { * if(sn != column) * try * { * if(!JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement)) * JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); * } * catch (Exception e) * { * //MessageBox.Show("1"+e.ToString()); * } * * } * else if(fn == beam) * { * if(sn != beam && sn != column) * try * { * if (!JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement)) * JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); * } * catch (Exception e) * { * MessageBox.Show(e.ToString()); * //MessageBox.Show("2"+e.ToString()); * } * } * else if(fn == board) * { * if(sn != board && sn != column && sn != beam) * try * { * if (!JoinGeometryUtils.AreElementsJoined(doc, firstElement, secondElement)) * JoinGeometryUtils.JoinGeometry(doc, firstElement, secondElement); * } * catch (Exception e) * { * // MessageBox.Show("3" + e.ToString()); * * } * * } * else * { * * } * trans.Commit(); * * //} * }*/ } return(Result.Succeeded); }
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(); } } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; var acview = doc.ActiveView; var floorTypes = doc.TCollector <FloorType>().ToList(); var selectorUI = FloorTypeSelector.Instance; selectorUI.floortypeBox.ItemsSource = floorTypes; selectorUI.floortypeBox.DisplayMemberPath = "Name"; selectorUI.floortypeBox.SelectedIndex = 0; selectorUI.ShowDialog(); var targetFloortype = selectorUI.floortypeBox.SelectedItem as FloorType; //目标楼板类型 var beamrefs = default(IList <Reference>); try { beamrefs = sel.PickObjects(ObjectType.Element, doc.GetSelectionFilter(m => m.Category.Id.IntegerValue == (int)BuiltInCategory.OST_StructuralFraming), "选择生成板的梁"); } catch (Exception e) { MessageBox.Show("用户取消了命令!"); return(Result.Cancelled); } var beams = beamrefs.Select(m => m.GetElement(doc)); //var ele = sel.PickObject(ObjectType.Element).GetElement(doc); //var solid = ele.get_Geometry(new Options()).GetSolidOfGeometryObject().First(); //var trans = Transform.Identity; //trans.Origin = new XYZ(-10, 0, 0); //doc.Invoke(m => //{ // var newsolid = SolidUtils.CreateTransformed(solid, trans); // var directshape = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); // directshape.AppendShape(new List<GeometryObject>() {newsolid}); //}, "test"); //doc.Create.NewFloor() Transaction temtran = new Transaction(doc, "temtran"); temtran.Start(); foreach (Element beam in beams) { var joinedelements = JoinGeometryUtils.GetJoinedElements(doc, beam); if (joinedelements.Count > 0) { foreach (var id in joinedelements) { var temele = id.GetElement(doc); var isjoined = JoinGeometryUtils.AreElementsJoined(doc, beam, temele); if (isjoined) { JoinGeometryUtils.UnjoinGeometry(doc, beam, temele); } } } } temtran.RollBack(); var solidss = new List <GeometryObject>();//beams.Select(m => m.Getsolids()); foreach (var element in beams) { solidss.AddRange(element.Getsolids()); } var joinedsolid = MergeSolids(solidss.Cast <Solid>().ToList()); //var upfaces = beams.Select(m => m.get_Geometry(new Options() { DetailLevel = ViewDetailLevel.Fine }).Getupfaces().First()); //MessageBox.Show(upfaces.Count().ToString()); //var solids = upfaces.Select(m => // GeometryCreationUtilities.CreateExtrusionGeometry(m.GetEdgesAsCurveLoops(), XYZ.BasisZ, 10)).ToList(); //MessageBox.Show("solids count" + solids.Count().ToString()); //var targetsolid = MergeSolids(solids); //List<GeometryObject> geoobjs = solids.Cast<GeometryObject>().ToList(); var upfaces = joinedsolid.Getupfaces(); var edgeArrays = upfaces.First().EdgeLoops.Cast <EdgeArray>().ToList(); //var curvearrays = curveloops.Select(); var curveloops = upfaces.First().GetEdgesAsCurveLoops(); var orderedcurveloops = curveloops.OrderBy(m => m.GetExactLength()).ToList(); orderedcurveloops.RemoveAt(orderedcurveloops.Count - 1); curveloops = orderedcurveloops; var curvearrays = curveloops.Select(m => m.ToCurveArray()); doc.Invoke(m => { foreach (var curvearray in curvearrays) { doc.Create.NewFloor(curvearray, false); //doc.Create.NewFloor(curvearray, false); //可指定楼板类型来创建 } }, "一键楼板"); //doc.Invoke(m => //{ // var directshape = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); // //directshape.AppendShape(new List<GeometryObject>(){targetsolid}); // //directshape.AppendShape(solidss); // directshape.AppendShape(new List<GeometryObject>() { joinedsolid }); //}, "temsolid"); return(Result.Succeeded); }
//---// private void button1_Click(object sender, EventArgs e) { //code here string chooseA = comboBoxA.SelectedItem.ToString(); string chooseB = comboBoxB.SelectedItem.ToString(); List <Element> listA = GetElementByKey(chooseA); List <Element> listB = GetElementByKey(chooseB); //Code if (AutoJoin.Checked) { //join try { Transaction tran = new Transaction(doc); tran.Start($"Join {chooseA} to {chooseB}"); int count = 0; foreach (Element a in listA) { foreach (Element b in listB) { try { JoinGeometryUtils.JoinGeometry(doc, a, b); count++; } catch (Exception exx) { } } } tran.Commit(); MessageBox.Show($"Auto Join {count} pairs of {chooseA} {chooseB} done!"); } catch (Exception ex) { } } else if (AutoUnJoin.Checked) { //Unjoin try { Transaction tran = new Transaction(doc); tran.Start($"UnJoin {chooseA} to {chooseB}"); int count = 0; foreach (Element a in listA) { foreach (Element b in listB) { try { JoinGeometryUtils.UnjoinGeometry(doc, a, b); count++; } catch (Exception exx) { } } } tran.Commit(); MessageBox.Show($"Auto UnJoin {count} pairs of {chooseA} {chooseB} done!"); } catch (Exception ex) { } } else if (SwitchJoin.Checked) { // Switch join try { Transaction tran = new Transaction(doc); tran.Start($"Switch {chooseA} PRT {chooseB}"); int count = 0; foreach (Element a in listA) { foreach (Element b in listB) { if (JoinGeometryUtils.AreElementsJoined(doc, a, b)) { if (!JoinGeometryUtils.IsCuttingElementInJoin(doc, b, a)) { JoinGeometryUtils.SwitchJoinOrder(doc, b, a); count++; } } } } tran.Commit(); MessageBox.Show($"Auto switchjoin {count} pairs of {chooseA} {chooseB} done!"); } catch (Exception ex) { } } else { MessageBox.Show("Please choose one option!"); } Close(); }