// for https://forums.autodesk.com/t5/revit-api-forum/how-to-calculate-the-center-point-of-elbow/m-p/9803893 /// <summary> /// Return elbow connector transforms. /// Return null if the given element is not a /// family instance with exactly two connectors. /// </summary> List <Transform> GetElbowConnectorTransforms(Element e) { List <Transform> xs = null; FamilyInstance fi = e as FamilyInstance; if (null != fi) { MEPModel m = fi.MEPModel; if (null != m) { ConnectorManager cm = m.ConnectorManager; if (null != cm) { ConnectorSet cs = cm.Connectors; if (2 == cs.Size) { xs = new List <Transform>(2); bool first = true; foreach (Connector c in cs) { if (first) { xs[0] = c.CoordinateSystem; } else { xs[1] = c.CoordinateSystem; } } } } } } return(xs); }
/// <summary> /// Check if an element assigned to IfcBuildingElementProxy is of MEP Type (by checking its connectors) to enable IfcBuildingElementProxy to take part /// in the System component and connectivity /// </summary> /// <param name="element">The element</param> /// <param name="exportType">IFC Export Type to check: only for IfcBuildingElementProxy or IfcBuildingElementProxyType</param> /// <returns></returns> public static bool ProxyForMEPType(Element element, IFCExportInfoPair exportType) { // In IFC4, the IfcBuildingElementProxy can no longer participate in the system connectivity (restricted only to IfcDistributionElement) if (ExporterCacheManager.ExportOptionsCache.ExportAs4) { return(false); } if ((exportType.ExportInstance == IFCEntityType.IfcBuildingElementProxy) || (exportType.ExportType == IFCEntityType.IfcBuildingElementProxyType)) { try { if (element is FamilyInstance) { MEPModel m = ((FamilyInstance)element).MEPModel; if (m != null && m.ConnectorManager != null) { return(true); } } else { return(false); } } catch { } } return(false); }
// for https://forums.autodesk.com/t5/revit-api-forum/how-to-calculate-the-center-point-of-elbow/m-p/9803893 /// <summary> /// Return elbow connectors. /// Return null if the given element is not a /// family instance with exactly two connectors. /// </summary> List <Connector> GetElbowConnectors(Element e) { List <Connector> cons = null; FamilyInstance fi = e as FamilyInstance; if (null != fi) { MEPModel m = fi.MEPModel; if (null != m) { ConnectorManager cm = m.ConnectorManager; if (null != cm) { ConnectorSet cs = cm.Connectors; if (2 == cs.Size) { cons = new List <Connector>(2); bool first = true; foreach (Connector c in cs) { if (first) { cons[0] = c; } else { cons[1] = c; } } } } } } return(cons); }
/// <summary> /// Gets a set of all connectors hosted by a single element. /// From http://thebuildingcoder.typepad.com/blog/2010/06/retrieve-mep-elements-and-connectors.html. /// </summary> /// <param name="e">The element that may host connectors</param> /// <returns>A set of connectors</returns> static ConnectorSet GetConnectors(Element e) { ConnectorSet connectors = null; try { if (e is FamilyInstance) { MEPModel m = ((FamilyInstance)e).MEPModel; if (m != null && m.ConnectorManager != null) { connectors = m.ConnectorManager.Connectors; } } else if (e is Wire) { connectors = ((Wire)e).ConnectorManager.Connectors; } else if (e is MEPCurve) { connectors = ((MEPCurve)e).ConnectorManager.Connectors; } } catch { } return(connectors); }
private bool VerifyUnusedConnectors(FamilyInstance fi) { bool hasUnusedElectricalConnector = false; try { MEPModel mepModel = fi.MEPModel; if (null == mepModel) { return(hasUnusedElectricalConnector); } ConnectorManager cm = mepModel.ConnectorManager; ConnectorSet unusedConnectors = cm.UnusedConnectors; if (null == unusedConnectors || unusedConnectors.IsEmpty) { return(hasUnusedElectricalConnector); } foreach (Connector connector in unusedConnectors) { if (connector.Domain == Domain.DomainElectrical) { hasUnusedElectricalConnector = true; break; } } } catch (Exception) { return(hasUnusedElectricalConnector); } return(hasUnusedElectricalConnector); }
/// <summary> /// List an electrical equipment instance and insert its data into /// the dictionary mapping panel + system name to equipment instances. /// </summary> static void ListEquipment( FamilyInstance elecEqip, IDictionary <string, List <Element> > mapPanelAndSystemToEquipment) { MEPModel mepModel = elecEqip.MEPModel; ElectricalSystemSet systems = mepModel.ElectricalSystems; string s = string.Empty; if (null == systems) { s = Unassigned + ":" + elecEqip.Name; } else { Debug.Assert(1 == systems.Size, "expected equipment to belong to one single panel and system"); foreach (ElectricalSystem system in systems) { if (0 < s.Length) { s += ", "; } s += system.PanelName + ":" + system.Name; } } Debug.WriteLine(" " + elecEqip.Name + ": " + s); Debug.Assert(!mapPanelAndSystemToEquipment.ContainsKey(s), "expected each panel and system to occur in one equipment element only"); if (!mapPanelAndSystemToEquipment.ContainsKey(s)) { mapPanelAndSystemToEquipment.Add(s, new List <Element>()); } mapPanelAndSystemToEquipment[s].Add(elecEqip); }
public static ConnectorSet GetConnectorSet(Element e) { ConnectorSet connectors = null; if (e is FamilyInstance) { MEPModel m = ((FamilyInstance)e).MEPModel; if (null != m && null != m.ConnectorManager) { connectors = m.ConnectorManager.Connectors; } } else if (e is Wire) { connectors = ((Wire)e).ConnectorManager.Connectors; } else { Debug.Assert(e.GetType().IsSubclassOf(typeof(MEPCurve)), "expected all candidate connector provider " + "elements to be either family instances or " + "derived from MEPCurve"); if (e is MEPCurve) { connectors = ((MEPCurve)e).ConnectorManager.Connectors; } } return(connectors); }
private ConnectorSet getConnectorSetFromElement(Element elem) { ConnectorSet connectors = null; bool flag = elem is FamilyInstance; if (flag) { MEPModel i = ((FamilyInstance)elem).MEPModel; connectors = i.ConnectorManager.Connectors; } else { bool flag2 = elem is FabricationPart; if (flag2) { connectors = ((FabricationPart)elem).ConnectorManager.Connectors; } else { bool flag3 = elem is MEPCurve; if (flag3) { connectors = ((MEPCurve)elem).ConnectorManager.Connectors; } else { Debug.Assert(elem.GetType().IsSubclassOf(typeof(MEPCurve)), "expected all candidate connector provider elements to be either family instances or derived from MEPCurve"); } } } return(connectors); }
public MEPViewModel() { Model = new MEPModel(); var line1 = new Line(); line1.X1 = 50; line1.X2 = 50; line1.Y1 = 0; line1.Y2 = 100; line1.Stroke = Brushes.Black; line1.StrokeThickness = 4; CenterCanvas.Children.Add(line1); var line2 = new Line(); line2.X1 = 50; line2.X2 = 25; line2.Y1 = 0; line2.Y2 = 25; line2.Stroke = Brushes.Black; line2.StrokeThickness = 4; CenterCanvas.Children.Add(line2); var line3 = new Line(); line3.X1 = 50; line3.X2 = 75; line3.Y1 = 0; line3.Y2 = 25; line3.Stroke = Brushes.Black; line3.StrokeThickness = 4; CenterCanvas.Children.Add(line3); }
/// <summary> /// Check if an element assigned to IfcBuildingElementProxy is of MEP Type (by checking its connectors) to enable IfcBuildingElementProxy to take part /// in the System component and connectivity /// </summary> /// <param name="element">The element</param> /// <param name="exportType">IFC Export Type to check: only for IfcBuildingElementProxy or IfcBuildingElementProxyType</param> /// <returns></returns> public static bool ProxyForMEPType(Element element, IFCExportInfoPair exportType) { if ((exportType.ExportInstance == IFCEntityType.IfcBuildingElementProxy) || (exportType.ExportType == IFCEntityType.IfcBuildingElementProxyType)) { try { if (element is FamilyInstance) { MEPModel m = ((FamilyInstance)element).MEPModel; if (m != null && m.ConnectorManager != null) { return(true); } } else { return(false); } } catch { } } return(false); }
/// <summary> /// 获得一个元素所有的Connector /// </summary> /// <param name="ele"></param> /// <returns></returns> public static ConnectorSet GetAllConnectors(Element ele) { ConnectorSet connectors = null; FamilyInstance familyInstance = ele as FamilyInstance; if (familyInstance != null) { MEPModel mEPModel = familyInstance.MEPModel; try { connectors = mEPModel.ConnectorManager.Connectors; } catch (Exception) { TaskDialog.Show("Error", ele.Id + " :没有找到连接点"); connectors = null; } } else { MEPCurve mepCurve = ele as MEPCurve; if (mepCurve != null) { connectors = mepCurve.ConnectorManager.Connectors; } } return(connectors); }
/// <summary> /// Add an element to circuit /// </summary> public void AddElementToCircuit() { // Clear selection before selecting the panel m_selection.Elements.Clear(); // Interact with UI to select a panel if (m_revitDoc.Selection.PickObject(ObjectType.Element) == null) { return; } // // Verify if the selected element can be added to the circuit // // Get selected element Element selectedElement = null; foreach (Element element in m_selection.Elements) { selectedElement = element; } // Get the MEP model of selected element MEPModel mepModel = null; FamilyInstance fi = selectedElement as FamilyInstance; if (null == fi || null == (mepModel = fi.MEPModel)) { ShowErrorMessage("SelectElectricalComponent"); return; } // Verify if the element has usable connector if (!VerifyUnusedConnectors(fi)) { ShowErrorMessage("NoUsableConnector"); return; } if (IsElementBelongsToCircuit(mepModel, m_selectedElectricalSystem)) { ShowErrorMessage("ElementInCircuit"); return; } try { if (!m_selectedElectricalSystem.AddToCircuit(m_selection.Elements)) { ShowErrorMessage("FailedToAddElement"); return; } } catch (Exception) { ShowErrorMessage("FailedToAddElement"); } }
/// <summary> /// /// </summary> /// <param name="mepInstance"></param> public MEPElectricalEquipment(FamilyInstance mepInstance) { if (mepInstance.MEPModel == null) { throw new ArgumentException("This familyInstance does not represent a MEP model."); } MepInstance = mepInstance; MepModel = mepInstance.MEPModel; }
/// <summary> /// Get The connector set of an element /// </summary> /// <param name="elem"></param> private ConnectorSet getConnectorSetFromElement(Element elem) { ConnectorSet connectors = null; //elemIds.Add(elem.Id); bool flag = elem is FamilyInstance; if (flag) { MEPModel i = ((FamilyInstance)elem).MEPModel; connectors = i.ConnectorManager.Connectors; } else { bool flag2 = elem is FabricationPart; if (flag2) { connectors = ((FabricationPart)elem).ConnectorManager.Connectors; } else { bool flag3 = elem is MEPCurve; if (flag3) { connectors = ((MEPCurve)elem).ConnectorManager.Connectors; } else { Debug.Assert(elem.GetType().IsSubclassOf(typeof(MEPCurve)), "expected all candidate connector provider elements to be either family instances or derived from MEPCurve"); } } } //foreach (Connector cone in connectors) //{ // if (!elemIds.Contains(cone.Owner.Id)) // elemIds.Add(cone.Owner.Id); //} ConnectorSet tempConnectors = new ConnectorSet(); foreach (Connector con in connectors) { if (!elemIds.Contains(con.Owner.Id)) { elemIds.Add(con.Owner.Id); Element tempElem = _doc.GetElement(con.Owner.Id); if (string.IsNullOrEmpty(tempElem.LookupParameter("Item Number").AsString())) { tempConnectors.Insert(con); } } } return(tempConnectors); }
private bool IsElementBelongsToCircuit(MEPModel mepModel, ElectricalSystem selectedElectricalSystem) { ElectricalSystemSet ess = mepModel.ElectricalSystems; if (null == ess || !ess.Contains(selectedElectricalSystem)) { return(false); } return(true); }
static private bool IsElementBelongsToCircuit(MEPModel mepModel, ElectricalSystem selectedElectricalSystem) { ISet <ElectricalSystem> ess = mepModel.GetElectricalSystems(); if (null == ess || !ess.Contains(selectedElectricalSystem)) { return(false); } return(true); }
// copied from sdk - TraverseSystem example // // (C) Copyright 2003-2010 by Autodesk, Inc. // /// <summary> /// Get the mechanical or piping system /// from selected element /// </summary> /// <param name="selectedElement">Selected element</param> /// <returns>The extracted mechanical or piping system, /// or null if no expected system is found.</returns> static public MEPSystem ExtractMechanicalOrPipingSystem( Element selectedElement) { MEPSystem system = null; if (selectedElement is MEPSystem) { if (selectedElement is MechanicalSystem || selectedElement is PipingSystem) { system = selectedElement as MEPSystem; return(system); } } else // Selected element is not a system { FamilyInstance fi = selectedElement as FamilyInstance; // If selected element is a family instance, // iterate its connectors and get the expected system if (fi != null) { MEPModel mepModel = fi.MEPModel; ConnectorSet connectors = null; try { connectors = mepModel.ConnectorManager.Connectors; } catch (System.Exception) { system = null; } system = ExtractSystemFromConnectors(connectors); } else { // If selected element is a MEPCurve (e.g. pipe or duct), // iterate its connectors and get the expected system MEPCurve mepCurve = selectedElement as MEPCurve; if (mepCurve != null) { ConnectorSet connectors = null; connectors = mepCurve.ConnectorManager.Connectors; system = ExtractSystemFromConnectors(connectors); } } } return(system); }
/// <summary> /// Remove an element from selected circuit /// </summary> public void RemoveElementFromCircuit() { // Clear selection before selecting the panel m_selection.GetElementIds().Clear(); // Interact with UI to select a panel if (m_revitDoc.Selection.PickObject(ObjectType.Element) == null) { return; } // Get the selected element Element selectedElement = null; foreach (ElementId elementId in m_revitDoc.Selection.GetElementIds()) { Element element = m_revitDoc.Document.GetElement(elementId); selectedElement = element; } // Get the MEP model of selected element MEPModel mepModel = null; FamilyInstance fi = selectedElement as FamilyInstance; if (null == fi || null == (mepModel = fi.MEPModel)) { ShowErrorMessage("SelectElectricalComponent"); return; } // Check whether the selected element belongs to the circuit if (!IsElementBelongsToCircuit(mepModel, m_selectedElectricalSystem)) { ShowErrorMessage("ElementNotInCircuit"); return; } try { // Remove the selected element from circuit ElementSet es = new ElementSet(); foreach (ElementId elementId in m_revitDoc.Selection.GetElementIds()) { es.Insert(m_revitDoc.Document.GetElement(elementId)); } m_selectedElectricalSystem.RemoveFromCircuit(es); } catch (Exception) { ShowErrorMessage("FailedToRemoveElement"); } }
Stream(ArrayList data, MEPModel mepModel) { data.Add(new Snoop.Data.ClassSeparator(typeof(MEPModel))); data.Add(new Snoop.Data.Object("Connector manager", mepModel.ConnectorManager)); data.Add(new Snoop.Data.Enumerable("Electrical systems", mepModel.ElectricalSystems)); ElectricalEquipment elecEquip = mepModel as ElectricalEquipment; if (elecEquip != null) { Stream(data, elecEquip); return; } LightingDevice lightDevice = mepModel as LightingDevice; if (lightDevice != null) { Stream(data, lightDevice); return; } LightingFixture lightFixture = mepModel as LightingFixture; if (lightFixture != null) { Stream(data, lightFixture); return; } MechanicalEquipment mechEquip = mepModel as MechanicalEquipment; if (mechEquip != null) { Stream(data, mechEquip); return; } MechanicalFitting mechFitting = mepModel as MechanicalFitting; if (mechFitting != null) { Stream(data, mechFitting); return; } }
//Input MEP Element object //Function returns list of connectors from MEP element public List <Connector> GetConnectors(Element element) { //1. Cast Element to FamilyInstance FamilyInstance inst = element as FamilyInstance; //2. Get MEPModel Property MEPModel mepModel = inst.MEPModel; //3. Get connector set of MEPModel ConnectorSet connectorSet = mepModel.ConnectorManager.Connectors; //4. Initialise empty list of connectors List <Connector> connectorList = new List <Connector>(); //5. Loop through connector set and add to list foreach (Connector connector in connectorSet) { connectorList.Add(connector); } return(connectorList); }
private MEPSystem ExtractMechanicalOrPipingSystem(Element selectedElement) { MEPSystem system = null; if (selectedElement is MEPSystem) { if (selectedElement is MechanicalSystem || selectedElement is PipingSystem) { system = selectedElement as MEPSystem; return(system); } } else { FamilyInstance fi = selectedElement as FamilyInstance; if (fi != null) { MEPModel mepModel = fi.MEPModel; ConnectorSet connectors = null; try { connectors = mepModel.ConnectorManager.Connectors; } catch (System.Exception) { system = null; } system = ExtractSystemFromConnectors(connectors, selectedElement); } else { MEPCurve mepCurve = selectedElement as MEPCurve; if (mepCurve != null) { ConnectorSet connectors = null; connectors = mepCurve.ConnectorManager.Connectors; system = ExtractSystemFromConnectors(connectors, selectedElement); } } } return(system); }
// Угол отводов public double GetAngle(Element i) { FamilyInstance fi = i as FamilyInstance; MEPModel mepModel = fi.MEPModel as MechanicalFitting; if ((fi.MEPModel as MechanicalFitting).PartType == PartType.Elbow) { ConnectorSet conSet = mepModel.ConnectorManager.Connectors; List <Connector> connectors = new List <Connector>(); foreach (Connector c in conSet) { connectors.Add(c); } angle = Math.Round(connectors[0].Angle, 2); } else { angle = 0.0; } return(angle); }
private bool CanExcuteOperation() { selection.GetElementIds().Clear(); // Interact with UI to select a panel if (uiDocument.Selection.PickObject(ObjectType.Element) == null) { return(false); } // Get the selected element Element selectedElement = null; foreach (ElementId elementId in uiDocument.Selection.GetElementIds()) { Element element = uiDocument.Document.GetElement(elementId); selectedElement = element; } // Get the MEP model of selected element MEPModel mepModel = null; FamilyInstance fi = selectedElement as FamilyInstance; if (null == fi || null == (mepModel = fi.MEPModel)) { ShowErrorMessage("SelectElectricalComponent"); return(false); } // Check whether the selected element belongs to the circuit if (!IsElementBelongsToCircuit(mepModel, m_selectedElectricalSystem)) { ShowErrorMessage("ElementNotInCircuit"); return(false); } return(true); }
private static bool IsElementBelongsToCircuit(MEPModel mepModel, ElectricalSystem selectedElectricalSystem) { ElectricalSystemSet ess = mepModel.ElectricalSystems; if (null == ess || !ess.Contains(selectedElectricalSystem)) { return false; } return true; }
public StringBuilder Export(string pipeLineAbbreviation, HashSet <Element> elements, Document document) { Document doc = document; string key = pipeLineAbbreviation; //The list of fittings, sorted by TYPE then SKEY IList <Element> fittingsList = elements. OrderBy(e => e.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString()). ThenBy(e => e.get_Parameter(new plst().PCF_ELEM_SKEY.Guid).AsString()).ToList(); StringBuilder sbFittings = new StringBuilder(); foreach (Element element in fittingsList) { //If the Element Type field is empty -> ignore the component if (string.IsNullOrEmpty(element.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString())) { continue; } sbFittings.AppendLine(element.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString()); sbFittings.AppendLine(" COMPONENT-IDENTIFIER " + element.get_Parameter(new plst().PCF_ELEM_COMPID.Guid).AsInteger()); //Write Plant3DIso entries if turned on if (iv.ExportToPlant3DIso) { sbFittings.Append(Composer.Plant3DIsoWriter(element, doc)); } //Cast the elements gathered by the collector to FamilyInstances FamilyInstance familyInstance = (FamilyInstance)element; Options options = new Options(); //MEPModel of the elements is accessed MEPModel mepmodel = familyInstance.MEPModel; //Get connector set for the element ConnectorSet connectorSet = mepmodel.ConnectorManager.Connectors; //Switch to different element type configurations switch (element.get_Parameter(new plst().PCF_ELEM_TYPE.Guid).AsString()) { case ("ELBOW"): Connector primaryConnector = null; Connector secondaryConnector = null; //Process endpoints of the component foreach (Connector connector in connectorSet) { if (connector.GetMEPConnectorInfo().IsPrimary) { primaryConnector = connector; } if (connector.GetMEPConnectorInfo().IsSecondary) { secondaryConnector = connector; } } sbFittings.Append(EndWriter.WriteEP1(element, primaryConnector)); sbFittings.Append(EndWriter.WriteEP2(element, secondaryConnector)); sbFittings.Append(EndWriter.WriteCP(familyInstance)); sbFittings.Append(" ANGLE "); sbFittings.Append((Conversion.RadianToDegree(element.LookupParameter("Angle").AsDouble()) * 100).ToString("0")); sbFittings.AppendLine(); break; case ("TEE"): //Sort connectors to primary, secondary and none primaryConnector = null; secondaryConnector = null; Connector tertiaryConnector = null; foreach (Connector connector in connectorSet) { #region Debug //Debug //sbFittings.Append(connector.GetMEPConnectorInfo().IsPrimary); //sbFittings.Append(connector.GetMEPConnectorInfo().IsSecondary); //sbFittings.Append((connector.GetMEPConnectorInfo().IsPrimary == false) & (connector.GetMEPConnectorInfo().IsSecondary == false)); //sbFittings.AppendLine(); #endregion if (connector.GetMEPConnectorInfo().IsPrimary) { primaryConnector = connector; } if (connector.GetMEPConnectorInfo().IsSecondary) { secondaryConnector = connector; } if ((connector.GetMEPConnectorInfo().IsPrimary == false) && (connector.GetMEPConnectorInfo().IsSecondary == false)) { tertiaryConnector = connector; } } //Process endpoints of the component sbFittings.Append(EndWriter.WriteEP1(element, primaryConnector)); sbFittings.Append(EndWriter.WriteEP2(element, secondaryConnector)); sbFittings.Append(EndWriter.WriteCP(familyInstance)); sbFittings.Append(EndWriter.WriteBP1(element, tertiaryConnector)); break; case ("REDUCER-CONCENTRIC"): //Process endpoints of the component primaryConnector = null; secondaryConnector = null; //Process endpoints of the component foreach (Connector connector in connectorSet) { if (connector.GetMEPConnectorInfo().IsPrimary) { primaryConnector = connector; } if (connector.GetMEPConnectorInfo().IsSecondary) { secondaryConnector = connector; } } sbFittings.Append(EndWriter.WriteEP1(element, primaryConnector)); sbFittings.Append(EndWriter.WriteEP2(element, secondaryConnector)); break; case ("REDUCER-ECCENTRIC"): goto case ("REDUCER-CONCENTRIC"); case ("FLANGE"): primaryConnector = null; secondaryConnector = null; tertiaryConnector = null; foreach (Connector connector in connectorSet) { if (connector.GetMEPConnectorInfo().IsPrimary) { primaryConnector = connector; } if (connector.GetMEPConnectorInfo().IsSecondary) { secondaryConnector = connector; } } //Process endpoints of the component //Secondary goes first because it is the weld neck point and the primary second because it is the flanged end //(dunno if it is significant); sbFittings.Append(EndWriter.WriteEP1(element, secondaryConnector)); sbFittings.Append(EndWriter.WriteEP2(element, primaryConnector)); break; case ("FLANGE-BLIND"): primaryConnector = null; foreach (Connector connector in connectorSet) { primaryConnector = connector; } //Connector information extraction sbFittings.Append(EndWriter.WriteEP1(element, primaryConnector)); XYZ endPointOriginFlangeBlind = primaryConnector.Origin; double connectorSizeFlangeBlind = primaryConnector.Radius; //Analyses the geometry to obtain a point opposite the main connector. //Extraction of the direction of the connector and reversing it XYZ reverseConnectorVector = -primaryConnector.CoordinateSystem.BasisZ; Line detectorLine = Line.CreateUnbound(endPointOriginFlangeBlind, reverseConnectorVector); //Begin geometry analysis GeometryElement geometryElement = familyInstance.get_Geometry(options); //Prepare resulting point XYZ endPointAnalyzed = null; foreach (GeometryObject geometry in geometryElement) { GeometryInstance instance = geometry as GeometryInstance; if (null != instance) { foreach (GeometryObject instObj in instance.GetInstanceGeometry()) { Solid solid = instObj as Solid; if (null == solid || 0 == solid.Faces.Size || 0 == solid.Edges.Size) { continue; } // Get the faces foreach (Face face in solid.Faces) { IntersectionResultArray results = null; XYZ intersection = null; SetComparisonResult result = face.Intersect(detectorLine, out results); if (result == SetComparisonResult.Overlap) { intersection = results.get_Item(0).XYZPoint; if (intersection.IsAlmostEqualTo(endPointOriginFlangeBlind) == false) { endPointAnalyzed = intersection; } } } } } } sbFittings.Append(EndWriter.WriteEP2(element, endPointAnalyzed, connectorSizeFlangeBlind)); break; case ("CAP"): goto case ("FLANGE-BLIND"); case ("OLET"): primaryConnector = null; secondaryConnector = null; foreach (Connector connector in connectorSet) { if (connector.GetMEPConnectorInfo().IsPrimary) { primaryConnector = connector; } if (connector.GetMEPConnectorInfo().IsSecondary) { secondaryConnector = connector; } } XYZ endPointOriginOletPrimary = primaryConnector.Origin; XYZ endPointOriginOletSecondary = secondaryConnector.Origin; //get reference elements ConnectorSet refConnectors = primaryConnector.AllRefs; Element refElement = null; foreach (Connector c in refConnectors) { refElement = c.Owner; } Pipe refPipe = (Pipe)refElement; //Get connector set for the pipes ConnectorSet refConnectorSet = refPipe.ConnectorManager.Connectors; //Filter out non-end types of connectors IEnumerable <Connector> connectorEnd = from Connector connector in refConnectorSet where connector.ConnectorType.ToString() == "End" select connector; //Following code is ported from my python solution in Dynamo. //The olet geometry is analyzed with congruent rectangles to find the connection point on the pipe even for angled olets. XYZ B = endPointOriginOletPrimary; XYZ D = endPointOriginOletSecondary; XYZ pipeEnd1 = connectorEnd.First().Origin; XYZ pipeEnd2 = connectorEnd.Last().Origin; XYZ BDvector = D - B; XYZ ABvector = pipeEnd1 - pipeEnd2; double angle = Conversion.RadianToDegree(ABvector.AngleTo(BDvector)); if (angle > 90) { ABvector = -ABvector; angle = Conversion.RadianToDegree(ABvector.AngleTo(BDvector)); } Line refsLine = Line.CreateBound(pipeEnd1, pipeEnd2); XYZ C = refsLine.Project(B).XYZPoint; double L3 = B.DistanceTo(C); XYZ E = refsLine.Project(D).XYZPoint; double L4 = D.DistanceTo(E); double ratio = L4 / L3; double L1 = E.DistanceTo(C); double L5 = L1 / (ratio - 1); XYZ A; if (angle < 89) { XYZ ECvector = C - E; ECvector = ECvector.Normalize(); double L = L1 + L5; ECvector = ECvector.Multiply(L); A = E.Add(ECvector); #region Debug //Debug //Place family instance at points to debug the alorithm //StructuralType strType = (StructuralType)4; //FamilySymbol familySymbol = null; //FilteredElementCollector collector = new FilteredElementCollector(doc); //IEnumerable<Element> collection = collector.OfClass(typeof(FamilySymbol)).ToElements(); //FamilySymbol marker = null; //foreach (Element e in collection) //{ // familySymbol = e as FamilySymbol; // if (null != familySymbol.Category) // { // if ("Structural Columns" == familySymbol.Category.Name) // { // break; // } // } //} //if (null != familySymbol) //{ // foreach (Element e in collection) // { // familySymbol = e as FamilySymbol; // if (familySymbol.FamilyName == "Marker") // { // marker = familySymbol; // Transaction trans = new Transaction(doc, "Place point markers"); // trans.Start(); // doc.Create.NewFamilyInstance(A, marker, strType); // doc.Create.NewFamilyInstance(B, marker, strType); // doc.Create.NewFamilyInstance(C, marker, strType); // doc.Create.NewFamilyInstance(D, marker, strType); // doc.Create.NewFamilyInstance(E, marker, strType); // trans.Commit(); // } // } //} #endregion } else { A = E; } angle = Math.Round(angle * 100); sbFittings.Append(EndWriter.WriteCP(A)); sbFittings.Append(EndWriter.WriteBP1(element, secondaryConnector)); sbFittings.Append(" ANGLE "); sbFittings.Append(Conversion.AngleToPCF(angle)); sbFittings.AppendLine(); break; } Composer elemParameterComposer = new Composer(); sbFittings.Append(elemParameterComposer.ElemParameterWriter(element)); #region CII export if (iv.ExportToCII) { sbFittings.Append(Composer.CIIWriter(doc, key)); } #endregion sbFittings.Append(" UNIQUE-COMPONENT-IDENTIFIER "); sbFittings.Append(element.UniqueId); sbFittings.AppendLine(); } //// Clear the output file //File.WriteAllBytes(InputVars.OutputDirectoryFilePath + "Fittings.pcf", new byte[0]); //// Write to output file //using (StreamWriter w = File.AppendText(InputVars.OutputDirectoryFilePath + "Fittings.pcf")) //{ // w.Write(sbFittings); // w.Close(); //} return(sbFittings); }
public Result Execute( ExternalCommandData commandData, ref String message, ElementSet elements) { try { // // dictionary defining tree view info displayed in modeless // dialogue mapping parent node to all its circuit elements: // null --> root panels // panel --> systems // system --> circuit elements, panels, ... // MapParentToChildren mapParentToChildren = new MapParentToChildren(); ElementId electricalEquipmentCategoryId = ElementId.InvalidElementId; List <Element> equipment; { // // run the analysis in its own scope, so the wait cursor // disappears before we display the modeless dialogue: // WaitCursor waitCursor = new WaitCursor(); UIApplication app = commandData.Application; Document doc = app.ActiveUIDocument.Document; ElementId nullId = ElementId.InvalidElementId; // // retrieve electrical equipment instances: // equipment = Util.GetElectricalEquipment(doc); int n = equipment.Count; Debug.WriteLine(string.Format("Retrieved {0} electrical equipment instance{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n))); Dictionary <string, FamilyInstance> mapPanel = new Dictionary <string, FamilyInstance>(); foreach (FamilyInstance e in equipment) { // // ensure that every panel shows up in the list, // even if it does not have children: // mapParentToChildren.Add(e.Id, null); mapPanel[e.Name] = e; MEPModel mepModel = e.MEPModel; ElectricalSystemSet systems2 = mepModel.ElectricalSystems; string panelAndSystem = string.Empty; if (null == systems2) { panelAndSystem = CmdElectricalSystemBrowser.Unassigned; // this is a root node } else { Debug.Assert(1 == systems2.Size, "expected equipment to belong to one single panel and system"); foreach (ElectricalSystem system in systems2) { if (0 < panelAndSystem.Length) { panelAndSystem += ", "; } panelAndSystem += system.PanelName + ":" + system.Name + ":" + system.Id.IntegerValue.ToString(); } } Debug.WriteLine(" " + Util.ElementDescriptionAndId(e) + " " + panelAndSystem); } // // retrieve electrical systems: // these are also returned by Util.GetCircuitElements(), by the way, // since they have the parameters RBS_ELEC_CIRCUIT_PANEL_PARAM and // RBS_ELEC_CIRCUIT_NUMBER that we use to identify those. // FilteredElementCollector c = new FilteredElementCollector(doc); IList <Element> systems = c.OfClass(typeof(ElectricalSystem)).ToElements(); n = systems.Count; Debug.WriteLine(string.Format("Retrieved {0} electrical system{1}{2}", n, Util.PluralSuffix(n), Util.DotOrColon(n))); foreach (ElectricalSystem system in systems) { string panelName = system.PanelName; if (0 == panelName.Length) { panelName = CmdElectricalSystemBrowser.Unassigned; // will not appear in tree } else { // // todo: is there a more direct way to identify // what panel a system belongs to? this seems error // prone ... what if a panel name occurs multiple times? // how do we identify which one to use? // FamilyInstance panel = mapPanel[panelName]; mapParentToChildren.Add(panel.Id, system); } string panelAndSystem = panelName + ":" + system.Name + ":" + system.Id.IntegerValue.ToString(); Debug.WriteLine(" " + Util.ElementDescriptionAndId(system) + " " + panelAndSystem); Debug.Assert(system.ConnectorManager.Owner.Id.Equals(system.Id), "expected electrical system's connector manager owner to be system itself"); } // // now we have the equipment and systems, // we can build the non-leaf levels of the tree: // foreach (FamilyInstance e in equipment) { MEPModel mepModel = e.MEPModel; ElectricalSystemSet systems2 = mepModel.ElectricalSystems; if (null == systems2) { mapParentToChildren.Add(nullId, e); // root node } else { Debug.Assert(1 == systems2.Size, "expected equipment to belong to one single panel and system"); foreach (ElectricalSystem system in systems2) { mapParentToChildren.Add(system.Id, e); } } } // // list all circuit elements: // BuiltInParameter bipPanel = BuiltInParameter.RBS_ELEC_CIRCUIT_PANEL_PARAM; BuiltInParameter bipCircuit = BuiltInParameter.RBS_ELEC_CIRCUIT_NUMBER; IList <Element> circuitElements = Util.GetCircuitElements(doc); n = circuitElements.Count; Debug.WriteLine(string.Format("Retrieved {0} circuit element{1}...", n, Util.PluralSuffix(n))); n = 0; foreach (Element e in circuitElements) { if (e is ElectricalSystem) { ++n; } else { string circuitName = e.get_Parameter(bipCircuit).AsString(); string panelName = e.get_Parameter(bipPanel).AsString(); string key = panelName + ":" + circuitName; string panelAndSystem = string.Empty; FamilyInstance inst = e as FamilyInstance; Debug.Assert(null != inst, "expected all circuit elements to be family instances"); MEPModel mepModel = inst.MEPModel; ElectricalSystemSet systems2 = mepModel.ElectricalSystems; Debug.Assert(null != systems2, "expected circuit element to belong to an electrical system"); // this fails in "2341_MEP - 2009 Central.rvt", says martin: // // a circuit element can belong to several systems ... imagine // a piece of telephone equipment which hooks up to a phone line // and also requires power ... so i removed this assertion: // //Debug.Assert( 1 == systems2.Size, "expected circuit element to belong to one single system" ); foreach (ElectricalSystem system in systems2) { if (0 < panelAndSystem.Length) { panelAndSystem += ", "; } panelAndSystem += system.PanelName + ":" + system.Name + ":" + system.Id.IntegerValue.ToString(); Debug.Assert(system.PanelName == panelName, "expected same panel name in parameter and electrical system"); // this fails in "2341_MEP - 2009 Central.rvt", says martin: //Debug.Assert( system.Name == circuitName, "expected same name in circuit parameter and system" ); mapParentToChildren.Add(system.Id, e); } Debug.WriteLine(string.Format(" {0} panel:circuit {1}", Util.ElementDescriptionAndId(e), panelAndSystem)); } } Debug.WriteLine(string.Format("{0} circuit element{1} were the electrical systems.", n, Util.PluralSuffix(n))); // // get the electrical equipment category id: // Categories categories = doc.Settings.Categories; electricalEquipmentCategoryId = categories.get_Item(BuiltInCategory.OST_ElectricalEquipment).Id; } // // we have assembled the entire required tree view structure, so let us display it: // CmdInspectElectricalForm2 dialog = new CmdInspectElectricalForm2(mapParentToChildren, electricalEquipmentCategoryId, equipment); dialog.Show(); return(Result.Succeeded); } catch (Exception ex) { message = ex.Message; return(Result.Failed); } }
public Result Execute(ExternalCommandData commandData, ref string msg, ElementSet elements) { UIApplication uiApp = commandData.Application; Document doc = uiApp.ActiveUIDocument.Document; UIDocument uidoc = uiApp.ActiveUIDocument; Transaction trans = new Transaction(doc, "Set System"); MEPModel mepModel = null; trans.Start(); try { //Select Element to provide a system //Pipe type to restrict selection of tapping element Type t = typeof(Pipe); //Select tap element Element systemDonor = BuildingCoderUtilities.SelectSingleElementOfType(uidoc, t, "Select a pipe in desired system.", false); if (systemDonor == null) { throw new Exception("System assignment cancelled!"); } //Select Element to add to system Element elementToAdd = BuildingCoderUtilities.SelectSingleElement(uidoc, "Select support to add to system."); if (elementToAdd == null) { throw new Exception("System assignment cancelled!"); } //Cast the selected element to Pipe Pipe pipe = (Pipe)systemDonor; //Get the pipe type from pipe ElementId pipeTypeId = pipe.PipeType.Id; //Get system type from pipe ConnectorSet pipeConnectors = pipe.ConnectorManager.Connectors; Connector pipeConnector = (from Connector c in pipeConnectors where true select c).FirstOrDefault(); ElementId pipeSystemType = pipeConnector.MEPSystem.GetTypeId(); //Collect levels and select one level FilteredElementCollector collector = new FilteredElementCollector(doc); ElementClassFilter levelFilter = new ElementClassFilter(typeof(Level)); ElementId levelId = collector.WherePasses(levelFilter).FirstElementId(); //Get the connector from the support FamilyInstance familyInstanceToAdd = (FamilyInstance)elementToAdd; ConnectorSet connectorSetToAdd = new ConnectorSet(); mepModel = familyInstanceToAdd.MEPModel; connectorSetToAdd = mepModel.ConnectorManager.Connectors; if (connectorSetToAdd.IsEmpty) { throw new Exception( "The support family lacks a connector. Please read the documentation for correct procedure of setting up a support element."); } Connector connectorToConnect = (from Connector c in connectorSetToAdd where true select c).FirstOrDefault(); //Create a point in space to connect the pipe XYZ direction = connectorToConnect.CoordinateSystem.BasisZ.Multiply(2); XYZ origin = connectorToConnect.Origin; XYZ pointInSpace = origin.Add(direction); //Create the pipe Pipe newPipe = Pipe.Create(doc, pipeTypeId, levelId, connectorToConnect, pointInSpace); //Change the pipe system type to match the picked pipe (it is not always matching) newPipe.SetSystemType(pipeSystemType); trans.Commit(); trans.Start("Delete the pipe"); //Delete the pipe doc.Delete(newPipe.Id); trans.Commit(); } catch (Autodesk.Revit.Exceptions.OperationCanceledException) { trans.RollBack(); return(Result.Cancelled); } catch (Exception ex) { trans.RollBack(); msg = ex.Message; return(Result.Failed); } return(Result.Succeeded); }
/// <summary> /// Determine element shape from its connectors. /// </summary> /// <param name="e">Checked element</param> /// <param name="pe">Previous element (optional), in case badly-connected MEP system</param> /// <param name="ne">Next element (optional), in case you want shape chenge through flow direction only /// (for elements with more than one output)</param> /// <returns>Element shape changes</returns> static public string GetElementShape( Element e, Element pe = null, Element ne = null) { if (is_element_of_category(e, BuiltInCategory.OST_DuctCurves)) { // assuming that transition is using to change shape.. ConnectorManager cm = (e as MEPCurve) .ConnectorManager; foreach (Connector c in cm.Connectors) { return(c.Shape.ToString() + " 2 " + c.Shape.ToString()); } } else if (is_element_of_category(e, BuiltInCategory.OST_DuctFitting)) { MEPSystem system = ExtractMechanicalOrPipingSystem(e); FamilyInstance fi = e as FamilyInstance; MEPModel mm = fi.MEPModel; ConnectorSet connectors = mm.ConnectorManager.Connectors; if (fi != null && mm is MechanicalFitting) { PartType partType = (mm as MechanicalFitting).PartType; if (PartType.Elbow == partType) { // assuming that transition is using to change shape.. foreach (Connector c in connectors) { return(c.Shape.ToString() + " 2 " + c.Shape.ToString()); } } else if (PartType.Transition == partType) { string[] tmp = new string[2]; if (system != null) { foreach (Connector c in connectors) { if (c.Direction == FlowDirectionType.In) { tmp[0] = c.Shape.ToString(); } if (c.Direction == FlowDirectionType.Out) { tmp[1] = c.Shape.ToString(); } } return(string.Join(" 2 ", tmp)); } else { int i = 0; foreach (Connector c in connectors) { if (pe != null) { if (is_connected_to(c, pe)) { tmp[0] = c.Shape.ToString(); } else { tmp[1] = c.Shape.ToString(); } } else { tmp[i] = c.Shape.ToString(); } ++i; } if (pe != null) { return(string.Join(" 2 ", tmp)); } return(string.Join("-", tmp)); } } else if (PartType.Tee == partType || PartType.Cross == partType || PartType.Pants == partType || PartType.Wye == partType) { string from, to; from = to = null; List <string> unk = new List <string>(); if (system != null) { foreach (Connector c in connectors) { if (c.Direction == FlowDirectionType.In) { from = c.Shape.ToString(); } else { unk.Add(c.Shape.ToString()); } if (ne != null && is_connected_to(c, ne)) { to = c.Shape.ToString(); } } if (to != null) { return(from + " 2 " + to); } return(from + " 2 " + string.Join("-", unk.ToArray())); } else { foreach (Connector c in connectors) { if (ne != null && is_connected_to( c, ne)) { to = c.Shape.ToString(); continue; } if (pe != null && is_connected_to( c, pe)) { from = c.Shape.ToString(); continue; } unk.Add(c.Shape.ToString()); } if (to != null) { return(from + " 2 " + to); } if (from != null) { return(from + " 2 " + string.Join("-", unk.ToArray())); } return(string.Join("-", unk.ToArray())); } } } } return("unknown"); }
/// <summary> /// Dump the node into XML file /// </summary> /// <param name="writer">XmlWriter object</param> public void DumpIntoXML(XmlWriter writer) { // Write node information Element element = GetElementById(m_Id); FamilyInstance fi = element as FamilyInstance; if (fi != null) { MEPModel mepModel = fi.MEPModel; String type = String.Empty; if (mepModel is MechanicalEquipment) { type = "MechanicalEquipment"; writer.WriteStartElement(type); } else if (mepModel is MechanicalFitting) { MechanicalFitting mf = mepModel as MechanicalFitting; type = "MechanicalFitting"; writer.WriteStartElement(type); writer.WriteAttributeString("Category", element.Category.Name); writer.WriteAttributeString("PartType", mf.PartType.ToString()); } else { type = "FamilyInstance"; writer.WriteStartElement(type); writer.WriteAttributeString("Category", element.Category.Name); } writer.WriteAttributeString("Name", element.Name); writer.WriteAttributeString("Id", element.Id.IntegerValue.ToString()); writer.WriteAttributeString("Direction", m_direction.ToString()); writer.WriteEndElement(); } else { String type = element.GetType().Name; writer.WriteStartElement(type); writer.WriteAttributeString("Name", element.Name); writer.WriteAttributeString("Id", element.Id.IntegerValue.ToString()); writer.WriteAttributeString("Direction", m_direction.ToString()); writer.WriteEndElement(); } foreach (TreeNode node in m_childNodes) { if (m_childNodes.Count > 1) { writer.WriteStartElement("Path"); } node.DumpIntoXML(writer); if (m_childNodes.Count > 1) { writer.WriteEndElement(); } } }
CollectEvent(object sender, CollectorEventArgs e) { // cast the sender object to the SnoopCollector we are expecting Collector snoopCollector = sender as Collector; if (snoopCollector == null) { Debug.Assert(false); // why did someone else send us the message? return; } // see if it is a type we are responsible for Connector connector = e.ObjToSnoop as Connector; if (connector != null) { Utils.StreamWithReflection(snoopCollector.Data(), typeof(Connector), connector); return; } ConnectorManager connectorMgr = e.ObjToSnoop as ConnectorManager; if (connectorMgr != null) { Stream(snoopCollector.Data(), connectorMgr); return; } CorrectionFactor correctionFactor = e.ObjToSnoop as CorrectionFactor; if (correctionFactor != null) { Stream(snoopCollector.Data(), correctionFactor); return; } ElectricalSetting elecSetting = e.ObjToSnoop as ElectricalSetting; if (elecSetting != null) { Stream(snoopCollector.Data(), elecSetting); return; } GroundConductorSize groundConductorSize = e.ObjToSnoop as GroundConductorSize; if (groundConductorSize != null) { Stream(snoopCollector.Data(), groundConductorSize); return; } MEPModel mepModel = e.ObjToSnoop as MEPModel; if (mepModel != null) { Stream(snoopCollector.Data(), mepModel); return; } WireSize wireSize = e.ObjToSnoop as WireSize; if (wireSize != null) { Stream(snoopCollector.Data(), wireSize); return; } }
/// <summary> /// Tests the diameter of the pipe or primary connector of element against the diameter limit set in the interface. /// </summary> /// <param name="passedElement"></param> /// <returns>True if diameter is larger than limit and false if smaller.</returns> public bool FilterDL(Element passedElement) { element = passedElement; diameterLimit = iv.DiameterLimit; diameterLimitBool = true; double testedDiameter = 0; switch (element.Category.Id.IntegerValue) { case (int)BuiltInCategory.OST_PipeCurves: if (iv.UNITS_BORE_MM) { testedDiameter = double.Parse(Conversion.PipeSizeToMm(((MEPCurve)element).Diameter / 2)); } else if (iv.UNITS_BORE_INCH) { testedDiameter = double.Parse(Conversion.PipeSizeToInch(((MEPCurve)element).Diameter / 2)); } if (testedDiameter <= diameterLimit) { diameterLimitBool = false; } break; case (int)BuiltInCategory.OST_PipeFitting: case (int)BuiltInCategory.OST_PipeAccessory: //Cast the element passed to method to FamilyInstance FamilyInstance familyInstance = (FamilyInstance)element; //MEPModel of the elements is accessed MEPModel mepmodel = familyInstance.MEPModel; //Get connector set for the element ConnectorSet connectorSet = mepmodel.ConnectorManager.Connectors; //Declare a variable for Connector testedConnector = null; if (connectorSet.IsEmpty) { break; } if (connectorSet.Size == 1) { foreach (Connector connector in connectorSet) { testedConnector = connector; } } else { testedConnector = (from Connector connector in connectorSet where connector.GetMEPConnectorInfo().IsPrimary select connector).FirstOrDefault(); } if (iv.UNITS_BORE_MM) { testedDiameter = double.Parse(Conversion.PipeSizeToMm(testedConnector.Radius)); } else if (iv.UNITS_BORE_INCH) { testedDiameter = double.Parse(Conversion.PipeSizeToInch(testedConnector.Radius)); } if (testedDiameter <= diameterLimit) { diameterLimitBool = false; } break; } return(diameterLimitBool); }