/// <summary> /// This method is used to create ReferencePlane along to a host referenceplane with a offset parameter /// </summary> /// <param name="doc">the document</param> /// <param name="host">the host ReferencePlane</param> /// <param name="view">the view</param> /// <param name="offSet">the offset of the host</param> /// <param name="cutVec">the cutVec of the ReferencePlane</param> /// <param name="name">the name of the ReferencePlane</param> /// <returns>ReferencePlane</returns> public ReferencePlane Create(Document doc, ReferencePlane host, View view, Autodesk.Revit.DB.XYZ offSet, Autodesk.Revit.DB.XYZ cutVec, string name) { Autodesk.Revit.DB.XYZ bubbleEnd = new Autodesk.Revit.DB.XYZ(); Autodesk.Revit.DB.XYZ freeEnd = new Autodesk.Revit.DB.XYZ(); ReferencePlane refPlane; try { refPlane = host as ReferencePlane; if (refPlane != null) { bubbleEnd = refPlane.BubbleEnd.Add(offSet); freeEnd = refPlane.FreeEnd.Add(offSet); SubTransaction subTransaction = new SubTransaction(doc); subTransaction.Start(); refPlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVec, view); refPlane.Name = name; subTransaction.Commit(); } return(refPlane); } catch { return(null); } }
/// <summary> /// This method is used to create ReferencePlane along to a host referenceplane with a offset parameter /// </summary> /// <param name="doc">the document</param> /// <param name="host">the host ReferencePlane</param> /// <param name="view">the view</param> /// <param name="offSet">the offset of the host</param> /// <param name="cutVec">the cutVec of the ReferencePlane</param> /// <param name="name">the name of the ReferencePlane</param> /// <returns>ReferencePlane</returns> public ReferencePlane Create(Document doc, ReferencePlane host, View view, Autodesk.Revit.DB.XYZ offSet, Autodesk.Revit.DB.XYZ cutVec, string name) { Autodesk.Revit.DB.XYZ bubbleEnd = new Autodesk.Revit.DB.XYZ (); Autodesk.Revit.DB.XYZ freeEnd = new Autodesk.Revit.DB.XYZ (); ReferencePlane refPlane; try { refPlane = host as ReferencePlane; if (refPlane != null) { bubbleEnd = refPlane.BubbleEnd.Add(offSet); freeEnd = refPlane.FreeEnd.Add(offSet); SubTransaction subTransaction = new SubTransaction(doc); subTransaction.Start(); refPlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVec, view); refPlane.Name = name; subTransaction.Commit(); } return refPlane; } catch { return null; } }
/// <summary> /// The implementation of CreateMaterial() /// </summary> public override void CreateMaterial() { SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); FilteredElementCollector elementCollector = new FilteredElementCollector(m_document); elementCollector.WherePasses(new ElementClassFilter(typeof(Material))); IList <Element> materials = elementCollector.ToElements(); foreach (Element materialElement in materials) { Material material = materialElement as Material; if (0 == material.Name.CompareTo(m_para.SashMat)) { m_sashMatID = material.Id.IntegerValue; } if (0 == material.Name.CompareTo(m_para.GlassMat)) { m_glassMatID = material.Id.IntegerValue; } } subTransaction.Commit(); }
public Dimension AddDimension(Document doc, Autodesk.Revit.DB.View view, Face face1, Face face2) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ(); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ(); Line line; Reference ref1; Reference ref2; ReferenceArray refArray = new ReferenceArray(); PlanarFace pFace1 = face1 as PlanarFace; ref1 = pFace1.Reference; PlanarFace pFace2 = face2 as PlanarFace; ref2 = pFace2.Reference; if (null != ref1 && null != ref2) { refArray.Append(ref1); refArray.Append(ref2); } startPoint = pFace1.Origin; endPoint = new Autodesk.Revit.DB.XYZ(startPoint.X, startPoint.Y, pFace2.Origin.Z); SubTransaction subTransaction = new SubTransaction(doc); subTransaction.Start(); line = Line.CreateBound(startPoint, endPoint); dim = doc.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return(dim); }
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 static TResult InvokeSub <TResult>(this Document doc, Func <SubTransaction, TResult> func) { using (var tr = new SubTransaction(doc)) { tr.Start(); var result = func(tr); var status = tr.GetStatus(); switch (status) { case TransactionStatus.Started: tr.Commit(); return(result); case TransactionStatus.Committed: case TransactionStatus.RolledBack: return(result); case TransactionStatus.Error: tr.RollBack(); return(result); default: return(result); } } }
public static void InvokeSub(this Document doc, Action <SubTransaction> action) { using (var tr = new SubTransaction(doc)) { tr.Start(); action(tr); var status = tr.GetStatus(); switch (status) { case TransactionStatus.Started: tr.Commit(); return; case TransactionStatus.Committed: case TransactionStatus.RolledBack: break; case TransactionStatus.Error: tr.RollBack(); return; default: return; } } }
/// <summary> /// Delete all unnecessary lines /// </summary> public void DeleteLines() { int delLineNum = 0; try { SubTransaction transaction = new SubTransaction(m_app.ActiveUIDocument.Document); transaction.Start(); List <Autodesk.Revit.DB.Element> list = new List <Autodesk.Revit.DB.Element>(); ElementClassFilter filter = new ElementClassFilter(typeof(Autodesk.Revit.DB.CurveElement)); FilteredElementCollector collector = new FilteredElementCollector(m_app.ActiveUIDocument.Document); list.AddRange(collector.WherePasses(filter).ToElements()); foreach (Autodesk.Revit.DB.Element e in list) { ModelCurve mc = e as ModelCurve; if (mc != null) { if (mc.LineStyle.Name == "bounce" || mc.LineStyle.Name == "normal") { m_app.ActiveUIDocument.Document.Delete(e.Id); delLineNum++; } } } transaction.Commit(); } catch (System.Exception) { } }
/// <summary> /// Auto tag rooms with specified RoomTagType in a level /// </summary> /// <param name="level">The level where rooms will be auto tagged</param> /// <param name="tagType">The room tag type</param> public void AutoTagRooms(Level level, RoomTagType tagType) { PlanTopology planTopology = m_revit.ActiveUIDocument.Document.get_PlanTopology(level); SubTransaction subTransaction = new SubTransaction(m_revit.ActiveUIDocument.Document); subTransaction.Start(); foreach (ElementId eid in planTopology.GetRoomIds()) { Room tmpRoom = m_revit.ActiveUIDocument.Document.GetElement(eid) as Room; if (m_revit.ActiveUIDocument.Document.GetElement(tmpRoom.LevelId) != null && tmpRoom.Location != null) { // Create a specified type RoomTag to tag a room LocationPoint locationPoint = tmpRoom.Location as LocationPoint; Autodesk.Revit.DB.UV point = new Autodesk.Revit.DB.UV(locationPoint.Point.X, locationPoint.Point.Y); RoomTag newTag = m_revit.ActiveUIDocument.Document.Create.NewRoomTag(new LinkElementId(tmpRoom.Id), point, null); newTag.RoomTagType = tagType; List <RoomTag> tagListInTheRoom = m_roomWithTags[newTag.Room.Id]; tagListInTheRoom.Add(newTag); } } subTransaction.Commit(); }
/// <summary> /// Create a new brick material /// </summary> /// <returns>The specific material</returns> private Material CreateSampleBrickMaterial() { SubTransaction createMaterial = new SubTransaction(this.m_document.Document); createMaterial.Start(); Material materialNew = null; //Try to copy an existing material. If it is not available, create a new one. Material masonry_Brick = GetMaterial("Brick, Common"); if (masonry_Brick != null) { materialNew = masonry_Brick.Duplicate(masonry_Brick.Name + "_new"); System.Diagnostics.Debug.WriteLine(masonry_Brick.MaterialClass); materialNew.MaterialClass = "Brick"; } else { ElementId idNew = Material.Create(m_document.Document, "New Brick Sample"); materialNew = m_document.Document.GetElement(idNew) as Material; materialNew.Color = new Autodesk.Revit.DB.Color(255, 0, 0); } createMaterial.Commit(); SubTransaction createPropertySets = new SubTransaction(this.m_document.Document); createPropertySets.Start(); //Create a new structural asset and set properties on it. StructuralAsset structuralAsssetBrick = new StructuralAsset("BrickStructuralAsset", Autodesk.Revit.DB.StructuralAssetClass.Generic); structuralAsssetBrick.DampingRatio = .5; PropertySetElement pseStructural = PropertySetElement.Create(m_document.Document, structuralAsssetBrick); //Create a new thermal asset and set properties on it. ThermalAsset thermalAssetBrick = new ThermalAsset("BrickThermalAsset", Autodesk.Revit.DB.ThermalMaterialType.Solid); thermalAssetBrick.Porosity = 0.1; thermalAssetBrick.Permeability = 0.2; thermalAssetBrick.Compressibility = .5; thermalAssetBrick.ThermalConductivity = .5; //Create PropertySets from assets and assign them to the material. PropertySetElement pseThermal = PropertySetElement.Create(m_document.Document, thermalAssetBrick); createPropertySets.Commit(); SubTransaction setPropertySets = new SubTransaction(this.m_document.Document); setPropertySets.Start(); materialNew.SetMaterialAspectByPropertySet(MaterialAspect.Structural, pseStructural.Id); materialNew.SetMaterialAspectByPropertySet(MaterialAspect.Thermal, pseThermal.Id); //also try //materialNew.ThermalAssetId = pseThermal.Id; setPropertySets.Commit(); return(materialNew); }
/// <summary> /// The method is used to create dimension between referenceplane and face /// </summary> /// <param name="view">the view in which the dimension is created</param> /// <param name="refPlane">the reference plane</param> /// <param name="face">the face</param> /// <returns>the new dimension</returns> public Dimension AddDimension(View view, ReferencePlane refPlane, Face face) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ(); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ(); Line line; Reference ref1; Reference ref2; ReferenceArray refArray = new ReferenceArray(); ref1 = refPlane.Reference; PlanarFace pFace = face as PlanarFace; ref2 = pFace.Reference; if (null != ref1 && null != ref2) { refArray.Append(ref1); refArray.Append(ref2); } startPoint = refPlane.FreeEnd; endPoint = new Autodesk.Revit.DB.XYZ(startPoint.X, pFace.Origin.Y, startPoint.Z); SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); line = m_application.Create.NewLineBound(startPoint, endPoint); dim = m_document.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return(dim); }
public static void ExecuteSubTransaction(Document document, Action action) { using (var subTransaction = new SubTransaction(document)) { try { if (subTransaction.Start() == TransactionStatus.Started) { action?.Invoke(); } if (subTransaction.Commit() != TransactionStatus.Committed) { subTransaction.RollBack(); } } catch (Exception) { if (subTransaction.HasStarted()) { subTransaction.RollBack(); } throw; } } }
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; Element element = doc.GetElement(uidoc.Selection.PickObject(ObjectType.Element)); using (TransactionGroup transg = new TransactionGroup(doc)) { transg.Start("Transaction Group"); //Exception(Out Side Transaction) //SetParameter(element,"Transaction Group"); using (Transaction tran = new Transaction(doc)) { tran.Start("Transaction"); SetParameter(element, "Transaction"); using (SubTransaction subtrans = new SubTransaction(doc)) { subtrans.Start(); SetParameter(element, "Sub Transaction"); subtrans.Commit(); } tran.Commit(); } transg.Commit(); } return Result.Succeeded; }
/// <summary> /// Executes the specified Revit command <see cref="ExternalCommand"/>. /// The main Execute method (inherited from IExternalCommand) must be public. /// </summary> /// <param name="commandData">The command data / context.</param> /// <param name="message">The message.</param> /// <param name="elements">The elements.</param> /// <returns>The result of command execution.</returns> public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { var uiapp = commandData?.Application; var uidoc = uiapp?.ActiveUIDocument; var app = uiapp?.Application; var doc = uidoc?.Document; if (null == app || null == doc) { // TODO it's just an example, an external command can open a document if needed MessageBox.Show(StringLocalizer.CallingAssembly["This command can be called only when a document is opened and ready!"]); return(Result.Cancelled); } // Example 1: pick one object from Revit. var selection = uidoc.Selection; var hasPickOne = selection?.PickObject(ObjectType.Element); if (hasPickOne != null) { Debug.Print(doc.GetElement(hasPickOne.ElementId).Name); } // Example 2: retrieve elements from database var walls = new FilteredElementCollector(doc) .WhereElementIsNotElementType() .OfCategory(BuiltInCategory.INVALID) .OfClass(typeof(Wall)); if (null != walls) { foreach (var wall in walls) { Debug.Print(wall.Name); } } // Example 3: Modify document within a transaction using (var transaction = new Transaction(doc, "Transaction name goes here, change it")) { if (TransactionStatus.Started != transaction.Start()) { return(Result.Failed); // TODO do something if transaction didn't start } using (var subTransaction = new SubTransaction(doc)) { subTransaction.Start(); // TODO: add you code here subTransaction.Commit(); } transaction.Commit(); } return(Result.Succeeded); }
/// <summary> /// Move a wall, append a node to tree view /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void moveWallButton_Click(object sender, EventArgs e) { if (m_lastCreatedWall == null) { return; } // a sub-transaction is not necessary in this case // it is used for illustration purposes only using (SubTransaction subTransaction = new SubTransaction(m_document)) { // if not handled explicitly, the sub-transaction will be rolled back when leaving this block try { if (subTransaction.Start() == TransactionStatus.Started) { Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(10, 10, 0); ElementTransformUtils.MoveElement(m_document, m_lastCreatedWall.Id, translationVec); updateModel(true); // immediately update the view to see the changes if (subTransaction.Commit() == TransactionStatus.Committed) { AddNode(OperationType.ObjectModification, "Moved wall " + m_lastCreatedWall.Id.IntegerValue.ToString()); return; } } } catch (System.Exception ex) { TaskDialog.Show("Revit", "Exception when moving a wall: " + ex.Message); } } TaskDialog.Show("Revit", "Moving wall failed."); }
public static GCAdaptiveComponent CreateComponentByPoints(GCRevitDocument doc, FamilySymbol sym, List <XYZ> locPts) { using (var subTrans = new SubTransaction(doc.Document)) { if (TransactionStatus.Started == subTrans.Start()) { var inst = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc.Document, sym); var comp = GCAdaptiveComponent.CreateGCAdaptiveComponent(inst); var ids = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(inst); if (ids.Count == locPts.Count) { for (var i = 0; i < ids.Count; i++) { var pt = doc.Document.GetElement(ids[i]); var trans = locPts[i] - (pt.Location as LocationPoint).Point; comp.MovePointById(ids[i], trans); } subTrans.Commit(); return(comp); } else { subTrans.RollBack(); throw new GCElementCreationException("The given point count does not match the instance point count"); } } else { throw new GCElementCreationException("Could not start subtransaction for adaptive component creation"); } } }
/// <summary> /// This method is used to create dimension among three reference planes /// </summary> /// <param name="view">the view</param> /// <param name="refPlane1">the first reference plane</param> /// <param name="refPlane2">the second reference plane</param> /// <param name="refPlane">the middle reference plane</param> /// <returns>the new dimension</returns> public Dimension AddDimension(View view, ReferencePlane refPlane1, ReferencePlane refPlane2, ReferencePlane refPlane) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ(); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ(); Line line; Reference ref1; Reference ref2; Reference ref3; ReferenceArray refArray = new ReferenceArray(); ref1 = refPlane1.Reference; ref2 = refPlane2.Reference; ref3 = refPlane.Reference; startPoint = refPlane1.FreeEnd; endPoint = refPlane2.FreeEnd; line = m_application.Create.NewLineBound(startPoint, endPoint); if (null != ref1 && null != ref2 && null != ref3) { refArray.Append(ref1); refArray.Append(ref3); refArray.Append(ref2); } SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); dim = m_document.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return(dim); }
public XYZ GetReferenceDirection(Reference ref1, Document doc) // returns the direction perpendicular to reference // returns XYZ.Zero on error; { XYZ res = XYZ.Zero; XYZ workPlaneNormal = doc.ActiveView.SketchPlane.GetPlane().Normal; if (ref1.ElementId == ElementId.InvalidElementId) { return(res); } Element elem = doc.GetElement(ref1.ElementId); if (elem == null) { return(res); } if (ref1.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_SURFACE || ref1.ElementReferenceType == ElementReferenceType.REFERENCE_TYPE_LINEAR) { // make a dimension to a point for direction XYZ bEnd = new XYZ(10, 10, 10); ReferenceArray refArr = new ReferenceArray(); refArr.Append(ref1); Dimension dim = null; using (Transaction t = new Transaction(doc, "test")) { FailureHandlingOptions failureHandlingOptions = t.GetFailureHandlingOptions(); FailureHandler failureHandler = new FailureHandler(); failureHandlingOptions.SetFailuresPreprocessor(failureHandler); failureHandlingOptions.SetClearAfterRollback(true); t.SetFailureHandlingOptions(failureHandlingOptions); t.Start(); using (SubTransaction st = new SubTransaction(doc)) { st.Start(); ReferencePlane refPlane = doc.Create.NewReferencePlane(XYZ.Zero, bEnd, bEnd.CrossProduct(XYZ.BasisZ).Normalize(), doc.ActiveView); ModelCurve mc = doc.Create.NewModelCurve(Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 10)), SketchPlane.Create(doc, refPlane.Id)); refArr.Append(mc.GeometryCurve.GetEndPointReference(0)); dim = doc.Create.NewDimension(doc.ActiveView, Line.CreateBound(XYZ.Zero, new XYZ(10, 0, 0)), refArr); ElementTransformUtils.MoveElement(doc, dim.Id, new XYZ(0, 0.1, 0)); st.Commit(); } if (dim != null) { Curve cv = dim.Curve; cv.MakeBound(0, 1); XYZ pt1 = cv.GetEndPoint(0); XYZ pt2 = cv.GetEndPoint(1); res = pt2.Subtract(pt1).Normalize(); } t.RollBack(); } } return(res); }
/// <summary> /// Get the view crop element and crop region curves /// </summary> /// <param name="view"></param> /// <returns></returns> internal static ViewCrop GetViewCrop(Autodesk.Revit.DB.View view) { var doc = DocumentManager.Instance.CurrentDBDocument; TransactionManager.Instance.EnsureInTransaction(doc); ViewCrop viewCrop; using (SubTransaction tGroup = new SubTransaction(doc)) { tGroup.Start(); using (SubTransaction t1 = new SubTransaction(doc)) { // Deactivate crop box t1.Start(); view.CropBoxVisible = false; t1.Commit(); doc.Regenerate(); // Get all visible elements, which does not include the crop box FilteredElementCollector collector = new FilteredElementCollector(doc, view.Id); ICollection <ElementId> shownElems = collector.ToElementIds(); // Activate the crop box t1.Start(); view.CropBoxVisible = true; t1.Commit(); doc.Regenerate(); // Get all visible elements, excluding everything but the crop box collector = new FilteredElementCollector(doc, view.Id); collector.Excluding(shownElems); viewCrop.cropElement = collector.FirstElement(); viewCrop.cropRegion = view.GetCropRegionShapeManager().GetCropShape().First(); } tGroup.RollBack(); } TransactionManager.Instance.TransactionTaskDone(); return(viewCrop); }
/// <summary> /// Rotate Element /// </summary> /// <param name="element">element rotate</param> /// <param name="lcPoint">location need rotate</param> /// <param name="angle">angle need rotate</param> void Rotate(Element element, XYZ lcPoint, double angle) { using (SubTransaction tran = new SubTransaction(element.Document)) { tran.Start(); Line line = Line.CreateBound(lcPoint, new XYZ(lcPoint.X, lcPoint.Y, lcPoint.Z + 10000)); ElementTransformUtils.RotateElement(element.Document, element.Id, line, angle * Math.PI / 180); tran.Commit(); } }
private static void ModifyTextElemTypes(Document doc, IList <TextElementType> textElementTypes, Font pickedFont) { using (Transaction t = new Transaction(doc, "Replace fonts in family")) { t.Start(); FailureHandlingOptions failureHandling = t.GetFailureHandlingOptions(); failureHandling.SetFailuresPreprocessor(new AllWarningSwallower()); t.SetFailureHandlingOptions(failureHandling); foreach (TextElementType textElementType in textElementTypes) { try { using (SubTransaction st = new SubTransaction(doc)) { // set the new font family to the existing type st.Start(); SetElemTypeAttributes(textElementType, pickedFont); st.Commit(); doc.Regenerate(); // rename the type st.Start(); if (textElementType.CanBeRenamed) { textElementType.Name = GenerateElemTypeName(textElementType); } st.Commit(); } } catch (Exception ex) { TaskDialog.Show("Exception", String.Format("Message:{0}\nStackTrace:{1}\n", ex.Message, ex.StackTrace)); return; } } t.Commit(); } }
static void SetElemTypeAttributes(ElementType elementType, Font pickedFont) { using (SubTransaction st = new SubTransaction(elementType.Document)) { st.Start(); elementType.get_Parameter(BuiltInParameter.TEXT_FONT).Set(pickedFont.FontName); elementType.get_Parameter(BuiltInParameter.TEXT_STYLE_BOLD).Set(pickedFont.IsBold ? 1 : 0); elementType.get_Parameter(BuiltInParameter.TEXT_STYLE_UNDERLINE).Set(pickedFont.IsUnderline ? 1 : 0); elementType.get_Parameter(BuiltInParameter.TEXT_STYLE_ITALIC).Set(pickedFont.IsItalic ? 1 : 0); elementType.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE).Set(pickedFont.WidthFactor); st.Commit(); } }
/// <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 static void ReplaceFontInDimTypes(Document doc, Font pickedFont) { IList <DimensionType> dimTypes = GetDimensionTypes(doc); if (dimTypes.Count == 0) { return; } using (Transaction t = new Transaction(doc, "Rename Dim Types")) { t.Start(); FailureHandlingOptions failureHandling = t.GetFailureHandlingOptions(); failureHandling.SetFailuresPreprocessor(new AllWarningSwallower()); t.SetFailureHandlingOptions(failureHandling); foreach (DimensionType dimType in dimTypes) { if (!dimType.CanBeRenamed) { continue; } using (SubTransaction st = new SubTransaction(doc)) { st.Start(); SetElemTypeAttributes(dimType, pickedFont); st.Commit(); doc.Regenerate(); st.Start(); dimType.Name = GenerateElemTypeName(dimType); st.Commit(); } } t.Commit(); } }
public static void SuntranInvoke(this Document doc, Action <SubTransaction> action) { using (SubTransaction subTransaction = new SubTransaction(doc)) { subTransaction.Start(); action(subTransaction); bool flag = subTransaction.GetStatus() == (TransactionStatus)1; if (flag) { subTransaction.Commit(); } } }
public static ModelCurve DrawCircle(Document doc, Plane p, SketchPlane sp, double radius) { SubTransaction st = new SubTransaction(doc); st.Start(); Curve circle = Arc.Create(p, radius, 0, Math.PI * 2.0 - 0.5); ModelCurve curve = doc.Create.NewModelCurve(circle, sp); st.Commit(); return(curve as ModelLine); }
/// <summary> /// The implementation of CombineAndBuild() ,defining New Window Types /// </summary> public override void CombineAndBuild() { SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); foreach (String type in m_para.WinParaTab.Keys) { WindowParameter para = m_para.WinParaTab[type] as WindowParameter; newFamilyType(para); } subTransaction.Commit(); }
public static List <ModelLine> DrawLines(Document doc, IEnumerable <Line> lines) { List <ModelLine> modelLines = new List <ModelLine>(); SubTransaction st = new SubTransaction(doc); st.Start(); XYZ lastNormal = new XYZ(999, 992, 200); // random Plane p = null; SketchPlane sp = null; foreach (Line ln in lines) { if (ln.Length < (1.0 / 24.0 / 12.0)) { continue; // too short for Revit! } // see what the plane is XYZ vector = ln.Direction; XYZ normal = null; if (vector.Normalize().IsAlmostEqualTo(XYZ.BasisZ) == false) { normal = vector.CrossProduct(XYZ.BasisZ); } else { normal = vector.CrossProduct(XYZ.BasisX); } if (lastNormal.IsAlmostEqualTo(normal) == false) { p = Plane.CreateByNormalAndOrigin(normal, ln.GetEndPoint(0)); sp = SketchPlane.Create(doc, p); normal = lastNormal; } ModelCurve curve = doc.Create.NewModelCurve(ln, sp); modelLines.Add(curve as ModelLine); } st.Commit(); return(modelLines); }
/// <summary> /// The implementation of CreateSash(),and creating the Window Sash Solid Geometry /// </summary> public override void CreateSash() { double frameCurveOffset1 = 0.075; double frameDepth = 7 * m_wallThickness / 12 + m_windowInset; double sashCurveOffset = 0.075; double sashDepth = (frameDepth - m_windowInset) / 2; //get the exterior view and sash referenceplane which are used in this process Autodesk.Revit.DB.View exteriorView = Utility.GetViewByName("Exterior", m_application, m_document); SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); //create fixed sash CurveArray curveArr5 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1, -m_width / 2 + frameCurveOffset1, m_sillHeight + m_height - frameCurveOffset1, m_sillHeight + frameCurveOffset1, 0); CurveArray curveArr6 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr5, sashCurveOffset); m_document.Regenerate(); CurveArrArray curveArrArray3 = new CurveArrArray(); curveArrArray3.Append(curveArr5); curveArrArray3.Append(curveArr6); Extrusion sash1 = m_extrusionCreator.NewExtrusion(curveArrArray3, m_sashPlane, 2 * sashDepth, sashDepth); m_document.Regenerate(); Face esashFace1 = GeoHelper.GetExtrusionFace(sash1, m_rightView, true); Face isashFace1 = GeoHelper.GetExtrusionFace(sash1, m_rightView, false); Dimension sashDim1 = m_dimensionCreator.AddDimension(m_rightView, esashFace1, isashFace1); sashDim1.IsLocked = true; Dimension sashWithPlane1 = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, isashFace1); sashWithPlane1.IsLocked = true; sash1.SetVisibility(CreateVisibility()); //set category of the sash extrusions if (m_frameCat != null) { sash1.Subcategory = m_frameCat; } Autodesk.Revit.DB.ElementId id = new ElementId(m_sashMatID); sash1.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM).Set(id); subTransaction.Commit(); }
private static MEPSystem GetOrCreateMEPSystemOnConnector(Document m_document, Connector connector) { if (connector.MEPSystem == null) { // if there is no system, let Revit automatically create it. system will start from the connector and continue to the air terminal using (SubTransaction subTransaction = new SubTransaction(m_document)) { subTransaction.Start(); ConnectorSet csi = new ConnectorSet(); csi.Insert(connector); MechanicalSystem mechSystem = m_document.Create.NewMechanicalSystem(null, csi, connector.DuctSystemType); subTransaction.Commit(); } } return(connector.MEPSystem); }
/// <summary> /// Initialize an AdaptiveComponent element /// </summary> /// <param name="pts">Points to use as reference</param> /// <param name="fs">FamilySymbol to place</param> private void InitAdaptiveComponent(Point[] pts, FamilySymbol fs) { // if the family instance is present in trace... var oldFam = ElementBinder.GetElementFromTrace <Autodesk.Revit.DB.FamilyInstance>(Document); // just mutate it... if (oldFam != null) { InternalSetFamilyInstance(oldFam); if (fs.InternalFamilySymbol.Id != oldFam.Symbol.Id) { InternalSetFamilySymbol(fs); } InternalSetPositions(pts.ToXyzs()); return; } // otherwise create a new family instance... TransactionManager.Instance.EnsureInTransaction(Document); using (Autodesk.Revit.DB.SubTransaction st = new SubTransaction(Document)) { try { st.Start(); var fam = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(Element.Document, fs.InternalFamilySymbol); InternalSetFamilyInstance(fam); InternalSetPositions(pts.ToXyzs()); st.Commit(); } catch (Exception ex) { st.RollBack(); throw new ArgumentException(Revit.Properties.Resources.Adaptive_Component_Creation_Failed + ex.Message); } } TransactionManager.Instance.TransactionTaskDone(); // remember this value ElementBinder.SetElementForTrace(this.InternalElement); }
private ElementId FindHost(XYZ location, int hostType, Document doc) { ElementId host = null; FilteredElementCollector collector = new FilteredElementCollector(doc); // Subtransaction to insert a family and use it to check for intersctions. // The family is then moved around to check for the host of each new object being created // After the element creation process is over the object and it's parent family are deleted form the project. using (SubTransaction subTrans = new SubTransaction(doc)) { subTrans.Start(); if (hostFinder == null) { // check if the point family exists string path = typeof(LyrebirdService).Assembly.Location.Replace("LMNA.Lyrebird.Revit2015.dll", "IntersectionPoint.rfa"); if (!System.IO.File.Exists(path)) { // save the file from this assembly and load it into project //string directory = System.IO.Path.GetDirectoryName(path); System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); WriteResource(assembly, "IntersectionPoint.rfa", path); } // Load the family and place an instance of it. Family insertPoint = null; try { if (System.IO.File.Exists(path)) { doc.LoadFamily(path, out insertPoint); } else { TaskDialog.Show("Error", "Could not find family to load"); } } catch (Exception ex) { Debug.WriteLine("Error", ex.Message); ; } if (insertPoint != null) { FamilySymbol ips = null; foreach (ElementId fsid in insertPoint.GetFamilySymbolIds()) { ips = doc.GetElement(fsid) as FamilySymbol; } // Create an instance hostFinder = AdaptiveComponentInstanceUtils.CreateAdaptiveComponentInstance(doc, ips); System.IO.File.Delete(path); } else { TaskDialog.Show("test", "InsertPoint family is still null, loading didn't work."); } } IList<ElementId> placePointIds = new List<ElementId>(); placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(hostFinder); try { ReferencePoint rp = doc.GetElement(placePointIds[0]) as ReferencePoint; XYZ movedPt; if (hostType == 1 || hostType == 3) { movedPt = new XYZ(location.X, location.Y, location.Z + 0.00328); } else { movedPt = new XYZ(location.X, location.Y, location.Z - 0.00328); } if (rp != null) { XYZ vector = movedPt.Subtract(rp.Position); ElementTransformUtils.MoveElement(doc, rp.Id, vector); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } Element elem = hostFinder as Element; if (elem != null) { // Find the host element if (hostType == 1) { // find a wall collector.OfCategory(BuiltInCategory.OST_Walls); collector.OfClass(typeof(Wall)); ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem); collector.WherePasses(intersectionFilter); foreach (Element e in collector) { host = e.Id; } } else if (hostType == 2) { // Find a floor collector.OfCategory(BuiltInCategory.OST_Floors); collector.OfClass(typeof(Floor)); ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem); collector.WherePasses(intersectionFilter); foreach (Element e in collector) { host = e.Id; } } else if (hostType == 3) { // find a ceiling collector.OfCategory(BuiltInCategory.OST_Ceilings); collector.OfClass(typeof(Ceiling)); ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem); collector.WherePasses(intersectionFilter); foreach (Element e in collector) { host = e.Id; } } else if (hostType == 4) { // find a roof collector.OfCategory(BuiltInCategory.OST_Roofs); collector.OfClass(typeof(RoofBase)); ElementIntersectsElementFilter intersectionFilter = new ElementIntersectsElementFilter(elem); collector.WherePasses(intersectionFilter); foreach (Element e in collector) { host = e.Id; } } } subTrans.Commit(); // Delete the family file } return host; }
/// <summary> /// Auto tag rooms with specified RoomTagType in a level /// </summary> /// <param name="level">The level where rooms will be auto tagged</param> /// <param name="tagType">The room tag type</param> public void AutoTagRooms(Level level, RoomTagType tagType) { PlanTopology planTopology = m_revit.ActiveUIDocument.Document.get_PlanTopology(level); SubTransaction subTransaction = new SubTransaction(m_revit.ActiveUIDocument.Document); subTransaction.Start(); foreach (Room tmpRoom in planTopology.Rooms) { if (tmpRoom.Level != null && tmpRoom.Location != null) { // Create a specified type RoomTag to tag a room LocationPoint locationPoint = tmpRoom.Location as LocationPoint; Autodesk.Revit.DB.UV point = new Autodesk.Revit.DB.UV (locationPoint.Point.X, locationPoint.Point.Y); RoomTag newTag = m_revit.ActiveUIDocument.Document.Create.NewRoomTag(tmpRoom, point, null); newTag.RoomTagType = tagType; List<RoomTag> tagListInTheRoom = m_roomWithTags[newTag.Room.Id.IntegerValue]; tagListInTheRoom.Add(newTag); } } subTransaction.Commit(); }
/// <summary> /// Some preparation and check before creating room. /// </summary> /// <param name="curPhase">Current phase used to create room, all rooms will be created in this phase.</param> /// <returns>Number indicates how many new rooms were created.</returns> private int RoomCreationStart() { int nNewRoomsSize = 0; // transaction is used to cancel room creation when exception occurs SubTransaction myTransaction = new SubTransaction(m_document); try { // Preparation before room creation starts Phase curPhase = null; if (!RoomCreationPreparation(ref curPhase)) { return 0; } // get all existing rooms which have mapped to spreadsheet rooms. // we should skip the creation for those spreadsheet rooms which have been mapped by Revit rooms. Dictionary<int, string> existingRooms = new Dictionary<int, string>(); foreach (Room room in m_roomData.Rooms) { Parameter sharedParameter = room.get_Parameter(RoomsData.SharedParam); if (null != sharedParameter && false == String.IsNullOrEmpty(sharedParameter.AsString())) { existingRooms.Add(room.Id.IntegerValue, sharedParameter.AsString()); } } #region Rooms Creation and Set myTransaction.Start(); // create rooms with spread sheet based rooms data for (int row = 0; row < m_spreadRoomsTable.Rows.Count; row++) { // get the ID column value and use it to check whether this spreadsheet room is mapped by Revit room. String externaId = m_spreadRoomsTable.Rows[row][RoomsData.RoomID].ToString(); if (existingRooms.ContainsValue(externaId)) { // skip the spreadsheet room creation if it's mapped by Revit room continue; } // create rooms in specified phase, but without placing them. Room newRoom = m_document.Create.NewRoom(curPhase); if (null == newRoom) { // abort the room creation and pop up failure message myTransaction.RollBack(); MyMessageBox("Create room failed.", MessageBoxIcon.Warning); return 0; } // set the shared parameter's value of Revit room Parameter sharedParam = newRoom.get_Parameter(RoomsData.SharedParam); if (null == sharedParam) { // abort the room creation and pop up failure message myTransaction.RollBack(); MyMessageBox("Failed to get shared parameter, please try again.", MessageBoxIcon.Warning); return 0; } else { sharedParam.Set(externaId); } // Update this new room with values of spreadsheet UpdateNewRoom(newRoom, row); // remember how many new rooms were created, based on spread sheet data nNewRoomsSize++; } // end this transaction if create all rooms successfully. myTransaction.Commit(); #endregion } catch (Exception ex) { // cancel this time transaction when exception occurs if (myTransaction.HasStarted()) { myTransaction.RollBack(); } MyMessageBox(ex.Message, MessageBoxIcon.Warning); return 0; } // output unplaced rooms creation message String strMessage = string.Empty; int nSkippedRooms = m_spreadRoomsTable.Rows.Count - nNewRoomsSize; if (nSkippedRooms > 0) { strMessage = string.Format("{0} unplaced {1} created successfully.\r\n{2} skipped, {3}", nNewRoomsSize, (nNewRoomsSize > 1) ? ("rooms were") : ("room was"), nSkippedRooms.ToString() + ((nSkippedRooms > 1) ? (" were") : (" was")), (nSkippedRooms > 1) ? ("because they were already mapped by Revit rooms.") : ("because it was already mapped by Revit rooms.")); } else { strMessage = string.Format("{0} unplaced {1} created successfully.", nNewRoomsSize, (nNewRoomsSize > 1) ? ("rooms were") : ("room was")); } // output creation message MyMessageBox(strMessage, MessageBoxIcon.Information); return nNewRoomsSize; }
/// <summary> /// Move a wall, append a node to tree view /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void moveWallButton_Click(object sender, EventArgs e) { if (m_lastCreatedWall == null) return; // a sub-transaction is not necessary in this case // it is used for illustration purposes only using (SubTransaction subTransaction = new SubTransaction(m_document)) { // if not handled explicitly, the sub-transaction will be rolled back when leaving this block try { if (subTransaction.Start() == TransactionStatus.Started) { Autodesk.Revit.DB.XYZ translationVec = new Autodesk.Revit.DB.XYZ(10, 10, 0); ElementTransformUtils.MoveElement(m_document, m_lastCreatedWall.Id, translationVec); updateModel(true); // immediately update the view to see the changes if (subTransaction.Commit() == TransactionStatus.Committed) { AddNode(OperationType.ObjectModification, "Moved wall " + m_lastCreatedWall.Id.IntegerValue.ToString()); return; } } } catch (System.Exception ex) { MessageBox.Show("Exception when moving a wall: " + ex.Message); } } MessageBox.Show("Moving wall failed."); }
/// <summary> /// Create a wall, append a node to tree view /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void createWallbutton_Click(object sender, EventArgs e) { // a sub-transaction is not necessary in this case // it is used for illustration purposes only using (SubTransaction subTransaction = new SubTransaction(m_document)) { // if not handled explicitly, the sub-transaction will be rolled back when leaving this block try { if (subTransaction.Start() == TransactionStatus.Started) { using (CreateWallForm createWallForm = new CreateWallForm(m_commandData)) { createWallForm.ShowDialog(); if (DialogResult.OK == createWallForm.DialogResult) { updateModel(true); // immediately update the view to see the changes if (subTransaction.Commit() == TransactionStatus.Committed) { m_lastCreatedWall = createWallForm.CreatedWall; AddNode(OperationType.ObjectModification, "Created wall " + m_lastCreatedWall.Id.IntegerValue.ToString()); UpdateButtonsStatus(); return; } } else { subTransaction.RollBack(); return; } } } } catch (System.Exception ex) { MessageBox.Show("Exception when creating a wall: " + ex.Message); } } MessageBox.Show("Creating wall failed"); }
/// <summary> /// The implementation of CreateMaterial() /// </summary> public override void CreateMaterial() { SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); FilteredElementCollector elementCollector = new FilteredElementCollector(m_document); elementCollector.WherePasses(new ElementClassFilter(typeof(Material))); IList<Element> materials = elementCollector.ToElements(); foreach (Element materialElement in materials) { Material material = materialElement as Material; if (0 == material.Name.CompareTo(m_para.SashMat)) { m_sashMatID = material.Id.IntegerValue; } if (0 == material.Name.CompareTo(m_para.GlassMat)) { m_glassMatID = material.Id.IntegerValue; } } subTransaction.Commit(); }
/// <summary> /// The implementation of CreateSash(),and creating the Window Sash Solid Geometry /// </summary> public override void CreateSash() { double frameCurveOffset1 = 0.075; double frameDepth = 7*m_wallThickness/12+m_windowInset; double sashCurveOffset = 0.075; double sashDepth = (frameDepth - m_windowInset) / 2; //get the exterior view and sash referenceplane which are used in this process Autodesk.Revit.DB.View exteriorView = Utility.GetViewByName("Exterior", m_application, m_document); SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); //add a middle reference plane between the top referenceplane and sill referenceplane CreateRefPlane refPlaneCreator = new CreateRefPlane(); ReferencePlane middlePlane=refPlaneCreator.Create(m_document, m_topPlane, exteriorView, new Autodesk.Revit.DB.XYZ (0, 0, -m_height / 2), new Autodesk.Revit.DB.XYZ (0, -1, 0), "tempmiddle"); m_document.Regenerate(); //add dimension between top, sill, and middle reference plane, make the dimension segment equal Dimension dim = m_dimensionCreator.AddDimension(exteriorView, m_topPlane, m_sillPlane, middlePlane); dim.AreSegmentsEqual = true; //create first sash CurveArray curveArr5 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1, -m_width / 2 + frameCurveOffset1, m_sillHeight + m_height / 2 + sashCurveOffset / 2, m_sillHeight + frameCurveOffset1, 0); CurveArray curveArr6 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr5, sashCurveOffset); m_document.Regenerate(); CurveArrArray curveArrArray3 = new CurveArrArray(); curveArrArray3.Append(curveArr5); curveArrArray3.Append(curveArr6); Extrusion sash1 = m_extrusionCreator.NewExtrusion(curveArrArray3, m_sashPlane, 2 * sashDepth, sashDepth); m_document.Regenerate(); Face esashFace1=GeoHelper.GetExtrusionFace(sash1,m_rightView,true); Face isashFace1=GeoHelper.GetExtrusionFace(sash1,m_rightView,false); Dimension sashDim1=m_dimensionCreator.AddDimension(m_rightView,esashFace1,isashFace1); sashDim1.IsLocked = true; Dimension sashWithPlane1 = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, isashFace1); sashWithPlane1.IsLocked = true; sash1.SetVisibility(CreateVisibility()); //create second sash CurveArray curveArr7 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1, -m_width / 2 + frameCurveOffset1, m_sillHeight + m_height - frameCurveOffset1, m_sillHeight + m_height / 2 - sashCurveOffset / 2, 0); CurveArray curveArr8 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr7, sashCurveOffset); m_document.Regenerate(); CurveArrArray curveArrArray4 = new CurveArrArray(); curveArrArray4.Append(curveArr7); curveArrArray4.Append(curveArr8); Extrusion sash2 = m_extrusionCreator.NewExtrusion(curveArrArray4, m_sashPlane, sashDepth, 0); sash2.SetVisibility(CreateVisibility()); m_document.Regenerate(); Face esashFace2 = GeoHelper.GetExtrusionFace(sash2, m_rightView, true); Face isashFace2 = GeoHelper.GetExtrusionFace(sash2, m_rightView, false); Dimension sashDim2 = m_dimensionCreator.AddDimension(m_rightView, esashFace2, isashFace2); sashDim2.IsLocked = true; Dimension sashWithPlane2 = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, isashFace2); m_document.Regenerate(); sashWithPlane2.IsLocked = true; //set category of the sash extrusions if (m_frameCat != null) { sash1.Subcategory = m_frameCat; sash2.Subcategory = m_frameCat; } Autodesk.Revit.DB.ElementId id = new ElementId(m_sashMatID); sash1.ParametersMap.get_Item("Material").Set(id); sash2.ParametersMap.get_Item("Material").Set(id); subTransaction.Commit(); }
/// <summary> /// The method is used to create extrusion using FamilyItemFactory.NewExtrusion() /// </summary> /// <param name="curveArrArray">the CurveArrArray parameter</param> /// <param name="workPlane">the reference plane is used to create SketchPlane</param> /// <param name="startOffset">the extrusion's StartOffset property</param> /// <param name="endOffset">the extrusion's EndOffset property</param> /// <returns>the new extrusion</returns> public Extrusion NewExtrusion(CurveArrArray curveArrArray, ReferencePlane workPlane, double startOffset, double endOffset) { Extrusion rectExtrusion = null; try { SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); SketchPlane sketch = m_familyCreator.NewSketchPlane(workPlane.Plane); rectExtrusion = m_familyCreator.NewExtrusion(true, curveArrArray, sketch, Math.Abs(endOffset - startOffset)); rectExtrusion.StartOffset = startOffset; rectExtrusion.EndOffset = endOffset; subTransaction.Commit(); return rectExtrusion; } catch { return null; } }
/// <summary> /// The method is used to create alignment between two faces /// </summary> /// <param name="view">the view</param> /// <param name="face1">face1</param> /// <param name="face2">face2</param> public void AddAlignment(View view, Face face1, Face face2) { PlanarFace pFace1 = null; PlanarFace pFace2 = null; if (face1 is PlanarFace) pFace1 = face1 as PlanarFace; if (face2 is PlanarFace) pFace2 = face2 as PlanarFace; if (pFace1 != null && pFace2 != null) { SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); m_familyCreator.NewAlignment(view, pFace1.Reference, pFace2.Reference); subTransaction.Commit(); } }
/// <summary> /// Implements the export of element. /// </summary> /// <param name="exporterIFC">The IFC exporter object.</param> /// <param name="element">The element to export.</param> /// <param name="productWrapper">The ProductWrapper object.</param> public virtual void ExportElementImpl(ExporterIFC exporterIFC, Element element, ProductWrapper productWrapper) { Options options; View ownerView = element.Document.GetElement(element.OwnerViewId) as View; if (ownerView == null) { options = GeometryUtil.GetIFCExportGeometryOptions(); } else { options = new Options(); options.View = ownerView; } GeometryElement geomElem = element.get_Geometry(options); // Default: we don't preserve the element parameter cache after export. bool shouldPreserveParameterCache = false; try { exporterIFC.PushExportState(element, geomElem); using (SubTransaction st = new SubTransaction(element.Document)) { st.Start(); // A long list of supported elements. Please keep in alphabetical order. if (element is AreaReinforcement || element is PathReinforcement || element is Rebar) { RebarExporter.Export(exporterIFC, element, productWrapper); } else if (element is AreaScheme) { AreaSchemeExporter.ExportAreaScheme(exporterIFC, element as AreaScheme, productWrapper); } else if (element is AssemblyInstance) { AssemblyInstance assemblyInstance = element as AssemblyInstance; AssemblyInstanceExporter.ExportAssemblyInstanceElement(exporterIFC, assemblyInstance, productWrapper); } else if (element is BeamSystem) { if (ExporterCacheManager.BeamSystemCache.Contains(element.Id)) AssemblyInstanceExporter.ExportBeamSystem(exporterIFC, element as BeamSystem, productWrapper); else { ExporterCacheManager.BeamSystemCache.Add(element.Id); shouldPreserveParameterCache = true; } } else if (element is Ceiling) { Ceiling ceiling = element as Ceiling; CeilingExporter.ExportCeilingElement(exporterIFC, ceiling, geomElem, productWrapper); } else if (element is CeilingAndFloor || element is Floor) { // This covers both Floors and Building Pads. HostObject hostObject = element as HostObject; FloorExporter.Export(exporterIFC, hostObject, geomElem, productWrapper); } else if (element is ContFooting) { ContFooting footing = element as ContFooting; FootingExporter.ExportFootingElement(exporterIFC, footing, geomElem, productWrapper); } else if (element is CurveElement) { CurveElement curveElem = element as CurveElement; CurveElementExporter.ExportCurveElement(exporterIFC, curveElem, geomElem, productWrapper); } else if (element is CurtainSystem) { CurtainSystem curtainSystem = element as CurtainSystem; CurtainSystemExporter.ExportCurtainSystem(exporterIFC, curtainSystem, productWrapper); } else if (CurtainSystemExporter.IsLegacyCurtainElement(element)) { CurtainSystemExporter.ExportLegacyCurtainElement(exporterIFC, element, productWrapper); } else if (element is DuctInsulation) { DuctInsulation ductInsulation = element as DuctInsulation; DuctInsulationExporter.ExportDuctInsulation(exporterIFC, ductInsulation, geomElem, productWrapper); } else if (element is DuctLining) { DuctLining ductLining = element as DuctLining; DuctLiningExporter.ExportDuctLining(exporterIFC, ductLining, geomElem, productWrapper); } else if (element is ElectricalSystem) { ExporterCacheManager.SystemsCache.AddElectricalSystem(element.Id); } else if (element is FabricArea) { // We are exporting the fabric area as a group only. FabricSheetExporter.ExportFabricArea(exporterIFC, element, productWrapper); } else if (element is FabricSheet) { FabricSheet fabricSheet = element as FabricSheet; FabricSheetExporter.ExportFabricSheet(exporterIFC, fabricSheet, geomElem, productWrapper); } else if (element is FaceWall) { WallExporter.ExportWall(exporterIFC, element, geomElem, productWrapper); } else if (element is FamilyInstance) { FamilyInstance familyInstanceElem = element as FamilyInstance; FamilyInstanceExporter.ExportFamilyInstanceElement(exporterIFC, familyInstanceElem, geomElem, productWrapper); } else if (element is FilledRegion) { FilledRegion filledRegion = element as FilledRegion; FilledRegionExporter.Export(exporterIFC, filledRegion, geomElem, productWrapper); } else if (element is Grid) { ExporterCacheManager.GridCache.Add(element); } else if (element is Group) { Group group = element as Group; GroupExporter.ExportGroupElement(exporterIFC, group, productWrapper); } else if (element is HostedSweep) { HostedSweep hostedSweep = element as HostedSweep; HostedSweepExporter.Export(exporterIFC, hostedSweep, geomElem, productWrapper); } else if (element is Part) { Part part = element as Part; if (ExporterCacheManager.ExportOptionsCache.ExportPartsAsBuildingElements) PartExporter.ExportPartAsBuildingElement(exporterIFC, part, geomElem, productWrapper); else PartExporter.ExportStandalonePart(exporterIFC, part, geomElem, productWrapper); } else if (element is PipeInsulation) { PipeInsulation pipeInsulation = element as PipeInsulation; PipeInsulationExporter.ExportPipeInsulation(exporterIFC, pipeInsulation, geomElem, productWrapper); } else if (element is Railing) { if (ExporterCacheManager.RailingCache.Contains(element.Id)) RailingExporter.ExportRailingElement(exporterIFC, element as Railing, productWrapper); else { ExporterCacheManager.RailingCache.Add(element.Id); RailingExporter.AddSubElementsToCache(element as Railing); shouldPreserveParameterCache = true; } } else if (RampExporter.IsRamp(element)) { RampExporter.Export(exporterIFC, element, geomElem, productWrapper); } else if (element is RoofBase) { RoofBase roofElement = element as RoofBase; RoofExporter.Export(exporterIFC, roofElement, geomElem, productWrapper); } else if (element is SpatialElement) { SpatialElement spatialElem = element as SpatialElement; SpatialElementExporter.ExportSpatialElement(exporterIFC, spatialElem, productWrapper); } else if (IsStairs(element)) { StairsExporter.Export(exporterIFC, element, geomElem, productWrapper); } else if (element is TextNote) { TextNote textNote = element as TextNote; TextNoteExporter.Export(exporterIFC, textNote, productWrapper); } else if (element is TopographySurface) { TopographySurface topSurface = element as TopographySurface; SiteExporter.ExportTopographySurface(exporterIFC, topSurface, geomElem, productWrapper); } else if (element is Truss) { if (ExporterCacheManager.TrussCache.Contains(element.Id)) AssemblyInstanceExporter.ExportTrussElement(exporterIFC, element as Truss, productWrapper); else { ExporterCacheManager.TrussCache.Add(element.Id); shouldPreserveParameterCache = true; } } else if (element is Wall) { Wall wallElem = element as Wall; WallExporter.Export(exporterIFC, wallElem, geomElem, productWrapper); } else if (element is WallSweep) { WallSweep wallSweep = element as WallSweep; WallSweepExporter.Export(exporterIFC, wallSweep, geomElem, productWrapper); } else if (element is Zone) { if (ExporterCacheManager.ZoneCache.Contains(element.Id)) ZoneExporter.ExportZone(exporterIFC, element as Zone, productWrapper); else { ExporterCacheManager.ZoneCache.Add(element.Id); shouldPreserveParameterCache = true; } } else { string ifcEnumType; IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, element, out ifcEnumType); bool exported = false; if (IsMEPType(exporterIFC, element, exportType)) exported = GenericMEPExporter.Export(exporterIFC, element, geomElem, exportType, ifcEnumType, productWrapper); else if (ExportAsProxy(element, exportType)) exported = ProxyElementExporter.Export(exporterIFC, element, geomElem, productWrapper); // For ducts and pipes, we will add a IfcRelCoversBldgElements during the end of export. if (exported && (element is Duct || element is Pipe)) ExporterCacheManager.MEPCache.CoveredElementsCache.Add(element.Id); } if (element.AssemblyInstanceId != ElementId.InvalidElementId) ExporterCacheManager.AssemblyInstanceCache.RegisterElements(element.AssemblyInstanceId, productWrapper); Group elementGroup = element.Group; if (elementGroup != null && elementGroup.Id != ElementId.InvalidElementId) ExporterCacheManager.GroupCache.RegisterElements(elementGroup.Id, productWrapper); if (ExporterCacheManager.ExportOptionsCache.GUIDOptions.StoreIFCGUID || ExporterCacheManager.ExportOptionsCache.GUIDOptions.Use2009BuildingStoreyGUIDs && (element is Level)) st.Commit(); else st.RollBack(); } } finally { exporterIFC.PopExportState(); ExporterStateManager.PreserveElementParameterCache(element, shouldPreserveParameterCache); } }
/// <summary> /// Delete all unnecessary lines /// </summary> public void DeleteLines() { int delLineNum = 0; try { SubTransaction transaction = new SubTransaction(m_app.ActiveUIDocument.Document); transaction.Start(); List<Autodesk.Revit.DB.Element> list = new List<Autodesk.Revit.DB.Element>(); ElementClassFilter filter = new ElementClassFilter(typeof(Autodesk.Revit.DB.CurveElement)); FilteredElementCollector collector = new FilteredElementCollector(m_app.ActiveUIDocument.Document); list.AddRange(collector.WherePasses(filter).ToElements()); foreach (Autodesk.Revit.DB.Element e in list) { ModelCurve mc = e as ModelCurve; if (mc != null) { if (mc.LineStyle.Name == "bounce" || mc.LineStyle.Name == "normal") { m_app.ActiveUIDocument.Document.Delete(e); delLineNum++; } } } transaction.Commit(); } catch (System.Exception) { } }
/// <summary> /// Completes the export process by writing information stored incrementally during export to the file. /// </summary> /// <param name="exporterIFC">The IFC exporter object.</param> /// <param name="document">The document to export.</param> private void EndExport(ExporterIFC exporterIFC, Document document) { IFCFile file = exporterIFC.GetFile(); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; using (IFCTransaction transaction = new IFCTransaction(file)) { // In some cases, like multi-story stairs and ramps, we may have the same Pset used for multiple levels. // If ifcParams is null, re-use the property set. ISet<string> locallyUsedGUIDs = new HashSet<string>(); // Relate Ducts and Pipes to their coverings (insulations and linings) foreach (ElementId ductOrPipeId in ExporterCacheManager.MEPCache.CoveredElementsCache) { IFCAnyHandle ductOrPipeHandle = ExporterCacheManager.MEPCache.Find(ductOrPipeId); if (IFCAnyHandleUtil.IsNullOrHasNoValue(ductOrPipeHandle)) continue; HashSet<IFCAnyHandle> coveringHandles = new HashSet<IFCAnyHandle>(); try { ICollection<ElementId> liningIds = InsulationLiningBase.GetLiningIds(document, ductOrPipeId); GetElementHandles(liningIds, coveringHandles); } catch { } try { ICollection<ElementId> insulationIds = InsulationLiningBase.GetInsulationIds(document, ductOrPipeId); GetElementHandles(insulationIds, coveringHandles); } catch { } if (coveringHandles.Count > 0) IFCInstanceExporter.CreateRelCoversBldgElements(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ductOrPipeHandle, coveringHandles); } // Relate stair components to stairs foreach (KeyValuePair<ElementId, StairRampContainerInfo> stairRamp in ExporterCacheManager.StairRampContainerInfoCache) { StairRampContainerInfo stairRampInfo = stairRamp.Value; IList<IFCAnyHandle> hnds = stairRampInfo.StairOrRampHandles; for (int ii = 0; ii < hnds.Count; ii++) { IFCAnyHandle hnd = hnds[ii]; if (IFCAnyHandleUtil.IsNullOrHasNoValue(hnd)) continue; IList<IFCAnyHandle> comps = stairRampInfo.Components[ii]; if (comps.Count == 0) continue; Element elem = document.GetElement(stairRamp.Key); string guid = GUIDUtil.CreateSubElementGUID(elem, (int)IFCStairSubElements.ContainmentRelation); if (locallyUsedGUIDs.Contains(guid)) guid = GUIDUtil.CreateGUID(); else locallyUsedGUIDs.Add(guid); ExporterUtil.RelateObjects(exporterIFC, guid, hnd, comps); } } ProjectInfo projectInfo = document.ProjectInformation; IFCAnyHandle buildingHnd = ExporterCacheManager.BuildingHandle; // relate assembly elements to assemblies foreach (KeyValuePair<ElementId, AssemblyInstanceInfo> assemblyInfoEntry in ExporterCacheManager.AssemblyInstanceCache) { AssemblyInstanceInfo assemblyInfo = assemblyInfoEntry.Value; if (assemblyInfo == null) continue; IFCAnyHandle assemblyInstanceHandle = assemblyInfo.AssemblyInstanceHandle; HashSet<IFCAnyHandle> elementHandles = assemblyInfo.ElementHandles; if (elementHandles != null && assemblyInstanceHandle != null && elementHandles.Contains(assemblyInstanceHandle)) elementHandles.Remove(assemblyInstanceHandle); if (assemblyInstanceHandle != null && elementHandles != null && elementHandles.Count != 0) { Element assemblyInstance = document.GetElement(assemblyInfoEntry.Key); string guid = GUIDUtil.CreateSubElementGUID(assemblyInstance, (int)IFCAssemblyInstanceSubElements.RelContainedInSpatialStructure); if (IFCAnyHandleUtil.IsSubTypeOf(assemblyInstanceHandle, IFCEntityType.IfcSystem)) { IFCInstanceExporter.CreateRelAssignsToGroup(file, guid, ownerHistory, null, null, elementHandles, null, assemblyInstanceHandle); } else { ExporterUtil.RelateObjects(exporterIFC, guid, assemblyInstanceHandle, elementHandles); // Set the PlacementRelTo of assembly elements to assembly instance. IFCAnyHandle assemblyPlacement = IFCAnyHandleUtil.GetObjectPlacement(assemblyInstanceHandle); AssemblyInstanceExporter.SetLocalPlacementsRelativeToAssembly(exporterIFC, assemblyPlacement, elementHandles); } // We don't do this in RegisterAssemblyElement because we want to make sure that the IfcElementAssembly has been created. ExporterCacheManager.ElementsInAssembliesCache.UnionWith(elementHandles); } } // relate group elements to groups foreach (KeyValuePair<ElementId, GroupInfo> groupEntry in ExporterCacheManager.GroupCache) { GroupInfo groupInfo = groupEntry.Value; if (groupInfo == null) continue; if (groupInfo.GroupHandle != null && groupInfo.ElementHandles != null && groupInfo.ElementHandles.Count != 0) { Element group = document.GetElement(groupEntry.Key); string guid = GUIDUtil.CreateSubElementGUID(group, (int)IFCGroupSubElements.RelAssignsToGroup); IFCAnyHandle groupHandle = groupInfo.GroupHandle; HashSet<IFCAnyHandle> elementHandles = groupInfo.ElementHandles; if (elementHandles != null && groupHandle != null && elementHandles.Contains(groupHandle)) elementHandles.Remove(groupHandle); if (elementHandles != null && groupHandle != null && elementHandles.Count > 0) { IFCInstanceExporter.CreateRelAssignsToGroup(file, guid, ownerHistory, null, null, elementHandles, null, groupHandle); } } } // create an association between the IfcBuilding and building elements with no other containment. HashSet<IFCAnyHandle> buildingElements = RemoveContainedHandlesFromSet(ExporterCacheManager.LevelInfoCache.OrphanedElements); buildingElements.UnionWith(exporterIFC.GetRelatedElements()); if (buildingElements.Count > 0) { HashSet<IFCAnyHandle> relatedElementSet = new HashSet<IFCAnyHandle>(buildingElements); string guid = GUIDUtil.CreateSubElementGUID(projectInfo, (int)IFCBuildingSubElements.RelContainedInSpatialStructure); IFCInstanceExporter.CreateRelContainedInSpatialStructure(file, guid, ownerHistory, null, null, relatedElementSet, buildingHnd); } // create an association between the IfcBuilding and spacial elements with no other containment. // The name "GetRelatedProducts()" is misleading; this only covers spaces. HashSet<IFCAnyHandle> buildingSapces = RemoveContainedHandlesFromSet(ExporterCacheManager.LevelInfoCache.OrphanedSpaces); buildingSapces.UnionWith(exporterIFC.GetRelatedProducts()); if (buildingSapces.Count > 0) { string guid = GUIDUtil.CreateSubElementGUID(projectInfo, (int)IFCBuildingSubElements.RelAggregatesProducts); ExporterCacheManager.ContainmentCache.SetGUIDForRelation(buildingHnd, guid); ExporterCacheManager.ContainmentCache.AddRelations(buildingHnd, buildingSapces); } // create a default site if we have latitude and longitude information. if (IFCAnyHandleUtil.IsNullOrHasNoValue(ExporterCacheManager.SiteHandle)) { using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { SiteExporter.ExportDefaultSite(exporterIFC, document, productWrapper); } } IFCAnyHandle siteHandle = ExporterCacheManager.SiteHandle; if (!IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle)) { ExporterCacheManager.ContainmentCache.AddRelation(ExporterCacheManager.ProjectHandle, siteHandle); // assoc. site to the building. ExporterCacheManager.ContainmentCache.AddRelation(siteHandle, buildingHnd); ExporterUtil.UpdateBuildingRelToPlacement(buildingHnd, siteHandle); } else { // relate building and project if no site ExporterCacheManager.ContainmentCache.AddRelation(ExporterCacheManager.ProjectHandle, buildingHnd); } // relate levels and products. RelateLevels(exporterIFC, document); // relate objects in containment cache. foreach (KeyValuePair<IFCAnyHandle, ICollection<IFCAnyHandle>> container in ExporterCacheManager.ContainmentCache) { if (container.Value.Count() > 0) { string relationGUID = ExporterCacheManager.ContainmentCache.GetGUIDForRelation(container.Key); ExporterUtil.RelateObjects(exporterIFC, relationGUID, container.Key, container.Value); } } // These elements are created internally, but we allow custom property sets for them. Create them here. using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { productWrapper.AddBuilding(projectInfo, buildingHnd); if (projectInfo != null) ExporterUtil.ExportRelatedProperties(exporterIFC, projectInfo, productWrapper); } // create material layer associations foreach (IFCAnyHandle materialSetLayerUsageHnd in ExporterCacheManager.MaterialLayerRelationsCache.Keys) { IFCInstanceExporter.CreateRelAssociatesMaterial(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ExporterCacheManager.MaterialLayerRelationsCache[materialSetLayerUsageHnd], materialSetLayerUsageHnd); } // create material associations foreach (IFCAnyHandle materialHnd in ExporterCacheManager.MaterialRelationsCache.Keys) { IFCInstanceExporter.CreateRelAssociatesMaterial(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ExporterCacheManager.MaterialRelationsCache[materialHnd], materialHnd); } // create type relations foreach (IFCAnyHandle typeObj in ExporterCacheManager.TypeRelationsCache.Keys) { IFCInstanceExporter.CreateRelDefinesByType(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ExporterCacheManager.TypeRelationsCache[typeObj], typeObj); } // create type property relations foreach (TypePropertyInfo typePropertyInfo in ExporterCacheManager.TypePropertyInfoCache.Values) { if (typePropertyInfo.AssignedToType) continue; ICollection<IFCAnyHandle> propertySets = typePropertyInfo.PropertySets; ISet<IFCAnyHandle> elements = typePropertyInfo.Elements; if (elements.Count == 0) continue; foreach (IFCAnyHandle propertySet in propertySets) { try { ExporterUtil.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, elements, propertySet); } catch { } } } // create space boundaries foreach (SpaceBoundary boundary in ExporterCacheManager.SpaceBoundaryCache) { SpatialElementExporter.ProcessIFCSpaceBoundary(exporterIFC, boundary, file); } // create wall/wall connectivity objects if (ExporterCacheManager.WallConnectionDataCache.Count > 0) { IList<IDictionary<ElementId, IFCAnyHandle>> hostObjects = exporterIFC.GetHostObjects(); List<int> relatingPriorities = new List<int>(); List<int> relatedPriorities = new List<int>(); foreach (WallConnectionData wallConnectionData in ExporterCacheManager.WallConnectionDataCache) { foreach (IDictionary<ElementId, IFCAnyHandle> mapForLevel in hostObjects) { IFCAnyHandle wallElementHandle, otherElementHandle; if (!mapForLevel.TryGetValue(wallConnectionData.FirstId, out wallElementHandle)) continue; if (!mapForLevel.TryGetValue(wallConnectionData.SecondId, out otherElementHandle)) continue; // NOTE: Definition of RelConnectsPathElements has the connection information reversed // with respect to the order of the paths. string connectionName = ExporterUtil.GetGlobalId(wallElementHandle) + "|" + ExporterUtil.GetGlobalId(otherElementHandle); string connectionType = "Structural"; // Assigned as Description IFCInstanceExporter.CreateRelConnectsPathElements(file, GUIDUtil.CreateGUID(), ownerHistory, connectionName, connectionType, wallConnectionData.ConnectionGeometry, wallElementHandle, otherElementHandle, relatingPriorities, relatedPriorities, wallConnectionData.SecondConnectionType, wallConnectionData.FirstConnectionType); } } } // create Zones { string relAssignsToGroupName = "Spatial Zone Assignment"; foreach (string zoneName in ExporterCacheManager.ZoneInfoCache.Keys) { ZoneInfo zoneInfo = ExporterCacheManager.ZoneInfoCache.Find(zoneName); if (zoneInfo != null) { IFCAnyHandle zoneHandle = IFCInstanceExporter.CreateZone(file, GUIDUtil.CreateGUID(), ownerHistory, zoneName, zoneInfo.Description, zoneInfo.ObjectType); IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory, relAssignsToGroupName, null, zoneInfo.RoomHandles, null, zoneHandle); HashSet<IFCAnyHandle> zoneHnds = new HashSet<IFCAnyHandle>(); zoneHnds.Add(zoneHandle); foreach (KeyValuePair<string, IFCAnyHandle> classificationReference in zoneInfo.ClassificationReferences) { IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(), ownerHistory, classificationReference.Key, "", zoneHnds, classificationReference.Value); } if (!IFCAnyHandleUtil.IsNullOrHasNoValue(zoneInfo.EnergyAnalysisProperySetHandle)) { ExporterUtil.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, zoneHnds, zoneInfo.EnergyAnalysisProperySetHandle); } if (!IFCAnyHandleUtil.IsNullOrHasNoValue(zoneInfo.ZoneCommonProperySetHandle)) { ExporterUtil.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, zoneHnds, zoneInfo.ZoneCommonProperySetHandle); } } } } // create Space Occupants { foreach (string spaceOccupantName in ExporterCacheManager.SpaceOccupantInfoCache.Keys) { SpaceOccupantInfo spaceOccupantInfo = ExporterCacheManager.SpaceOccupantInfoCache.Find(spaceOccupantName); if (spaceOccupantInfo != null) { IFCAnyHandle person = IFCInstanceExporter.CreatePerson(file, null, spaceOccupantName, null, null, null, null, null, null); IFCAnyHandle spaceOccupantHandle = IFCInstanceExporter.CreateOccupant(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceOccupantName, person, IFCOccupantType.NotDefined); IFCInstanceExporter.CreateRelOccupiesSpaces(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceOccupantInfo.RoomHandles, null, spaceOccupantHandle, null); HashSet<IFCAnyHandle> spaceOccupantHandles = new HashSet<IFCAnyHandle>(); spaceOccupantHandles.Add(spaceOccupantHandle); foreach (KeyValuePair<string, IFCAnyHandle> classificationReference in spaceOccupantInfo.ClassificationReferences) { IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(), ownerHistory, classificationReference.Key, "", spaceOccupantHandles, classificationReference.Value); } if (spaceOccupantInfo.SpaceOccupantProperySetHandle != null && spaceOccupantInfo.SpaceOccupantProperySetHandle.HasValue) { ExporterUtil.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceOccupantHandles, spaceOccupantInfo.SpaceOccupantProperySetHandle); } } } } // Create systems. HashSet<IFCAnyHandle> relatedBuildings = new HashSet<IFCAnyHandle>(); relatedBuildings.Add(buildingHnd); using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { foreach (KeyValuePair<ElementId, ISet<IFCAnyHandle>> system in ExporterCacheManager.SystemsCache.BuiltInSystemsCache) { MEPSystem systemElem = document.GetElement(system.Key) as MEPSystem; if (systemElem == null) continue; Element baseEquipment = systemElem.BaseEquipment; if (baseEquipment != null) { IFCAnyHandle memberHandle = ExporterCacheManager.MEPCache.Find(baseEquipment.Id); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(memberHandle)) system.Value.Add(memberHandle); } ElementType systemElemType = document.GetElement(systemElem.GetTypeId()) as ElementType; string name = NamingUtil.GetNameOverride(systemElem, systemElem.Name); string desc = NamingUtil.GetDescriptionOverride(systemElem, null); string objectType = NamingUtil.GetObjectTypeOverride(systemElem, (systemElemType != null) ? systemElemType.Name : ""); string systemGUID = GUIDUtil.CreateGUID(systemElem); IFCAnyHandle systemHandle = IFCInstanceExporter.CreateSystem(file, systemGUID, ownerHistory, name, desc, objectType); // Create classification reference when System has classification filed name assigned to it ClassificationUtil.CreateClassification(exporterIFC, file, systemElem, systemHandle); productWrapper.AddSystem(systemElem, systemHandle); IFCAnyHandle relServicesBuildings = IFCInstanceExporter.CreateRelServicesBuildings(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, systemHandle, relatedBuildings); IFCObjectType? objType = null; if (!ExporterCacheManager.ExportOptionsCache.ExportAsCoordinationView2) objType = IFCObjectType.Product; IFCAnyHandle relAssignsToGroup = IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, system.Value, objType, systemHandle); } } using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { foreach (KeyValuePair<ElementId, ISet<IFCAnyHandle>> entries in ExporterCacheManager.SystemsCache.ElectricalSystemsCache) { ElementId systemId = entries.Key; MEPSystem systemElem = document.GetElement(systemId) as MEPSystem; if (systemElem == null) continue; Element baseEquipment = systemElem.BaseEquipment; if (baseEquipment != null) { IFCAnyHandle memberHandle = ExporterCacheManager.MEPCache.Find(baseEquipment.Id); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(memberHandle)) entries.Value.Add(memberHandle); } // The Elements property below can throw an InvalidOperationException in some cases, which could // crash the export. Protect against this without having too generic a try/catch block. try { ElementSet members = systemElem.Elements; foreach (Element member in members) { IFCAnyHandle memberHandle = ExporterCacheManager.MEPCache.Find(member.Id); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(memberHandle)) entries.Value.Add(memberHandle); } } catch { } if (entries.Value.Count == 0) continue; ElementType systemElemType = document.GetElement(systemElem.GetTypeId()) as ElementType; string name = NamingUtil.GetNameOverride(systemElem, systemElem.Name); string desc = NamingUtil.GetDescriptionOverride(systemElem, null); string objectType = NamingUtil.GetObjectTypeOverride(systemElem, (systemElemType != null) ? systemElemType.Name : ""); string systemGUID = GUIDUtil.CreateGUID(systemElem); IFCAnyHandle systemHandle = IFCInstanceExporter.CreateSystem(file, systemGUID, ownerHistory, name, desc, objectType); // Create classification reference when System has classification filed name assigned to it ClassificationUtil.CreateClassification(exporterIFC, file, systemElem, systemHandle); productWrapper.AddSystem(systemElem, systemHandle); IFCAnyHandle relServicesBuildings = IFCInstanceExporter.CreateRelServicesBuildings(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, systemHandle, relatedBuildings); IFCObjectType? objType = null; if (!ExporterCacheManager.ExportOptionsCache.ExportAsCoordinationView2) objType = IFCObjectType.Product; IFCAnyHandle relAssignsToGroup = IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, entries.Value, objType, systemHandle); } } // Add presentation layer assignments - this is in addition to those added in EndExportInternal, and will // eventually replace the internal routine. foreach (KeyValuePair<string, ICollection<IFCAnyHandle>> presentationLayerSet in ExporterCacheManager.PresentationLayerSetCache) { ISet<IFCAnyHandle> validHandles = new HashSet<IFCAnyHandle>(); foreach (IFCAnyHandle handle in presentationLayerSet.Value) { if (!IFCAnyHandleUtil.IsNullOrHasNoValue(handle)) validHandles.Add(handle); } if (validHandles.Count > 0) IFCInstanceExporter.CreatePresentationLayerAssignment(file, presentationLayerSet.Key, null, validHandles, null); } // Add door/window openings. ExporterCacheManager.DoorWindowDelayedOpeningCreatorCache.ExecuteCreators(exporterIFC, document); foreach (SpaceInfo spaceInfo in ExporterCacheManager.SpaceInfoCache.SpaceInfos.Values) { if (spaceInfo.RelatedElements.Count > 0) { IFCInstanceExporter.CreateRelContainedInSpatialStructure(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceInfo.RelatedElements, spaceInfo.SpaceHandle); } } // Potentially modify elements with GUID values. if (ExporterCacheManager.GUIDsToStoreCache.Count > 0 && !ExporterCacheManager.ExportOptionsCache.ExportingLink) { using (SubTransaction st = new SubTransaction(document)) { st.Start(); foreach (KeyValuePair<KeyValuePair<Element, BuiltInParameter>, string> elementAndGUID in ExporterCacheManager.GUIDsToStoreCache) { if (elementAndGUID.Key.Key == null || elementAndGUID.Key.Value == BuiltInParameter.INVALID || elementAndGUID.Value == null) continue; ParameterUtil.SetStringParameter(elementAndGUID.Key.Key, elementAndGUID.Key.Value, elementAndGUID.Value); } st.Commit(); } } // Allow native code to remove some unused handles, assign presentation map information and clear internal caches. ExporterIFCUtils.EndExportInternal(exporterIFC); transaction.Commit(); } }
/// <summary> /// The implementation of CreateGlass(), creating the Window Glass Solid Geometry /// </summary> public override void CreateGlass() { double frameCurveOffset1 = 0.075; double frameDepth = m_wallThickness - 0.15; double sashCurveOffset = 0.075; double sashDepth = (frameDepth - m_windowInset) / 2; double glassDepth = 0.05; double glassOffsetSash = 0.05; //from the exterior of the sash //create first glass SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); CurveArray curveArr9 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1 - sashCurveOffset, -m_width / 2 + frameCurveOffset1 + sashCurveOffset, m_sillHeight + m_height / 2 - sashCurveOffset / 2, m_sillHeight + frameCurveOffset1 + sashCurveOffset, 0); m_document.Regenerate(); CurveArrArray curveArrArray5 = new CurveArrArray(); curveArrArray5.Append(curveArr9); Extrusion glass1 = m_extrusionCreator.NewExtrusion(curveArrArray5, m_sashPlane, sashDepth + glassOffsetSash + glassDepth, sashDepth + glassOffsetSash); m_document.Regenerate(); glass1.SetVisibility(CreateVisibility()); m_document.Regenerate(); Face eglassFace1 = GeoHelper.GetExtrusionFace(glass1, m_rightView, true); Face iglassFace1 = GeoHelper.GetExtrusionFace(glass1, m_rightView, false); Dimension glassDim1 = m_dimensionCreator.AddDimension(m_rightView, eglassFace1, iglassFace1); glassDim1.IsLocked = true; Dimension glass1WithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, eglassFace1); glass1WithSashPlane.IsLocked = true; //create the second glass CurveArray curveArr10 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1 - sashCurveOffset, -m_width / 2 + frameCurveOffset1 + sashCurveOffset, m_sillHeight + m_height - frameCurveOffset1 - sashCurveOffset, m_sillHeight + m_height / 2 + sashCurveOffset / 2, 0); CurveArrArray curveArrArray6 = new CurveArrArray(); curveArrArray6.Append(curveArr10); Extrusion glass2 = m_extrusionCreator.NewExtrusion(curveArrArray6, m_sashPlane, glassOffsetSash + glassDepth, glassOffsetSash); m_document.Regenerate(); glass2.SetVisibility(CreateVisibility()); m_document.Regenerate(); Face eglassFace2 = GeoHelper.GetExtrusionFace(glass2, m_rightView, true); Face iglassFace2 = GeoHelper.GetExtrusionFace(glass2, m_rightView, false); Dimension glassDim2 = m_dimensionCreator.AddDimension(m_rightView, eglassFace2, iglassFace2); glassDim2.IsLocked = true; Dimension glass2WithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, eglassFace2); glass2WithSashPlane.IsLocked = true; //set category if (null != m_glassCat) { glass1.Subcategory = m_glassCat; glass2.Subcategory = m_glassCat; } Autodesk.Revit.DB.ElementId id = new ElementId(m_glassMatID); glass1.ParametersMap.get_Item("Material").Set(id); glass2.ParametersMap.get_Item("Material").Set(id); subTransaction.Commit(); }
/// <summary> /// Delete a wall, append a node to tree view /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void deleteWallButton_Click(object sender, EventArgs e) { if (m_lastCreatedWall == null) return; // a sub-transaction is not necessary in this case // it is used for illustration purposes only using (SubTransaction subTransaction = new SubTransaction(m_document)) { // if not handled explicitly, the sub-transaction will be rolled back when leaving this block try { String wallId = m_lastCreatedWall.Id.IntegerValue.ToString(); if (DialogResult.No == MessageBox.Show("Do you really want to delete wall with id " + wallId + "?", "Warning", MessageBoxButtons.YesNo)) { return; } if (subTransaction.Start() == TransactionStatus.Started) { m_document.Delete(m_lastCreatedWall); updateModel(false); // immediately update the view to see the changes if (subTransaction.Commit() == TransactionStatus.Committed) { AddNode(OperationType.ObjectDeletion, "Deleted wall " + wallId); m_lastCreatedWall = null; UpdateButtonsStatus(); return; } } } catch (System.Exception ex) { MessageBox.Show("Exception when deleting a wall: " + ex.Message); } } MessageBox.Show("Deleting wall failed."); }
/// <summary> /// The implementation of CreateFrame() /// </summary> public override void CreateFrame() { SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); //get the wall in the document and retrieve the exterior face List<Wall> walls = Utility.GetElements<Wall>(m_application, m_document); Face exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true); //create sash referenceplane and exterior referenceplane CreateRefPlane refPlaneCreator = new CreateRefPlane(); if(m_sashPlane==null) m_sashPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ (0, m_wallThickness / 2 - m_windowInset, 0), new Autodesk.Revit.DB.XYZ (0, 0, 1), "Sash"); if (m_exteriorPlane==null) m_exteriorPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ (0, m_wallThickness / 2, 0), new Autodesk.Revit.DB.XYZ (0, 0, 1), "MyExterior"); m_document.Regenerate(); //add dimension between sash reference plane and wall face,and add parameter "Window Inset",label the dimension with window-inset parameter Dimension windowInsetDimension = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorWallFace); FamilyParameter windowInsetPara = m_familyManager.AddParameter("Window Inset", BuiltInParameterGroup.INVALID, ParameterType.Length, false); m_familyManager.Set(windowInsetPara, m_windowInset); windowInsetDimension.Label = windowInsetPara; //create the exterior frame double frameCurveOffset1 = 0.075; CurveArray curveArr1 = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0); CurveArray curveArr2 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr1, frameCurveOffset1); CurveArrArray curveArrArray1 = new CurveArrArray(); curveArrArray1.Append(curveArr1); curveArrArray1.Append(curveArr2); Extrusion extFrame = m_extrusionCreator.NewExtrusion(curveArrArray1, m_sashPlane, m_wallThickness / 2 + m_wallThickness/12, -m_windowInset); extFrame.SetVisibility( CreateVisibility()); m_document.Regenerate(); //add alignment between wall face and exterior frame face Face exteriorExtrusionFace1=GeoHelper.GetExtrusionFace(extFrame,m_rightView,true); Face interiorExtrusionFace1 = GeoHelper.GetExtrusionFace(extFrame,m_rightView,false); CreateAlignment alignmentCreator = new CreateAlignment(m_document); alignmentCreator.AddAlignment(m_rightView,exteriorWallFace,exteriorExtrusionFace1); //add dimension between sash referenceplane and exterior frame face and lock the dimension Dimension extFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, interiorExtrusionFace1); extFrameWithSashPlane.IsLocked = true; m_document.Regenerate(); //create the interior frame double frameCurveOffset2 = 0.125; CurveArray curveArr3 = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0); CurveArray curveArr4 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr3, frameCurveOffset2); m_document.Regenerate(); CurveArrArray curveArrArray2 = new CurveArrArray(); curveArrArray2.Append(curveArr3); curveArrArray2.Append(curveArr4); Extrusion intFrame = m_extrusionCreator.NewExtrusion(curveArrArray2, m_sashPlane, m_wallThickness - m_windowInset, m_wallThickness / 2 + m_wallThickness / 12); intFrame.SetVisibility( CreateVisibility()); m_document.Regenerate(); //add alignment between interior face of wall and interior frame face Face interiorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, false); Face interiorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, false); Face exteriorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, true); alignmentCreator.AddAlignment(m_rightView, interiorWallFace, interiorExtrusionFace2); //add dimension between sash referenceplane and interior frame face and lock the dimension Dimension intFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorExtrusionFace2); intFrameWithSashPlane.IsLocked = true; //create the sill frame CurveArray sillCurs = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + frameCurveOffset1, m_sillHeight, 0); CurveArrArray sillCurveArray = new CurveArrArray(); sillCurveArray.Append(sillCurs); Extrusion sillFrame= m_extrusionCreator.NewExtrusion(sillCurveArray, m_sashPlane, -m_windowInset, -m_windowInset - 0.1); m_document.Regenerate(); //add alignment between wall face and sill frame face Face sillExtFace = GeoHelper.GetExtrusionFace(sillFrame, m_rightView, false); alignmentCreator.AddAlignment(m_rightView, sillExtFace, exteriorWallFace); m_document.Regenerate(); //set subcategories of the frames if (m_frameCat != null) { extFrame.Subcategory = m_frameCat; intFrame.Subcategory = m_frameCat; sillFrame.Subcategory = m_frameCat; } subTransaction.Commit(); }
/// <summary> /// Completes the export process by writing information stored incrementally during export to the file. /// </summary> /// <param name="exporterIFC">The IFC exporter object.</param> /// <param name="document">The document to export.</param> private void EndExport(ExporterIFC exporterIFC, Document document) { IFCFile file = exporterIFC.GetFile(); IFCAnyHandle ownerHistory = exporterIFC.GetOwnerHistoryHandle(); using (IFCTransaction transaction = new IFCTransaction(file)) { // In some cases, like multi-story stairs and ramps, we may have the same Pset used for multiple levels. // If ifcParams is null, re-use the property set. ISet<string> locallyUsedGUIDs = new HashSet<string>(); // Relate Ducts and Pipes to their coverings (insulations and linings) foreach (ElementId ductOrPipeId in ExporterCacheManager.MEPCache.CoveredElementsCache) { IFCAnyHandle ductOrPipeHandle = ExporterCacheManager.MEPCache.Find(ductOrPipeId); if (IFCAnyHandleUtil.IsNullOrHasNoValue(ductOrPipeHandle)) continue; HashSet<IFCAnyHandle> coveringHandles = new HashSet<IFCAnyHandle>(); try { ICollection<ElementId> liningIds = InsulationLiningBase.GetLiningIds(document, ductOrPipeId); GetElementHandles(liningIds, coveringHandles); } catch { } try { ICollection<ElementId> insulationIds = InsulationLiningBase.GetInsulationIds(document, ductOrPipeId); GetElementHandles(insulationIds, coveringHandles); } catch { } if (coveringHandles.Count > 0) IFCInstanceExporter.CreateRelCoversBldgElements(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ductOrPipeHandle, coveringHandles); } // Relate stair components to stairs foreach (KeyValuePair<ElementId, StairRampContainerInfo> stairRamp in ExporterCacheManager.StairRampContainerInfoCache) { StairRampContainerInfo stairRampInfo = stairRamp.Value; IList<IFCAnyHandle> hnds = stairRampInfo.StairOrRampHandles; for (int ii = 0; ii < hnds.Count; ii++) { IFCAnyHandle hnd = hnds[ii]; if (IFCAnyHandleUtil.IsNullOrHasNoValue(hnd)) continue; IList<IFCAnyHandle> comps = stairRampInfo.Components[ii]; if (comps.Count == 0) continue; Element elem = document.GetElement(stairRamp.Key); string guid = GUIDUtil.CreateSubElementGUID(elem, (int)IFCStairSubElements.ContainmentRelation); if (locallyUsedGUIDs.Contains(guid)) guid = GUIDUtil.CreateGUID(); else locallyUsedGUIDs.Add(guid); ExporterUtil.RelateObjects(exporterIFC, guid, hnd, comps); } } ProjectInfo projectInfo = document.ProjectInformation; IFCAnyHandle buildingHnd = ExporterCacheManager.BuildingHandle; // relate assembly elements to assemblies foreach (KeyValuePair<ElementId, AssemblyInstanceInfo> assemblyInfoEntry in ExporterCacheManager.AssemblyInstanceCache) { AssemblyInstanceInfo assemblyInfo = assemblyInfoEntry.Value; if (assemblyInfo == null) continue; IFCAnyHandle assemblyInstanceHandle = assemblyInfo.AssemblyInstanceHandle; HashSet<IFCAnyHandle> elementHandles = assemblyInfo.ElementHandles; if (elementHandles != null && assemblyInstanceHandle != null && elementHandles.Contains(assemblyInstanceHandle)) elementHandles.Remove(assemblyInstanceHandle); if (assemblyInstanceHandle != null && elementHandles != null && elementHandles.Count != 0) { Element assemblyInstance = document.GetElement(assemblyInfoEntry.Key); string guid = GUIDUtil.CreateSubElementGUID(assemblyInstance, (int)IFCAssemblyInstanceSubElements.RelContainedInSpatialStructure); if (IFCAnyHandleUtil.IsSubTypeOf(assemblyInstanceHandle, IFCEntityType.IfcSystem)) { IFCInstanceExporter.CreateRelAssignsToGroup(file, guid, ownerHistory, null, null, elementHandles, null, assemblyInstanceHandle); } else { ExporterUtil.RelateObjects(exporterIFC, guid, assemblyInstanceHandle, elementHandles); // Set the PlacementRelTo of assembly elements to assembly instance. IFCAnyHandle assemblyPlacement = IFCAnyHandleUtil.GetObjectPlacement(assemblyInstanceHandle); AssemblyInstanceExporter.SetLocalPlacementsRelativeToAssembly(exporterIFC, assemblyPlacement, elementHandles); } // We don't do this in RegisterAssemblyElement because we want to make sure that the IfcElementAssembly has been created. ExporterCacheManager.ElementsInAssembliesCache.UnionWith(elementHandles); } } // relate group elements to groups foreach (KeyValuePair<ElementId, GroupInfo> groupEntry in ExporterCacheManager.GroupCache) { GroupInfo groupInfo = groupEntry.Value; if (groupInfo == null) continue; if (groupInfo.GroupHandle != null && groupInfo.ElementHandles != null && groupInfo.ElementHandles.Count != 0) { Element group = document.GetElement(groupEntry.Key); string guid = GUIDUtil.CreateSubElementGUID(group, (int)IFCGroupSubElements.RelAssignsToGroup); IFCAnyHandle groupHandle = groupInfo.GroupHandle; HashSet<IFCAnyHandle> elementHandles = groupInfo.ElementHandles; if (elementHandles != null && groupHandle != null && elementHandles.Contains(groupHandle)) elementHandles.Remove(groupHandle); if (elementHandles != null && groupHandle != null && elementHandles.Count > 0) { IFCInstanceExporter.CreateRelAssignsToGroup(file, guid, ownerHistory, null, null, elementHandles, null, groupHandle); } } } // create spatial structure holder ICollection<IFCAnyHandle> relatedElements = exporterIFC.GetRelatedElements(); if (relatedElements.Count > 0) { HashSet<IFCAnyHandle> relatedElementSet = new HashSet<IFCAnyHandle>(relatedElements); string guid = GUIDUtil.CreateSubElementGUID(projectInfo, (int)IFCBuildingSubElements.RelContainedInSpatialStructure); IFCInstanceExporter.CreateRelContainedInSpatialStructure(file, guid, ownerHistory, null, null, relatedElementSet, buildingHnd); } ICollection<IFCAnyHandle> relatedProducts = exporterIFC.GetRelatedProducts(); if (relatedProducts.Count > 0) { string guid = GUIDUtil.CreateSubElementGUID(projectInfo, (int)IFCBuildingSubElements.RelAggregatesProducts); ExporterCacheManager.ContainmentCache.SetGUIDForRelation(buildingHnd, guid); ExporterCacheManager.ContainmentCache.AddRelations(buildingHnd, relatedProducts); } // create a default site if we have latitude and longitude information. if (IFCAnyHandleUtil.IsNullOrHasNoValue(exporterIFC.GetSite())) { using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { SiteExporter.ExportDefaultSite(exporterIFC, document, productWrapper); } } IFCAnyHandle siteHandle = exporterIFC.GetSite(); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(siteHandle)) { ExporterCacheManager.ContainmentCache.AddRelation(exporterIFC.GetProject(), siteHandle); // assoc. site to the building. ExporterCacheManager.ContainmentCache.AddRelation(siteHandle, buildingHnd); ExporterUtil.UpdateBuildingRelToPlacement(buildingHnd, siteHandle); } else { // relate building and project if no site ExporterCacheManager.ContainmentCache.AddRelation(exporterIFC.GetProject(), buildingHnd); } // relate levels and products. RelateLevels(exporterIFC, document); // relate objects in containment cache. foreach (KeyValuePair<IFCAnyHandle, ICollection<IFCAnyHandle>> container in ExporterCacheManager.ContainmentCache) { if (container.Value.Count() > 0) { string relationGUID = ExporterCacheManager.ContainmentCache.GetGUIDForRelation(container.Key); ExporterUtil.RelateObjects(exporterIFC, relationGUID, container.Key, container.Value); } } // These elements are created internally, but we allow custom property sets for them. Create them here. using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { productWrapper.AddBuilding(projectInfo, buildingHnd); if (projectInfo != null) ExporterUtil.ExportRelatedProperties(exporterIFC, projectInfo, productWrapper); } // create material layer associations foreach (IFCAnyHandle materialSetLayerUsageHnd in ExporterCacheManager.MaterialLayerRelationsCache.Keys) { IFCInstanceExporter.CreateRelAssociatesMaterial(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ExporterCacheManager.MaterialLayerRelationsCache[materialSetLayerUsageHnd], materialSetLayerUsageHnd); } // create material associations foreach (IFCAnyHandle materialHnd in ExporterCacheManager.MaterialRelationsCache.Keys) { IFCInstanceExporter.CreateRelAssociatesMaterial(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ExporterCacheManager.MaterialRelationsCache[materialHnd], materialHnd); } // create type relations foreach (IFCAnyHandle typeObj in ExporterCacheManager.TypeRelationsCache.Keys) { IFCInstanceExporter.CreateRelDefinesByType(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, ExporterCacheManager.TypeRelationsCache[typeObj], typeObj); } // create type property relations foreach (TypePropertyInfo typePropertyInfo in ExporterCacheManager.TypePropertyInfoCache.Values) { if (typePropertyInfo.AssignedToType) continue; ICollection<IFCAnyHandle> propertySets = typePropertyInfo.PropertySets; ISet<IFCAnyHandle> elements = typePropertyInfo.Elements; if (elements.Count == 0) continue; foreach (IFCAnyHandle propertySet in propertySets) { try { IFCInstanceExporter.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, elements, propertySet); } catch { } } } // create space boundaries foreach (SpaceBoundary boundary in ExporterCacheManager.SpaceBoundaryCache) { SpatialElementExporter.ProcessIFCSpaceBoundary(exporterIFC, boundary, file); } // create wall/wall connectivity objects if (ExporterCacheManager.WallConnectionDataCache.Count > 0) { IList<IDictionary<ElementId, IFCAnyHandle>> hostObjects = exporterIFC.GetHostObjects(); List<int> relatingPriorities = new List<int>(); List<int> relatedPriorities = new List<int>(); foreach (WallConnectionData wallConnectionData in ExporterCacheManager.WallConnectionDataCache) { foreach (IDictionary<ElementId, IFCAnyHandle> mapForLevel in hostObjects) { IFCAnyHandle wallElementHandle, otherElementHandle; if (!mapForLevel.TryGetValue(wallConnectionData.FirstId, out wallElementHandle)) continue; if (!mapForLevel.TryGetValue(wallConnectionData.SecondId, out otherElementHandle)) continue; // NOTE: Definition of RelConnectsPathElements has the connection information reversed // with respect to the order of the paths. string connectionName = IFCAnyHandleUtil.GetStringAttribute(wallElementHandle, "GlobalId") + "|" + IFCAnyHandleUtil.GetStringAttribute(otherElementHandle, "GlobalId"); string connectionType = "Structural"; // Assigned as Description IFCInstanceExporter.CreateRelConnectsPathElements(file, GUIDUtil.CreateGUID(), ownerHistory, connectionName, connectionType, wallConnectionData.ConnectionGeometry, wallElementHandle, otherElementHandle, relatingPriorities, relatedPriorities, wallConnectionData.SecondConnectionType, wallConnectionData.FirstConnectionType); } } } // create Zones { string relAssignsToGroupName = "Spatial Zone Assignment"; foreach (string zoneName in ExporterCacheManager.ZoneInfoCache.Keys) { ZoneInfo zoneInfo = ExporterCacheManager.ZoneInfoCache.Find(zoneName); if (zoneInfo != null) { IFCAnyHandle zoneHandle = IFCInstanceExporter.CreateZone(file, GUIDUtil.CreateGUID(), ownerHistory, zoneName, zoneInfo.Description, zoneInfo.ObjectType); IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory, relAssignsToGroupName, null, zoneInfo.RoomHandles, null, zoneHandle); HashSet<IFCAnyHandle> zoneHnds = new HashSet<IFCAnyHandle>(); zoneHnds.Add(zoneHandle); foreach (KeyValuePair<string, IFCAnyHandle> classificationReference in zoneInfo.ClassificationReferences) { IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(), ownerHistory, classificationReference.Key, "", zoneHnds, classificationReference.Value); } if (!IFCAnyHandleUtil.IsNullOrHasNoValue(zoneInfo.EnergyAnalysisProperySetHandle)) { IFCInstanceExporter.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, zoneHnds, zoneInfo.EnergyAnalysisProperySetHandle); } if (!IFCAnyHandleUtil.IsNullOrHasNoValue(zoneInfo.ZoneCommonProperySetHandle)) { IFCInstanceExporter.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, zoneHnds, zoneInfo.ZoneCommonProperySetHandle); } } } } // create Space Occupants { foreach (string spaceOccupantName in ExporterCacheManager.SpaceOccupantInfoCache.Keys) { SpaceOccupantInfo spaceOccupantInfo = ExporterCacheManager.SpaceOccupantInfoCache.Find(spaceOccupantName); if (spaceOccupantInfo != null) { IFCAnyHandle person = IFCInstanceExporter.CreatePerson(file, null, spaceOccupantName, null, null, null, null, null, null); IFCAnyHandle spaceOccupantHandle = IFCInstanceExporter.CreateOccupant(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceOccupantName, person, IFCOccupantType.NotDefined); IFCInstanceExporter.CreateRelOccupiesSpaces(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceOccupantInfo.RoomHandles, null, spaceOccupantHandle, null); HashSet<IFCAnyHandle> spaceOccupantHandles = new HashSet<IFCAnyHandle>(); spaceOccupantHandles.Add(spaceOccupantHandle); foreach (KeyValuePair<string, IFCAnyHandle> classificationReference in spaceOccupantInfo.ClassificationReferences) { IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(), ownerHistory, classificationReference.Key, "", spaceOccupantHandles, classificationReference.Value); } if (spaceOccupantInfo.SpaceOccupantProperySetHandle != null && spaceOccupantInfo.SpaceOccupantProperySetHandle.HasValue) { IFCAnyHandle relHnd = IFCInstanceExporter.CreateRelDefinesByProperties(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceOccupantHandles, spaceOccupantInfo.SpaceOccupantProperySetHandle); } } } } // Create systems. HashSet<IFCAnyHandle> relatedBuildings = new HashSet<IFCAnyHandle>(); relatedBuildings.Add(buildingHnd); using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { foreach (KeyValuePair<ElementId, ISet<IFCAnyHandle>> system in ExporterCacheManager.SystemsCache.BuiltInSystemsCache) { MEPSystem systemElem = document.GetElement(system.Key) as MEPSystem; if (systemElem == null) continue; Element baseEquipment = systemElem.BaseEquipment; if (baseEquipment != null) { IFCAnyHandle memberHandle = ExporterCacheManager.MEPCache.Find(baseEquipment.Id); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(memberHandle)) system.Value.Add(memberHandle); } ElementType systemElemType = document.GetElement(systemElem.GetTypeId()) as ElementType; string name = NamingUtil.GetNameOverride(systemElem, systemElem.Name); string desc = NamingUtil.GetDescriptionOverride(systemElem, null); string objectType = NamingUtil.GetObjectTypeOverride(systemElem, (systemElemType != null) ? systemElemType.Name : ""); string systemGUID = GUIDUtil.CreateGUID(systemElem); IFCAnyHandle systemHandle = IFCInstanceExporter.CreateSystem(file, systemGUID, ownerHistory, name, desc, objectType); // Create classification reference when System has classification filed name assigned to it ClassificationUtil.CreateClassification(exporterIFC, file, systemElem, systemHandle); productWrapper.AddSystem(systemElem, systemHandle); IFCAnyHandle relServicesBuildings = IFCInstanceExporter.CreateRelServicesBuildings(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, systemHandle, relatedBuildings); IFCObjectType? objType = null; if (!ExporterCacheManager.ExportOptionsCache.ExportAsCoordinationView2) objType = IFCObjectType.Product; IFCAnyHandle relAssignsToGroup = IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, system.Value, objType, systemHandle); } } using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { foreach (KeyValuePair<ElementId, ISet<IFCAnyHandle>> entries in ExporterCacheManager.SystemsCache.ElectricalSystemsCache) { ElementId systemId = entries.Key; MEPSystem systemElem = document.GetElement(systemId) as MEPSystem; if (systemElem == null) continue; Element baseEquipment = systemElem.BaseEquipment; if (baseEquipment != null) { IFCAnyHandle memberHandle = ExporterCacheManager.MEPCache.Find(baseEquipment.Id); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(memberHandle)) entries.Value.Add(memberHandle); } // The Elements property below can throw an InvalidOperationException in some cases, which could // crash the export. Protect against this without having too generic a try/catch block. try { ElementSet members = systemElem.Elements; foreach (Element member in members) { IFCAnyHandle memberHandle = ExporterCacheManager.MEPCache.Find(member.Id); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(memberHandle)) entries.Value.Add(memberHandle); } } catch { } if (entries.Value.Count == 0) continue; ElementType systemElemType = document.GetElement(systemElem.GetTypeId()) as ElementType; string name = NamingUtil.GetNameOverride(systemElem, systemElem.Name); string desc = NamingUtil.GetDescriptionOverride(systemElem, null); string objectType = NamingUtil.GetObjectTypeOverride(systemElem, (systemElemType != null) ? systemElemType.Name : ""); string systemGUID = GUIDUtil.CreateGUID(systemElem); IFCAnyHandle systemHandle = IFCInstanceExporter.CreateSystem(file, systemGUID, ownerHistory, name, desc, objectType); // Create classification reference when System has classification filed name assigned to it ClassificationUtil.CreateClassification(exporterIFC, file, systemElem, systemHandle); productWrapper.AddSystem(systemElem, systemHandle); IFCAnyHandle relServicesBuildings = IFCInstanceExporter.CreateRelServicesBuildings(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, systemHandle, relatedBuildings); IFCObjectType? objType = null; if (!ExporterCacheManager.ExportOptionsCache.ExportAsCoordinationView2) objType = IFCObjectType.Product; IFCAnyHandle relAssignsToGroup = IFCInstanceExporter.CreateRelAssignsToGroup(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, entries.Value, objType, systemHandle); } } // Add presentation layer assignments - this is in addition to those added in EndExportInternal, and will // eventually replace the internal routine. foreach (KeyValuePair<string, ICollection<IFCAnyHandle>> presentationLayerSet in ExporterCacheManager.PresentationLayerSetCache) { ISet<IFCAnyHandle> validHandles = new HashSet<IFCAnyHandle>(); foreach (IFCAnyHandle handle in presentationLayerSet.Value) { if (!IFCAnyHandleUtil.IsNullOrHasNoValue(handle)) validHandles.Add(handle); } if (validHandles.Count > 0) IFCInstanceExporter.CreatePresentationLayerAssignment(file, presentationLayerSet.Key, null, validHandles, null); } // Add door/window openings. ExporterCacheManager.DoorWindowDelayedOpeningCreatorCache.ExecuteCreators(exporterIFC, document); foreach (SpaceInfo spaceInfo in ExporterCacheManager.SpaceInfoCache.SpaceInfos.Values) { if (spaceInfo.RelatedElements.Count > 0) { IFCInstanceExporter.CreateRelContainedInSpatialStructure(file, GUIDUtil.CreateGUID(), ownerHistory, null, null, spaceInfo.RelatedElements, spaceInfo.SpaceHandle); } } // Potentially modify elements with GUID values. if (ExporterCacheManager.GUIDsToStoreCache.Count > 0 && !ExporterCacheManager.ExportOptionsCache.ExportingLink) { using (SubTransaction st = new SubTransaction(document)) { st.Start(); foreach (KeyValuePair<KeyValuePair<Element, BuiltInParameter>, string> elementAndGUID in ExporterCacheManager.GUIDsToStoreCache) { if (elementAndGUID.Key.Key == null || elementAndGUID.Key.Value == BuiltInParameter.INVALID || elementAndGUID.Value == null) continue; ParameterUtil.SetStringParameter(elementAndGUID.Key.Key, elementAndGUID.Key.Value, elementAndGUID.Value); } st.Commit(); } } // Allow native code to remove some unused handles, assign presentation map information and clear internal caches. ExporterIFCUtils.EndExportInternal(exporterIFC); //create header ExportOptionsCache exportOptionsCache = ExporterCacheManager.ExportOptionsCache; string coordinationView = null; if (exportOptionsCache.ExportAsCoordinationView2) coordinationView = "CoordinationView_V2.0"; else coordinationView = "CoordinationView"; List<string> descriptions = new List<string>(); if (ExporterCacheManager.ExportOptionsCache.ExportAs2x2 || ExporterUtil.DoCodeChecking(exportOptionsCache)) { descriptions.Add("IFC2X_PLATFORM"); } else { string currentLine; if (ExporterUtil.IsFMHandoverView()) { currentLine = string.Format("ViewDefinition [{0}{1}{2}{3}]", coordinationView, exportOptionsCache.ExportBaseQuantities ? ", QuantityTakeOffAddOnView" : "", ", ", "FMHandOverView"); } else { currentLine = string.Format("ViewDefinition [{0}{1}]", coordinationView, exportOptionsCache.ExportBaseQuantities ? ", QuantityTakeOffAddOnView" : ""); } descriptions.Add(currentLine); } string projectNumber = (projectInfo != null) ? projectInfo.Number : null; string projectName = (projectInfo != null) ? projectInfo.Name : null; string projectStatus = (projectInfo != null) ? projectInfo.Status : null; if (projectNumber == null) projectNumber = string.Empty; if (projectName == null) projectName = exportOptionsCache.FileName; if (projectStatus == null) projectStatus = string.Empty; IFCAnyHandle project = exporterIFC.GetProject(); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(project)) IFCAnyHandleUtil.UpdateProject(project, projectNumber, projectName, projectStatus); IFCInstanceExporter.CreateFileSchema(file); IFCInstanceExporter.CreateFileDescription(file, descriptions); // Get stored File Header information from the UI and use it for export IFCFileHeader fHeader = new IFCFileHeader(); IFCFileHeaderItem fHItem = null; fHeader.GetSavedFileHeader(document, out fHItem); List<string> author = new List<string>(); if (String.IsNullOrEmpty(fHItem.AuthorName) == false) { author.Add(fHItem.AuthorName); if (String.IsNullOrEmpty(fHItem.AuthorEmail) == false) author.Add(fHItem.AuthorEmail); } else author.Add(String.Empty); List<string> organization = new List<string>(); if (String.IsNullOrEmpty(fHItem.Organization) == false) organization.Add(fHItem.Organization); else organization.Add(String.Empty); string versionInfos = document.Application.VersionBuild + " - " + ExporterCacheManager.ExportOptionsCache.ExporterVersion + " - " + ExporterCacheManager.ExportOptionsCache.ExporterUIVersion; if (fHItem.Authorization == null) fHItem.Authorization = String.Empty; IFCInstanceExporter.CreateFileName(file, projectNumber, author, organization, document.Application.VersionName, versionInfos, fHItem.Authorization); transaction.Commit(); IFCFileWriteOptions writeOptions = new IFCFileWriteOptions(); writeOptions.FileName = exportOptionsCache.FileName; writeOptions.FileFormat = exportOptionsCache.IFCFileFormat; if (writeOptions.FileFormat == IFCFileFormat.IfcXML || writeOptions.FileFormat == IFCFileFormat.IfcXMLZIP) { writeOptions.XMLConfigFileName = Path.Combine(ExporterUtil.RevitProgramPath, "EDM\\ifcXMLconfiguration.xml"); } file.Write(writeOptions); // Reuse almost all of the information above to write out extra copies of the IFC file. if (exportOptionsCache.ExportingLink) { int numRevitLinkInstances = exportOptionsCache.GetNumLinkInstanceInfos(); for (int ii = 1; ii < numRevitLinkInstances; ii++) { Transform linkTrf = ExporterCacheManager.ExportOptionsCache.GetLinkInstanceTransform(ii); IFCAnyHandle relativePlacement = ExporterUtil.CreateAxis2Placement3D(file, linkTrf.Origin, linkTrf.BasisZ, linkTrf.BasisX); ExporterUtil.UpdateBuildingRelativePlacement(buildingHnd, relativePlacement); writeOptions.FileName = exportOptionsCache.GetLinkInstanceFileName(ii); file.Write(writeOptions); } } } }
/// <summary> /// The implementation of CombineAndBuild() ,defining New Window Types /// </summary> public override void CombineAndBuild() { SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); foreach (String type in m_para.WinParaTab.Keys) { WindowParameter para = m_para.WinParaTab[type] as WindowParameter; newFamilyType(para); } subTransaction.Commit(); try { m_document.SaveAs(m_para.PathName); } catch(Exception e) { System.Diagnostics.Debug.WriteLine("Write to " + m_para.PathName + " Failed"); System.Diagnostics.Debug.WriteLine(e.Message); } }
/// <summary> /// The method is used to create dimension between two faces /// </summary> /// <param name="view">the view</param> /// <param name="face1">the first face</param> /// <param name="face2">the second face</param> /// <returns>the new dimension</returns> public Dimension AddDimension(View view, Face face1, Face face2) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ (); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ (); Line line; Reference ref1; Reference ref2; ReferenceArray refArray = new ReferenceArray(); PlanarFace pFace1 = face1 as PlanarFace; ref1 = pFace1.Reference; PlanarFace pFace2 = face2 as PlanarFace; ref2 = pFace2.Reference; if (null != ref1 && null != ref2) { refArray.Append(ref1); refArray.Append(ref2); } startPoint = pFace1.Origin; endPoint = new Autodesk.Revit.DB.XYZ (startPoint.X, pFace2.Origin.Y, startPoint.Z); SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); line = m_application.Create.NewLineBound(startPoint, endPoint); dim = m_document.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return dim; }
/// <summary> /// This method is used to create dimension among three reference planes /// </summary> /// <param name="view">the view</param> /// <param name="refPlane1">the first reference plane</param> /// <param name="refPlane2">the second reference plane</param> /// <param name="refPlane">the middle reference plane</param> /// <returns>the new dimension</returns> public Dimension AddDimension(View view, ReferencePlane refPlane1, ReferencePlane refPlane2, ReferencePlane refPlane) { Dimension dim; Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ (); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ (); Line line; Reference ref1; Reference ref2; Reference ref3; ReferenceArray refArray = new ReferenceArray(); ref1 = refPlane1.Reference; ref2 = refPlane2.Reference; ref3 = refPlane.Reference; startPoint = refPlane1.FreeEnd; endPoint = refPlane2.FreeEnd; line = m_application.Create.NewLineBound(startPoint, endPoint); if (null != ref1 && null != ref2 && null != ref3) { refArray.Append(ref1); refArray.Append(ref3); refArray.Append(ref2); } SubTransaction subTransaction = new SubTransaction(m_document); subTransaction.Start(); dim = m_document.FamilyCreate.NewDimension(view, line, refArray); subTransaction.Commit(); return dim; }