public static ElementId CreateJoinedWall(Document doc, ElementId wallId, FamilyInstance familyInstance) { //create a line to represent the wall center line var line = Line.CreateBound(XYZ.Zero, XYZ.BasisX); //find first level var collector = new FilteredElementCollector(doc); var filter = new ElementClassFilter(typeof(Level)); var level = collector.WherePasses(filter).FirstElement() as Level; //create wall var wall = Wall.Create(doc, line, level.Id, false); //save the id so we can delete the wall later wallId = wall.Id; //if the selected element var subIds = familyInstance.GetSubComponentIds(); if (subIds.Count > 0) { foreach (var id in subIds) { var subelement = doc.GetElement(id); JoinGeometryUtils.JoinGeometry(doc, wall, subelement); } } else { JoinGeometryUtils.JoinGeometry(doc, wall, familyInstance); } return(wallId); }
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(); } }
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); } }
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); }
private void CreateParapetWall(CurveArray curveArray) { foreach (Curve curve in curveArray) { XYZ curveMiddlePoint = GetCurveMiddlePoint(curve); WallType wallType = revitDB.GetWallType(Properties.Settings.Default.WallTypeName); Wall parapetWall = Wall.Create(document, curve, wallType.Id, roofLevel.Id, UnitUtils.ConvertToInternalUnits(0.8, UnitTypeId.Meters), 0, false, false); Wall wall = hb.FindWall(curveMiddlePoint, baseLevel); if (wall != null) { try { JoinGeometryUtils.JoinGeometry(document, wall, parapetWall); } catch { continue; } } } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uidoc = commandData.Application.ActiveUIDocument; var doc = uidoc.Document; var connForm = new ConnectElmFrm(uidoc); if (connForm.ShowDialog() != DialogResult.OK) { return(Result.Cancelled); } doc.AutoTransaction(() => { var combins = new CombinableElementArray(); var elms = connForm.Elms; elms.OfType <CombinableElement>().ToList().ForEach(f => combins.Append(f)); if (doc.IsFamilyDocument && combins.Size >= 2) { doc.CombineElements(combins); } else if (!doc.IsFamilyDocument && elms.Count >= 2) { elms.ForEach(f1 => elms.ForEach(f2 => { ExceptionUtil.AutoTry(() => { if (f1 == f2) { return; } if (!doc.CrossSpaceBox(f1, f2)) { return; } JoinGeometryUtils.JoinGeometry(doc, f1, f2); }); })); } }); return(Result.Succeeded); }
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 collectorDeck = new FilteredElementCollector(doc); List <Element> listDecks = collectorDeck.OfCategory(BuiltInCategory.OST_Floors) .WhereElementIsNotElementType().ToElements().ToList(); Transaction tran = new Transaction(doc); tran.Start("Join beam to deck"); int count = 0; foreach (Element deck in listDecks) { foreach (Element column in listColumns) { try { JoinGeometryUtils.JoinGeometry(doc, deck, column); count++; } catch (Exception ex) { } } } tran.Commit(); MessageBox.Show($"Auto join {count} pairs of column deck done!"); } catch (Exception ex) { } return(Result.Succeeded); }
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 { } } }
private void JoinGeometry(Document doc, Dictionary <ElementId, ElementId> skirtingDictionary) { foreach (ElementId skirtingId in skirtingDictionary.Keys) { Wall skirtingWall = doc.GetElement(skirtingId) as Wall; if (skirtingWall != null) { Parameter wallJustification = skirtingWall.get_Parameter(BuiltInParameter.WALL_KEY_REF_PARAM); wallJustification.Set(3); Wall baseWall = doc.GetElement(skirtingDictionary[skirtingId]) as Wall; if (baseWall != null) { JoinGeometryUtils.JoinGeometry(doc, skirtingWall, baseWall); } } } }
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 Result Execute(ExternalCommandData revit, ref string message, ElementSet elements) { var uiapp = revit.Application; var doc = uiapp.ActiveUIDocument.Document; var uidoc = uiapp.ActiveUIDocument; var allWalls = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_Walls) .WhereElementIsNotElementType(); var allColumns = new FilteredElementCollector(doc) .OfCategory(BuiltInCategory.OST_Columns) .WhereElementIsNotElementType(); // collect the wall ids var columnIds = allColumns.ToElementIds(); // place all your actions in a single transaction for easy undo var trans = new Transaction(doc, "AutoJoinFunction"); trans.Start(); foreach (Element wall in allWalls) { var wbb = wall.get_BoundingBox(doc.ActiveView); // see https://apidocs.co/apps/revit/2020/901f78a0-1f6c-217b-ea48-8b404324e88b.htm var bboxChecker = new FilteredElementCollector(doc, columnIds) .WherePasses( new BoundingBoxIntersectsFilter( new Outline(wbb.Min, wbb.Max) ) ); foreach (Element column in bboxChecker) { JoinGeometryUtils.JoinGeometry(doc, column, wall); } } trans.Commit(); return(Result.Succeeded); }
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; View activeView = doc.ActiveView; Reference firstElement = uidoc.Selection.PickObject(ObjectType.Element, "Select First Element"); IList <Reference> selectedElements = uidoc.Selection.PickObjects(ObjectType.Element, "Select Elements to be joined"); int count = 0; using (Transaction t = new Transaction(doc, "Multiple join")) { t.Start(); foreach (Reference eleRef in selectedElements) { try { JoinGeometryUtils.JoinGeometry(doc, doc.GetElement(firstElement), doc.GetElement(eleRef)); count += 1; } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } } t.Commit(); } TaskDialog.Show("Result", String.Format("{0} have been joined", count)); return(Result.Succeeded); }
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; // get all walls on the active view FilteredElementCollector floors = new FilteredElementCollector(doc, doc.ActiveView.Id); floors.OfClass(typeof(Floor)); foreach (Floor w in floors) { // get columns on the active view FilteredElementCollector beams = new FilteredElementCollector(doc, doc.ActiveView.Id) .OfClass(typeof(FamilyInstance)) .OfCategory(BuiltInCategory.OST_StructuralFraming); // as we don't want all columns, let's filter // by the wall bounding box (intersect) BoundingBoxXYZ bb = w.get_BoundingBox(doc.ActiveView); Outline outline = new Outline(bb.Min, bb.Max); BoundingBoxIntersectsFilter bbfilter = new BoundingBoxIntersectsFilter(outline); beams.WherePasses(bbfilter); using (Transaction t = new Transaction(doc, "Join Elements")) { t.Start(); foreach (FamilyInstance b in beams) { JoinGeometryUtils.JoinGeometry(doc, w, b); } t.Commit(); } } return(Result.Succeeded); }
/// <summary> /// To connect elements on same floor. /// </summary> /// <param name="doc"></param> /// <param name="wallGroups"></param> /// <returns></returns> private static int JoinElmBySameFloor <T>(Document doc, List <IGrouping <ElementId, T> > wallGroups) where T : Element { var result = 0; foreach (var group in wallGroups) { foreach (var walli in group) { if (!(walli.Location is LocationCurve c1)) { continue; } foreach (var wallj in group) { if (!(wallj.Location is LocationCurve c2)) { continue; } if (!doc.RejectSpaceBox(walli, wallj)) { continue; } if ((c1.Curve as Line).GetSpacePosition(c2.Curve as Line, out _) != GeometryPosition.Parallel) { continue; } ExceptionUtil.AutoTry(() => { JoinGeometryUtils.JoinGeometry(doc, walli, wallj); result++; }); } } } return(result); }
//new ElementCategoryFilter(BuiltInCategory.OST_StructuralColumns), //new ElementCategoryFilter(BuiltInCategory.OST_StructuralFraming) static void JoinAllIntrudingElems(Document doc, Element elem) { IList <Element> intruders = GetWallsIntersectBoundingBox(doc, elem); Trace.Write("GetIntersetBoundingBoxElems.Count = " + intruders.Count); int loops = 0; Transaction: if (intruders.Count > 0) { using (Transaction t = new Transaction(doc, "Join all elements")) { FailureHandlingOptions failureHandling = t.GetFailureHandlingOptions(); failureHandling.SetFailuresPreprocessor(new AllWarningSwallower()); t.SetFailureHandlingOptions(failureHandling); t.Start(); foreach (Element intruder in intruders) { try { JoinGeometryUtils.JoinGeometry (doc, elem, intruder); } catch (Exception) { continue; } } t.Commit(); } } intruders = GetIntersectSolidElems(doc, elem); Trace.Write("GetIntersectSolidElems.Count = " + intruders.Count); if (intruders.Count != 0 && loops < 1) { ++loops; goto Transaction; } }
/// <summary> /// To connect elements on adjacent floor. /// </summary> /// <param name="doc"></param> /// <param name="wallGroups"></param> /// <returns></returns> private static int JoinElmByAdjacentFloor <T>(Document doc, IReadOnlyList <IGrouping <double, T> > wallGroups) where T : Element { var result = 0; for (var i = 0; i < wallGroups.Count - 1; i++) { foreach (var walli in wallGroups[i]) { if (!(walli.Location is LocationCurve c1)) { continue; } foreach (var wallj in wallGroups[i + 1]) { if (!(wallj.Location is LocationCurve c2)) { continue; } if (!doc.RejectSpaceBox(walli, wallj)) { continue; } if ((c1.Curve as Line).GetSpacePosition(c2.Curve as Line, out _) != GeometryPosition.Parallel) { continue; } ExceptionUtil.AutoTry(() => { JoinGeometryUtils.JoinGeometry(doc, walli, wallj); result++; }); } } } return(result); }
public void Restore() { var doc = this.elements.First().Document; foreach (var p in this.joinMap) { var e1 = doc.GetElement(p.Key); var ids = p.Value; foreach (var id in ids) { var e2 = doc.GetElement(id); try { JoinGeometryUtils.JoinGeometry(doc, e1, e2); } catch { } } } }
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 { } } }
/// <summary> /// Creates a Gable Roof within the footPrint. /// </summary> /// <param name="footPrint">An curve array that represents the footprint of the roof</param> /// <param name="overhang">The overhang value.</param> /// <param name="slope">The slope of the roof.</param> /// <param name="slopeDirection">The edges that are perpendicular to this vector will have the slope applied.</param> private void CreateGableRoof(CurveArray footPrint, double overhang, double slope, XYZ slopeDirection) { List <FootPrintRoof> roofs = new List <FootPrintRoof>(); List <Line> cutLines = new List <Line>(); List <Wall> gableWalls = new List <Wall>(); Polygon roofPolygon = new Polygon(footPrint); List <CurveArray> convexFootPrint = roofPolygon.GetConvexPerimeters(slopeDirection, cutLines); int n = convexFootPrint.Count(); // create the n convex compenents of the roof for (int i = 0; i < n; i++) { Polygon p = new Polygon(convexFootPrint[i]); CurveArray offsetedFootPrint = p.CreateOffsetedCurveArray(overhang, cutLines); if (offsetedFootPrint != null) { FootPrintRoof footPrintRoof = CreateFootPrintRoof(overhang, slope, slopeDirection, offsetedFootPrint); CreateAllGableWalls(slopeDirection, slope, convexFootPrint[i], gableWalls); roofs.Add(footPrintRoof); } } // try to connect the components foreach (FootPrintRoof roof in roofs) { foreach (FootPrintRoof uniteRoof in roofs) { try { JoinGeometryUtils.JoinGeometry(document, roof, uniteRoof); } catch (Exception) { continue; } } } }
//---------------------------------------------------------- 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 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); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; Selection sel = uidoc.Selection; try { ElementsJoinUI currentUI = new ElementsJoinUI(); 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(firstCatName); BuiltInCategory secondCat = checkCategory(seconCatName); if (firstCat == BuiltInCategory.INVALID || secondCat == BuiltInCategory.INVALID) { return(Result.Cancelled); } IList <Element> ElementsToJoin = new FilteredElementCollector(doc).OfCategory(firstCat).WhereElementIsNotElementType().ToList(); using (Transaction t = new Transaction(doc, Properties.Messages.ElementJoin_Transaction)) { t.Start(); FailureHandlingOptions joinFailOp = t.GetFailureHandlingOptions(); joinFailOp.SetFailuresPreprocessor(new JoinFailureHandler()); t.SetFailureHandlingOptions(joinFailOp); foreach (Element currentElementToJoin in ElementsToJoin) { 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)); IList <Element> elementsIntersecting = new FilteredElementCollector(doc).OfCategory(secondCat).WhereElementIsNotElementType().WherePasses(bbIntersects).ToList(); foreach (Element currentElementToBeJoined in elementsIntersecting) { try { JoinGeometryUtils.JoinGeometry(doc, currentElementToJoin, currentElementToBeJoined); } catch { } } } t.Commit(); } } catch (Exception excep) { ExceptionManager eManager = new ExceptionManager(excep); } 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); }
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 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); } }
public WallsMPWRequest(UIApplication uiApp, String text) { MainUI uiForm = BARevitTools.Application.thisApp.newMainUi; RVTDocument doc = uiApp.ActiveUIDocument.Document; //Collect all the levels FilteredElementCollector levelsCollector = new FilteredElementCollector(doc); ICollection <Element> existingLevels = levelsCollector.OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements(); //Collect the wall types FilteredElementCollector wallTypesCollector = new FilteredElementCollector(doc); ICollection <Element> existingWallTypes = wallTypesCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsElementType().ToElements(); List <Line> wallLines = new List <Line>(); List <Wall> newWalls = new List <Wall>(); List <Element> selectedElements = new List <Element>(); //Get the wall type name from the MainUI combobox string selectedWallTypeName = uiForm.wallsMPWComboBoxWall.Text.ToString(); WallType wallTypeInput = null; double wallHeightInput = 0; //Ensure the active view is a plan view if (doc.ActiveView.GetType().ToString() != "Autodesk.Revit.DB.ViewPlan") { MessageBox.Show("Please run from a plan view"); } else { try { //Get the height of the walls to create from the MainUI, converted to a Double value in decimal feet wallHeightInput = (Convert.ToDouble(uiForm.wallsMPWNumericUpDownWallHeightFt.Value + (uiForm.wallsMPWNumericUpDownWallHeightIn.Value / 12))); } catch { //If the wall height input is invalid, let the user know throw new System.ArgumentException("Invalid wall height"); } double offsetDistance = 0; try { //To get the distance to offset the wall, get the wall type's thickness, then divide it in half because walls are placed along the centerline foreach (WallType wallType in existingWallTypes) { if (wallType.Name == selectedWallTypeName) { wallTypeInput = wallType; offsetDistance = (wallTypeInput.Width) / 2; break; } } } catch { new System.ArgumentException("No wall type was selected"); } //Get the active view and its associated level ViewPlan activeView = doc.ActiveView as ViewPlan; Level levelInput = activeView.GenLevel; //If the user selected a wall type, the level was obtained from the view, and the wall height is valid, continue if (wallTypeInput != null && levelInput != null && wallHeightInput != 0) { //Invoke selection of the rooms and get them from either the rooms or room tags selected List <Room> selectedRoomElements = RVTOperations.SelectRoomElements(uiApp); //Cycle through the room elements foreach (Room roomElem in selectedRoomElements) { try { //Get the location of the room as a point Location roomLocation = roomElem.Location; LocationPoint rlp = roomLocation as LocationPoint; //Get the room geometry Options geomOptions = new Options(); geomOptions.IncludeNonVisibleObjects = true; GeometryElement geomElements = roomElem.get_Geometry(geomOptions); foreach (GeometryObject geomObject in geomElements) { if (geomObject.GetType().ToString() == "Autodesk.Revit.DB.Solid") { //Grab the solid form of the room geometry Solid roomSolid = geomObject as Solid; FaceArray roomSolidFaces = roomSolid.Faces; foreach (PlanarFace roomSolidFace in roomSolidFaces) { //Get the bottom face of the room which is the face that has a -Z vector XYZ faceNormal = roomSolidFace.FaceNormal; if (faceNormal.Z == -1) { //Get the CurveLoops for the bottom face IList <CurveLoop> faceCurveLoops = roomSolidFace.GetEdgesAsCurveLoops(); foreach (CurveLoop curveLoop in faceCurveLoops) { //Offset the CurveLoop by the half thickness of the wall CurveLoop offsetCurveLoops = CurveLoop.CreateViaOffset(curveLoop, offsetDistance, XYZ.BasisZ); foreach (Line line in offsetCurveLoops) { //Collect the lines to draw walls along wallLines.Add(line); } } } } } } } catch { continue; } } //Start a transaction using (Transaction t1 = new Transaction(doc, "MakeWalls")) { t1.Start(); foreach (Line wallLine in wallLines) { //Draw a line along each of the lines and add them to a list of walls created Wall newWall = Wall.Create(doc, wallLine, wallTypeInput.Id, levelInput.Id, wallHeightInput, 0, true, false); newWalls.Add(newWall); } t1.Commit(); } //Start a new transaction to join the walls to adjacent walls using (Transaction t2 = new Transaction(doc, "JoinWalls")) { t2.Start(); foreach (Wall newWall in newWalls) { //Collect the walls in the project FilteredElementCollector existingWallsCollector = new FilteredElementCollector(doc, doc.ActiveView.Id); existingWallsCollector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements(); //Get the bounding box of each wall BoundingBoxXYZ wallBBox = newWall.get_BoundingBox(doc.ActiveView); //Get the outline of the bounding box using the minimum and maximum points Outline wallBBoxOutline = new Outline(wallBBox.Min, wallBBox.Max); //Generate a new BoundingBoxIntersectsFilter to find the other bounding boxes that intersect the outline BoundingBoxIntersectsFilter bBoxFilter = new BoundingBoxIntersectsFilter(wallBBoxOutline); //Get all walls that pass the filter (they intersect the evaluated new wall's outline) existingWallsCollector.WherePasses(bBoxFilter); foreach (Wall existingWall in existingWallsCollector) { try { //Try to joing the new wall to the existing walls so they are cut by the hosted elements JoinGeometryUtils.JoinGeometry(doc, newWall, existingWall); } catch { continue; } } } t2.Commit(); } } else if (levelInput == null) { //Let the user know if the level could not be obtained MessageBox.Show("No level set"); } else if (wallTypeInput == null) { //Let the user know if they didn't select a wall type MessageBox.Show("No wall type set"); } else if (wallHeightInput <= 0) { //Let the user know if they specified a 0 or negative wall height MessageBox.Show("Wall height must be set to greater than 0'"); } else { //If for some reason the script fails, report that one of the following settings could not be used. This is highly unlikely though MessageBox.Show(String.Format("One of the following settings could not be used: Wall Type = '{0}'; " + "Level = '{1}'; " + "Wall Height = '{2}'", ((Wall)doc.GetElement(wallTypeInput.Id)).WallType.Name.ToString(), ((Level)doc.GetElement(levelInput.Id)).Name.ToString(), (wallHeightInput / 12d).ToString())); } } }