Контекстная аналитическая модель в API Revit

Ознакомьтесь с новыми интерфейсом API в контексте аналитического моделирования.

Этот проект является частью более широкой инициативы по аналитическому моделированию для Revit, в рамках которой мы представляем новый подход к аналитическому моделированию с расширенными возможностями моделирования строительных конструкций. Аналитическая модель является неотъемлемой частью данных BIM и зависит от процессов совместной работы внутри проектных групп и между проектными группами. Программа Revit с новым набором функций и режимов обеспечивает инженерам следующие возможности.

Элементы Revit с новым API

Новые классы API

AnalyticalElement — элемент, представляющий базовый класс для всех аналитических объектов. Он заменил собой элемент AnaltyicalModel.

AnalyticalMember — элемент, представляющий линейный элемент в аналитической модели несущей конструкции. Он заменил собой элементы AnalyticalModelStick и AnalyticalModelColumn.

AnalyticalPanel — элемент, представляющий поверхность в аналитической модели несущей конструкции. Он заменил собой элемент AnalyticalModelSurface.
  • AnalyticalPanel Create(Document aDoc, CurveLoop curveLoop) - Method which creates a new instance of an Analytical Panel within the project.
  • CurveLoop GetOuterContour() - Returns the Curve Loop that defines the geometry of the Analytical Surface element.
  • bool IsCurveLoopValid(CurveLoop profile) - Checks if curve loop is valid for Analytical Panel.
    • Для изменения геометрии аналитической панели следует использовать структуру SketchEditScope. В эту структуру добавлен новый метод:
      •  void StartWithNewSketch(ElementId elementId) - Starts a sketch edit mode for an element which, at this moment, doesn't have a sketch.
    • Другой способ редактирования геометрии:
      • void SetOuterContour(CurveLoop outerContour) - Sets the Curve Loop that defines the geometry of the Analytical Surface element.


      • Как и для AnalyticalMember, задание контура для аналитической панели приведет к разрыву соединения с другими аналитическими элементами. Существуют другие способы переместить угол и сохранить соединение, например ElementTransformUtils.moveElements.

  •  ISet<ElementId> GetAnalyticalOpeningsIds() - Returns the Analytical Openings Ids of the Analytical Panel.
  • ElementId SketchId - Sketch associated to this Revit element.
    
  • AnalyticalStructuralRole StructuralRole - Structural role assigned to the Analytical Panel.
AnalyticalOpening — элемент, представляющий проем в аналитической панели. Это новый объект в API Revit (до этой версии отдельного элемента для аналитических проемов не существовало).
  • AnalyticalOpening Create(Document doc, CurveLoop curveLoop, ElementId panelId) - Method which creates a new instance of an Analytical Opening within the project.
  • CurveLoop GetOuterContour () - Returns the Curve Loop that defines the geometry of the Analytical Surface element.
    
  •  bool IsCurveLoopValidForAnalyticalOpening(CurveLoop loop, Document aDoc, ElementId panelId) - Checks if curve loop is valid for Analytical Opening.
    • Для изменения геометрии аналитического проема используется структура SketchEditScope.
    • Еще один способ изменения геометрии аналитического проема:
      •  void SetOuterContour(CurveLoop outerContour) - Sets the Curve Loop that defines the geometry of the Analytical Surface element.
  • ElementId PanelId - ElementId of the host Analytical Panel.
    
  •  ElementId SketchId - Sketch associated to this Revit element.

AnalyticalToPhysicalAssociationManager — элемент, управляющий ассоциациями между аналитическими и физическими элементами. Раньше элементы сами получали сведения друг о друге, а у пользователя не было возможности управлять ими (ассоциацию нельзя было изменить). Новый подход позволяет редактировать ассоциацию. Поддерживается ассоциация «один к одному», при этом каждый элемент не могут быть частью нескольких связей одновременно.

AnalyticalNodeData — элемент, содержащий информацию о статусе соединения аналитических узлов.
  • AnalyticalNodeData GetAnalyticalNodeData ( Element element) - Returns AnalyticalNodeData associated with this element, if it exists.
    
  • AnalyticalNodeConnectionStatus GetConnectionStatus () - Returns the Connections Status for an
    Analytical Node.

Для работы с новыми элементами были перенесены классы AnalyticalLinks, BoundaryConditions и Loads. В большинстве случаев интерфейс API, связанный с ними, остается неизменным. Некоторые усовершенствования были внесены в класс Loads.

Нагрузки
  •  LineLoad.Create(Document aDoc,ElementId hostElemId, XYZ forceVector1, XYZmomentVector1, LineLoadType symbol).
  •  LineLoad.Create(Document aDoc,ElementId hostElemId, int curveIndex, XYZ forceVector1, XYZ momentVector1, Structure.LineLoadType symbol).
  •  LineLoad.IsValidHostId(Document doc, ElementId hostElemId).
  •  AreaLoad.IsValidHostId(Document doc, ElementId hostElemId).
  •  AreaLoad.Create(Document doc, ElementId hostElemId, XYZ forceVector1, AreaLoadType symbol).
  •  PointLoad.Create(Document doc, ElementId hostElemId, AnalyticalElementSelector selector, XYZ forceVector, XYZ momentVector, AreaLoadTyp 
    symbol).
  • PointLoad.IsValidHostId(Document doc, ElementId hostElemId).

Образцы

Создание аналитического элемента

      using (Transaction transaction = new Transaction(document, "Create Analytical Member"))
               {
                  transaction.Start();
                  //create curve which will be assigned to the analytical member
                  Line line = Line.CreateBound(new XYZ(0, 0, 0), new XYZ(5, 0, 0));
                  //create the AnalyticalMember
                  AnalyticalMember analyticalMember = AnalyticalMember.Create(document, line);
                  analyticalMember.StructuralRole = AnalyticalStructuralRole.StructuralRoleBeam;
                  transaction.Commit();
                }

Создание аналитической панели

 using (Transaction transaction = new Transaction(revitDoc, "Create Analytical Panel"))
         {
            transaction.Start();
            //create the curveLoop for the AnalyticalPanel element
            CurveLoop profileloop = new CurveLoop();
            profileloop.Append(Line.CreateBound(new XYZ(1, 1, 0), new XYZ(2, 1, 0)));
            profileloop.Append(Line.CreateBound(new XYZ(2, 1, 0), new XYZ(2, 2, 0)));
            profileloop.Append(Line.CreateBound(new XYZ(2, 2, 0), new XYZ(1, 2, 0)));
            profileloop.Append(Line.CreateBound(new XYZ(1, 2, 0), new XYZ(1, 1, 0)));
            //create the AnalyticalPanel 
            analyticalPanel = AnalyticalPanel .Create(revitDoc, profileloop);
            transaction.Commit();
          }

Добавление новой ассоциации между физическим и аналитическим элементами

using (Transaction trans = new Transaction(doc, "AddAssociationBetweenPhysicalAndAnalyticalElements"))
 {
            trans.Start();
            ElementId analyticalElementId = ContextualAnalyticalModel.Utilities.GetSelectedObject(activeDoc, "Please select analytical element");
            ElementId physicalElementId = ContextualAnalyticalModel.Utilities.GetSelectedObject(activeDoc, "Please select physical element");
            //gets the AnalyticalToPhysicalAssociationManager for the current document
            AnalyticalToPhysicalAssociationManager analyticalToPhysicalManager = AnalyticalToPhysicalAssociationManager.GetAnalyticalToPhysicalAssociationManager(doc);
            if (analyticalToPhysicalManager == null)
               return Result.Failed;
            //creates a new association between physical and analytical elements
            analyticalToPhysicalManager.AddAssociation(analyticalElementId, physicalElementId);
            trans.Commit();
  }

Редактирование границы аналитической панели с помощью структуры SketchEditScope



             // Start a sketch edit scope
             SketchEditScope sketchEditScope = new SketchEditScope(document, "Replace line with an arc");
               sketchEditScope.StartWithNewSketch(analyticalPanel.Id);
               using (Transaction transaction = new Transaction(document, "Modify sketch"))
               {
                  transaction.Start();
                  //replace a boundary line with an arc
                  Line line = null;
                  Sketch sketch = document.GetElement(analyticalPanel.SketchId) as Sketch;
                  if (sketch != null)
                  {
                     //find first line in the sketch profile
                    …..
                  }
  	              // Create arc
                  XYZ normal = line.Direction.CrossProduct(XYZ.BasisZ).Normalize().Negate();
                  XYZ middle = line.GetEndPoint(0).Add(line.Direction.Multiply(line.Length / 2));
                  Curve arc = Arc.Create(line.GetEndPoint(0), line.GetEndPoint(1), middle.Add(normal.Multiply(20)));
                  // Remove element referenced by the found line. 
                  document.Delete(line.Reference.ElementId);
                  // Model curve creation automatically puts the curve into the sketch, if sketch edit scope is running.
                  document.Create.NewModelCurve(arc, sketch.SketchPlane);
                  transaction.Commit();
               }
               sketchEditScope.Commit(new FailurePreproccessor());

Перемещение узла аналитической модели и сохранение соединения



            // Create Analytical Panel
            AnalyticalPanel analyticalPanel = CreateAnalyticalPanel.CreateAMPanel(document);
            // Create the connected Analytical Member
            AnalyticalMember analyticalMember = CreateAnalyticalMember.CreateMember(document);
            // Select the node
            Reference eRef = activeDoc.Selection.PickObject(ObjectType.PointOnElement , "Select an Analytical Node");
          
            // Move the Analytical Node using ElementTransformUtils
            using (Transaction transaction = new Transaction(document, "Move node with ElementTransformUtils"))
            {
               transaction.Start();
               ElementTransformUtils.MoveElement(document, eRef.ElementId, new XYZ(-5, -5, 0));
               transaction.Commit();
            }

Получение точек контура аналитической поверхности

Предыдущее решение:
    
      private List<XYZ> GetSurfaceContourPoints( Document doc, ElementId elementId )
      {
         	// Create point list, get list of curves from analytical model
         	List<XYZ> contourPoints = new List<XYZ>();
         	AnalyticalModel analyticalModel = (doc.GetElement(elementId) as AnalyticalModel);
         	IList<Curve> curves = analyticalModel.GetCurves(AnalyticalCurveType.RawCurves);
         
         	// Iterate over curves and make the desired processing   
         …...	
        	return contourPoints;
      }
Новое решение:
     
      private List<XYZ> GetSurfaceContourPoints( Document doc, ElementId elementId )
      {
         	// Create point list, get list of curves from analytical model
         	List<XYZ> contourPoints = new List<XYZ>();
         	AnalyticalPanel analyticalPanel = (doc.GetElement(elementId) as AnalyticalPanel);
          CurveLoop outerContour = analyticalPanel.GetOuterContour();
         
         	// Iterate over curves and make the desired processing 
          …...	
        	return contourPoints;
      }

Получение связанного аналитического элемента для физического

     
      AnalyticalElement GetAnalyticalElement(Element physicalElement)
      {
         AnalyticalElement analyticalElement = null;
         Document document = element.Document;
         AnalyticalToPhysicalAssociationManager assocManager = AnalyticalToPhysicalAssociationManager.GetAnalyticalToPhysicalAssociationManager(document);
         if (assocManager != null)
         {
            ElementId associatedElementId = assocManager.GetAssociatedElementId(physicalElement.Id);
            if (associatedElementId != ElementId.InvalidElementId)
            {
               Element associatedElement = document.GetElement(associatedElementId);
               if (associatedElement != null && associatedElement is AnalyticalElement)
               {
                  analyticalElement = associatedElement as AnalyticalElement;
               }
            }
         }
         return analyticalElement;
      }

Создание граничных условий «Линия»

Предыдущее решение:

       
        private BoundaryConditions CreateLineBC(Element hostElement)
        {
										    Document createDoc = hostElement.Document.Create;
 
             	// use Document.NewLineBoundaryConditions Method
              BoundaryConditions createdBC = 
                    createDoc.NewLineBoundaryConditions(hostElement.GetAnalyticalModel(), 0, 0, 0, 0, 0, 0, 0, 0);
 
            return createdBC;
        }

Новое решение:

      private BoundaryConditions CreateLineBC(Element hostElement)
      {
         Document createDoc = hostElement.Document.Create;

         // use Document.NewLineBoundaryConditions Method
         AnalyticalElement analyticalElement = GetAnalyticalElement(hostElement);
         BoundaryConditions createdBC =
                    createDoc.NewLineBoundaryConditions(analyticalElement, 0, 0, 0, 0, 0, 0, 0, 0);
         return createdBC;
      }