/// <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 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 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(); } } }
/// <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(); } }
public TransactionGridCellViewModel( TransactionGridColumnViewModel column, TransactionGridRowViewModel row, Transaction transaction, SubTransactionRowViewModel subTransactionRow, SubTransaction subTransaction) { _column = column; _row = row; _row.PropertyChanged += Row_PropertyChanged; _transaction = transaction; _subTransaction = subTransaction; _subTransactionRow = subTransactionRow; _isEditing = row.IsEditing; CellType = ColumnType.SubTransaction; _entity = subTransaction; }
/// <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(); }
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); }
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); }
private void RebuildSchema(Document doc, Schema schema, List <ElementId> elementIds, List <string> paths, List <string> worksheets, List <string> dateTimes, List <int> pathTypes) { using (Transaction trans = new Transaction(doc, "Updating Excel Link Information")) { trans.Start(); try { SubTransaction deleteTrans = new SubTransaction(doc); deleteTrans.Start(); // Delete the schema/entity from the ProjectInformation doc.ProjectInformation.DeleteEntity(schema); Schema.EraseSchemaAndAllEntities(schema, false); deleteTrans.Commit(); // Start a subtransaction for create the datastorage and entity SubTransaction createTrans = new SubTransaction(doc); createTrans.Start(); // Build the schedule Entity ExcelScheduleEntity schedEntity = new ExcelScheduleEntity() { DateTime = dateTimes, ExcelFilePath = paths, PathType = pathTypes, ScheduleId = elementIds, WorksheetName = worksheets }; // Create a DataStorage for the entity DataStorage ds = DataStorage.Create(doc); ds.Name = Properties.Settings.Default.DataStorageName; ds.SetEntity(schedEntity); // complete the Create subtransaction createTrans.Commit(); } catch (Exception ex) { TaskDialog.Show("Test", ex.ToString()); } trans.Commit(); } }
/// <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> /// 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 (TaskDialogResult.No == TaskDialog.Show("Warning", "Do you really want to delete wall with id " + wallId + "?", TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No)) { return; } if (subTransaction.Start() == TransactionStatus.Started) { m_document.Delete(m_lastCreatedWall.Id); 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) { TaskDialog.Show("Revit", "Exception when deleting a wall: " + ex.Message); } } TaskDialog.Show("Revit", "Deleting wall failed."); }
/// <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); }
/// <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 left 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 - frameCurveOffset1 - sashCurveOffset, 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; //set category if (null != m_glassCat) { glass1.Subcategory = m_glassCat; } Autodesk.Revit.DB.ElementId id = new ElementId(m_glassMatID); glass1.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM).Set(id); subTransaction.Commit(); }
/// <summary> /// Initialize an AdaptiveComponent element /// </summary> /// <param name="uvParams">Parameters to use as reference</param> /// <param name="f">Face to use as reference</param> /// <param name="ft">familyType to place</param> private void InitAdaptiveComponent(double[][] uvParams, ElementFaceReference f, FamilyType ft) { // 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 (ft.InternalFamilySymbol.Id != oldFam.Symbol.Id) { InternalSetFamilySymbol(ft); } InternalSetUvsAndFace(uvParams.ToUvs(), f.InternalReference); 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, ft.InternalFamilySymbol); InternalSetFamilyInstance(fam); InternalSetUvsAndFace(uvParams.ToUvs(), f.InternalReference); st.Commit(); } catch (Exception ex) { st.RollBack(); throw new ArgumentException(Revit.Properties.Resources.Adaptive_Component_Creation_Failed + ex.Message); } } TransactionManager.Instance.TransactionTaskDone(); ElementBinder.SetElementForTrace(InternalElement); }
public void Execute(UpdaterData data) { Document Doc = data.GetDocument(); using (SubTransaction str = new SubTransaction(Doc)) { try { var addedElementIds = data.GetAddedElementIds(); var modifiedElementIds = data.GetModifiedElementIds(); var deletedElementIds = data.GetDeletedElementIds(); // Your Code Goes Here } catch { str.RollBack(); } } }
/// <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 = SketchPlane.Create(m_document, workPlane.GetPlane()); 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> /// 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) { TaskDialog.Show("Revit", "Exception when creating a wall: " + ex.Message); } } TaskDialog.Show("Revit", "Creating wall failed"); }
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(); } }
/// <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(); } }
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 Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { UIDocument uidoc = commandData.Application.ActiveUIDocument; Document doc = uidoc.Document; TransactionGroup tg = new TransactionGroup(doc, "TG"); tg.Start(); Transaction t1 = new Transaction(doc, "T1"); t1.Start(); Wall.Create(doc, Line.CreateBound(new XYZ(), new XYZ(0, 10, 0)), Level.Create(doc, 0).Id, false); t1.Commit(); TaskDialog.Show("提示", "已经生成第一道墙"); Transaction t2 = new Transaction(doc, "T2"); t2.Start(); Wall.Create(doc, Line.CreateBound(new XYZ(), new XYZ(0, 10, 0)), Level.Create(doc, 0).Id, false); t2.Commit(); tg.Commit(); Transaction tt = new Transaction(doc, "Transact"); tt.Start(); SubTransaction st1 = new SubTransaction(doc); st1.Start(); SubTransaction st2 = new SubTransaction(doc); st2.Start(); st2.Commit(); TaskDialog.Show("提示", "t2已提交"); st1.Commit(); TaskDialog.Show("提示", "t1已提交"); tt.Commit(); return(Result.Succeeded); }
/// <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> /// 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); } }
public static ModelLine GetSpanDirection(this Floor floor) { var doc = floor.Document; using (var tran = new SubTransaction(doc)) { tran.Start(); var relatedElementIds = doc.Delete(floor.Id); tran.RollBack(); foreach (var id in relatedElementIds) { var element = doc.GetElement(id); if (element is ModelLine && element.Name.Contains("Span")) { return(element as ModelLine); } } } return(null); }
public TransactionStatus Start() { if (HasStarted()) { throw new InvalidOperationException($"{name} transaction is already started."); } TransactionStatus status; if (document.IsModifiable) { var subtr = new SubTransaction(document); status = subtr.Start(); subTransaction = subtr; } else { var trans = new Transaction(document, name); status = trans.Start(); transaction = trans; } return(status); }
private IList <Plane> CreatePlaneBound2(Document doc, XYZ startingPoint, double mainPosition, double secondPosition, double mainDirectionAmount, double secondDirectionAmount, XYZ mainDirection, XYZ secondDirection) { IList <Plane> currentPlanes = new List <Plane>(); double xMult = (secondPosition * secondDirectionAmount); double yMult = (mainPosition * mainDirectionAmount); using (SubTransaction st = new SubTransaction(doc)) { st.Start(); XYZ firstPoint = startingPoint + secondDirection.Multiply(xMult) + mainDirection.Multiply(yMult); XYZ secondPoint = firstPoint + mainDirection.Multiply(mainDirectionAmount); XYZ thirdPoint = new XYZ(0, 0, 1); XYZ midp1 = Utils.GetPoint.getMidPoint(firstPoint, secondPoint); Plane currentPlane = doc.Create.NewReferencePlane(secondPoint, firstPoint, thirdPoint, doc.ActiveView).GetPlane(); XYZ firstPoint2 = firstPoint + secondDirection.Multiply(secondDirectionAmount - Utils.ConvertM.cmToFeet(2)); XYZ secondPoint2 = firstPoint2 + mainDirection.Multiply(mainDirectionAmount); XYZ midp2 = Utils.GetPoint.getMidPoint(firstPoint2, secondPoint2); Plane currentPlane2 = doc.Create.NewReferencePlane(firstPoint2, secondPoint2, thirdPoint, doc.ActiveView).GetPlane(); currentPlanes.Add(currentPlane); currentPlanes.Add(currentPlane2); st.RollBack(); } //normalPoint.Activate(); //doc.Create.NewFamilyInstance(midp1 + currentPlane.Normal, normalPoint, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); //doc.Create.NewFamilyInstance(midp2 + currentPlane2.Normal, normalPoint, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); return(currentPlanes); }
void SetTangentLockInProfileSketch2( Document famdoc, Form[] extrusions) { ICollection <ElementId> delIds = null; List <ElementId> enmIDs = new List <ElementId>(); using (SubTransaction delTrans = new SubTransaction(famdoc)) { try { delTrans.Start(); delIds = famdoc.Delete(extrusions[0].Id); delTrans.RollBack(); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.ToString()); } } // Get the model lines in the profile and use the end // points for reference the sketch dimensions diameter List <ModelArc> mArcsR1 = new List <ModelArc>(); List <ModelArc> mArcsR2 = new List <ModelArc>(); List <ModelLine> mLines = new List <ModelLine>(); foreach (ElementId id in delIds) { enmIDs.Add(id); } for (int i = 0; i < enmIDs.Count; i++) { Element ele = famdoc.GetElement(enmIDs[i]); if (ele is ModelArc) { ModelArc ma = ele as ModelArc; Curve c = ma.GeometryCurve; Arc a = c as Arc; if (Math.Round(r1, 6) == Math.Round(a.Radius, 6)) { mArcsR1.Add(ma); } if (Math.Round(r2, 6) == Math.Round(a.Radius, 6)) { mArcsR2.Add(ma); } } if (ele is ModelLine) { ModelLine ml = ele as ModelLine; ElementId beforeId = null; ElementId afterId = null; ISet <ElementId> joinedBefore = ml.GetAdjoinedCurveElements(0); foreach (ElementId id in joinedBefore) { Element joinedEle = famdoc.GetElement(id); if (joinedEle is ModelArc) { beforeId = id; break; } } ISet <ElementId> joinedAfter = ml.GetAdjoinedCurveElements(1); foreach (ElementId id in joinedAfter) { Element joinedEle = famdoc.GetElement(id); if (joinedEle is ModelArc) { afterId = id; break; } } if (beforeId != null && afterId != null && ml.HasTangentJoin(0, beforeId) && ml.HasTangentJoin(1, afterId)) { ml.SetTangentLock(0, beforeId, true); ml.SetTangentLock(1, afterId, true); } } } }
public void AddValue(String txtFileName) { var wb = new XLWorkbook(txtFileName); var ws = wb.Worksheet(1); var firstRowUsed = ws.FirstRowUsed(); var categoryRow = firstRowUsed.RowUsed(); categoryRow = categoryRow.RowBelow(); var firstPossibleAddress = ws.Row(categoryRow.RowNumber()).FirstCell().Address; var lastPossibleAddress = ws.LastCellUsed().Address; var Range = ws.Range(firstPossibleAddress, lastPossibleAddress).RangeUsed(); var Table = Range.AsTable(); var cellRowAddress = string.Empty; var cellColumnAddress = string.Empty; var cellColumnName = string.Empty; //int k = 0; //int k = MappingColumnParameter.mappingParameter.Count; //string greska = ""; //public static List<String> mappingParameter = new List<string>(); Parameter mappingParameter = null; //List<String> nisujednakiP = new List<string>(); //List<String> nisujednakiK = new List<string>(); //List<String> jednaki = new List<string>(); List <String> pomocna = new List <string>(); List <String> greska = new List <string>(); string invalidInput = ""; List <string> valuesParameter = Table.DataRange.Rows().Select(companyRow => companyRow.Field(ShowColumnCategory.uniqueParameter).GetString()).ToList(); //try //{ using (Transaction t = new Transaction(LoadExcelFile.document, "AddValue")) { t.Start(); foreach (string item in valuesParameter) { Categories categories = LoadExcelFile.document.Settings.Categories; Category cat; cat = categories.get_Item(Form1.selectedCategory); BuiltInCategory builtInCategory = (BuiltInCategory)cat.Id.IntegerValue; FilteredElementCollector collector = new FilteredElementCollector(LoadExcelFile.document); IList <Element> elementsOfCategory = collector.WhereElementIsNotElementType().OfCategory(builtInCategory).ToElements(); for (int i = 0; i < MappingColumnParameter.mappingColumn.Count; i++) { foreach (Element el in elementsOfCategory) { Parameter uniqueParameter = el.LookupParameter(ShowColumnCategory.uniqueParameter); if (item.ToString() == uniqueParameter.AsString()) { foreach (IXLCell cell in Range.Cells()) { //----------------------------------------------- //var itemm = from val in valuesParameter // where val.ToString() == uniqueParameter.AsString() // select val; //----------------------------------------------- if (cell.Value.ToString() == item.ToString()) { cellRowAddress = cell.Address.RowNumber.ToString(); var row = ws.Row(int.Parse(cellRowAddress)); foreach (IXLCell cellCol in Range.FirstRow().Cells()) { if (cellCol.Value.ToString() == MappingColumnParameter.mappingColumn[i]) { cellColumnAddress = cellCol.Address.ColumnNumber.ToString(); //cellColumnName = cellCol.Address.ColumnLetter.ToString(); cellColumnName = cellCol.Value.ToString(); } } } } var vrij = ws.Cell(int.Parse(cellRowAddress), int.Parse(cellColumnAddress)).Value.ToString(); mappingParameter = el.LookupParameter(MappingColumnParameter.mappingParameter[i]); using (SubTransaction subtr = new SubTransaction(LoadExcelFile.document)) { subtr.Start(); ////mappingParameter.Set(vrij); ////mappingParameter.SetValueString(vrij); try { SetParameterValue.SetParamValue(mappingParameter, vrij); //pomocna.Add("\nSuccessfully entered column " + MappingColumnParameter.mappingColumn[i] + " in parameter " + mappingParameter.Definition.Name); } catch { greska.Add("Parameter " + mappingParameter.Definition.Name + " storage type is: " + mappingParameter.StorageType + " \nand type of column " + cellColumnName + " is: " + cellColumnAddress.GetType().Name + "\n"); continue; } subtr.Commit(); } } } } } invalidInput = string.Empty; for (int j = 0; j < (greska.Count / 32); j++) { if (greska.Count == 0) { continue; } else { invalidInput += greska[j]; } } greska.Clear(); cellColumnName = string.Empty; MappingColumnParameter.mappingColumn.Clear(); MappingColumnParameter.mappingParameter.Clear(); if (invalidInput == string.Empty) { TaskDialog.Show("Finish", "Successfully entered values of parameters!"); } else { TaskDialog.Show("Warning!", "Invalid Value Input! \n" + invalidInput); TaskDialog.Show("Finish", "Successfully entered values of parameters!"); } //TaskDialog.Show("Finish", "Successfully entered values of parameters!"); //Successfully successfully = new Successfully(); //successfully.ShowDialog(); t.Commit(); } //} //catch //{ // TaskDialog.Show("Error!", "Invalid Value Input! " + " \nParameter " + mappingParameter.Definition.Name + " storage type is: " + mappingParameter.StorageType + " \nand type of column " + cellColumnName + " is: " + cellColumnName.GetType().Name + "\nRemove it!"); //} }
/// <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); Autodesk.Revit.DB.Document doc = element.Document; using (SubTransaction st = new SubTransaction(doc)) { 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. CeilingAndFloor hostObject = element as CeilingAndFloor; FloorExporter.ExportCeilingAndFloorElement(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, null, 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); if (element.GroupId != ElementId.InvalidElementId) ExporterCacheManager.GroupCache.RegisterElements(element.GroupId, productWrapper); st.RollBack(); } } finally { exporterIFC.PopExportState(); ExporterStateManager.PreserveElementParameterCache(element, shouldPreserveParameterCache); } }
/// <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> /// 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> /// 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> /// 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> /// 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> /// 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 static List <Element> DrawLines(Document doc, IEnumerable <Line> lines) { List <Element> modelLines = new List <Element>(); SubTransaction st = new SubTransaction(doc); st.Start(); XYZ lastNormal = new XYZ(999, 992, 200); // random Plane p = null; SketchPlane sp = null; bool useLines = false; FilteredElementCollector coll = new FilteredElementCollector(doc); var fs = coll.OfClass(typeof(FamilySymbol)).OfCategory(BuiltInCategory.OST_DetailComponents).Cast <FamilySymbol>().Where(f => f.Name.ToUpper().Replace(" ", "") == "EGRESSPATH").FirstOrDefault(); if (fs == null) { //ugly to do this here. Autodesk.Revit.UI.TaskDialog td = new Autodesk.Revit.UI.TaskDialog("Egress Path"); td.MainContent = "The 'EgressPath' Line-based detail family is not loaded. Model Lines will be shown instead."; td.Show(); useLines = true; } 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; } if (!useLines) { if (fs.IsActive == false) { fs.Activate(); } FamilyInstance fi = doc.Create.NewFamilyInstance(ln, fs, doc.ActiveView); modelLines.Add(fi); } else { ModelCurve curve = doc.Create.NewModelCurve(ln, sp); modelLines.Add(curve as ModelLine); } } st.Commit(); return(modelLines); }
/// <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="filterView">The view to export, if it exists.</param> /// <param name="productWrapper">The ProductWrapper object.</param> public virtual void ExportElementImpl(ExporterIFC exporterIFC, Element element, Autodesk.Revit.DB.View filterView, 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); try { exporterIFC.PushExportState(element, geomElem); using (SubTransaction st = new SubTransaction(element.Document)) { st.Start(); if (element is AssemblyInstance) { AssemblyInstance assemblyInstance = element as AssemblyInstance; AssemblyInstanceExporter.ExportAssemblyInstanceElement(exporterIFC, assemblyInstance, productWrapper); } 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 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 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 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 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); } } else if (RampExporter.IsRamp(element)) { RampExporter.Export(exporterIFC, element, geomElem, productWrapper); } else if (element is Rebar || element is AreaReinforcement || element is PathReinforcement) { RebarExporter.Export(exporterIFC, element, filterView, 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 Wall) { Wall wallElem = element as Wall; WallExporter.Export(exporterIFC, wallElem, geomElem, productWrapper); } else if (element is FaceWall) { WallExporter.ExportWall(exporterIFC, element, geomElem, productWrapper); } else if (element is WallSweep) { WallSweep wallSweep = element as WallSweep; WallSweepExporter.Export(exporterIFC, wallSweep, geomElem, productWrapper); } else if (element is RoofBase) { RoofBase roofElement = element as RoofBase; RoofExporter.Export(exporterIFC, roofElement, 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); PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, element, productWrapper); } else { string ifcEnumType; IFCExportType exportType = ExporterUtil.GetExportType(exporterIFC, element, out ifcEnumType); if (IsMEPType(exporterIFC, element, exportType)) { GenericMEPExporter.Export(exporterIFC, element, geomElem, productWrapper); } else if (ExportAsProxy(element, exportType)) { ProxyElementExporter.Export(exporterIFC, element, geomElem, productWrapper); } } if (element.AssemblyInstanceId != ElementId.InvalidElementId) ExporterCacheManager.AssemblyInstanceCache.RegisterElements(element.AssemblyInstanceId, productWrapper); st.RollBack(); } } finally { exporterIFC.PopExportState(); } }
/// <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(); }
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; }
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; using ( Transaction tx = new Transaction( doc ) ) { tx.Start( "Mirror and List Added" ); //Line line = app.Create.NewLine( // XYZ.Zero, XYZ.BasisX, true ); // 2011 //ElementSet els = uidoc.Selection.Elements; // 2011 //Plane plane = new Plane( XYZ.BasisY, XYZ.Zero ); // added in 2012, used until 2016 Plane plane = Plane.CreateByNormalAndOrigin( XYZ.BasisY, XYZ.Zero ); // 2017 ICollection<ElementId> elementIds = uidoc.Selection.GetElementIds(); // 2012 using ( SubTransaction t = new SubTransaction( doc ) ) { // determine newly added elements relying on the // element sequence as returned by the filtered collector. // this approach works in both Revit 2010 and 2011: t.Start(); int n = GetElementCount( doc ); //doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true ); // 2016 List<Element> a = GetElementsAfter( n, doc ); t.RollBack(); } using ( SubTransaction t = new SubTransaction( doc ) ) { // here is an idea for a new approach in 2011: // determine newly added elements relying on // monotonously increasing element id values: t.Start(); FilteredElementCollector a = GetElements( doc ); int i = a.Max<Element>( e => e.Id.IntegerValue ); ElementId maxId = new ElementId( i ); // doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true ); // 2016 // get all elements in document with an // element id greater than maxId: a = GetElementsAfter( doc, maxId ); Report( a ); t.RollBack(); } using ( SubTransaction t = new SubTransaction( doc ) ) { // similar to the above approach relying on // monotonously increasing element id values, // but apply a quick filter first: t.Start(); FilteredElementCollector a = GetElements( doc ); int i = a.Max<Element>( e => e.Id.IntegerValue ); ElementId maxId = new ElementId( i ); //doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true ); // 2016 // only look at non-ElementType elements // instead of all document elements: a = GetElements( doc ); a = GetElementsAfter( a, maxId ); Report( a ); t.RollBack(); } using ( SubTransaction t = new SubTransaction( doc ) ) { // use a local and temporary DocumentChanged event // handler to directly obtain a list of all newly // created elements. // unfortunately, this canot be tested in this isolated form, // since the DocumentChanged event is only triggered when the // real outermost Revit transaction is committed, i.e. our // local sub-transaction makes no difference. since we abort // the sub-transaction before the command terminates and no // elements are really added to the database, our event // handler is never called: t.Start(); app.DocumentChanged += new EventHandler<DocumentChangedEventArgs>( app_DocumentChanged ); //doc.Mirror( els, line ); // 2011 //ElementTransformUtils.MirrorElements( // doc, elementIds, plane ); // 2012-2015 ElementTransformUtils.MirrorElements( doc, elementIds, plane, true ); // 2016 app.DocumentChanged -= new EventHandler<DocumentChangedEventArgs>( app_DocumentChanged ); Debug.Assert( null == _addedElementIds, "never expected the event handler to be called" ); if ( null != _addedElementIds ) { int n = _addedElementIds.Count; string s = string.Format( _msg, n, Util.PluralSuffix( n ) ); foreach ( ElementId id in _addedElementIds ) { Element e = doc.GetElement( id ); s += string.Format( "\r\n {0}", Util.ElementDescription( e ) ); } Util.InfoMsg( s ); } t.RollBack(); } tx.RollBack(); } return Result.Succeeded; }
/// <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 = null; ownerView = element.Document.GetElement(element.OwnerViewId) as View; if (ExporterCacheManager.ExportOptionsCache.UseActiveViewGeometry) { ownerView = ExporterCacheManager.ExportOptionsCache.ActiveView; } else { 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); Autodesk.Revit.DB.Document doc = element.Document; using (SubTransaction st = new SubTransaction(doc)) { st.Start(); // A long list of supported elements. Please keep in alphabetical order by the first item in the list.. 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. CeilingAndFloor hostObject = element as CeilingAndFloor; FloorExporter.ExportCeilingAndFloorElement(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, null, 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 (IsRebarType(element)) { RebarExporter.Export(exporterIFC, element, 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); // The intention with the code below is to make this the "generic" element exporter, which would export any Revit element as any IFC instance. // We would then in addition have specialized functions that would convert specific Revit elements to specific IFC instances where extra information // could be gathered from the element. 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); else if ((element is HostObject) || (element is DirectShape)) { // This is intended to work for any element. However, there are some hidden elements that we likely want to ignore. // As such, this is currently limited to the two types of elements that we know we want to export that aren't covered above. // Note the general comment that we would like to revamp this whole routine to be cleaner and simpler. // Note 2: Known lists of DirectShapes that aren't exported: // 1. IfcSpace (roundtripped IFC spaces). // 2. Railings exported = FamilyInstanceExporter.ExportGenericBuildingElement(exporterIFC, element, geomElem, exportType, ifcEnumType, 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); if (element.GroupId != ElementId.InvalidElementId) ExporterCacheManager.GroupCache.RegisterElements(element.GroupId, productWrapper); st.RollBack(); } } finally { exporterIFC.PopExportState(); ExporterStateManager.PreserveElementParameterCache(element, shouldPreserveParameterCache); } }
/// <summary> /// Export spatial elements, including rooms, areas and spaces. 2nd level space boundaries. /// </summary> /// <param name="ifcExporter"> /// The Exporter object. /// </param> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="document"> /// The Revit document. /// </param> /// <param name="filterView"> /// The view not exported. /// </param> /// <param name="spaceExported"> /// The output boolean value indicates if exported successfully. /// </param> public static void ExportSpatialElement2ndLevel(BIM.IFC.Exporter.Exporter ifcExporter, ExporterIFC exporterIFC, Document document, View filterView) { using (SubTransaction st = new SubTransaction(document)) { st.Start(); bool createEnergyAnalysisDetailModelFailed = false; EnergyAnalysisDetailModel model = null; try { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions(); options.Tier = EnergyAnalysisDetailModelTier.SecondLevelBoundaries; //2nd level space boundaries options.SimplifyCurtainSystems = true; try { model = EnergyAnalysisDetailModel.Create(document, options); } catch (Exception) { createEnergyAnalysisDetailModelFailed = true; throw; } IList<EnergyAnalysisSpace> spaces = model.GetAnalyticalSpaces(); foreach (EnergyAnalysisSpace space in spaces) { SpatialElement spatialElement = document.get_Element(space.SpatialElementId) as SpatialElement; if (spatialElement == null) continue; //quick reject bool isArea = spatialElement is Area; if (isArea) { if (!IsAreaGrossInterior(exporterIFC, spatialElement)) continue; } //current view only if (filterView != null && !ElementFilteringUtil.IsElementVisible(filterView, spatialElement)) continue; // if (!ElementFilteringUtil.ShouldCategoryBeExported(exporterIFC, spatialElement)) continue; Options geomOptions = new Options(); View ownerView = spatialElement.Document.get_Element(spatialElement.OwnerViewId) as View; if (ownerView != null) geomOptions.View = ownerView; GeometryElement geomElem = spatialElement.get_Geometry(geomOptions); try { exporterIFC.PushExportState(spatialElement, geomElem); using (IFCProductWrapper productWrapper = IFCProductWrapper.Create(exporterIFC, true)) { ElementId levelId = spatialElement.Level != null ? spatialElement.Level.Id : ElementId.InvalidElementId; using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, spatialElement, null, null, levelId)) { try { CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter); } catch (System.Exception) { continue; } //get boundary information from surfaces IList<EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces(); foreach (EnergyAnalysisSurface surface in surfaces) { Element boundingElement = GetBoundaryElement(document, surface.OriginatingElementId); if (boundingElement == null) continue; IList<EnergyAnalysisOpening> openings = surface.GetAnalyticalOpenings(); IFCAnyHandle connectionGeometry = CreateConnectionSurfaceGeometry(file, surface, openings); CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, boundingElement, connectionGeometry); // try to add doors and windows for host objects if appropriate. if (boundingElement is HostObject) { foreach (EnergyAnalysisOpening opening in openings) { Element openingBoundingElem = GetBoundaryElement(document, opening.OriginatingElementId); IFCAnyHandle openingConnectionGeom = CreateConnectionSurfaceGeometry(file, opening); CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, openingBoundingElem, openingConnectionGeom); } } } ExporterIFCUtils.CreateSpatialElementPropertySet(exporterIFC, spatialElement, productWrapper); ifcExporter.ExportElementProperties(exporterIFC, spatialElement, productWrapper); ifcExporter.ExportElementQuantities(exporterIFC, spatialElement, productWrapper); } } } finally { exporterIFC.PopExportState(); } } tr.Commit(); } } catch (System.Exception ex) { document.Application.WriteJournalComment("IFC error: " + ex.ToString(), true); } finally { if (model != null) EnergyAnalysisDetailModel.Destroy(model); } //if failed, just export the space element if (createEnergyAnalysisDetailModelFailed) { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction tr = new IFCTransaction(file)) { ElementFilter spatialElementFilter = ElementFilteringUtil.GetSpatialElementFilter(document, exporterIFC); FilteredElementCollector collector = (filterView == null) ? new FilteredElementCollector(document) : new FilteredElementCollector(document, filterView.Id); collector.WherePasses(spatialElementFilter); foreach (Element elem in collector) { SpatialElement spatialElement = elem as SpatialElement; if (spatialElement == null) continue; //current view only if (filterView != null && !ElementFilteringUtil.IsElementVisible(filterView, spatialElement)) continue; // if (!ElementFilteringUtil.ShouldCategoryBeExported(exporterIFC, spatialElement)) continue; Options geomOptions = new Options(); View ownerView = spatialElement.Document.get_Element(spatialElement.OwnerViewId) as View; if (ownerView != null) geomOptions.View = ownerView; GeometryElement geomElem = spatialElement.get_Geometry(geomOptions); try { exporterIFC.PushExportState(spatialElement, geomElem); using (IFCProductWrapper productWrapper = IFCProductWrapper.Create(exporterIFC, true)) { ElementId levelId = spatialElement.Level != null ? spatialElement.Level.Id : ElementId.InvalidElementId; using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, spatialElement, null, null, levelId)) { try { CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter); } catch (System.Exception) { continue; } if (!(spatialElement is Area)) ExporterIFCUtils.CreateSpatialElementPropertySet(exporterIFC, spatialElement, productWrapper); ifcExporter.ExportElementProperties(exporterIFC, spatialElement, productWrapper); ifcExporter.ExportElementQuantities(exporterIFC, spatialElement, productWrapper); } } } finally { exporterIFC.PopExportState(); } } tr.Commit(); } } st.RollBack(); } }
/// <summary> /// Exports spatial elements, including rooms, areas and spaces. 2nd level space boundaries. /// </summary> /// <param name="ifcExporter">The Exporter object.</param> /// <param name="exporterIFC"> The ExporterIFC object.</param> /// <param name="document">The Revit document.</param> /// <returns>The set of exported spaces. This is used to try to export using the standard routine for spaces that failed.</returns> public static ISet<ElementId> ExportSpatialElement2ndLevel(Revit.IFC.Export.Exporter.Exporter ifcExporter, ExporterIFC exporterIFC, Document document) { ISet<ElementId> exportedSpaceIds = new HashSet<ElementId>(); using (SubTransaction st = new SubTransaction(document)) { st.Start(); EnergyAnalysisDetailModel model = null; try { View filterView = ExporterCacheManager.ExportOptionsCache.FilterViewForExport; IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions(); options.Tier = EnergyAnalysisDetailModelTier.SecondLevelBoundaries; //2nd level space boundaries options.SimplifyCurtainSystems = true; try { model = EnergyAnalysisDetailModel.Create(document, options); } catch (System.Exception) { return exportedSpaceIds; } IList<EnergyAnalysisSpace> spaces = model.GetAnalyticalSpaces(); foreach (EnergyAnalysisSpace space in spaces) { SpatialElement spatialElement = document.GetElement(space.CADObjectUniqueId) as SpatialElement; if (spatialElement == null) continue; //current view only if (!ElementFilteringUtil.IsElementVisible(spatialElement)) continue; if (!ElementFilteringUtil.ShouldElementBeExported(exporterIFC, spatialElement, false)) continue; if (ElementFilteringUtil.IsRoomInInvalidPhase(spatialElement)) continue; Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions(); View ownerView = spatialElement.Document.GetElement(spatialElement.OwnerViewId) as View; if (ownerView != null) geomOptions.View = ownerView; GeometryElement geomElem = spatialElement.get_Geometry(geomOptions); try { exporterIFC.PushExportState(spatialElement, geomElem); using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { using (PlacementSetter setter = PlacementSetter.Create(exporterIFC, spatialElement)) { // We won't use the SpatialElementGeometryResults, as these are 1st level boundaries, not 2nd level. SpatialElementGeometryResults results = null; if (!CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter, out results)) continue; exportedSpaceIds.Add(spatialElement.Id); XYZ offset = GetSpaceBoundaryOffset(setter); //get boundary information from surfaces IList<EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces(); foreach (EnergyAnalysisSurface surface in surfaces) { Element boundingElement = GetBoundaryElement(document, surface.CADLinkUniqueId, surface.CADObjectUniqueId); IList<EnergyAnalysisOpening> openings = surface.GetAnalyticalOpenings(); IFCAnyHandle connectionGeometry = CreateConnectionSurfaceGeometry(exporterIFC, surface, openings, offset); CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, boundingElement, setter.LevelId, connectionGeometry); // try to add doors and windows for host objects if appropriate. if (boundingElement is HostObject) { foreach (EnergyAnalysisOpening opening in openings) { Element openingBoundingElem = GetBoundaryElement(document, opening.CADLinkUniqueId, opening.CADObjectUniqueId); IFCAnyHandle openingConnectionGeom = CreateConnectionSurfaceGeometry(exporterIFC, opening, offset); CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, openingBoundingElem, setter.LevelId, openingConnectionGeom); } } } CreateZoneInfos(exporterIFC, file, spatialElement, productWrapper); CreateSpaceOccupantInfo(exporterIFC, file, spatialElement, productWrapper); ExporterUtil.ExportRelatedProperties(exporterIFC, spatialElement, productWrapper); } } } catch (Exception ex) { ifcExporter.HandleUnexpectedException(ex, exporterIFC, spatialElement); } finally { exporterIFC.PopExportState(); } } transaction.Commit(); } } finally { if (model != null) EnergyAnalysisDetailModel.Destroy(model); } st.RollBack(); return exportedSpaceIds; } }
/// <summary> /// Exports spatial elements, including rooms, areas and spaces. 2nd level space boundaries. /// </summary> /// <param name="ifcExporter"> /// The Exporter object. /// </param> /// <param name="exporterIFC"> /// The ExporterIFC object. /// </param> /// <param name="document"> /// The Revit document. /// </param> /// <param name="filterView"> /// The view not exported. /// </param> /// <param name="spaceExported"> /// The output boolean value indicates if exported successfully. /// </param> public static void ExportSpatialElement2ndLevel(BIM.IFC.Exporter.Exporter ifcExporter, ExporterIFC exporterIFC, Document document, View filterView, ref bool spaceExported) { using (SubTransaction st = new SubTransaction(document)) { st.Start(); EnergyAnalysisDetailModel model = null; try { IFCFile file = exporterIFC.GetFile(); using (IFCTransaction transaction = new IFCTransaction(file)) { EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions(); options.Tier = EnergyAnalysisDetailModelTier.SecondLevelBoundaries; //2nd level space boundaries options.SimplifyCurtainSystems = true; try { model = EnergyAnalysisDetailModel.Create(document, options); } catch (System.Exception) { spaceExported = false; return; } IList<EnergyAnalysisSpace> spaces = model.GetAnalyticalSpaces(); spaceExported = true; foreach (EnergyAnalysisSpace space in spaces) { SpatialElement spatialElement = document.GetElement(space.SpatialElementId) as SpatialElement; if (spatialElement == null) continue; //quick reject bool isArea = spatialElement is Area; if (isArea) { if (!IsAreaGrossInterior(exporterIFC, spatialElement)) continue; } //current view only if (filterView != null && !ElementFilteringUtil.IsElementVisible(filterView, spatialElement)) continue; // if (!ElementFilteringUtil.ShouldCategoryBeExported(exporterIFC, spatialElement)) continue; Options geomOptions = GeometryUtil.GetIFCExportGeometryOptions(); View ownerView = spatialElement.Document.GetElement(spatialElement.OwnerViewId) as View; if (ownerView != null) geomOptions.View = ownerView; GeometryElement geomElem = spatialElement.get_Geometry(geomOptions); try { exporterIFC.PushExportState(spatialElement, geomElem); using (ProductWrapper productWrapper = ProductWrapper.Create(exporterIFC, true)) { ElementId levelId = spatialElement.Level != null ? spatialElement.Level.Id : ElementId.InvalidElementId; using (IFCPlacementSetter setter = IFCPlacementSetter.Create(exporterIFC, spatialElement, null, null, levelId)) { if (!CreateIFCSpace(exporterIFC, spatialElement, productWrapper, setter)) continue; XYZ offset = GetSapceBoundaryOffset(setter); //get boundary information from surfaces IList<EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces(); foreach (EnergyAnalysisSurface surface in surfaces) { Element boundingElement = GetBoundaryElement(document, surface.OriginatingElementId); IList<EnergyAnalysisOpening> openings = surface.GetAnalyticalOpenings(); IFCAnyHandle connectionGeometry = CreateConnectionSurfaceGeometry(file, surface, openings, offset); CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, boundingElement, setter.LevelId, connectionGeometry); // try to add doors and windows for host objects if appropriate. if (boundingElement is HostObject) { foreach (EnergyAnalysisOpening opening in openings) { Element openingBoundingElem = GetBoundaryElement(document, opening.OriginatingElementId); IFCAnyHandle openingConnectionGeom = CreateConnectionSurfaceGeometry(file, opening, offset); CreateIFCSpaceBoundary(file, exporterIFC, spatialElement, openingBoundingElem, setter.LevelId, openingConnectionGeom); } } } PropertyUtil.CreateInternalRevitPropertySets(exporterIFC, spatialElement, productWrapper); CreateZoneInfos(exporterIFC, file, spatialElement, productWrapper); CreateSpaceOccupantInfo(exporterIFC, file, spatialElement, productWrapper); ifcExporter.ExportElementProperties(exporterIFC, spatialElement, productWrapper); ifcExporter.ExportElementQuantities(exporterIFC, spatialElement, productWrapper); } } } catch (Exception ex) { ifcExporter.HandleUnexpectedException(ex, exporterIFC, spatialElement); } finally { exporterIFC.PopExportState(); } } transaction.Commit(); } } finally { if (model != null) EnergyAnalysisDetailModel.Destroy(model); } st.RollBack(); } }
/// <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 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> /// 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> /// 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 IFCProductWrapper object.</param> private void ExportElementImpl(ExporterIFC exporterIFC, Element element, IFCProductWrapper productWrapper) { Options options = new Options(); View ownerView = element.Document.get_Element(element.OwnerViewId) as View; if (ownerView != null) options.View = ownerView; GeometryElement geomElem = element.get_Geometry(options); try { exporterIFC.PushExportState(element, geomElem); using (SubTransaction st = new SubTransaction(element.Document)) { st.Start(); if (element is CurveElement) { CurveElement curveElem = element as CurveElement; CurveElementExporter.ExportCurveElement(exporterIFC, curveElem, geomElem, productWrapper, m_CurveAnnotationCache); } else if (element is FamilyInstance) { FamilyInstance familyInstanceElem = element as FamilyInstance; FamilyInstanceExporter.ExportFamilyInstanceElement(exporterIFC, familyInstanceElem, geomElem, productWrapper); } else if (element is Floor) { Floor floorElem = element as Floor; FloorExporter.ExportFloor(exporterIFC, floorElem, geomElem, productWrapper); } else if (element is SpatialElement) { SpatialElement spatialElem = element as SpatialElement; SpatialElementExporter.ExportSpatialElement(exporterIFC, spatialElem, productWrapper); } else if (element is TextNote) { TextNote textNote = element as TextNote; TextNoteExporter.Export(exporterIFC, textNote, productWrapper, m_PresentationStyleCache); } else if (element is Wall) { Wall wallElem = element as Wall; WallExporter.Export(exporterIFC, wallElem, geomElem, productWrapper); } else if (IsMEPType(exporterIFC, element)) { GenericMEPExporter.Export(exporterIFC, element, geomElem, productWrapper); } else if (element is FilledRegion) { // FilledRegion is still handled by internal Revit code, but the get_Geometry call makes sure // that the Owner view is clean before we get the region's GeometryElement. ExporterIFCUtils.ExportElementInternal(exporterIFC, element, productWrapper); } st.RollBack(); } } finally { exporterIFC.PopExportState(); } }
/// <summary> /// Exports a CeilingAndFloor element to IFC. /// </summary> /// <param name="exporterIFC">The ExporterIFC object.</param> /// <param name="floor">The floor element.</param> /// <param name="geometryElement">The geometry element.</param> /// <param name="productWrapper">The ProductWrapper.</param> public static void ExportCeilingAndFloorElement(ExporterIFC exporterIFC, CeilingAndFloor floorElement, GeometryElement geometryElement, ProductWrapper productWrapper) { if (geometryElement == null) { return; } // export parts or not bool exportParts = PartExporter.CanExportParts(floorElement); if (exportParts && !PartExporter.CanExportElementInPartExport(floorElement, floorElement.LevelId, false)) { return; } IFCFile file = exporterIFC.GetFile(); string ifcEnumType; IFCExportInfoPair exportType = ExporterUtil.GetExportType(exporterIFC, floorElement, out ifcEnumType); IFCAnyHandle type = null; MaterialLayerSetInfo layersetInfo = null; if (!ElementFilteringUtil.IsElementVisible(floorElement)) { return; } // Check the intended IFC entity or type name is in the exclude list specified in the UI Common.Enums.IFCEntityType elementClassTypeEnum; if (Enum.TryParse <Common.Enums.IFCEntityType>(exportType.ExportInstance.ToString(), out elementClassTypeEnum) || Enum.TryParse <Common.Enums.IFCEntityType>(exportType.ExportType.ToString(), out elementClassTypeEnum)) { if (ExporterCacheManager.ExportOptionsCache.IsElementInExcludeList(elementClassTypeEnum)) { return; } } Document doc = floorElement.Document; using (SubTransaction tempPartTransaction = new SubTransaction(doc)) { // For IFC4RV export, Floor will be split into its parts(temporarily) in order to export the floor by its parts bool exportByComponents = ExporterUtil.ShouldExportByComponents(floorElement, exportParts); using (IFCTransaction tr = new IFCTransaction(file)) { bool canExportAsContainerOrWithExtrusionAnalyzer = (!exportParts && (floorElement is Floor)); if (canExportAsContainerOrWithExtrusionAnalyzer) { // Try to export the Floor slab as a container. If that succeeds, we are done. // If we do export the floor as a container, it will take care of the local placement and transform there, so we need to leave // this out of the IFCTransformSetter and PlacementSetter scopes below, or else we'll get double transforms. IFCAnyHandle floorHnd = RoofExporter.ExportRoofOrFloorAsContainer(exporterIFC, floorElement, geometryElement, productWrapper); if (!IFCAnyHandleUtil.IsNullOrHasNoValue(floorHnd)) { tr.Commit(); return; } } IList <IFCAnyHandle> slabHnds = new List <IFCAnyHandle>(); IList <IFCAnyHandle> brepSlabHnds = new List <IFCAnyHandle>(); IList <IFCAnyHandle> nonBrepSlabHnds = new List <IFCAnyHandle>(); IFCAnyHandle ownerHistory = ExporterCacheManager.OwnerHistoryHandle; using (IFCTransformSetter transformSetter = IFCTransformSetter.Create()) { // Check for containment override IFCAnyHandle overrideContainerHnd = null; ElementId overrideContainerId = ParameterUtil.OverrideContainmentParameter(exporterIFC, floorElement, out overrideContainerHnd); using (PlacementSetter placementSetter = PlacementSetter.Create(exporterIFC, floorElement, null, null, overrideContainerId, overrideContainerHnd)) { IFCAnyHandle localPlacement = placementSetter.LocalPlacement; // The routine ExportExtrudedSlabOpenings is called if exportedAsInternalExtrusion is true, and it requires having a valid level association. // Disable calling ExportSlabAsExtrusion if we can't handle potential openings. bool canExportAsInternalExtrusion = placementSetter.LevelInfo != null; bool exportedAsInternalExtrusion = false; ElementId catId = CategoryUtil.GetSafeCategoryId(floorElement); IList <IFCAnyHandle> prodReps = new List <IFCAnyHandle>(); IList <ShapeRepresentationType> repTypes = new List <ShapeRepresentationType>(); IList <IList <CurveLoop> > extrusionLoops = new List <IList <CurveLoop> >(); IList <IFCExtrusionCreationData> loopExtraParams = new List <IFCExtrusionCreationData>(); Plane floorPlane = GeometryUtil.CreateDefaultPlane(); IList <IFCAnyHandle> localPlacements = new List <IFCAnyHandle>(); if (canExportAsContainerOrWithExtrusionAnalyzer) { Floor floor = floorElement as Floor; // Next, try to use the ExtrusionAnalyzer for the limited cases it handles - 1 solid, no openings, end clippings only. // Also limited to cases with line and arc boundaries. // SolidMeshGeometryInfo solidMeshInfo = GeometryUtil.GetSplitSolidMeshGeometry(geometryElement); IList <Solid> solids = solidMeshInfo.GetSolids(); IList <Mesh> meshes = solidMeshInfo.GetMeshes(); IList <GeometryObject> gObjs = FamilyExporterUtil.RemoveInvisibleSolidsAndMeshes(floorElement.Document, exporterIFC, ref solids, ref meshes); if (solids.Count == 1 && meshes.Count == 0) { bool completelyClipped; // floorExtrusionDirection is set to (0, 0, -1) because extrusionAnalyzerFloorPlane is computed from the top face of the floor XYZ floorExtrusionDirection = new XYZ(0, 0, -1); XYZ modelOrigin = XYZ.Zero; XYZ floorOrigin = floor.GetVerticalProjectionPoint(modelOrigin, FloorFace.Top); if (floorOrigin == null) { // GetVerticalProjectionPoint may return null if FloorFace.Top is an edited face that doesn't // go through the Revit model origin. We'll try the midpoint of the bounding box instead. BoundingBoxXYZ boundingBox = floorElement.get_BoundingBox(null); modelOrigin = (boundingBox.Min + boundingBox.Max) / 2.0; floorOrigin = floor.GetVerticalProjectionPoint(modelOrigin, FloorFace.Top); } if (floorOrigin != null) { XYZ floorDir = floor.GetNormalAtVerticalProjectionPoint(floorOrigin, FloorFace.Top); Plane extrusionAnalyzerFloorBasePlane = GeometryUtil.CreatePlaneByNormalAtOrigin(floorDir); GenerateAdditionalInfo additionalInfo = GenerateAdditionalInfo.GenerateBody; additionalInfo |= ExporterCacheManager.ExportOptionsCache.ExportAs4 ? GenerateAdditionalInfo.GenerateFootprint : GenerateAdditionalInfo.None; // Skip generate body item for IFC4RV. It will be handled later in PartExporter.ExportHostPartAsShapeAspects() if (exportByComponents) { additionalInfo &= ~GenerateAdditionalInfo.GenerateBody; } HandleAndData floorAndProperties = ExtrusionExporter.CreateExtrusionWithClippingAndProperties(exporterIFC, floorElement, catId, solids[0], extrusionAnalyzerFloorBasePlane, floorOrigin, floorExtrusionDirection, null, out completelyClipped, addInfo: additionalInfo); if (completelyClipped) { return; } IList <IFCAnyHandle> representations = new List <IFCAnyHandle>(); if (floorAndProperties.Handle != null) { representations.Add(floorAndProperties.Handle); repTypes.Add(ShapeRepresentationType.SweptSolid); } // Footprint representation will only be exported in export to IFC4 if (((additionalInfo & GenerateAdditionalInfo.GenerateFootprint) != 0) && (floorAndProperties.FootprintInfo != null)) { IFCAnyHandle footprintShapeRep = floorAndProperties.FootprintInfo.CreateFootprintShapeRepresentation(exporterIFC); representations.Add(footprintShapeRep); } if (exportByComponents) { IFCAnyHandle prodRep = RepresentationUtil.CreateProductDefinitionShapeWithoutBodyRep(exporterIFC, floorElement, catId, geometryElement, representations); prodReps.Add(prodRep); } else if (representations.Count > 0 && floorAndProperties.Handle != null) // Only when at least the body rep exists will come here { IFCAnyHandle prodRep = IFCInstanceExporter.CreateProductDefinitionShape(file, null, null, representations); prodReps.Add(prodRep); } if (floorAndProperties.Data != null) { loopExtraParams.Add(floorAndProperties.Data); } } } } // Use internal routine as backup that handles openings. if (prodReps.Count == 0 && canExportAsInternalExtrusion && !exportByComponents) { exportedAsInternalExtrusion = ExporterIFCUtils.ExportSlabAsExtrusion(exporterIFC, floorElement, geometryElement, transformSetter, localPlacement, out localPlacements, out prodReps, out extrusionLoops, out loopExtraParams, floorPlane); PotentiallyFixPresentationLayerAssignment(floorElement, prodReps); for (int ii = 0; ii < prodReps.Count; ii++) { // all are extrusions repTypes.Add(ShapeRepresentationType.SweptSolid); // Footprint representation will only be exported in export to IFC4 if (ExporterCacheManager.ExportOptionsCache.ExportAs4) { if (extrusionLoops.Count > ii) { if (extrusionLoops[ii].Count > 0) { // Get the extrusion footprint using the first Curveloop. Transform needs to be obtained from the returned local placement Transform lcs = ExporterIFCUtils.GetUnscaledTransform(exporterIFC, localPlacements[ii]); IFCAnyHandle footprintGeomRepItem = GeometryUtil.CreateIFCCurveFromCurveLoop(exporterIFC, extrusionLoops[ii][0], lcs, floorPlane.Normal); IFCAnyHandle contextOfItemsFootprint = exporterIFC.Get3DContextHandle("FootPrint"); ISet <IFCAnyHandle> repItem = new HashSet <IFCAnyHandle>(); repItem.Add(footprintGeomRepItem); IFCAnyHandle footprintShapeRepresentation = RepresentationUtil.CreateBaseShapeRepresentation(exporterIFC, contextOfItemsFootprint, "FootPrint", "Curve2D", repItem); IList <IFCAnyHandle> reps = new List <IFCAnyHandle>(); reps.Add(footprintShapeRepresentation); IFCAnyHandleUtil.AddRepresentations(prodReps[ii], reps); } } } } } IFCAnyHandle prodDefHnd; if (prodReps.Count == 0) { if (exportByComponents) { prodDefHnd = RepresentationUtil.CreateProductDefinitionShapeWithoutBodyRep(exporterIFC, floorElement, catId, geometryElement, null); prodReps.Add(prodDefHnd); } else { using (IFCExtrusionCreationData ecData = new IFCExtrusionCreationData()) { // Brep representation using tesellation after ExportSlabAsExtrusion does not return prodReps BodyExporterOptions bodyExporterOptions = new BodyExporterOptions(true, ExportOptionsCache.ExportTessellationLevel.Medium); BodyData bodyData; prodDefHnd = RepresentationUtil.CreateAppropriateProductDefinitionShape(exporterIFC, floorElement, catId, geometryElement, bodyExporterOptions, null, ecData, out bodyData); if (IFCAnyHandleUtil.IsNullOrHasNoValue(prodDefHnd)) { ecData.ClearOpenings(); return; } prodReps.Add(prodDefHnd); repTypes.Add(bodyData.ShapeRepresentationType); } } } // Create the slab from either the extrusion or the BRep information. string ifcGUID = GUIDUtil.CreateGUID(floorElement); int numReps = exportParts ? 1 : prodReps.Count; // Deal with a couple of cases that have non-standard defaults. switch (exportType.ExportInstance) { case IFCEntityType.IfcCovering: exportType.ValidatedPredefinedType = IFCValidateEntry.GetValidIFCType <IFCCoveringType>(floorElement, ifcEnumType, "FLOORING"); break; case IFCEntityType.IfcSlab: bool isBaseSlab = false; AnalyticalModel analyticalModel = floorElement.GetAnalyticalModel(); if (analyticalModel != null) { AnalyzeAs slabFoundationType = analyticalModel.GetAnalyzeAs(); isBaseSlab = (slabFoundationType == AnalyzeAs.SlabOnGrade) || (slabFoundationType == AnalyzeAs.Mat); } exportType.ValidatedPredefinedType = IFCValidateEntry.GetValidIFCType <IFCSlabType>(floorElement, ifcEnumType, isBaseSlab ? "BASESLAB" : "FLOOR"); break; } for (int ii = 0; ii < numReps; ii++) { string ifcName = NamingUtil.GetNameOverride(floorElement, NamingUtil.GetIFCNamePlusIndex(floorElement, ii == 0 ? -1 : ii + 1)); string currentGUID = (ii == 0) ? ifcGUID : GUIDUtil.CreateGUID(); IFCAnyHandle localPlacementHnd = exportedAsInternalExtrusion ? localPlacements[ii] : localPlacement; IFCAnyHandle slabHnd = null; slabHnd = IFCInstanceExporter.CreateGenericIFCEntity(exportType, exporterIFC, floorElement, currentGUID, ownerHistory, localPlacementHnd, exportParts ? null : prodReps[ii]); if (IFCAnyHandleUtil.IsNullOrHasNoValue(slabHnd)) { return; } if (!string.IsNullOrEmpty(ifcName)) { IFCAnyHandleUtil.OverrideNameAttribute(slabHnd, ifcName); } // Pre IFC4 Slab does not have PredefinedType if (!string.IsNullOrEmpty(exportType.ValidatedPredefinedType) && !ExporterCacheManager.ExportOptionsCache.ExportAsOlderThanIFC4) { IFCAnyHandleUtil.SetAttribute(slabHnd, "PredefinedType", exportType.ValidatedPredefinedType, true); } if (exportParts && !ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView) { PartExporter.ExportHostPart(exporterIFC, floorElement, slabHnd, productWrapper, placementSetter, localPlacementHnd, null); } else if (exportByComponents) { IFCExtrusionCreationData partECData = new IFCExtrusionCreationData(); IFCAnyHandle hostShapeRepFromParts = PartExporter.ExportHostPartAsShapeAspects(exporterIFC, floorElement, prodReps[ii], productWrapper, placementSetter, localPlacement, ElementId.InvalidElementId, out layersetInfo, partECData); loopExtraParams.Add(partECData); } slabHnds.Add(slabHnd); // For IFC4RV, export of the geometry is already handled in PartExporter.ExportHostPartAsShapeAspects() if (!exportParts && !exportByComponents) { if (repTypes[ii] == ShapeRepresentationType.Brep || repTypes[ii] == ShapeRepresentationType.Tessellation) { brepSlabHnds.Add(slabHnd); } else { nonBrepSlabHnds.Add(slabHnd); } } } for (int ii = 0; ii < numReps; ii++) { IFCExtrusionCreationData loopExtraParam = ii < loopExtraParams.Count ? loopExtraParams[ii] : null; productWrapper.AddElement(floorElement, slabHnds[ii], placementSetter, loopExtraParam, true, exportType); type = ExporterUtil.CreateGenericTypeFromElement(floorElement, exportType, file, ownerHistory, exportType.ValidatedPredefinedType, productWrapper); ExporterCacheManager.TypeRelationsCache.Add(type, slabHnds[ii]); ExporterUtil.AddIntoComplexPropertyCache(slabHnds[ii], layersetInfo); } // This call to the native function appears to create Brep opening also when appropriate. But the creation of the IFC instances is not // controllable from the managed code. Therefore in some cases BRep geometry for Opening will still be exported even in the Reference View if (exportedAsInternalExtrusion) { ISet <IFCAnyHandle> oldCreatedObjects = productWrapper.GetAllObjects(); ExporterIFCUtils.ExportExtrudedSlabOpenings(exporterIFC, floorElement, placementSetter.LevelInfo, localPlacements[0], slabHnds, extrusionLoops, floorPlane, productWrapper.ToNative()); ISet <IFCAnyHandle> newCreatedObjects = productWrapper.GetAllObjects(); newCreatedObjects.ExceptWith(oldCreatedObjects); PotentiallyFixPresentationLayerAssignment(floorElement, newCreatedObjects); } } if (!exportParts) { if (ExporterCacheManager.ExportOptionsCache.ExportAs4ReferenceView) { HostObjectExporter.ExportHostObjectMaterials(exporterIFC, floorElement, productWrapper.GetAnElement(), geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, false, type); } else { if (nonBrepSlabHnds.Count > 0) { HostObjectExporter.ExportHostObjectMaterials(exporterIFC, floorElement, nonBrepSlabHnds, geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, false, type); } if (brepSlabHnds.Count > 0) { HostObjectExporter.ExportHostObjectMaterials(exporterIFC, floorElement, brepSlabHnds, geometryElement, productWrapper, ElementId.InvalidElementId, Toolkit.IFCLayerSetDirection.Axis3, true, type); } } } } tr.Commit(); return; } } }
/// <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; }
private void ModifyObjects(List<RevitObject> existingObjects, List<ElementId> existingElems, Document doc, Guid uniqueId, bool profileWarning, string nickName, int runId) { // Create new Revit objects. //List<LyrebirdId> newUniqueIds = new List<LyrebirdId>(); // Determine what kind of object we're creating. RevitObject ro = existingObjects[0]; #region Normal Origin based FamilyInstance // Modify origin based family instances if (ro.Origin != null) { // Find the FamilySymbol FamilySymbol symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc); LevelType lt = FindLevelType(ro.TypeName, doc); GridType gt = FindGridType(ro.TypeName, doc); if (symbol != null || lt != null) { // Get the hosting ID from the family. Family fam = null; Parameter hostParam = null; int hostBehavior = 0; try { fam = symbol.Family; hostParam = fam.get_Parameter(BuiltInParameter.FAMILY_HOSTING_BEHAVIOR); hostBehavior = hostParam.AsInteger(); } catch{} //FamilyInstance existingInstance = doc.GetElement(existingElems[0]) as FamilyInstance; using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects")) { t.Start(); try { Schema instanceSchema = null; try { instanceSchema = Schema.Lookup(instanceSchemaGUID); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (instanceSchema == null) { SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID); sb.SetWriteAccessLevel(AccessLevel.Vendor); sb.SetReadAccessLevel(AccessLevel.Public); sb.SetVendorId("LMNA"); // Create the field to store the data in the family FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string)); guidFB.SetDocumentation("Component instance GUID from Grasshopper"); // Create a filed to store the run number FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int)); runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data"); // Create a field to store the GH component nickname. FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string)); nickNameFB.SetDocumentation("Component NickName from Grasshopper"); sb.SetSchemaName("LMNAInstanceGUID"); instanceSchema = sb.Finish(); } FamilyInstance fi = null; XYZ origin = XYZ.Zero; if (lt != null) { for (int i = 0; i < existingObjects.Count; i++) { RevitObject obj = existingObjects[i]; Level lvl = doc.GetElement(existingElems[i]) as Level; if (lvl.ProjectElevation != (UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT))) { double offset = lvl.Elevation - lvl.ProjectElevation; lvl.Elevation = (UnitUtils.ConvertToInternalUnits(obj.Origin.Z + offset, lengthDUT)); } SetParameters(lvl, obj.Parameters, doc); } } else if (hostBehavior == 0) { for (int i = 0; i < existingObjects.Count; i++) { RevitObject obj = existingObjects[i]; fi = doc.GetElement(existingElems[i]) as FamilyInstance; // Change the family and symbol if necessary if (fi != null && (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name)) { try { fi.Symbol = symbol; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } try { // Move family origin = new XYZ(UnitUtils.ConvertToInternalUnits(obj.Origin.X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT)); if (fi != null) { LocationPoint lp = fi.Location as LocationPoint; if (lp != null) { XYZ oldLoc = lp.Point; XYZ translation = origin.Subtract(oldLoc); ElementTransformUtils.MoveElement(doc, fi.Id, translation); } } } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } // Rotate if (obj.Orientation != null) { if (Math.Round(Math.Abs(obj.Orientation.Z - 0), 10) < double.Epsilon) { XYZ orientation = fi.FacingOrientation; orientation = orientation.Multiply(-1); XYZ incomingOrientation = new XYZ(obj.Orientation.X, obj.Orientation.Y, obj.Orientation.Z); XYZ normalVector = new XYZ(0, -1, 0); double currentAngle = 0; if (orientation.X < 0 && orientation.Y < 0) { currentAngle = (2 * Math.PI) - normalVector.AngleTo(orientation); } else if (orientation.Y == 0 && orientation.X < 0) { currentAngle = 1.5 * Math.PI; } else if (orientation.X < 0) { currentAngle = (Math.PI - normalVector.AngleTo(orientation)) + Math.PI; } else { currentAngle = normalVector.AngleTo(orientation); } double incomingAngle = 0; if (incomingOrientation.X < 0 && incomingOrientation.Y < 0) { incomingAngle = (2 * Math.PI) - normalVector.AngleTo(incomingOrientation); } else if (incomingOrientation.Y == 0 && incomingOrientation.X < 0) { incomingAngle = 1.5 * Math.PI; } else if (incomingOrientation.X < 0) { incomingAngle = (Math.PI - normalVector.AngleTo(incomingOrientation)) + Math.PI; } else { incomingAngle = normalVector.AngleTo(incomingOrientation); } double angle = incomingAngle - currentAngle; //TaskDialog.Show("Test", "CurrentAngle: " + currentAngle.ToString() + "\nIncoming Angle: " + incomingAngle.ToString() + "\nResulting Rotation: " + angle.ToString() + // "\nFacingOrientation: " + orientation.ToString() + "\nIncoming Orientation: " + incomingOrientation.ToString()); Line axis = Line.CreateBound(origin, origin + XYZ.BasisZ); ElementTransformUtils.RotateElement(doc, fi.Id, axis, angle); } } SetParameters(fi, obj.Parameters, doc); } } else { for (int i = 0; i < existingObjects.Count; i++) { RevitObject obj = existingObjects[i]; fi = doc.GetElement(existingElems[i]) as FamilyInstance; // Change the family and symbol if necessary if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name) { try { fi.Symbol = symbol; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } origin = new XYZ(UnitUtils.ConvertToInternalUnits(obj.Origin.X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.Origin.Z, lengthDUT)); // Find the level List<LyrebirdPoint> lbPoints = new List<LyrebirdPoint> { obj.Origin }; Level lvl = GetLevel(lbPoints, doc); // Get the host if (hostBehavior == 5) { // Face based family. Find the face and create the element XYZ normVector = new XYZ(obj.Orientation.X, obj.Orientation.Y, obj.Orientation.Z); XYZ faceVector; if (obj.FaceOrientation != null) { faceVector = new XYZ(obj.FaceOrientation.X, obj.FaceOrientation.Y, obj.FaceOrientation.Z); } else { faceVector = XYZ.BasisZ; } Face face = FindFace(origin, normVector, doc); if (face != null) { if (face.Reference.ElementId == fi.HostFace.ElementId) { //fi = doc.Create.NewFamilyInstance(face, origin, faceVector, symbol); // Just move the host and update the parameters as needed. LocationPoint lp = fi.Location as LocationPoint; if (lp != null) { XYZ oldLoc = lp.Point; XYZ translation = origin.Subtract(oldLoc); ElementTransformUtils.MoveElement(doc, fi.Id, translation); } SetParameters(fi, obj.Parameters, doc); } else { FamilyInstance origInst = fi; fi = doc.Create.NewFamilyInstance(face, origin, faceVector, symbol); foreach (Parameter p in origInst.Parameters) { try { Parameter newParam = fi.get_Parameter(p.GUID); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Delete the original instance of the family doc.Delete(origInst.Id); // Assign the parameters SetParameters(fi, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(fi, uniqueId, instanceSchema, runId, nickName); } } } else { // typical hosted family. Can be wall, floor, roof or ceiling. ElementId host = FindHost(origin, hostBehavior, doc); if (host != null) { if (host.IntegerValue != fi.Host.Id.IntegerValue) { // We'll have to recreate the element FamilyInstance origInst = fi; fi = doc.Create.NewFamilyInstance(origin, symbol, doc.GetElement(host), lvl, Autodesk.Revit.DB.Structure.StructuralType.NonStructural); foreach (Parameter p in origInst.Parameters) { try { Parameter newParam = fi.LookupParameter(p.Definition.Name); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Delete the original instance of the family doc.Delete(origInst.Id); // Assign the parameters SetParameters(fi, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(fi, uniqueId, instanceSchema, runId, nickName); } else { // Just move the host and update the parameters as needed. LocationPoint lp = fi.Location as LocationPoint; if (lp != null) { XYZ oldLoc = lp.Point; XYZ translation = origin.Subtract(oldLoc); ElementTransformUtils.MoveElement(doc, fi.Id, translation); } // Assign the parameters SetParameters(fi, obj.Parameters, doc); } } } // Assign the parameters SetParameters(fi, obj.Parameters, doc); } // delete the host finder ElementId hostFinderFamily = hostFinder.Symbol.Family.Id; doc.Delete(hostFinder.Id); doc.Delete(hostFinderFamily); hostFinder = null; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } t.Commit(); } } } #endregion #region Adaptive Components FamilyInstance adaptInst; try { adaptInst = doc.GetElement(existingElems[0]) as FamilyInstance; } catch { adaptInst = null; } if (adaptInst != null && AdaptiveComponentInstanceUtils.IsAdaptiveComponentInstance(adaptInst)) { // Find the FamilySymbol FamilySymbol symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc); if (symbol != null) { using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects")) { t.Start(); try { // Create the Schema for the instances to store the GH Component InstanceGUID and the path Schema instanceSchema = null; try { instanceSchema = Schema.Lookup(instanceSchemaGUID); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (instanceSchema == null) { SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID); sb.SetWriteAccessLevel(AccessLevel.Vendor); sb.SetReadAccessLevel(AccessLevel.Public); sb.SetVendorId("LMNA"); // Create the field to store the data in the family FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string)); guidFB.SetDocumentation("Component instance GUID from Grasshopper"); // Create a filed to store the run number FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int)); runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data"); // Create a field to store the GH component nickname. FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string)); nickNameFB.SetDocumentation("Component NickName from Grasshopper"); sb.SetSchemaName("LMNAInstanceGUID"); instanceSchema = sb.Finish(); } try { for (int i = 0; i < existingElems.Count; i++) { RevitObject obj = existingObjects[i]; FamilyInstance fi = doc.GetElement(existingElems[i]) as FamilyInstance; // Change the family and symbol if necessary if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name) { try { fi.Symbol = symbol; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } IList<ElementId> placePointIds = new List<ElementId>(); placePointIds = AdaptiveComponentInstanceUtils.GetInstancePlacementPointElementRefIds(fi); for (int ptNum = 0; ptNum < obj.AdaptivePoints.Count; ptNum++) { try { ReferencePoint rp = doc.GetElement(placePointIds[ptNum]) as ReferencePoint; XYZ pt = new XYZ(UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].X, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(obj.AdaptivePoints[ptNum].Z, lengthDUT)); XYZ vector = pt.Subtract(rp.Position); ElementTransformUtils.MoveElement(doc, rp.Id, vector); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Assign the parameters SetParameters(fi, obj.Parameters, doc); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } t.Commit(); } } } #endregion #region Curve based components if (ro.Curves != null && ro.Curves.Count > 0) { // Find the FamilySymbol FamilySymbol symbol = null; WallType wallType = null; FloorType floorType = null; RoofType roofType = null; GridType gridType = null; bool typeFound = false; FilteredElementCollector famCollector = new FilteredElementCollector(doc); if (ro.CategoryId == -2000011) { famCollector.OfClass(typeof(WallType)); foreach (WallType wt in famCollector) { if (wt.Name == ro.TypeName) { wallType = wt; typeFound = true; break; } } } else if (ro.CategoryId == -2000032) { famCollector.OfClass(typeof(FloorType)); foreach (FloorType ft in famCollector) { if (ft.Name == ro.TypeName) { floorType = ft; typeFound = true; break; } } } else if (ro.CategoryId == -2000035) { famCollector.OfClass(typeof(RoofType)); foreach (RoofType rt in famCollector) { if (rt.Name == ro.TypeName) { roofType = rt; typeFound = true; break; } } } else if (ro.CategoryId == -2000220) { famCollector.OfClass(typeof(GridType)); foreach (GridType gt in famCollector) { if (gt.Name == ro.TypeName) { gridType = gt; typeFound = true; break; } } } else { symbol = FindFamilySymbol(ro.FamilyName, ro.TypeName, doc); if (symbol != null) typeFound = true; } if (typeFound) { using (Transaction t = new Transaction(doc, "Lyrebird Modify Objects")) { t.Start(); try { // Create the Schema for the instances to store the GH Component InstanceGUID and the path Schema instanceSchema = null; try { instanceSchema = Schema.Lookup(instanceSchemaGUID); } catch (Exception ex) { Debug.WriteLine(ex.Message); } if (instanceSchema == null) { SchemaBuilder sb = new SchemaBuilder(instanceSchemaGUID); sb.SetWriteAccessLevel(AccessLevel.Vendor); sb.SetReadAccessLevel(AccessLevel.Public); sb.SetVendorId("LMNA"); // Create the field to store the data in the family FieldBuilder guidFB = sb.AddSimpleField("InstanceID", typeof(string)); guidFB.SetDocumentation("Component instance GUID from Grasshopper"); // Create a filed to store the run number FieldBuilder runIDFB = sb.AddSimpleField("RunID", typeof(int)); runIDFB.SetDocumentation("RunID for when multiple runs are created from the same data"); // Create a field to store the GH component nickname. FieldBuilder nickNameFB = sb.AddSimpleField("NickName", typeof(string)); nickNameFB.SetDocumentation("Component NickName from Grasshopper"); sb.SetSchemaName("LMNAInstanceGUID"); instanceSchema = sb.Finish(); } FamilyInstance fi = null; Grid grid = null; try { bool supress = Properties.Settings.Default.suppressWarning; bool supressedReplace = false; bool supressedModify = true; for (int i = 0; i < existingObjects.Count; i++) { RevitObject obj = existingObjects[i]; if (obj.CategoryId != -2000011 && obj.CategoryId != -2000032 && obj.CategoryId != -2000035 && obj.CategoryId != -2000220) { fi = doc.GetElement(existingElems[i]) as FamilyInstance; // Change the family and symbol if necessary if (fi.Symbol.Family.Name != symbol.Family.Name || fi.Symbol.Name != symbol.Name) { try { fi.Symbol = symbol; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } else if (obj.CategoryId == -2000220) { grid = doc.GetElement(existingElems[i]) as Grid; // Get the grid location and compare against the incoming curve Curve gridCrv = grid.Curve; LyrebirdCurve lbc = obj.Curves[0]; try { Arc arc = gridCrv as Arc; if (arc != null && lbc.CurveType == "Arc") { // Test that the arcs are similar XYZ startPoint = arc.GetEndPoint(0); XYZ endPoint = arc.GetEndPoint(1); XYZ centerPoint = arc.Center; double rad = arc.Radius; XYZ lbcStartPt = new XYZ(lbc.ControlPoints[0].X, lbc.ControlPoints[0].Y, lbc.ControlPoints[0].Z); XYZ lbcEndPt = new XYZ(lbc.ControlPoints[1].X, lbc.ControlPoints[1].Y, lbc.ControlPoints[1].Z); XYZ lbcMidPt = new XYZ(lbc.ControlPoints[2].X, lbc.ControlPoints[2].Y, lbc.ControlPoints[2].Z); Arc lbcArc = Arc.Create(lbcStartPt, lbcEndPt, lbcMidPt); XYZ lbcCenterPt = lbcArc.Center; double lbcRad = lbcArc.Radius; if (centerPoint.DistanceTo(lbcCenterPt) < 0.001 && lbcRad == rad && startPoint.DistanceTo(lbcStartPt) < 0.001) { // Do not create } else { // Delete the grid and rebuild it with the new curve. } } else { // Probably need to rebuild the curve } } catch { } try { Line line = gridCrv as Line; if (line != null && lbc.CurveType == "Line") { // Test that the arcs are similar XYZ startPoint = line.GetEndPoint(0); XYZ endPoint = line.GetEndPoint(1); XYZ lbcStartPt = new XYZ(lbc.ControlPoints[0].X, lbc.ControlPoints[0].Y, lbc.ControlPoints[0].Z); XYZ lbcEndPt = new XYZ(lbc.ControlPoints[1].X, lbc.ControlPoints[1].Y, lbc.ControlPoints[1].Z); if (endPoint.DistanceTo(lbcEndPt) < 0.001 && startPoint.DistanceTo(lbcStartPt) < 0.001) { // Do not create } else { // Delete the grid and rebuild it with the new curve. } } else { // Probably need to rebuild the curve } } catch { } if (grid.GridType.Name != gridType.Name) { try { grid.GridType = gridType; } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); Debug.WriteLine(ex.Message); } } } #region single line based family if (obj.Curves.Count == 1 && obj.Curves[0].CurveType != "Circle") { LyrebirdCurve lbc = obj.Curves[0]; List<LyrebirdPoint> curvePoints = lbc.ControlPoints.OrderBy(p => p.Z).ToList(); // linear // can be a wall or line based family. // Wall objects if (obj.CategoryId == -2000011) { // draw a wall Curve crv = null; if (lbc.CurveType == "Line") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); crv = Line.CreateBound(pt1, pt2); } else if (lbc.CurveType == "Arc") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT)); crv = Arc.Create(pt1, pt3, pt2); } if (crv != null) { // Find the level Level lvl = GetLevel(lbc.ControlPoints, doc); double offset = 0; if (Math.Abs(UnitUtils.ConvertToInternalUnits(curvePoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon) { offset = lvl.Elevation - UnitUtils.ConvertToInternalUnits(curvePoints[0].Z, lengthDUT); } // Modify the wall Wall w = null; try { w = doc.GetElement(existingElems[i]) as Wall; LocationCurve lc = w.Location as LocationCurve; lc.Curve = crv; // Change the family and symbol if necessary if (w.WallType.Name != wallType.Name) { try { w.WallType = wallType; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } catch (Exception ex) { TaskDialog.Show("ERROR", ex.Message); } // Assign the parameters SetParameters(w, obj.Parameters, doc); } } // See if it's a structural column else if (obj.CategoryId == -2001330) { if (symbol != null && lbc.CurveType == "Line") { Curve crv = null; XYZ origin = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); crv = Line.CreateBound(origin, pt2); // Find the level //Level lvl = GetLevel(lbc.ControlPoints, doc); // Create the column //fi = doc.Create.NewFamilyInstance(origin, symbol, lvl, Autodesk.Revit.DB.Structure.StructuralType.Column); // Change it to a slanted column Parameter slantParam = fi.get_Parameter(BuiltInParameter.SLANTED_COLUMN_TYPE_PARAM); // SlantedOrVerticalColumnType has 3 options, CT_Vertical (0), CT_Angle (1), or CT_EndPoint (2) // CT_EndPoint is what we want for a line based column. slantParam.Set(2); // Set the location curve of the column to the line LocationCurve lc = fi.Location as LocationCurve; if (lc != null) { lc.Curve = crv; } // Change the family and symbol if necessary if (fi.Symbol.Name != symbol.Name) { try { fi.Symbol = symbol; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Assign the parameters SetParameters(fi, obj.Parameters, doc); } } else if (obj.CategoryId == -2000220) { // draw a grid Curve crv = null; if (lbc.CurveType == "Line") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); crv = Line.CreateBound(pt1, pt2); } else if (lbc.CurveType == "Arc") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT)); crv = Arc.Create(pt1, pt3, pt2); } if (crv != null && grid != null) { // Determine if it's possible to edit the grid curve or if it needs to be deleted/replaced. // Assign the parameters SetParameters(grid, obj.Parameters, doc); } } // Otherwise create a family it using the line else { if (symbol != null) { Curve crv = null; if (lbc.CurveType == "Line") { XYZ origin = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); crv = Line.CreateBound(origin, pt2); } else if (lbc.CurveType == "Arc") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT)); crv = Arc.Create(pt1, pt3, pt2); } // Change the family and symbol if necessary if (fi.Symbol.Name != symbol.Name) { try { fi.Symbol = symbol; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } try { LocationCurve lc = fi.Location as LocationCurve; lc.Curve = crv; } catch (Exception ex) { Debug.WriteLine(ex.Message); } // Assign the parameters SetParameters(fi, obj.Parameters, doc); } } } #endregion #region Closed Curve Family else { bool replace = false; if (supress) { if (supressedReplace) { replace = true; } else { replace = false; } } if (profileWarning && !supress) { TaskDialog warningDlg = new TaskDialog("Warning") { MainInstruction = "Profile based Elements warning", MainContent = "Elements that require updates to a profile sketch may not be updated if the number of curves in the sketch differs from the incoming curves." + " In such cases the element and will be deleted and replaced with new elements." + " Doing so will cause the loss of any elements hosted to the original instance. How would you like to proceed" }; warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink1, "Replace the existing elements, understanding hosted elements may be lost"); warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink2, "Only updated parameter information and not profile or location information"); warningDlg.AddCommandLink(TaskDialogCommandLinkId.CommandLink3, "Cancel"); //warningDlg.VerificationText = "Supress similar warnings"; TaskDialogResult result = warningDlg.Show(); if (result == TaskDialogResult.CommandLink1) { replace = true; supressedReplace = true; supressedModify = true; //supress = warningDlg.WasVerificationChecked(); } if (result == TaskDialogResult.CommandLink2) { supressedReplace = false; supressedModify = true; //supress = warningDlg.WasVerificationChecked(); } if (result == TaskDialogResult.CommandLink3) { supressedReplace = false; supressedModify = false; //supress = warningDlg.WasVerificationChecked(); } } // A list of curves. These should equate a closed planar curve from GH. // Determine category and create based on that. #region walls if (obj.CategoryId == -2000011) { // Create line based wall // Find the level Level lvl = null; double offset = 0; List<LyrebirdPoint> allPoints = new List<LyrebirdPoint>(); foreach (LyrebirdCurve lc in obj.Curves) { foreach (LyrebirdPoint lp in lc.ControlPoints) { allPoints.Add(lp); } } allPoints.Sort((x, y) => x.Z.CompareTo(y.Z)); lvl = GetLevel(allPoints, doc); if (Math.Abs(allPoints[0].Z - lvl.Elevation) > double.Epsilon) { offset = allPoints[0].Z - lvl.Elevation; } // Generate the curvearray from the incoming curves List<Curve> crvArray = new List<Curve>(); try { foreach (LyrebirdCurve lbc in obj.Curves) { if (lbc.CurveType == "Circle") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT)); XYZ pt4 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[3].Z, lengthDUT)); XYZ pt5 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[4].Z, lengthDUT)); Arc arc1 = Arc.Create(pt1, pt3, pt2); Arc arc2 = Arc.Create(pt3, pt5, pt4); crvArray.Add(arc1); crvArray.Add(arc2); } else if (lbc.CurveType == "Arc") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); XYZ pt3 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[2].Z, lengthDUT)); Arc arc = Arc.Create(pt1, pt3, pt2); crvArray.Add(arc); } else if (lbc.CurveType == "Line") { XYZ pt1 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[0].Z, lengthDUT)); XYZ pt2 = new XYZ(UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].X, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lbc.ControlPoints[1].Z, lengthDUT)); Line line = Line.CreateBound(pt1, pt2); crvArray.Add(line); } else if (lbc.CurveType == "Spline") { List<XYZ> controlPoints = new List<XYZ>(); List<double> weights = lbc.Weights; List<double> knots = lbc.Knots; foreach (LyrebirdPoint lp in lbc.ControlPoints) { XYZ pt = new XYZ(UnitUtils.ConvertToInternalUnits(lp.X, lengthDUT), UnitUtils.ConvertToInternalUnits(lp.Y, lengthDUT), UnitUtils.ConvertToInternalUnits(lp.Z, lengthDUT)); controlPoints.Add(pt); } NurbSpline spline; if (lbc.Degree < 3) spline = NurbSpline.Create(controlPoints, weights); else spline = NurbSpline.Create(controlPoints, weights, knots, lbc.Degree, false, true); crvArray.Add(spline); } } } catch (Exception ex) { TaskDialog.Show("ERROR", ex.Message); } // Create the wall Wall w = null; if (replace) { Wall origWall = doc.GetElement(existingElems[i]) as Wall; // Find the model curves for the original wall ICollection<ElementId> ids; using (SubTransaction st = new SubTransaction(doc)) { st.Start(); ids = doc.Delete(origWall.Id); st.RollBack(); } List<ModelCurve> mLines = new List<ModelCurve>(); foreach (ElementId id in ids) { Element e = doc.GetElement(id); if (e is ModelCurve) { mLines.Add(e as ModelCurve); } } // Walls don't appear to be updatable like floors and roofs //if (mLines.Count != crvArray.Count) //{ w = Wall.Create(doc, crvArray, wallType.Id, lvl.Id, false); foreach (Parameter p in origWall.Parameters) { try { Parameter newParam = w.LookupParameter(p.Definition.Name); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception ex) { //TaskDialog.Show("Errorsz", ex.Message); Debug.WriteLine(ex.Message); } } if (Math.Abs(offset - 0) > double.Epsilon) { Parameter p = w.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET); p.Set(offset); } doc.Delete(origWall.Id); // Assign the parameters SetParameters(w, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(w, uniqueId, instanceSchema, runId, nickName); } else if (supressedModify) // Just update the parameters and don't change the wall { w = doc.GetElement(existingElems[i]) as Wall; // Change the family and symbol if necessary if (w.WallType.Name != wallType.Name) { try { w.WallType = wallType; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Assign the parameters SetParameters(w, obj.Parameters, doc); } } #endregion #region floors else if (obj.CategoryId == -2000032) { // Create a profile based floor // Find the level Level lvl = GetLevel(obj.Curves[0].ControlPoints, doc); double offset = 0; if (Math.Abs(UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon) { offset = UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation; } // Generate the curvearray from the incoming curves CurveArray crvArray = GetCurveArray(obj.Curves); // Create the floor Floor flr = null; if (replace) { Floor origFloor = doc.GetElement(existingElems[i]) as Floor; // Find the model curves for the original wall ICollection<ElementId> ids; using (SubTransaction st = new SubTransaction(doc)) { st.Start(); ids = doc.Delete(origFloor.Id); st.RollBack(); } // Get only the modelcurves List<ModelCurve> mLines = new List<ModelCurve>(); foreach (ElementId id in ids) { Element e = doc.GetElement(id); if (e is ModelCurve) { mLines.Add(e as ModelCurve); } } // Floors have an extra modelcurve for the SpanDirection. Remove the last Item to get rid of it. mLines.RemoveAt(mLines.Count - 1); if (mLines.Count != crvArray.Size) // The sketch is different from the incoming curves so floor is recreated { if (obj.CurveIds != null && obj.CurveIds.Count > 0) { // get the main profile int crvCount = obj.CurveIds[0]; List<LyrebirdCurve> primaryCurves = obj.Curves.GetRange(0, crvCount); crvArray = GetCurveArray(primaryCurves); flr = doc.Create.NewFloor(crvArray, floorType, lvl, false); } else { flr = doc.Create.NewFloor(crvArray, floorType, lvl, false); } foreach (Parameter p in origFloor.Parameters) { try { Parameter newParam = flr.LookupParameter(p.Definition.Name); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } if (Math.Abs(offset - 0) > double.Epsilon) { Parameter p = flr.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM); p.Set(offset); } doc.Delete(origFloor.Id); // Assign the parameters SetParameters(flr, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(flr, uniqueId, instanceSchema, runId, nickName); } else // The curves coming in should match the floor sketch. Let's modify the floor's locationcurves to edit it's location/shape { try { int crvCount = 0; foreach (ModelCurve l in mLines) { LocationCurve lc = l.Location as LocationCurve; lc.Curve = crvArray.get_Item(crvCount); crvCount++; } // Change the family and symbol if necessary if (origFloor.FloorType.Name != floorType.Name) { try { origFloor.FloorType = floorType; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Set the incoming parameters SetParameters(origFloor, obj.Parameters, doc); } catch // There was an error in trying to recreate it. Just delete the original and recreate the thing. { flr = doc.Create.NewFloor(crvArray, floorType, lvl, false); // Assign the parameters in the new floor to match the original floor object. foreach (Parameter p in origFloor.Parameters) { try { Parameter newParam = flr.LookupParameter(p.Definition.Name); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception exception) { Debug.WriteLine(exception.Message); } } if (Math.Abs(offset - 0) > double.Epsilon) { Parameter p = flr.get_Parameter(BuiltInParameter.FLOOR_HEIGHTABOVELEVEL_PARAM); p.Set(offset); } doc.Delete(origFloor.Id); // Set the incoming parameters SetParameters(flr, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(flr, uniqueId, instanceSchema, runId, nickName); } } } else if (supressedModify) // Just modify the floor and don't risk replacing it. { flr = doc.GetElement(existingElems[i]) as Floor; // Change the family and symbol if necessary if (flr.FloorType.Name != floorType.Name) { try { flr.FloorType = floorType; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Assign the parameters SetParameters(flr, obj.Parameters, doc); } } #endregion else if (obj.CategoryId == -2000035) { // Create a RoofExtrusion // Find the level Level lvl = GetLevel(obj.Curves[0].ControlPoints, doc); double offset = 0; if (Math.Abs(UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation) > double.Epsilon) { offset = UnitUtils.ConvertToInternalUnits(obj.Curves[0].ControlPoints[0].Z, lengthDUT) - lvl.Elevation; } // Generate the curvearray from the incoming curves CurveArray crvArray = GetCurveArray(obj.Curves); // Create the roof FootPrintRoof roof = null; ModelCurveArray roofProfile = new ModelCurveArray(); if (replace) // Try to modify or create a new roof. { FootPrintRoof origRoof = doc.GetElement(existingElems[i]) as FootPrintRoof; // Find the model curves for the original wall ICollection<ElementId> ids; using (SubTransaction st = new SubTransaction(doc)) { st.Start(); ids = doc.Delete(origRoof.Id); st.RollBack(); } // Get the sketch curves for the roof object. List<ModelCurve> mLines = new List<ModelCurve>(); foreach (ElementId id in ids) { Element e = doc.GetElement(id); if (e is ModelCurve) { mLines.Add(e as ModelCurve); } } if (mLines.Count != crvArray.Size) // Sketch curves qty doesn't match up with the incoming cuves. Just recreate the roof. { roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile); // Match parameters from the original roof to it's new iteration. foreach (Parameter p in origRoof.Parameters) { try { Parameter newParam = roof.LookupParameter(p.Definition.Name); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } if (Math.Abs(offset - 0) > double.Epsilon) { Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM); p.Set(offset); } doc.Delete(origRoof.Id); // Set the new parameters SetParameters(roof, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(roof, uniqueId, instanceSchema, runId, nickName); } else // The curves qty lines up, lets try to modify the roof sketch so we don't have to replace it. { if (obj.CurveIds != null && obj.CurveIds.Count > 0) { // Just recreate the roof roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile); // Match parameters from the original roof to it's new iteration. foreach (Parameter p in origRoof.Parameters) { try { Parameter newParam = roof.LookupParameter(p.Definition.Name); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } if (Math.Abs(offset - 0) > double.Epsilon) { Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM); p.Set(offset); } // Set the parameters from the incoming data SetParameters(roof, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(roof, uniqueId, instanceSchema, runId, nickName); doc.Delete(origRoof.Id); } else { try { int crvCount = 0; foreach (ModelCurve l in mLines) { LocationCurve lc = l.Location as LocationCurve; lc.Curve = crvArray.get_Item(crvCount); crvCount++; } // Change the family and symbol if necessary if (origRoof.RoofType.Name != roofType.Name) { try { origRoof.RoofType = roofType; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } SetParameters(origRoof, obj.Parameters, doc); } catch // Modificaiton failed, lets just create a new roof. { roof = doc.Create.NewFootPrintRoof(crvArray, lvl, roofType, out roofProfile); // Match parameters from the original roof to it's new iteration. foreach (Parameter p in origRoof.Parameters) { try { Parameter newParam = roof.LookupParameter(p.Definition.Name); if (newParam != null) { switch (newParam.StorageType) { case StorageType.Double: newParam.Set(p.AsDouble()); break; case StorageType.ElementId: newParam.Set(p.AsElementId()); break; case StorageType.Integer: newParam.Set(p.AsInteger()); break; case StorageType.String: newParam.Set(p.AsString()); break; default: newParam.Set(p.AsString()); break; } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } if (Math.Abs(offset - 0) > double.Epsilon) { Parameter p = roof.get_Parameter(BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM); p.Set(offset); } // Set the parameters from the incoming data SetParameters(roof, obj.Parameters, doc); // Assign the GH InstanceGuid AssignGuid(roof, uniqueId, instanceSchema, runId, nickName); doc.Delete(origRoof.Id); } } } } else if (supressedModify) // Only update the parameters { roof = doc.GetElement(existingElems[i]) as FootPrintRoof; // Change the family and symbol if necessary if (roof.RoofType.Name != roofType.Name) { try { roof.RoofType = roofType; } catch (Exception ex) { Debug.WriteLine(ex.Message); } } // Assign the parameters SetParameters(roof, obj.Parameters, doc); } } } #endregion } } catch (Exception ex) { TaskDialog.Show("Error", ex.Message); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } t.Commit(); } } } #endregion //return succeeded; }
void SetTangentLockInProfileSketch1( Document famdoc, Form [] extrusions) { ICollection <ElementId> delIds = null; List <ElementId> enmIDs = new List <ElementId>(); using (SubTransaction delTrans = new SubTransaction(famdoc)) { try { delTrans.Start(); delIds = famdoc.Delete(extrusions[0].Id); delTrans.RollBack(); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.ToString()); } } // Get the model lines in the profile and use the // end points for reference the sketch dimensions diameter List <ModelArc> mArcsR1 = new List <ModelArc>(); List <ModelArc> mArcsR2 = new List <ModelArc>(); List <ModelLine> mLines = new List <ModelLine>(); foreach (ElementId id in delIds) { enmIDs.Add(id); } for (int i = 0; i < enmIDs.Count; i++) { Element ele = famdoc.GetElement(enmIDs[i]); if (ele is ModelArc) { ModelArc ma = ele as ModelArc; Curve c = ma.GeometryCurve; Arc a = c as Arc; if (Math.Round(r1, 6) == Math.Round(a.Radius, 6)) { mArcsR1.Add(ma); } if (Math.Round(r2, 6) == Math.Round(a.Radius, 6)) { mArcsR2.Add(ma); } } if (ele is ModelLine) { ModelLine ml = ele as ModelLine; Element before = null; Element after = null; ElementId beforeId = null; ElementId afterId = null; if (i > 0) { before = famdoc.GetElement(enmIDs[i - 1]); beforeId = enmIDs[i - 1]; } else { before = famdoc.GetElement(enmIDs[enmIDs.Count - 1]); beforeId = enmIDs[enmIDs.Count - 1]; } if (i == enmIDs.Count - 1) { after = famdoc.GetElement(enmIDs[0]); afterId = enmIDs[0]; } else { after = famdoc.GetElement(enmIDs[i + 1]); afterId = enmIDs[i + 1]; } if (before is ModelArc && after is ModelArc) { ml.SetTangentLock(0, beforeId, true); ml.SetTangentLock(1, afterId, true); } } } }
/// <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> /// Return a reference to the topmost face of the given element. /// </summary> private Reference FindTopMostReference(Element e) { Reference ret = null; Document doc = e.Document; #region Revit 2012 #if _2012 using (SubTransaction t = new SubTransaction(doc)) { t.Start(); // Create temporary 3D view //View3D view3D = doc.Create.NewView3D( // 2012 // viewDirection ); // 2012 ViewFamilyType vft = new FilteredElementCollector(doc) .OfClass(typeof(ViewFamilyType)) .Cast <ViewFamilyType>() .FirstOrDefault <ViewFamilyType>(x => ViewFamily.ThreeDimensional == x.ViewFamily); Debug.Assert(null != vft, "expected to find a valid 3D view family type"); View3D view = View3D.CreateIsometric(doc, vft.Id); // 2013 XYZ eyePosition = XYZ.BasisZ; XYZ upDirection = XYZ.BasisY; XYZ forwardDirection = -XYZ.BasisZ; view.SetOrientation(new ViewOrientation3D( eyePosition, upDirection, forwardDirection)); XYZ viewDirection = -XYZ.BasisZ; BoundingBoxXYZ bb = e.get_BoundingBox(view); XYZ max = bb.Max; XYZ minAtMaxElevation = Create.NewXYZ( bb.Min.X, bb.Min.Y, max.Z); XYZ centerOfTopOfBox = 0.5 * (minAtMaxElevation + max); centerOfTopOfBox += 10 * XYZ.BasisZ; // Cast a ray through the model // to find the topmost surface #if DEBUG //ReferenceArray references // = doc.FindReferencesByDirection( // centerOfTopOfBox, viewDirection, view3D ); // 2011 IList <ReferenceWithContext> references = doc.FindReferencesWithContextByDirection( centerOfTopOfBox, viewDirection, view); // 2012 double closest = double.PositiveInfinity; //foreach( Reference r in references ) //{ // // 'Autodesk.Revit.DB.Reference.Element' is // // obsolete: Property will be removed. Use // // Document.GetElement(Reference) instead. // //Element re = r.Element; // 2011 // Element re = doc.GetElement( r ); // 2012 // if( re.Id.IntegerValue == e.Id.IntegerValue // && r.ProximityParameter < closest ) // { // ret = r; // closest = r.ProximityParameter; // } //} foreach (ReferenceWithContext r in references) { Element re = doc.GetElement( r.GetReference()); // 2012 if (re.Id.IntegerValue == e.Id.IntegerValue && r.Proximity < closest) { ret = r.GetReference(); closest = r.Proximity; } } string stable_reference = null == ret ? null : ret.ConvertToStableRepresentation(doc); #endif // DEBUG ReferenceIntersector ri = new ReferenceIntersector( e.Id, FindReferenceTarget.Element, view); ReferenceWithContext r2 = ri.FindNearest( centerOfTopOfBox, viewDirection); if (null == r2) { Debug.Print("ReferenceIntersector.FindNearest returned null!"); } else { ret = r2.GetReference(); Debug.Assert(stable_reference.Equals(ret .ConvertToStableRepresentation(doc)), "expected same reference from " + "FindReferencesWithContextByDirection and " + "ReferenceIntersector"); } t.RollBack(); } #endif // _2012 #endregion // Revit 2012 Options opt = doc.Application.Create .NewGeometryOptions(); opt.ComputeReferences = true; GeometryElement geo = e.get_Geometry(opt); foreach (GeometryObject obj in geo) { GeometryInstance inst = obj as GeometryInstance; if (null != inst) { geo = inst.GetSymbolGeometry(); break; } } Solid solid = geo.OfType <Solid>() .First <Solid>(sol => null != sol); double z = double.MinValue; foreach (Face f in solid.Faces) { BoundingBoxUV b = f.GetBoundingBox(); UV p = b.Min; UV q = b.Max; UV midparam = p + 0.5 * (q - p); XYZ midpoint = f.Evaluate(midparam); XYZ normal = f.ComputeNormal(midparam); if (Util.PointsUpwards(normal)) { if (midpoint.Z > z) { z = midpoint.Z; ret = f.Reference; } } } return(ret); }
/// <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; }