public static Element Element(this Document document, LinkElementId linkElementId) { if (document == null || linkElementId == null) { return(null); } Document revitDocument = null; if (linkElementId.LinkInstanceId != Autodesk.Revit.DB.ElementId.InvalidElementId) { revitDocument = (document.GetElement(linkElementId.LinkInstanceId) as RevitLinkInstance).GetLinkDocument(); } else { revitDocument = document; } if (linkElementId.LinkedElementId != Autodesk.Revit.DB.ElementId.InvalidElementId) { return(revitDocument.GetElement(linkElementId.LinkedElementId)); } else { return(revitDocument.GetElement(linkElementId.HostElementId)); } }
public static IntersectionMepCurve HTMLRowToIntersection(CollisionReportRow row, Document hostdoc, ElementProcessingLog rowLog, ElementProcessingLog angledPipeLog) { GetElementsFromReportRow(hostdoc, row, out ICollection <Element> docElems, out ICollection <Element> linkElems, out RevitLinkInstance linkdocInstance); // в Naviswork система координат по внутренней площадке документа // поэтому необходимо и корректировать по местной системе координат ProjectLocation pl = hostdoc.ActiveProjectLocation; XYZ centerPoint = pl.GetTransform().OfPoint(row.Point); // определяем, где конструкция, а где сеть var findedElems = docElems.Concat(linkElems); Element host = findedElems.FirstOrDefault(x => x is Wall || x is Floor); if (host == null) { // Случай, когда стена разбита на части Part part = findedElems.FirstOrDefault(x => x is Part) as Part; if (part != null) { LinkElementId linkId = part.GetSourceElementIds().First(); host = hostdoc.GetElement(linkId.HostElementId); } } Element pipe = findedElems.FirstOrDefault(x => x is MEPCurve || (x is FamilyInstance && (x as FamilyInstance).MEPModel.ConnectorManager != null)); // создание объекта пересечения if (host != null && pipe != null) { try { var intr = new IntersectionMepCurve(host, pipe, centerPoint, linkdocInstance); return(intr); } catch (NotImplementedException) { angledPipeLog.AddError(row.Name); } } else { rowLog.AddError(row.Name); } return(null); }
Element GetElementFromLinkedElement(LinkElementId leid, Document doc) { var lih = doc.GetElement(leid.HostElementId); if (lih != null) { return(lih); } var li = doc.GetElement(leid.LinkInstanceId) as RevitLinkInstance; var linkedDoc = li != null?li.GetLinkDocument() : doc; var elm = linkedDoc.GetElement(leid.LinkedElementId); return(elm); }
public static List <LinkElementId> FindExteriorWallsByParameterValues(Document doc, bool isHost, ElementId linkInstanceId) { List <LinkElementId> exteriorElementIds = new List <LinkElementId>(); try { FilteredElementCollector collector = new FilteredElementCollector(doc); Wall wall = collector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements().Cast <Wall>().First(); Parameter param = wall.LookupParameter(LEEDParameters.LEED_IsExteriorWall.ToString()); ElementId paramId = ElementId.InvalidElementId; if (null != param) { paramId = param.Id; } ParameterValueProvider pvp = new ParameterValueProvider(paramId); FilterNumericEquals fnrv = new FilterNumericEquals(); FilterIntegerRule paramFr = new FilterIntegerRule(pvp, fnrv, 1); ElementParameterFilter paramFilter = new ElementParameterFilter(paramFr); collector = new FilteredElementCollector(doc); List <ElementId> eIds = collector.OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().WherePasses(paramFilter).ToElementIds().ToList(); foreach (ElementId eId in eIds) { if (isHost) { LinkElementId linkId = new LinkElementId(eId); exteriorElementIds.Add(linkId); } else { LinkElementId linkId = new LinkElementId(linkInstanceId, eId); exteriorElementIds.Add(linkId); } } } catch (Exception ex) { MessageBox.Show("Failed to find exterior walls.\n" + ex.Message, "Find Exterior Walls by Parameter", MessageBoxButton.OK, MessageBoxImage.Warning); } return(exteriorElementIds); }
/// <summary> /// Tag all walls in all linked documents /// </summary> void TagAllLinkedWalls(Document doc) { // Point near my wall XYZ xyz = new XYZ(-20, 20, 0); // At first need to find our links FilteredElementCollector collector = new FilteredElementCollector(doc) .OfClass(typeof(RevitLinkInstance)); foreach (Element elem in collector) { // Get linkInstance RevitLinkInstance instance = elem as RevitLinkInstance; // Get linkDocument Document linkDoc = instance.GetLinkDocument(); // Get linkType RevitLinkType type = doc.GetElement( instance.GetTypeId()) as RevitLinkType; // Check if link is loaded if (RevitLinkType.IsLoaded(doc, type.Id)) { // Find walls for tagging FilteredElementCollector walls = new FilteredElementCollector(linkDoc) .OfCategory(BuiltInCategory.OST_Walls) .OfClass(typeof(Wall)); // Create reference foreach (Wall wall in walls) { Reference newRef = new Reference(wall) .CreateLinkReference(instance); // Create transaction using (Transaction tx = new Transaction(doc)) { tx.Start("Create tags"); IndependentTag newTag = IndependentTag.Create( doc, doc.ActiveView.Id, newRef, true, TagMode.TM_ADDBY_MATERIAL, TagOrientation.Horizontal, xyz); // Use TaggedElementId.LinkInstanceId and // TaggedElementId.LinkInstanceId to retrieve // the id of the tagged link and element: LinkElementId linkId = newTag.TaggedElementId; ElementId linkInstanceId = linkId.LinkInstanceId; ElementId linkedElementId = linkId.LinkedElementId; tx.Commit(); } } } } }
/// <summary> /// Test whether each room has a roof to bound it. /// </summary> /// <param name="message">Error message to be dumped.</param> /// <param name="elements">Some elements to return.</param> /// <returns></returns> private bool FindRoomBoundingRoofs(ref string message, Autodesk.Revit.DB.ElementSet elements) { // Get all rooms List <Element> rooms = GetRoomsElements(); if (rooms.Count == 0) { message = "Unable to identify any rooms, please create room first!"; return(false); } // Represents the criteria for boundary elements to be considered bounding roofs LogicalOrFilter categoryFilter = new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_Roofs), new ElementCategoryFilter(BuiltInCategory.OST_RoofSoffit)); // Calculator for room/space geometry. SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(m_document); // Stores the resulting room->roof relationships Dictionary <Element, List <ElementId> > roomsAndRoofs = new Dictionary <Element, List <ElementId> >(); foreach (Element room in rooms) { // Get room geometry & boundaries SpatialElementGeometryResults results = calculator.CalculateSpatialElementGeometry((SpatialElement)room); // Get solid geometry so we can examine each face Solid geometry = results.GetGeometry(); foreach (Face face in geometry.Faces) { // Get list of roof boundary subfaces for a given face IList <SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face); foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces) { // Get boundary element LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement; // Only considering local file room bounding elements ElementId localElementId = boundaryElementId.HostElementId; // Evaluate if element meets criteria using PassesFilter() if (localElementId != ElementId.InvalidElementId && categoryFilter.PassesFilter(m_document, localElementId)) { // Room already has roofs, add more if (roomsAndRoofs.ContainsKey(room)) { List <ElementId> roofs = roomsAndRoofs[room]; if (!roofs.Contains(localElementId)) { roofs.Add(localElementId); } } // Room found first roof else { List <ElementId> roofs = new List <ElementId>(); roofs.Add(localElementId); roomsAndRoofs.Add(room, roofs); } break; } } } } // Format results if (roomsAndRoofs.Count > 0) { String logs = String.Format("Rooms that have a bounding roof:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (KeyValuePair <Element, List <ElementId> > kvp in roomsAndRoofs) { // remove this room from all rooms list rooms.Remove(kvp.Key); List <ElementId> roofs = kvp.Value; String roofsString; // Single roof boundary if (roofs.Count == 1) { Element roof = m_document.GetElement(roofs[0]); roofsString = String.Format("Roof: Id = {0}, Name = {1}", roof.Id.IntegerValue, roof.Name); } // Multiple roofs else { roofsString = "Roofs ids = " + string.Join(", ", Array.ConvertAll <ElementId, string>(roofs.ToArray(), i => i.ToString())); } // Save results logs = String.Format( " Room: Id = {0}, Name = {1} --> {2}", kvp.Key.Id.IntegerValue, kvp.Key.Name, roofsString); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } // Format the rooms that have no bounding roof Trace.WriteLine("Geometry relationship checking finished..."); if (rooms.Count != 0) { String logs = String.Format("Below rooms don't have bounding roofs:"); message += logs + "\t\r\n"; Trace.WriteLine(logs); foreach (Element room in rooms) { elements.Insert(room); logs = String.Format(" Room Id: {0}, Room Name: {1}", room.Id.IntegerValue, room.Name); message += logs + "\t\r\n"; Trace.WriteLine(logs); } } return(true); }
public static List <Panel> Panels(this SpatialElement spatialElement, SpatialElementGeometryCalculator spatialElementGeometryCalculator, Core.Revit.ConvertSettings convertSettings) { if (spatialElement == null || spatialElementGeometryCalculator == null) { return(null); } SpatialElementGeometryResults spatialElementGeometryResults = spatialElementGeometryCalculator.CalculateSpatialElementGeometry(spatialElement); if (spatialElementGeometryResults == null) { return(null); } Solid solid = spatialElementGeometryResults.GetGeometry(); if (solid == null) { return(null); } List <Tuple <Face, LinkElementId, SubfaceType> > tuples = new List <Tuple <Face, LinkElementId, SubfaceType> >(); foreach (Face face in solid.Faces) { IList <SpatialElementBoundarySubface> spatialElementBoundarySubfaces = spatialElementGeometryResults.GetBoundaryFaceInfo(face); if (spatialElementBoundarySubfaces == null || spatialElementBoundarySubfaces.Count == 0) { tuples.Add(new Tuple <Face, LinkElementId, SubfaceType>(face, null, SubfaceType.Side)); continue; } foreach (SpatialElementBoundarySubface spatialElementBoundarySubface in spatialElementBoundarySubfaces) { if (spatialElementBoundarySubface == null) { continue; } Face face_Subface = spatialElementBoundarySubface.GetSubface(); //Face face_Subface = spatialElementBoundarySubface.GetSpatialElementFace(); LinkElementId linkElementId = spatialElementBoundarySubface.SpatialBoundaryElement; tuples.Add(new Tuple <Face, LinkElementId, SubfaceType>(face_Subface, linkElementId, spatialElementBoundarySubface.SubfaceType)); } } List <Panel> result = new List <Panel>(); foreach (Tuple <Face, LinkElementId, SubfaceType> tuple in tuples) { List <Geometry.Spatial.Face3D> face3Ds = Geometry.Revit.Convert.ToSAM(tuple.Item1); if (face3Ds == null || face3Ds.Count == 0) { continue; } foreach (Geometry.Spatial.Face3D face3D in face3Ds) { PanelType panelType = PanelType.Undefined; Construction construction = null; Panel panel = null; if (tuple.Item2 != null) { Element element = Core.Revit.Query.Element(spatialElement.Document, tuple.Item2); if (element != null) { HostObject hostObject = element as HostObject; if (hostObject != null) { List <Panel> panels = hostObject.ToSAM(convertSettings); if (panels != null && panels.Count > 0) { panel = panels[0]; } if (panel != null) { construction = panel.Construction; panelType = Analytical.Query.PanelType(construction?.Name); if (panelType == PanelType.Undefined) { panelType = panel.PanelType; } } if (panelType == PanelType.Undefined) { panelType = Query.PanelType(hostObject); } if (construction == null) { ElementId elementId_Type = hostObject.GetTypeId(); if (elementId_Type != null && elementId_Type != ElementId.InvalidElementId) { construction = ((HostObjAttributes)hostObject.Document.GetElement(elementId_Type)).ToSAM(convertSettings); } } } } } if (panelType == PanelType.Undefined) { panelType = Analytical.Query.PanelType(face3D.GetPlane()?.Normal); } if (panelType == PanelType.Undefined) { switch (tuple.Item3) { case SubfaceType.Bottom: panelType = PanelType.Floor; break; case SubfaceType.Top: panelType = PanelType.Roof; break; case SubfaceType.Side: panelType = PanelType.Wall; break; } } if (construction == null) { construction = Analytical.Query.DefaultConstruction(panelType); //Default Construction } if (panel == null) { panel = Analytical.Create.Panel(construction, panelType, face3D); } else { panel = Analytical.Create.Panel(panel.Guid, panel, face3D); } result.Add(panel); } } return(result); }
/// <summary> /// Gets element from LinkElementId. /// </summary> /// <param name="document"> /// The Revit document. /// </param> /// <param name="linkElementId"> /// The link element id. /// </param> /// <returns> /// The element. /// </returns> static Element GetBoundaryElement(Document document, LinkElementId linkElementId) { ElementId elemId = linkElementId.LinkInstanceId; if (elemId == ElementId.InvalidElementId) { elemId = linkElementId.HostElementId; } return document.GetElement(elemId); }
// defines the Main Method with 1 argument: ActiveUIDoc public void SetRoomFinishingParameters(UIDocument ActiveUIDoc) { //Active document in Revit application Document doc = ActiveUIDoc.Document; //Get collection of Rooms in indicated level IEnumerable <Element> collector = FindRooms(ActiveUIDoc); //List of RoomData List <RoomData> roomDataList = new List <RoomData>(); foreach (Room r in collector) { #region Retrieving of Room Data //List of RoomBoudingElements List <Element> roomBoundingElems = new List <Element>(); // Calculate a room's geometry and find its boundary faces SpatialElementGeometryCalculator calculator = new SpatialElementGeometryCalculator(doc); SpatialElementGeometryResults results = calculator.CalculateSpatialElementGeometry(r); // compute the room geometry Solid roomSolid = results.GetGeometry(); // get the solid representing the room's geometry // Go through the boundary faces to add this element to the list of roomBoundingElems foreach (Face face in roomSolid.Faces) { IList <SpatialElementBoundarySubface> boundaryFaces = results.GetBoundaryFaceInfo(face); foreach (SpatialElementBoundarySubface boundaryFace in boundaryFaces) { // Get boundary element LinkElementId boundaryElementId = boundaryFace.SpatialBoundaryElement; // Only considering local file room bounding elements ElementId localElementId = boundaryElementId.HostElementId; Element elem = doc.GetElement(localElementId); //Add Room Bounding Element to list roomBoundingElems.Add(elem); } } //List of all Element Types of the Room Bounding Elements List <Element> elemsType = new List <Element>(); foreach (Element elem in roomBoundingElems) { ElementId id = elem.GetTypeId(); Element elemType = doc.GetElement(id); elemsType.Add(elemType); } //List of all unique Element Types of the Room Bounding Elements List <Element> elemsTypeDist = elemsType.Distinct(new ElemTypeIdEqualityComparer()).ToList(); //List of all unique Element Types of the Room Bounding Elements with the Floors Assembly Code indicated IEnumerable <Element> finishingFloorsElemsTypes = GetFinishingElemsTypes(elemsTypeDist, finishingFloorsAssemblyCode); //Dictionary with Key values and Keynote Texts Dictionary <string, string> finishingFloorsKeynote = GetKeynote(finishingFloorsElemsTypes, ActiveUIDoc); //Dictionary<string, string> //List of all unique Element Types of the Room Bounding Elements with the Floors Assembly Code indicated IEnumerable <Element> finishingWallsElemsTypes = GetFinishingElemsTypes(elemsTypeDist, finishingWallsAssemblyCode); //Dictionary with Key values and Keynote Texts Dictionary <string, string> finishingWallsKeynote = GetKeynote(finishingWallsElemsTypes, ActiveUIDoc); //List of all unique Element Types of the Room Bounding Elements with the Floors Assembly Code indicated IEnumerable <Element> ceilingsElemsTypes = GetFinishingElemsTypes(elemsTypeDist, ceilingsAssemblyCode); //Dictionary with Key values and Keynote Texts Dictionary <string, string> ceilingsKeynote = GetKeynote(ceilingsElemsTypes, ActiveUIDoc); #endregion // Retrieving of Room Data //new RoomData class per room var RD = new RoomData { room = r, elems = roomBoundingElems, finishingFloors = finishingFloorsKeynote, finishingWalls = finishingWallsKeynote, ceilings = ceilingsKeynote, }; //Adds Room Data to Room Data List roomDataList.Add(RD); } //Fills Parameters FillParameters(roomDataList, doc); }
public static Result Execute2( ExternalCommandData commandData, bool exportToSatFormat) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; if (null == doc) { ErrorMsg("Please run this command in a valid" + " Revit project document."); return(Result.Failed); } View view = doc.ActiveView; if (null == view || !(view is View3D)) { ErrorMsg("Please run this command in a valid" + " 3D view."); return(Result.Failed); } if (PartsVisibility.ShowPartsOnly != view.PartsVisibility) { ErrorMsg("Please run this command in a view" + " displaying parts and not source elements."); return(Result.Failed); } // Define the list of views to export, // including only the current 3D view List <ElementId> viewIds = new List <ElementId>(1); viewIds.Add(view.Id); // Iterate over all pre-selected parts List <ElementId> ids = null; Selection sel = uidoc.Selection; ICollection <ElementId> selIds = sel.GetElementIds(); // 2015 //if( 0 < sel.Elements.Size ) // 2014 if (0 < selIds.Count) // 2015 { //foreach( Element e in sel.Elements ) // 2014 foreach (ElementId id in selIds) // 2015 { Element e = doc.GetElement(id); if (!(e is Part)) { ErrorMsg("Please pre-select only gyp wallboard" + " parts before running this command."); return(Result.Failed); } Part part = e as Part; ICollection <LinkElementId> lids = part.GetSourceElementIds(); if (1 != lids.Count) { ErrorMsg("Gyp wallboard part has multiple" + " source elements."); return(Result.Failed); } LinkElementId lid = lids.First <LinkElementId>(); ElementId hostId = lid.HostElementId; ElementId linkedId = lid.LinkedElementId; ElementId parentId = hostId; ElementId partId = e.Id; // Determine parent category Element parent = doc.GetElement(parentId); Category cat = parent.Category; ICollection <ElementId> cids = part.GetSourceElementOriginalCategoryIds(); if (1 != cids.Count) { ErrorMsg("Gyp wallboard part has multiple" + " source element categories."); return(Result.Failed); } ElementId cid = cids.First <ElementId>(); //cat = doc.GetElement( id ) as Category; // Expected parent category is OST_Walls BuiltInCategory bic = (BuiltInCategory)cid.IntegerValue; if (BuiltInCategory.OST_Walls != bic) { ErrorMsg("Please pre-select only " + " gyp wallboard parts."); return(Result.Failed); } if (null == ids) { ids = new List <ElementId>(1); } ids.Add(partId); } if (null == ids) { ErrorMsg("Please pre-select only gyp wallboard" + " parts before running this command."); return(Result.Failed); } } // If no parts were pre-selected, // prompt for post-selection if (null == ids) { IList <Reference> refs = null; try { refs = sel.PickObjects(ObjectType.Element, new WallPartSelectionFilter(), "Please select wall parts."); } catch (Autodesk.Revit.Exceptions .OperationCanceledException) { return(Result.Cancelled); } ids = new List <ElementId>( refs.Select <Reference, ElementId>( r => r.ElementId)); } if (0 == ids.Count) { ErrorMsg("No valid parts selected."); return(Result.Failed); } // Check for shared parameters // to record export history ExportParameters exportParameters = new ExportParameters( doc.GetElement(ids[0])); if (!exportParameters.IsValid) { ErrorMsg("Please initialise the CNC fabrication " + "export history shared parameters before " + "launching this command."); return(Result.Failed); } if (!Util.BrowseDirectory(ref _folder, true)) { return(Result.Cancelled); } try { // Register event handler for // "TaskDialog_Really_Print_Or_Export_Temp_View_Modes" // dialogue uiapp.DialogBoxShowing += new EventHandler <DialogBoxShowingEventArgs>( OnDialogBoxShowing); object opt = exportToSatFormat ? (object)new SATExportOptions() : (object)new DXFExportOptions(); //opt.FileVersion = ACADVersion.R2000; string filename; using (TransactionGroup txg = new TransactionGroup(doc)) { txg.Start("Export Wall Parts"); foreach (ElementId id in ids) { Element e = doc.GetElement(id); Debug.Assert(e is Part, "expected parts only"); Part part = e as Part; ICollection <LinkElementId> lids = part.GetSourceElementIds(); Debug.Assert(1 == lids.Count, "unexpected multiple part source elements."); LinkElementId lid = lids.First <LinkElementId>(); ElementId hostId = lid.HostElementId; ElementId linkedId = lid.LinkedElementId; ElementId parentId = hostId; ElementId partId = e.Id; filename = string.Format("{0}_{1}", parentId, partId); Element host = doc.GetElement(hostId); Debug.Assert(null != host, "expected to be able to access host element"); //Debug.Assert( ( host is Wall ), "expected host element to be a wall" ); Debug.Assert((host is Wall) || (host is Part), "expected host element to be a wall or part"); Debug.Assert(null != host.Category, "expected host element to have a valid category"); //Debug.Assert( host.Category.Id.IntegerValue.Equals( (int) BuiltInCategory.OST_Walls ), "expected host element to have wall category" ); Debug.Assert(host.Category.Id.IntegerValue.Equals((int)BuiltInCategory.OST_Walls) || host.Category.Id.IntegerValue.Equals((int)BuiltInCategory.OST_Parts), "expected host element to have wall or part category"); Debug.Assert(ElementId.InvalidElementId != host.LevelId, "expected host element to have a valid level id"); if (ElementId.InvalidElementId != host.LevelId) { Element level = doc.GetElement(host.LevelId); filename = level.Name.Replace(' ', '_') + "_" + filename; } if (view.IsTemporaryHideIsolateActive()) { using (Transaction tx = new Transaction(doc)) { tx.Start("Disable Temporary Isolate"); view.DisableTemporaryViewMode( TemporaryViewMode.TemporaryHideIsolate); tx.Commit(); } Debug.Assert(!view.IsTemporaryHideIsolateActive(), "expected to turn off temporary hide/isolate"); } using (Transaction tx = new Transaction(doc)) { tx.Start("Export Wall Part " + partId.ToString()); // This call requires a transaction. view.IsolateElementTemporary(partId); //List<ElementId> unhideIds = new List<ElementId>( 1 ); //unhideIds.Add( partId ); //view.UnhideElements( unhideIds ); //doc.Regenerate(); // this is insufficient tx.Commit(); } if (exportToSatFormat) { //ViewSet viewSet = new ViewSet(); // //foreach( ElementId vid in viewIds ) //{ // viewSet.Insert( doc.GetElement( vid ) // as View ); //} // //doc.Export( _folder, filename, viewSet, // (SATExportOptions) opt ); // 2013 doc.Export(_folder, filename, viewIds, (SATExportOptions)opt); // 2014 } else { doc.Export(_folder, filename, viewIds, (DXFExportOptions)opt); } // Update CNC fabrication // export shared parameters -- oops, // cannot do this immediately, since // this transaction group will be // rolled back ... just save the // element id and do it later // searately. //exportParameters.UpdateExportHistory( e ); exportParameters.Add(e.Id); } // We do not commit the transaction group, // because no modifications should be saved. // The transaction group is only created and // started to encapsulate the transactions // required by the IsolateElementTemporary // method. Since the transaction group is not // committed, the changes are automatically // discarded. //txg.Commit(); } } finally { uiapp.DialogBoxShowing -= new EventHandler <DialogBoxShowingEventArgs>( OnDialogBoxShowing); } using (Transaction tx = new Transaction(doc)) { tx.Start("Update CNC Fabrication Export " + "History Shared Parameters"); exportParameters.UpdateExportHistory(); tx.Commit(); } return(Result.Succeeded); }