Exemple #1
0
 /// <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;
     }
 }
Exemple #2
0
 /// <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 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;

            //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); // 2012

            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

                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

                // 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

                // 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

                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();
            }
            return(Result.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>
        /// 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();
            }
        }
Exemple #6
0
        }//execute

        //以下为各种method---------------------------------分割线---------------------------------
        //外部事件方法建立
        //所有相关族实例的类型标记-事务

        public void MainMethod_tmep(UIApplication uiapp)
        {
            UIDocument uidoc = uiapp.ActiveUIDocument;
            Document   doc   = uidoc.Document;
            Selection  sel   = uidoc.Selection;//Revit文档数据读取

            Autodesk.Revit.DB.View activeView = doc.ActiveView;
            ElementId activeViewId            = activeView.Id;

            //下列数据需要winform获得
            Document originDoc = getDocment(CMD.documentSet, CMD.originFileName); //获取源文档
            Document targetDoc = getDocment(CMD.documentSet, CMD.targetFileName); //获取目标文档

            //获取源与目标文档的组元素列表
            ICollection <Element> targetMoGroupTypes = (new FilteredElementCollector(targetDoc))
                                                       .WherePasses(new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_IOSModelGroups), new ElementCategoryFilter(BuiltInCategory.OST_IOSDetailGroups)))
                                                       .WhereElementIsElementType()
                                                       .ToElements();
            //ICollection<Element> targetMoGroupTypes = (new FilteredElementCollector(targetDoc)).OfCategory(BuiltInCategory.OST_IOSModelGroups).WhereElementIsElementType().ToElements();
            //获取源与源文档的模型组元素类别列表
            //ICollection<Element> originMoGroupTypes = (new FilteredElementCollector(originDoc)).OfCategory(BuiltInCategory.OST_IOSModelGroups).WhereElementIsElementType().ToElements();
            ICollection <Element> originMoGroupTypes = (new FilteredElementCollector(originDoc))
                                                       .WherePasses(new LogicalOrFilter(new ElementCategoryFilter(BuiltInCategory.OST_IOSModelGroups), new ElementCategoryFilter(BuiltInCategory.OST_IOSDetailGroups)))
                                                       .WhereElementIsElementType()
                                                       .ToElements();

            IList <string> originMoDeGroupTypeNames = getIlistNames(originMoGroupTypes); //源文档内的组类型name-list

            if (CMD.selectedGroupNames.Count > 0)                                        //判断选择的组是否为空
            {
                using (Transaction modifyPara = new Transaction(targetDoc))
                {
                    modifyPara.Start("modifyParameters");

                    foreach (string str in CMD.selectedGroupNames)
                    {
                        if (originMoDeGroupTypeNames.Contains(str))//判断选择组类型是否存在源文档组类型中
                        {
                            //源文档操作
                            GroupType originGroupType = GetGroupTypeFromStr(originMoGroupTypes, str) as GroupType;                 //通过选择字符串获取源文档中对应的组类别元素
                            ICollection <ElementId> originfamilysymbolIds = GetfamilysymbolIdsInGroup(originDoc, originGroupType); //获取源文档中目标组内的所有元素唯一族类型Id列表
                                                                                                                                   //目标文档操作
                            GroupType targetGroupType = GetGroupTypeFromStr(targetMoGroupTypes, str) as GroupType;                 //通过选择字符串获取源文档中对应的组类别元素
                            ICollection <ElementId> targetfamilysymbolIds = GetfamilysymbolIdsInGroup(targetDoc, targetGroupType); //获取源文档中目标组内的的所有元素唯一族类型Id列表

                            //尝试族类型参数传递
                            foreach (ElementId orieleId in originfamilysymbolIds)
                            {
                                Element oriEle     = originDoc.GetElement(orieleId);
                                string  orieleName = oriEle.Name;

                                foreach (ElementId targeldId in targetfamilysymbolIds)
                                {
                                    Element targEle     = targetDoc.GetElement(targeldId);
                                    string  targeleName = targEle.Name;

                                    if (orieleName == targeleName)//如果元素类型的名字一致,则对其进行族类型参数传递
                                    {
                                        //ShowTaskDialog("异常提示", orieleName);

                                        ParameterSet ori_parameterSet   = oriEle.Parameters;  //源文档参数集
                                        ParameterSet targe_parameterSet = targEle.Parameters; //目标文档参数集

                                        foreach (Parameter ori_parameter in ori_parameterSet)
                                        {
                                            string ori_paraName = ori_parameter.Definition.Name;

                                            foreach (Parameter targe_parameter in targe_parameterSet)
                                            {
                                                string targe_paraName = targe_parameter.Definition.Name;

                                                if (ori_paraName == targe_paraName)
                                                {
                                                    //过滤的参数均为StorageType == Integer的参数
                                                    if (!targe_parameter.IsReadOnly && targe_parameter.StorageType != StorageType.ElementId)
                                                    {
                                                        //开展子事务SubTransaction
                                                        using (SubTransaction subModifyPara = new SubTransaction(targetDoc))
                                                        {
                                                            subModifyPara.Start();
                                                            Object ori_object = ParameterExtension_temp.GetMeaningfulValue_temp(ori_parameter); //原始参数读取
                                                            ParameterExtension_temp.SetValue_temp(targe_parameter, ori_object);                 //目标参数修改
                                                            subModifyPara.Commit();
                                                        }
                                                    }
                                                    else
                                                    {
                                                        continue;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            ShowTaskDialog("成功提示", "组名为-" + str + "-的族类型参数传递完毕。");
                        }
                        else
                        {
                            ShowTaskDialog("异常提示", "源文档不存在名为-" + str + "-的组类型");
                            continue;
                        }
                    }
                    modifyPara.Commit();
                }//transaction

                CMD.selectedGroupNames = new List <string>();//避免选项被累计的问题
            }
            else
            {
                ShowTaskDialog("异常提示", "未选择任何组。");
            }
        } //main method
Exemple #7
0
 /// <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;
 }
        /// <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 = m_sashMatID;
            sash1.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM).Set(id);
            sash2.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM).Set(id);
            subTransaction.Commit();
        }
      /// <summary>
        /// Implements the export of element.
        /// </summary>
        /// <param name="exporterIFC">The IFC exporter object.</param>
        /// <param name="element">The element to export.</param>
        /// <param name="productWrapper">The ProductWrapper object.</param>
        public virtual void ExportElementImpl(ExporterIFC exporterIFC, Element element, ProductWrapper productWrapper)
        {
            Options options;
            View ownerView = 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);
            }
        }
Exemple #10
0
        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;
        }
Exemple #11
0
        protected override void TrySolveInstance(IGH_DataAccess dataAccess)
        {
            int index = -1;

            bool run = false;

            index = Params.IndexOfInputParam("_run");
            if (index == -1 || !dataAccess.GetData(index, ref run) || !run)
            {
                return;
            }

            double maxDistance = 0.2;

            index = Params.IndexOfInputParam("_maxDistance");
            if (index == -1 || !dataAccess.GetData(index, ref maxDistance))
            {
                return;
            }

            RhinoInside.Revit.GH.Types.Level level_GH = null;
            index = Params.IndexOfInputParam("_level");
            if (index == -1 || !dataAccess.GetData(index, ref level_GH))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            RhinoInside.Revit.GH.Types.Level referenceLevel_GH = null;
            index = Params.IndexOfInputParam("_referenceLevel");
            if (index == -1 || !dataAccess.GetData(index, ref referenceLevel_GH))
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Level level = level_GH.Value;

            if (level == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Level referenceLevel = referenceLevel_GH.Value;

            if (level == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

#if Revit2017 || Revit2018 || Revit2019 || Revit2020
            double elevation          = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS);
            double referenceElevation = UnitUtils.ConvertFromInternalUnits(referenceLevel.Elevation, DisplayUnitType.DUT_METERS);
#else
            double elevation          = UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters);
            double referenceElevation = UnitUtils.ConvertFromInternalUnits(referenceLevel.Elevation, UnitTypeId.Meters);
#endif

            Document document = level.Document;

            IEnumerable <Autodesk.Revit.DB.Wall> walls_All = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.Wall)).Cast <Autodesk.Revit.DB.Wall>();
            if (walls_All == null || walls_All.Count() == 0)
            {
                return;
            }

            StartTransaction(document);

            ConvertSettings convertSettings = new ConvertSettings(true, true, true);

            List <Panel> panels           = new List <Panel>();
            List <Panel> panels_Reference = new List <Panel>();
            foreach (Autodesk.Revit.DB.Wall wall in walls_All)
            {
                List <Panel> panels_Temp = Analytical.Revit.Convert.ToSAM(wall, convertSettings);
                foreach (Panel panel in panels_Temp)
                {
                    double max = panel.MaxElevation();
                    double min = panel.MinElevation();

                    if (Math.Abs(min - elevation) < Core.Tolerance.Distance || (min - Core.Tolerance.Distance < elevation && max - Core.Tolerance.Distance > elevation))
                    {
                        panels.Add(panel);
                    }

                    if (Math.Abs(min - referenceElevation) < Core.Tolerance.Distance || (min - Core.Tolerance.Distance < referenceElevation && max - Core.Tolerance.Distance > referenceElevation))
                    {
                        panels_Reference.Add(panel);
                    }
                }
            }

            IEnumerable <ElementId> elementIds           = panels.ConvertAll(x => x.ElementId()).Distinct();
            IEnumerable <ElementId> elementIds_Reference = panels_Reference.ConvertAll(x => x.ElementId()).Distinct();

            Geometry.Spatial.Plane plane = new Geometry.Spatial.Plane(new Point3D(0, 0, elevation), Vector3D.WorldZ);

            Dictionary <Segment2D, HostObjAttributes> dictionary_Reference = new Dictionary <Segment2D, HostObjAttributes>();
            foreach (ElementId elementId in elementIds_Reference)
            {
                Element element = document.GetElement(elementId);
                if (element == null)
                {
                    continue;
                }

                HostObjAttributes hostObjAttributes = document.GetElement(element.GetTypeId()) as HostObjAttributes;
                if (hostObjAttributes == null)
                {
                    continue;
                }

                LocationCurve  locationCurve = element.Location as LocationCurve;
                ISegmentable3D segmentable3D = locationCurve.ToSAM() as ISegmentable3D;
                if (segmentable3D == null)
                {
                    continue;
                }

                List <Segment3D> segment3Ds = segmentable3D.GetSegments();
                if (segment3Ds == null || segment3Ds.Count == 0)
                {
                    continue;
                }

                segment3Ds.ForEach(x => dictionary_Reference[plane.Convert(x)] = hostObjAttributes);
            }

            Dictionary <Segment2D, ElementId> dictionary = new Dictionary <Segment2D, ElementId>();
            foreach (ElementId elementId in elementIds)
            {
                LocationCurve locationCurve = document.GetElement(elementId).Location as LocationCurve;
                Segment3D     segment3D     = locationCurve.ToSAM() as Segment3D;
                if (segment3D == null)
                {
                    continue;
                }

                dictionary[plane.Convert(plane.Project(segment3D))] = elementId;
            }

            Dictionary <Segment2D, ElementId> dictionary_Result = new Dictionary <Segment2D, ElementId>();
            foreach (KeyValuePair <Segment2D, ElementId> keyValuePair in dictionary)
            {
                Segment2D segment2D = keyValuePair.Key;

                List <Segment2D> segment2Ds_Temp = dictionary_Reference.Keys.ToList().FindAll(x => x.Collinear(segment2D) && x.Distance(segment2D) <= maxDistance + Core.Tolerance.MacroDistance && x.Distance(segment2D) > Core.Tolerance.MacroDistance);
                if (segment2Ds_Temp == null || segment2Ds_Temp.Count == 0)
                {
                    continue;
                }

                Element element = document.GetElement(keyValuePair.Value);
                if (element == null)
                {
                    continue;
                }

                HostObjAttributes hostObjAttributes = document.GetElement(element.GetTypeId()) as HostObjAttributes;
                if (hostObjAttributes == null)
                {
                    continue;
                }

                segment2Ds_Temp.Sort((x, y) => segment2D.Distance(x).CompareTo(segment2D.Distance(y)));

                Segment2D segment2D_Reference = null;

                foreach (Segment2D segment2D_Temp in segment2Ds_Temp)
                {
                    HostObjAttributes hostObjAttributes_Temp = dictionary_Reference[segment2D_Temp];
                    if (hostObjAttributes.Name.Equals(hostObjAttributes_Temp.Name))
                    {
                        segment2D_Reference = segment2D_Temp;
                        break;
                    }
                }

                if (segment2D_Reference == null)
                {
                    HashSet <PanelType> panelTypes = new HashSet <PanelType>();
                    panelTypes.Add(Analytical.Revit.Query.PanelType(hostObjAttributes));
                    switch (panelTypes.First())
                    {
                    case PanelType.CurtainWall:
                        panelTypes.Add(PanelType.WallExternal);
                        break;

                    case PanelType.UndergroundWall:
                        panelTypes.Add(PanelType.WallExternal);
                        break;

                    case PanelType.Undefined:
                        panelTypes.Add(PanelType.WallInternal);
                        break;
                    }

                    foreach (Segment2D segment2D_Temp in segment2Ds_Temp)
                    {
                        HostObjAttributes hostObjAttributes_Temp = dictionary_Reference[segment2D_Temp];
                        PanelType         panelType_Temp         = Analytical.Revit.Query.PanelType(hostObjAttributes_Temp);
                        if (panelTypes.Contains(panelType_Temp))
                        {
                            segment2D_Reference = segment2D_Temp;
                            break;
                        }
                    }
                }

                if (segment2D_Reference == null)
                {
                    segment2D_Reference = segment2Ds_Temp.First();
                }

                Segment2D segment2D_Project = segment2D_Reference.Project(segment2D);
                if (segment2D_Project == null)
                {
                    continue;
                }

                dictionary_Result[segment2D_Project] = dictionary[segment2D];
            }

            List <HostObject> result = new List <HostObject>();

            foreach (KeyValuePair <Segment2D, ElementId> keyValuePair in dictionary_Result)
            {
                Autodesk.Revit.DB.Wall wall = document.GetElement(keyValuePair.Value) as Autodesk.Revit.DB.Wall;

                if (wall == null || !wall.IsValidObject)
                {
                    continue;
                }

                Segment2D segment2D = keyValuePair.Key;

                bool pinned = wall.Pinned;

                if (wall.Pinned)
                {
                    using (SubTransaction subTransaction = new SubTransaction(document))
                    {
                        subTransaction.Start();
                        wall.Pinned = false;
                        subTransaction.Commit();
                    }
                }

                Segment3D     segment3D     = plane.Convert(segment2D);
                LocationCurve locationCurve = wall.Location as LocationCurve;

                using (SubTransaction subTransaction = new SubTransaction(document))
                {
                    subTransaction.Start();

                    document.Regenerate();
                    locationCurve.Curve = Geometry.Revit.Convert.ToRevit(segment3D);

                    subTransaction.Commit();
                }

                if (wall.Pinned != pinned)
                {
                    using (SubTransaction subTransaction = new SubTransaction(document))
                    {
                        subTransaction.Start();
                        wall.Pinned = pinned;
                        subTransaction.Commit();
                    }
                }
                result.Add(wall);
            }

            index = Params.IndexOfOutputParam("walls");
            if (index != -1)
            {
                dataAccess.SetDataList(index, result);
            }
        }
        /// <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();
         }
      }
Exemple #13
0
        /// <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;
        }
Exemple #14
0
        /***************************************************/

        private static FreeFormProfile FreeFormProfileFromRevit(this FamilySymbol familySymbol, RevitSettings settings)
        {
            XYZ direction;

            if (familySymbol.Family.FamilyPlacementType == FamilyPlacementType.CurveDrivenStructural)
            {
                direction = XYZ.BasisX;
            }
            else if (familySymbol.Family.FamilyPlacementType == FamilyPlacementType.TwoLevelsBased)
            {
                direction = XYZ.BasisZ;
            }
            else
            {
                BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                return(null);
            }

            // Check if one and only one solid exists to make sure that the column is a single piece
            Solid   solid   = null;
            Options options = new Options();

            options.DetailLevel = ViewDetailLevel.Fine;
            options.IncludeNonVisibleObjects = false;

            // Activate the symbol temporarily if not active, then extract its geometry (open either transaction or subtransaction, depending on whether one is already open).
            if (!familySymbol.IsActive)
            {
                Document doc = familySymbol.Document;
                if (!doc.IsModifiable)
                {
                    using (Transaction tempTransaction = new Transaction(doc, "Temp activate family symbol"))
                    {
                        tempTransaction.Start();

                        familySymbol.Activate();
                        doc.Regenerate();
                        solid = familySymbol.get_Geometry(options).SingleSolid();
                        if (solid != null)
                        {
                            solid = SolidUtils.Clone(solid);
                        }

                        tempTransaction.RollBack();
                    }
                }
                else
                {
                    using (SubTransaction tempTransaction = new SubTransaction(doc))
                    {
                        tempTransaction.Start();

                        familySymbol.Activate();
                        doc.Regenerate();
                        solid = familySymbol.get_Geometry(options).SingleSolid();
                        if (solid != null)
                        {
                            solid = SolidUtils.Clone(solid);
                        }

                        tempTransaction.RollBack();
                    }
                }
            }
            else
            {
                solid = familySymbol.get_Geometry(options).SingleSolid();
            }

            if (solid == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found because it is empty or it consists of more than one solid. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                return(null);
            }

            Autodesk.Revit.DB.Face face = null;
            foreach (Autodesk.Revit.DB.Face f in solid.Faces)
            {
                if (f is PlanarFace && (f as PlanarFace).FaceNormal.Normalize().IsAlmostEqualTo(-direction, 0.001))
                {
                    if (face == null)
                    {
                        face = f;
                    }
                    else
                    {
                        BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                        return(null);
                    }
                }
            }

            if (face == null)
            {
                BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be found. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                return(null);
            }

            List <ICurve> profileCurves = new List <ICurve>();

            foreach (EdgeArray curveArray in (face as PlanarFace).EdgeLoops)
            {
                foreach (Edge c in curveArray)
                {
                    ICurve curve = c.AsCurve().IFromRevit();
                    if (curve == null)
                    {
                        BH.Engine.Reflection.Compute.RecordWarning("The profile of a family type could not be converted due to curve conversion issues. ElementId: " + familySymbol.Id.IntegerValue.ToString());
                        return(null);
                    }
                    profileCurves.Add(curve);
                }
            }

            if (profileCurves.Count != 0)
            {
                BH.oM.Geometry.Point centroid = solid.ComputeCentroid().PointFromRevit();
                Vector tan = direction.VectorFromRevit().Normalise();

                // Adjustment of the origin to global (0,0,0).
                Vector adjustment = oM.Geometry.Point.Origin - centroid + (centroid - profileCurves[0].IStartPoint()).DotProduct(tan) * tan;
                if (adjustment.Length() > settings.DistanceTolerance)
                {
                    profileCurves = profileCurves.Select(x => x.ITranslate(adjustment)).ToList();
                }

                // Check if the curves are in the horizontal plane, if not then align them.
                if (familySymbol.Family.FamilyPlacementType == FamilyPlacementType.CurveDrivenStructural)
                {
                    // First rotate the profile to align its local plane with global XY, then rotate to align its local Z with global Y.
                    double angle = -Math.PI * 0.5;
                    profileCurves = profileCurves.Select(x => x.IRotate(oM.Geometry.Point.Origin, Vector.YAxis, angle)).ToList();
                    profileCurves = profileCurves.Select(x => x.IRotate(oM.Geometry.Point.Origin, Vector.ZAxis, angle)).ToList();
                }
            }

            return(BHS.Create.FreeFormProfile(profileCurves));
        }
Exemple #15
0
        public MiscEDVRequest(UIApplication uiApp, String text)
        {
            MainUI     uiForm = BARevitTools.Application.thisApp.newMainUi;
            UIDocument uidoc  = uiApp.ActiveUIDocument;

            if (uiForm.miscEDVSelectDirectoryTextBox.Text != "")
            {
                //Create a list for storing drafting views to export
                List <ViewDrafting> viewsToUse = new List <ViewDrafting>();
                foreach (DataGridViewRow row in uiForm.miscEDVDataGridView.Rows)
                {
                    //If the rows's Select column checkbox is checked, get the element and add it to the views to use
                    if (row.Cells["Select"].Value.ToString() == "True")
                    {
                        DataRow dgvRow = (row.DataBoundItem as DataRowView).Row;
                        viewsToUse.Add(dgvRow["View Element"] as ViewDrafting);
                    }
                }

                //Preparing the progress bar
                int filesToProcess = viewsToUse.Count;
                uiForm.miscEDVProgressBar.Value   = 0;
                uiForm.miscEDVProgressBar.Minimum = 0;
                uiForm.miscEDVProgressBar.Maximum = filesToProcess;
                uiForm.miscEDVProgressBar.Step    = 1;
                uiForm.miscEDVProgressBar.Visible = true;

                //For each drafting view to export...
                foreach (ViewDrafting fromView in viewsToUse)
                {
                    //Make a new Revit document file
                    RVTDocument newDoc = uiApp.Application.NewProjectDocument(UnitSystem.Imperial);

                    //Start the transaction
                    Transaction t1 = new Transaction(newDoc, "ExportDraftingViews");
                    t1.Start();

                    //Start a subtransaction
                    SubTransaction s1 = new SubTransaction(newDoc);
                    s1.Start();
                    //In the new file, get the first view family type that is a drafting view type
                    FilteredElementCollector collector = new FilteredElementCollector(newDoc);
                    collector.OfClass(typeof(ViewFamilyType));
                    ViewFamilyType viewFamilyType = collector.Cast <ViewFamilyType>().First(vft => vft.ViewFamily == ViewFamily.Drafting);
                    //In the new file, make a new drafting view using the view family type found in it
                    ViewDrafting toView = ViewDrafting.Create(newDoc, viewFamilyType.Id);
                    //Commit the sub transaction
                    s1.Commit();

                    //Now the the drafting view exists in the new file, collect the elements in the originating drafting view
                    List <ElementId> viewElementIds   = new FilteredElementCollector(uidoc.Document, fromView.Id).ToElementIds().Cast <ElementId>().ToList();
                    CopyPasteOptions copyPasteOptions = new CopyPasteOptions();
                    copyPasteOptions.SetDuplicateTypeNamesHandler(new RVTDuplicateTypesHandler());
                    //Copy and paste the elements from the originating drafting view into the new file's drafting view
                    ElementTransformUtils.CopyElements(fromView, viewElementIds, toView, null, copyPasteOptions);
                    t1.Commit();

                    //Find the newly created drafting view's ID so the view can be used as the preview view when saving the new project file
                    ElementId viewPreviewId = null;
                    var       newDocViews   = new FilteredElementCollector(newDoc).OfClass(typeof(ViewDrafting)).ToElements().Cast <Element>().ToList();
                    foreach (ViewDrafting newDocView in newDocViews)
                    {
                        if (newDocView.Name == fromView.Name)
                        {
                            viewPreviewId = newDocView.Id;
                            break;
                        }
                    }

                    //Set the SaveAsOptions as follows, including the PreviewViewId
                    SaveAsOptions saveAsOptions = new SaveAsOptions();
                    saveAsOptions.Compact               = true;
                    saveAsOptions.MaximumBackups        = 1;
                    saveAsOptions.OverwriteExistingFile = true;
                    saveAsOptions.PreviewViewId         = viewPreviewId;

                    //The string array of illegal characters in the name is used to determine
                    string[] illegalCharacters = { "<", ">", ":", "/", @"\", @"|", "?", "*" };
                    //Also remove quotation marks and periods from the view name
                    string fileName = fromView.Name.Replace("\"", "").Replace(".", "");
                    //For each illegal character in the string array, remove it from the view name if it exists
                    foreach (string item in illegalCharacters)
                    {
                        if (fileName.Contains(item))
                        {
                            fileName.Replace(item, "");
                        }
                    }

                    //With a cleaned view name for saving to a file, save the new project file containing the new drafting view with the cleaned name
                    string savePath = uiForm.miscEDVSelectDirectoryTextBox.Text + "\\" + fileName + ".rvt";
                    if (File.Exists(savePath))
                    {
                        try
                        {
                            //Delete the file if it already exists
                            File.Delete(savePath);
                        }
                        catch { continue; }
                    }
                    newDoc.SaveAs(savePath, saveAsOptions);
                    newDoc.Close(false);
                    //Step forward the progress bar.
                    uiForm.miscEDVProgressBar.PerformStep();
                }
            }
            else
            {
                //If the user forgot to set the directory of where to export the drafting views, let them know
                MessageBox.Show("No save directory is set. Please pick a directory.");
            }
        }
        /// <summary>
        /// The implementation of CreateFrame()
        /// </summary>
        public override void CreateFrame()
        {
            SubTransaction subTransaction = new SubTransaction(m_document);

            subTransaction.Start();

            //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();

            //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);

            if (exteriorWallFace == null)
            {
                return;
            }

            //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.FamilyLabel = 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
            exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);  // Get the face again as the document is regenerated.
            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
            exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);  // Get the face again as the document is regenerated.
            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();
        }
Exemple #17
0
        /// <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>
        /// 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();
            }
        }
Exemple #19
0
        private static bool MyCreateGuizheng(ElementId gId, Document doc, IList <Curve> curs, ElementId leveId)
        {
            if (gId != null)
            {
                DateTime     oTimeStart          = DateTime.Now;
                FamilySymbol guiZhenFamilySymbol = doc.GetElement(gId) as FamilySymbol;
                Level        level        = doc.GetElement(leveId) as Level;
                int          numOfGuiZhen = 0;
                Transaction  tr           = new Transaction(doc); //创建对象必须添加事务
                tr.Start("轨枕");
                foreach (Curve c in curs)
                {
                    SubTransaction str = new SubTransaction(doc);
                    str.Start();
                    double l   = c.Length * 304.8;
                    int    n   = (int)Math.Floor(l / 650);
                    double ang = 0;
                    if (c is Line)
                    {
                        Line   line = c as Line;
                        double lAng = line.Direction.AngleTo(XYZ.BasisX);
                        ang = line.Direction.Y >= 0 ? lAng + Math.PI / 2 : Math.PI / 2 - lAng;
                        for (double i = 0.5; i < n; i += 1)
                        {
                            XYZ            pt         = c.Evaluate(i / n, true);
                            Transform      t          = c.ComputeDerivatives(i / n, true);
                            FamilyInstance gzInstance = doc.Create.NewFamilyInstance(pt, guiZhenFamilySymbol, level, StructuralType.NonStructural);
                            ElementTransformUtils.RotateElement(doc, gzInstance.Id, Line.CreateBound(pt, new XYZ(pt.X, pt.Y, pt.Z + 1)), ang);
                            numOfGuiZhen++;
                        }
                    }
                    else
                    {
                        for (double i = 0.5; i < n; i += 1)
                        {
                            Transform t    = c.ComputeDerivatives(i / n, true);
                            XYZ       pt   = t.Origin;
                            double    lAng = t.BasisY.AngleTo(new XYZ(1, 0, 0));
                            ang = t.BasisY.Y >= 0 ? lAng : -lAng;
                            FamilyInstance gzInstance = doc.Create.NewFamilyInstance(pt, guiZhenFamilySymbol, level,
                                                                                     StructuralType.NonStructural);
                            ElementTransformUtils.RotateElement(doc, gzInstance.Id,
                                                                Line.CreateBound(pt, new XYZ(pt.X, pt.Y, pt.Z + 1)), ang);
                            numOfGuiZhen++;
                        }
                    }

                    str.Commit();
                }

                tr.Commit();
                DateTime oTimeEnd = DateTime.Now;
                TimeSpan time     = oTimeEnd.Subtract(oTimeStart);
                TaskDialog.Show("轨枕创建成功", $"本次共创建了{numOfGuiZhen}根轨枕!" +
                                $"\n\t共耗时{time.Seconds}秒!");
                return(true);
            }
            else
            {
                TaskDialog.Show("ERR", "对象为空");
                return(false);
            }
        }
        /// <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;
            }
        }
Exemple #21
0
 /// <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;
 }
Exemple #22
0
        /// <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);
                    }
                }
            }
        }
Exemple #23
0
        public SheetsISFLRequest(UIApplication uiApp, String text)
        {
            MainUI     uiForm = BARevitTools.Application.thisApp.newMainUi;
            UIDocument uidoc  = uiApp.ActiveUIDocument;

            //Start a transaction
            Transaction t1 = new Transaction(uidoc.Document, "InsertSheetsFromLink");

            t1.Start();
            //Cycle through each row in the DataGridView
            foreach (DataGridViewRow row in uiForm.sheetsISFLDataGridView.Rows)
            {
                if (row.Cells["To Add"].Value != null)
                {
                    //If the checkbox to add the sheet is checked, and the sheet already exists
                    if (row.Cells["To Add"].Value.ToString() == "True" && row.Cells["Pre-exists"].Value.ToString() == "True")
                    {
                        //Get the sheet number of the old sheet
                        string sheetToDelete = row.Cells["Sheet Number"].Value.ToString();
                        //Collect the sheets in the project
                        IList <Element> sheetsCollector = new FilteredElementCollector(uidoc.Document).OfClass(typeof(ViewSheet)).ToElements();
                        foreach (Element elem in sheetsCollector)
                        {
                            ViewSheet viewSheet = elem as ViewSheet;
                            //If the sheet number of the sheet to delete matches the sheet being evaluated, and the sheet being evaluated is a placeholder, continue
                            //It is important that the sheet is placeholder and not a sheet that could potentially have views on it
                            if (viewSheet.SheetNumber == sheetToDelete && viewSheet.IsPlaceholder == true)
                            {
                                try
                                {
                                    //Use a subtransaction to delete the sheet view
                                    SubTransaction deleteTransaction = new SubTransaction(uidoc.Document);
                                    deleteTransaction.Start();
                                    uidoc.Document.Delete(viewSheet.Id);
                                    deleteTransaction.Commit();
                                }
                                catch { continue; }
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    //Otherwise, if the sheet does not already exist, continue
                    if (row.Cells["To Add"].Value.ToString() == "True")
                    {
                        try
                        {
                            //Create a new placeholder sheet
                            ViewSheet newSheet = ViewSheet.CreatePlaceholder(uidoc.Document);
                            newSheet.SheetNumber = row.Cells["Sheet Number"].Value.ToString();
                            //Set the new placeholder sheet's name
                            if (row.Cells["Host Sheet Name"].Value.ToString() == "" || row.Cells["Host Sheet Name"].Value.ToString() == "Sheet")
                            {
                                newSheet.Name = row.Cells["Link Sheet Name"].Value.ToString();
                            }
                            else
                            {
                                newSheet.Name = row.Cells["Host Sheet Name"].Value.ToString();
                            }
                            //Get the list of sheet parameters and find the BA Sheet Discipline parameter
                            IList <Parameter> disciplineParameters = newSheet.GetParameters(Properties.Settings.Default.BASheetDisciplineParameter);
                            foreach (Parameter param in disciplineParameters)
                            {
                                try
                                {
                                    //Set the BA Sheet Discipline from the value in the DataGridView
                                    param.Set(row.Cells["Discipline"].Value.ToString());
                                }
                                catch { continue; }
                            }
                        }
                        catch { continue; }
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    continue;
                }
            }
            t1.Commit();
            //Update the DataGridView with fresh data using the inserted sheets and sheets from the link
            RVTDocument linkDoc = uiForm.SheetsISFLGetLinkDoc();

            uiForm.SheetsISFLUpdateDataGridView(linkDoc);
        }
Exemple #24
0
        public AdminDataGFFRequest(UIApplication uiApp, String text)
        {
            //Items pertaining to the open UI
            MainUI        uiForm         = BARevitTools.Application.thisApp.newMainUi;
            List <string> itemsToCollect = uiForm.adminDataGFFItemsToCollect;

            //UI settings related to the proggress bar
            int filesToProcess = uiForm.adminDataGFFFiles.Count;

            uiForm.adminDataGFFDataProgressBar.Value   = 0;
            uiForm.adminDataGFFDataProgressBar.Minimum = 0;
            uiForm.adminDataGFFDataProgressBar.Maximum = filesToProcess;
            uiForm.adminDataGFFDataProgressBar.Step    = 1;
            uiForm.adminDataGFFDataProgressBar.Visible = true;

            //New objects
            DataTable dt             = new DataTable();
            int       selectionGroup = -2;

            //Getting the items from the list obtained from checked listbox items to determine what datatable columns are needed
            //The items below are able to be obtained without API calls. Statementselect remains -1 to indicate no API request will be needed, saving time.
            if (itemsToCollect.Contains("Family Name"))
            {
                DataColumn familyNameColumn = dt.Columns.Add("FamilyName", typeof(String));
                selectionGroup = -1;
            }

            if (itemsToCollect.Contains("Family Size"))
            {
                DataColumn familySizeColumn = dt.Columns.Add("FamilySize", typeof(Double));
                selectionGroup = -1;
            }

            if (itemsToCollect.Contains("Date Last Modified"))
            {
                DataColumn dateLastModifiedColumn = dt.Columns.Add("DateLastModified", typeof(String));
                selectionGroup = -1;
            }

            //Here is where items must be obtained via API calls. Statementselect changes from -1 to 0 to later indicate that API usage will be needed.
            if (itemsToCollect.Contains("Revit Version"))
            {
                DataColumn revitVersionColumn = dt.Columns.Add("RevitVersion", typeof(String));
                selectionGroup = 0;
            }

            if (itemsToCollect.Contains("Family Category"))
            {
                DataColumn familyCategoryColumn = dt.Columns.Add("FamilyCategory", typeof(String));
                selectionGroup = 0;
            }

            //From here, the IF statments indicate the files will need to be opened and API calls will be used, resulting in a slow data collection. Statementselect becomes 1
            if (itemsToCollect.Contains("Family Types"))
            {
                DataColumn familyTypeColumn = dt.Columns.Add("FamilyType", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Name"))
            {
                DataColumn parameterNameColumn = dt.Columns.Add("ParameterName", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Group"))
            {
                DataColumn parameterGroupColumn = dt.Columns.Add("ParameterGroup", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Type"))
            {
                DataColumn parameterTypeColumn = dt.Columns.Add("ParameterType", typeof(String));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Value"))
            {
                //If the parameter value is to be collected, it could be either an integer, double, or string, so create all three columns anyways
                DataColumn parameterValueIntegerColumn = dt.Columns.Add("ParameterValueInteger", typeof(Int32));
                parameterValueIntegerColumn.AllowDBNull = true;
                DataColumn parameterValueDoubleColumn = dt.Columns.Add("ParameterValueDouble", typeof(Double));
                parameterValueDoubleColumn.AllowDBNull = true;
                DataColumn parameterValueStringColumn = dt.Columns.Add("ParameterValueString", typeof(String));
                parameterValueStringColumn.AllowDBNull = true;
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Is Instance"))
            {
                DataColumn parameterIsInstanceColumn = dt.Columns.Add("ParameterIsInstance", typeof(Boolean));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter Is Shared"))
            {
                DataColumn parameterIsSharedColumn = dt.Columns.Add("ParameterIsShared", typeof(Boolean));
                selectionGroup = 1;
            }

            if (itemsToCollect.Contains("Parameter GUID"))
            {
                DataColumn parameterGUIDColumn = dt.Columns.Add("ParameterGUID", typeof(String));
                selectionGroup = 1;
            }

            //Cycle through the file paths obtained from the open UI
            foreach (string filePath in uiForm.adminDataGFFFiles)
            {
                //Increment the progress bar of the open UI
                uiForm.adminDataGFFDataProgressBar.PerformStep();
                // If selectionGroup is -1, no use of the API will be used
                if (selectionGroup == -1)
                {
                    DataRow row = dt.NewRow();
                    if (dt.Columns.Contains("FamilyName"))
                    {
                        row["FamilyName"] = GeneralOperations.GetFileName(filePath);
                    }

                    if (dt.Columns.Contains("FamilySize"))
                    {
                        row["FamilySize"] = GeneralOperations.GetFileSize(filePath);
                    }

                    if (dt.Columns.Contains("DateLastModified"))
                    {
                        row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath);
                    }

                    dt.Rows.Add(row);
                }

                //If selectionGroup is 0, then the API will be used, resulting in slower processing
                else if (selectionGroup == 0)
                {
                    //Get the Revit version year of the file
                    int rvtNumber = RVTOperations.GetRevitNumber(filePath);
                    //Check to see if the GetRevitNumber did not return 0 (could not be determined), and that the saved in version is not newer that the one running.
                    if (rvtNumber != 0 && Convert.ToInt32(uiApp.Application.VersionNumber) >= rvtNumber)
                    {
                        DataRow row = dt.NewRow();

                        if (dt.Columns.Contains("FamilyName"))
                        {
                            row["FamilyName"] = GeneralOperations.GetFileName(filePath);
                        }

                        if (dt.Columns.Contains("FamilySize"))
                        {
                            row["FamilySize"] = GeneralOperations.GetFileSize(filePath);
                        }

                        if (dt.Columns.Contains("DateLastModified"))
                        {
                            row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath);
                        }

                        if (dt.Columns.Contains("RevitVersion"))
                        {
                            row["RevitVersion"] = RVTOperations.GetRevitVersion(filePath);
                        }

                        RVTDocument doc = RVTOperations.OpenRevitFile(uiApp, filePath);
                        if (dt.Columns.Contains("FamilyCategory") && doc.IsFamilyDocument)
                        {
                            row["FamilyCategory"] = RVTOperations.GetRevitFamilyCategory(doc);
                        }

                        doc.Close(false);
                        dt.Rows.Add(row);
                    }
                }

                //If selectionGroup is 1, then the API will be used, and the file must be opened to obtain the information
                else if (selectionGroup == 1)
                {
                    //Verifying Revit version year
                    int rvtNumber = RVTOperations.GetRevitNumber(filePath);
                    if (rvtNumber != 0 && Convert.ToInt32(uiApp.Application.VersionNumber) >= rvtNumber)
                    {
                        //Open the Revit file
                        RVTDocument doc = RVTOperations.OpenRevitFile(uiApp, filePath);
                        //Ensure it is a family document
                        if (doc.IsFamilyDocument)
                        {
                            //Get the family manager of the family file
                            FamilyManager famMan = doc.FamilyManager;
                            //Get the set of family types from the family file
                            FamilyTypeSet familyTypes = famMan.Types;

                            Transaction t1 = new Transaction(doc, "CycleFamilyTypes");
                            t1.Start();
                            FailureHandlingOptions failureHandlingOptions = t1.GetFailureHandlingOptions();
                            failureHandlingOptions.SetFailuresPreprocessor(new RVTFailuresPreprocessor());
                            t1.SetFailureHandlingOptions(failureHandlingOptions);

                            //For each family type...
                            foreach (FamilyType famType in familyTypes)
                            {
                                //Create a subtransaction to change the current family type in the family manager
                                SubTransaction s1 = new SubTransaction(doc);
                                s1.Start();

                                famMan.CurrentType = famType;
                                s1.Commit();

                                //Get each parameter from the current family type, and create a row for each parameter
                                foreach (FamilyParameter param in famMan.GetParameters())
                                {
                                    DataRow row = dt.NewRow();
                                    if (dt.Columns.Contains("FamilyName"))
                                    {
                                        try { row["FamilyName"] = GeneralOperations.GetFileName(filePath); }
                                        catch { row["FamilyName"] = ""; }
                                    }
                                    if (dt.Columns.Contains("FamilySize"))
                                    {
                                        try { row["FamilySize"] = GeneralOperations.GetFileSize(filePath); }
                                        catch { row["FamilySize"] = 0; }
                                    }
                                    if (dt.Columns.Contains("DateLastModified"))
                                    {
                                        try { row["DateLastModified"] = GeneralOperations.GetFileLastModifiedDate(filePath); }
                                        catch { row["DateLastModified"] = ""; }
                                    }
                                    if (dt.Columns.Contains("RevitVersion"))
                                    {
                                        try { row["RevitVersion"] = RVTOperations.GetRevitVersion(filePath); }
                                        catch { row["RevitVersion"] = ""; }
                                    }
                                    if (dt.Columns.Contains("FamilyCategory"))
                                    {
                                        try { row["FamilyCategory"] = RVTOperations.GetRevitFamilyCategory(doc); }
                                        catch { row["FamilyCategory"] = ""; }
                                    }
                                    if (dt.Columns.Contains("FamilyType"))
                                    {
                                        try { row["FamilyType"] = famType.Name.ToString(); }
                                        catch { row["FamilyType"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterName"))
                                    {
                                        try { row["ParameterName"] = param.Definition.Name; }
                                        catch { row["ParameterName"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterGroup"))
                                    {
                                        try { row["ParameterGroup"] = param.Definition.ParameterGroup.ToString(); }
                                        catch { row["ParameterGroup"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterType"))
                                    {
                                        try { row["ParameterType"] = param.Definition.ParameterType.ToString(); }
                                        catch { row["ParameterType"] = ""; }
                                    }

                                    //Here is where the attempts to get the parameter values begins. Get the StorageType of the parameter, then determine which column the data goes in
                                    if (dt.Columns.Contains("ParameterValueInteger") && param.StorageType == StorageType.Integer)
                                    {
                                        try { row["ParameterValueInteger"] = famType.AsInteger(param); }
                                        catch { row["ParameterValueInteger"] = 0; }
                                    }

                                    if (dt.Columns.Contains("ParameterValueDouble") && param.StorageType == StorageType.Double)
                                    {
                                        try { row["ParameterValueDouble"] = famType.AsDouble(param); }
                                        catch { row["ParameterValueDouble"] = 0; }
                                    }

                                    if (dt.Columns.Contains("ParameterValueString") && param.StorageType == StorageType.ElementId)
                                    {
                                        //Instead of getting the ElementID, which is limited in value to someone reading the data, get the element name instead
                                        try { row["ParameterValueString"] = doc.GetElement(famType.AsElementId(param)).Name; }
                                        catch { row["ParameterValueString"] = ""; }
                                    }

                                    if (dt.Columns.Contains("ParameterValueString") && param.StorageType == StorageType.String)
                                    {
                                        //First, try getting the parameter string as a string. If that fails, try getting it as a ValueString
                                        try
                                        {
                                            string paramValue = famType.AsString(param);
                                            row["ParameterValueString"] = paramValue;
                                        }
                                        catch
                                        {
                                            try
                                            {
                                                string paramValue = famType.AsValueString(param).ToString();
                                                row["ParameterValueString"] = paramValue;
                                            }
                                            catch
                                            {
                                                row["ParameterValueString"] = "";
                                            }
                                        }
                                    }

                                    if (dt.Columns.Contains("ParameterIsInstance"))
                                    {
                                        try { row["ParameterIsInstance"] = param.IsInstance; }
                                        catch { row["ParameterIsInstance"] = false; }
                                    }

                                    if (dt.Columns.Contains("ParameterIsShared"))
                                    {
                                        try { row["ParameterIsShared"] = param.IsShared; }
                                        catch { row["ParameterIsShared"] = false; }
                                    }

                                    if (dt.Columns.Contains("ParameterGUID"))
                                    {
                                        try { row["ParameterGUID"] = param.GUID.ToString(); }
                                        catch { row["ParameterGUID"] = ""; }
                                    }
                                    //Add the datatable row to the datatable
                                    dt.Rows.Add(row);
                                }
                            }
                            //Commit the primary transaction
                            t1.Commit();
                        }
                        //Close the document, do not save
                        doc.Close(false);
                    }
                }
                else
                {
                    //selectionGroup is still -2, and thus nothing was selected. Do nothing.
                    continue;
                }
            }

            //Set the datatable of the open UI to the one with the obtained data
            uiForm.adminDataGFFDataTable = dt;
            //Indicate the collection is done with the label
            uiForm.adminDataGFFCollectDataWaitLabel.Text = "Done!";
            //Hide the progress bar when done, and clear out the list of data items to collect
            uiForm.adminDataGFFDataProgressBar.Visible = false;
            uiForm.adminDataGFFItemsToCollect.Clear();
        }
Exemple #25
0
 /// <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 = m_glassMatID;

            glass1.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM).Set(id);
            glass2.get_Parameter(BuiltInParameter.MATERIAL_ID_PARAM).Set(id);
            subTransaction.Commit();
        }
Exemple #27
0
        /// <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();
        }
Exemple #28
0
 /// <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>
        /// 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();
            }
        }
Exemple #30
0
        public QaqcRLSRequest(UIApplication uiApp, String text)
        {
            MainUI       uiForm = BARevitTools.Application.thisApp.newMainUi;
            DataGridView dgv    = uiForm.qaqcRLSDataGridView;
            RVTDocument  doc    = uiApp.ActiveUIDocument.Document;

            List <ElementId> unswitchableElements = new List <ElementId>();

            //Creating a DataTable for this tool's operations
            DataTable  dt = new DataTable();
            DataColumn elementIdColumn = dt.Columns.Add("Element Id", typeof(ElementId));
            DataColumn groupNameColumn = dt.Columns.Add("Group Name", typeof(String));

            if (uiForm.qaqcRLSReplaceComboBox.Text == "<Replace>")
            {
                //If the user has not selected a line style to replace, remind them
                MessageBox.Show("Select the line style to replace");
            }
            else if (uiForm.qaqcRLSReplaceWithComboBox.Text == "<With>")
            {
                //If the user has not selected a line style to use as a replacement, remind them
                MessageBox.Show("Select the line style to replace with");
            }
            else
            {
                //Otherwise, they did a good job following instructions and they can continue. Get the line styles to use from the dictionary
                Category replaceStyle     = uiForm.qaqcLineStyleDict[uiForm.qaqcRLSReplaceComboBox.Text.ToString()];
                Category replaceWithStyle = uiForm.qaqcLineStyleDict[uiForm.qaqcRLSReplaceWithComboBox.Text.ToString()];
                //The Projection style is needed from the line style to use in the replacement
                GraphicsStyle setStyle = replaceWithStyle.GetGraphicsStyle(GraphicsStyleType.Projection);

                //Start a new transaction
                Transaction t1 = new Transaction(doc, "ConvertLines");
                t1.Start();

                //Collect all of the lines in the project, then cycle through them
                var lineCollector = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Lines).ToElements();
                foreach (CurveElement elem in lineCollector)
                {
                    //Get the name of the line style and the GroupId of the group it belongs to
                    string    lineStyleName = elem.LineStyle.Name;
                    ElementId groupId       = elem.GroupId;

                    //If the name of the line style is the same as the one to replace, and its GroupId is -1 (no group), continue
                    if (lineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(elem.GroupId.ToString()) == -1)
                    {
                        //Create a boolean variable to save the pinned state
                        bool wasPinned = false;

                        //If the line is pinned, unpin it and set the wasPinned variable to true
                        if (elem.Pinned)
                        {
                            elem.Pinned = false;
                            wasPinned   = true;
                        }

                        //Then, set the line's line style to the style to use in the replacement
                        try
                        {
                            elem.LineStyle = setStyle;
                        }
                        catch (Exception e)
                        {
                            //If it could not be switched, add it to the list
                            MessageBox.Show(e.ToString());
                            unswitchableElements.Add(elem.Id);
                            continue;
                        }

                        //If the line had been pinned, repin it
                        if (wasPinned)
                        {
                            elem.Pinned = true;
                        }
                    }

                    //If the line style matched the name of the line style to replace, but it belonged to a group, add the line to the list of elements that could not be switched
                    else if (lineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(elem.GroupId.ToString()) != -1)
                    {
                        unswitchableElements.Add(elem.Id);
                    }
                    else
                    {
                        continue;
                    }
                }
                t1.Commit();

                //Start another transaction
                Transaction t2 = new Transaction(doc, "ReplaceRegions");
                t2.Start();
                //Next, evaluate all filled regions for their sketch boundary lines
                var regionCollector = new FilteredElementCollector(doc).OfClass(typeof(FilledRegion)).ToElements().ToList();
                foreach (FilledRegion region in regionCollector)
                {
                    //Get the ID of the filled region
                    ElementId regionId = region.Id;
                    //Start a subtransaction because the region must be deleted to get the sketch lines that were deleted.
                    SubTransaction st2 = new SubTransaction(doc);
                    st2.Start();
                    //Collect the list of element Ids deleted from the deletion
                    List <ElementId> deletedIds = doc.Delete(regionId).ToList();
                    //Roll back the subtransaction to undelete the filled region
                    st2.RollBack();

                    //Now we know what sketch lines belong to the filled region. Evaluate each ElementId from the subtransaction
                    foreach (ElementId id in deletedIds)
                    {
                        Element regionSubElem = doc.GetElement(id);
                        //Determine if the element is a detail line
                        if (regionSubElem.GetType().ToString() == "Autodesk.Revit.DB.DetailLine")
                        {
                            //If it is a detail line, get the curve of the line, then its line style name
                            CurveElement curveElement        = regionSubElem as CurveElement;
                            string       sketchLineStyleName = curveElement.LineStyle.Name;
                            //If the line style name matches the name of the line style to replace, and the region does not belong to a group, continue
                            if (sketchLineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(region.GroupId.ToString()) == -1)
                            {
                                //Again, determin if the region was pinned, just like the lines
                                bool wasPinned = false;
                                if (region.Pinned)
                                {
                                    region.Pinned = false;
                                    wasPinned     = true;
                                }

                                try
                                {
                                    //Change the line style of the curve
                                    curveElement.LineStyle = setStyle;
                                    XYZ z = XYZ.BasisZ;
                                    //Then, move the region up and then down in the Z axis to cause a redraw.
                                    ElementTransformUtils.MoveElement(doc, region.Id, z);
                                    ElementTransformUtils.MoveElement(doc, region.Id, -z);
                                }
                                catch (Exception e)
                                {
                                    //If the region's sketch lines could not be switched, add it to the list of elements that could not be switched
                                    MessageBox.Show(e.ToString());
                                    unswitchableElements.Add(region.Id);
                                    continue;
                                }

                                if (wasPinned)
                                {
                                    region.Pinned = true;
                                }
                            }
                            //If the region belonged to a group, add it to the list of elements that could not be switched immediately
                            else if (sketchLineStyleName == uiForm.qaqcRLSReplaceComboBox.Text.ToString() && Convert.ToInt32(region.GroupId.ToString()) != -1)
                            {
                                unswitchableElements.Add(region.Id);
                                continue;
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            continue;
                        }
                    }
                }
                t2.Commit();

                //Now, for each element in the unswitchableElements list...
                foreach (ElementId elemId in unswitchableElements)
                {
                    //Create a new row and fill it out with the ElementId and group name if it exists
                    DataRow row = dt.NewRow();
                    row["Element Id"] = elemId;
                    if (doc.GetElement(elemId).GroupId.IntegerValue != -1)
                    {
                        row["Group Name"] = doc.GetElement(doc.GetElement(elemId).GroupId).Name;
                    }
                    else
                    {
                        row["Group Name"] = "";
                    }
                    dt.Rows.Add(row);
                }

                //Bind the DataTable to the DataGridView
                BindingSource bs = new BindingSource();
                bs.DataSource  = dt;
                dgv.DataSource = bs;
                //Turn off the blank column at the beginning of the rows
                dgv.RowHeadersVisible = false;
                //Set the row selection to be full row selection
                dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                //Sort the rows by the group name
                dgv.Sort(dgv.Columns["Group Name"], ListSortDirection.Ascending);

                //If the user wanted to delete the line styles, and nothing is preventing it because the DataTable has no rows, continue
                if (uiForm.qaqcRLSDeleteCheckBox.Checked && dt.Rows.Count == 0)
                {
                    //New transaction
                    Transaction t = new Transaction(doc, String.Format("Delete{0}", replaceStyle.Name));
                    t.Start();
                    try
                    {
                        //Delete the linestyle
                        doc.Delete(replaceStyle.Id);
                        t.Commit();
                        //Reset the combo boxes from the MainUI and reset them with new data of existing Line Styles
                        uiForm.qaqcRLSReplaceComboBox.Text = "<Replace>";
                        uiForm.qaqcRLSReplaceComboBox.Items.Clear();
                        uiForm.qaqcRLSReplaceWithComboBox.Items.Clear();
                        uiForm.qaqcRLSReplaceWithComboBox.Text = "<With>";
                        uiForm.QaqcRLSSetReplaceComboBox(uiForm, doc);
                    }
                    catch
                    {
                        //If the deletion fails, roll back the transaction and let the user know
                        t.RollBack();
                        MessageBox.Show(String.Format("Could not delete {0}", replaceStyle.Name));
                    }
                }
                else
                {
                    //If there were instances that could not be switched, report this to the user, and instruct them to check the table for the groups where the instances occur
                    MessageBox.Show(String.Format("Could not delete {0} because {1} instances could not be switched. See the the table for instances in groups +" +
                                                  "that could not be switched.", replaceStyle.Name, dgv.Rows.Count.ToString()));
                }
            }
        }
Exemple #31
0
        /// <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);
        }
        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 DrawSolution(Objects.Solution sol, IList <Objects.Node> nodes, ElementId system, ElementId ductType)
        {
            Transaction t = null;

            if (_uiDoc.Document.IsModifiable == false)
            {
                t = new Transaction(_uiDoc.Document, "Create Ductwork");
                t.Start();
            }

            Utilities.AVFUtility.Clear(_uiDoc);


            // start with the corridor
            IList <Objects.Edge> corrEdges = sol.GetCorridorEdges(nodes);

            List <Duct>    corrDucts = new List <Duct>();
            List <Duct>    allDucts  = new List <Duct>();
            SubTransaction st        = new SubTransaction(_uiDoc.Document);

            st.Start();
            foreach (var edge in corrEdges)
            {
                Objects.Node n1 = nodes.Single(n => n.Id == edge.Node1);
                Objects.Node n2 = nodes.Single(n => n.Id == edge.Node2);

                Duct d =
                    MEPController.MakeDuct(_uiDoc.Document, n1.Location, n2.Location, ductType, system, edge.Diameter, 0.0);

                corrDucts.Add(d);
                allDucts.Add(d);
            }
            st.Commit();
            _uiDoc.Document.Regenerate();

            IList <FamilyInstance> fittings = MEPController.JoinDucts(corrDucts);

            IList <Objects.Edge> vavEdges = sol.GetVAVEdges(nodes);

            IList <MEPCurve> crvDucts = corrDucts.Cast <MEPCurve>().ToList();

            var vavInstances = GetAllVAVs();

            foreach (var edge in vavEdges)
            {
                //Objects.Node n1 = nodes.Single(n => n.Id == edge.Node1);
                //Objects.Node n2 = nodes.Single(n => n.Id == edge.Node2);

                //MEPController.MakeDuct(_uiDoc.Document, n1.Location, n2.Location, ductType, system, edge.Diameter, 0.0);

                Duct d = createVAVConnection(edge, ductType, system, nodes, crvDucts, vavInstances, fittings);
            }

            IList <Objects.Edge> shaftEdges = sol.GetShaftEdges(nodes);

            foreach (var edge in shaftEdges)
            {
                Objects.Node n1 = nodes.Single(n => n.Id == edge.Node1);
                Objects.Node n2 = nodes.Single(n => n.Id == edge.Node2);

                MEPController.MakeDuct(_uiDoc.Document, n1.Location, n2.Location, ductType, system, edge.Diameter, 0.0);
            }

            if (t != null)
            {
                t.Commit();
            }
        }
Exemple #34
0
        /// <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);
            }
        }
Exemple #35
0
        /// <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();
        }
        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;
        }
Exemple #37
0
        /// <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>
        /// 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();
            }
        }
Exemple #39
0
        /// <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();
        }
Exemple #40
0
        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;
        }
Exemple #41
0
        /// <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();
        }
Exemple #42
0
        /// <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>
        /// Renames all sheets that contain exactly one floor plan to match the name of that view
        /// Copy the whole method into the macro file on your machine,
        /// or download this file and add it to the solution in the macro editor
        /// </summary>
        public void RenameSheetsToMatchViewNames()
        {
            UIDocument uidoc = this.ActiveUIDocument;
            Document   doc   = uidoc.Document;

            // Retrieve all sheets, cast them to type ViewSheet and save them in a list
            // It is important to use ToList or ToElements when modifying elements
            // from a FilteredElementCollector
            var sheets = new FilteredElementCollector(doc)
                         .OfClass(typeof(ViewSheet))
                         .Cast <ViewSheet>().ToList();

            // Initialize a counter that will identify how many sheets have been modified
            int renamedSheetsCount = 0;

            // Open a transaction that allows changes to be made to the model
            using (Transaction trans = new Transaction(doc, "Rename sheets"))
            {
                // Start the transaction
                trans.Start();

                // Loop through each sheet retrieved above
                foreach (var sheet in sheets)
                {
                    // Get all the views placed on the sheet
                    var viewsOnSheet = sheet.GetAllPlacedViews();

                    // If there is not exactly 1 view on the sheet,
                    // Skip this sheet and continue to the next one
                    if (viewsOnSheet.Count != 1)
                    {
                        continue;
                    }

                    // Get the id of the view
                    // The single call is used because we know there is only 1
                    // based on the check above
                    var viewId = viewsOnSheet.Single();

                    // Get the view from the id, and cast it to type View
                    var view = (View)doc.GetElement(viewId);

                    // If the view is not a floor plan,
                    // skip the sheet and continue to the next one
                    if (view.ViewType != ViewType.FloorPlan)
                    {
                        continue;
                    }

                    // Open a sub-transaction for the upcoming modification to the sheet
                    using (SubTransaction subTrans = new SubTransaction(doc))
                    {
                        // Start the sub-transaction
                        subTrans.Start();

                        // Set the sheet name to the view name
                        sheet.Name = view.Name;

                        // Commit the change made
                        subTrans.Commit();

                        // Increment the sheet counter by 1
                        renamedSheetsCount++;
                    }

                    // End of foreach loop
                }

                // Commit the transaction
                trans.Commit();
            }

            // Show a message indicating how many sheets were modified
            TaskDialog.Show("Done", "Renamed " + renamedSheetsCount + " sheets");
        }
Exemple #44
0
        /// <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>
        /// 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 <ElementId, string> existingRooms = new Dictionary <ElementId, string>();
                foreach (Room room in m_roomData.Rooms)
                {
                    Parameter sharedParameter = room.LookupParameter(RoomsData.SharedParam);
                    if (null != sharedParameter && false == String.IsNullOrEmpty(sharedParameter.AsString()))
                    {
                        existingRooms.Add(room.Id, 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.LookupParameter(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);
        }
Exemple #46
0
        /// <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);
            }
        }
Exemple #47
0
        public AdminFamiliesBAPRequest(UIApplication uiApp, String text)
        {
            MainUI uiForm = BARevitTools.Application.thisApp.newMainUi;

            uiForm.adminFamiliesBAPDoneLabel.Visible = false;
            RVTDocument   doc           = uiApp.ActiveUIDocument.Document;
            SaveAsOptions saveAsOptions = new SaveAsOptions();

            saveAsOptions.Compact               = true;
            saveAsOptions.MaximumBackups        = 3;
            saveAsOptions.OverwriteExistingFile = true;
            Dictionary <string, ExternalDefinition> sharedParameterDefinitions = new Dictionary <string, ExternalDefinition>();

            //Determine if the shared parameters file is accessible and try to get the shared parameters so their definition names and definitions could be added to a dictionary
            bool sharedParametersIsAccessible = true;

            try
            {
                DefinitionGroups sharedParameterGroups = uiApp.Application.OpenSharedParameterFile().Groups;
                foreach (DefinitionGroup group in sharedParameterGroups)
                {
                    foreach (ExternalDefinition definition in group.Definitions)
                    {
                        if (!sharedParameterDefinitions.Keys.Contains(definition.Name))
                        {
                            sharedParameterDefinitions.Add(definition.Name, definition);
                        }
                    }
                }
            } //If the access fails, then the shared parameters file was not accessible.
            catch { sharedParametersIsAccessible = false; }

            //Get the number of families to process from the DataGridView
            int filesToProcess = 0;

            foreach (DataGridViewRow rowCount in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
            {
                if (rowCount.Cells["Family Select"].Value.ToString() == "True")
                {
                    filesToProcess++;
                }
            }

            //Prepare the progress bar
            uiForm.adminFamiliesBAPProgressBar.Value   = 0;
            uiForm.adminFamiliesBAPProgressBar.Minimum = 0;
            uiForm.adminFamiliesBAPProgressBar.Maximum = filesToProcess;
            uiForm.adminFamiliesBAPProgressBar.Step    = 1;
            uiForm.adminFamiliesBAPProgressBar.Visible = true;

            //Stop any edits to the DataGridView of parameters to add
            uiForm.adminFamiliesBAPParametersDGV.EndEdit();
            try
            {
                foreach (DataGridViewRow row in uiForm.adminFamiliesBAPFamiliesDGV.Rows)
                {
                    try
                    {
                        //If the checkbox for including the family in the process is not null, continue
                        if (row.Cells["Family Select"].Value != null)
                        {
                            //Grab the file path for the family
                            string        filePath      = row.Cells["Family Path"].Value.ToString();
                            List <string> famParamNames = new List <string>();
                            //If the checkbox is checked to select the family
                            if (row.Cells["Family Select"].Value.ToString() == "True")
                            {
                                //Open the family document
                                RVTDocument famDoc = RVTOperations.OpenRevitFile(uiApp, filePath);
                                if (famDoc.IsFamilyDocument)
                                {
                                    //Grab the family manager and make a list of parameter names already in the family
                                    FamilyManager familyManager = famDoc.FamilyManager;
                                    foreach (FamilyParameter famParam in familyManager.Parameters)
                                    {
                                        if (!famParamNames.Contains(famParam.Definition.Name))
                                        {
                                            famParamNames.Add(famParam.Definition.Name);
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }

                                    foreach (DataGridViewRow newParamRow in uiForm.adminFamiliesBAPParametersDGV.Rows)
                                    {
                                        try
                                        {
                                            //Get the name of the parameter, group, and type of parameter to add
                                            string name = newParamRow.Cells["Parameter Name"].Value.ToString();
                                            BuiltInParameterGroup group = RVTOperations.GetBuiltInParameterGroupFromString(newParamRow.Cells["Parameter Group"].Value.ToString());
                                            ParameterType         type  = RVTOperations.GetParameterTypeFromString(newParamRow.Cells["Parameter Type"].Value.ToString());
                                            //Determine if the checkbox for making the parameter an instance parameter is checked
                                            bool isInstance = false;
                                            try
                                            {
                                                isInstance = Convert.ToBoolean(newParamRow.Cells["Parameter Is Instance"].Value.ToString());
                                            }
                                            catch { isInstance = false; }

                                            //Determine if the read-only checkbox for the parameter being a shared parameter is checked.
                                            bool isShared = false;
                                            try
                                            {
                                                isShared = Convert.ToBoolean(newParamRow.Cells["Parameter Is Shared"].Value.ToString());
                                            }
                                            catch { isShared = false; }

                                            //If the parameter is shared, and the parameter file is still accessible, and the family does not already contain a parameter with that name, continue
                                            if (isShared == true && sharedParametersIsAccessible == true && !famParamNames.Contains(name))
                                            {
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    //Get the parameter definition from the dictionary of shared parameters, then add it to the family
                                                    ExternalDefinition definition = sharedParameterDefinitions[newParamRow.Cells["Parameter Name"].Value.ToString()];
                                                    FamilyParameter    newParam   = familyManager.AddParameter(definition, group, isInstance);
                                                    try
                                                    {
                                                        //Try to assign the parameter value if one is to be assigned
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            //If the number of types is greater than 0, cycle through them
                                                            if (familyManager.Types.Size > 0)
                                                            {
                                                                foreach (FamilyType familyType in familyManager.Types)
                                                                {
                                                                    //For each type, make a subtransaction
                                                                    SubTransaction s1 = new SubTransaction(famDoc);
                                                                    s1.Start();
                                                                    try
                                                                    {
                                                                        //Then set the family type as current
                                                                        familyManager.CurrentType = familyType;
                                                                        //Attempt to set the parameter value
                                                                        RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                                        s1.Commit();
                                                                    }
                                                                    catch
                                                                    {
                                                                        //If that fails, let the user know and break out of the loop
                                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for type {2} in family {3}.", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], familyType.Name, row.Cells["Family Name"]));
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                //If there was was no family types in the family, just set it for the default one
                                                                RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                            }
                                                        }
                                                    }
                                                    catch
                                                    {
                                                        //If assignment fails, let the user know the parameter value, parameter name, and the family where the failure occured.
                                                        MessageBox.Show(String.Format("Could not assign value {0} to parameter {1} for family {2}", newParamRow.Cells["Parameter Value"], newParamRow.Cells["Parameter Name"], row.Cells["Family Name"]));
                                                    }
                                                    t.Commit();
                                                }
                                            }
                                            else if (isShared == true && sharedParametersIsAccessible == false && !famParamNames.Contains(name))
                                            {
                                                //If the shared parameter file could not be accessed, let the user know
                                                MessageBox.Show(String.Format("Could not set the shared parameter {0} because the shared parameters file for this project could not be found. " +
                                                                              "Verify the shared parameters file is mapped correctly.", name));
                                            }
                                            else if (isShared != true && !famParamNames.Contains(name))
                                            {
                                                //Otherwise, just make a standard parameter
                                                using (Transaction t = new Transaction(famDoc, "Add Parameter"))
                                                {
                                                    t.Start();
                                                    FamilyParameter newParam = familyManager.AddParameter(name, group, type, isInstance);
                                                    try
                                                    {
                                                        if (newParamRow.Cells["Parameter Value"].Value != null)
                                                        {
                                                            RVTOperations.SetFamilyParameterValue(familyManager, newParam, RVTOperations.SetParameterValueFromString(newParamRow.Cells["Parameter Type"].Value.ToString(), newParamRow.Cells["Parameter Value"].Value));
                                                        }
                                                    }
                                                    catch { continue; }
                                                    t.Commit();
                                                }
                                            }
                                            else
                                            {
                                                //If all other conditions were not met, then the parameter already exists.
                                                MessageBox.Show(String.Format("Could not make parameter '{0}' for {1} because it already exists.", name, famDoc.Title));
                                            }
                                        }
                                        catch { continue; }
                                        finally
                                        {
                                            //Save the family
                                            ModelPath modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(filePath);
                                            famDoc.SaveAs(filePath, saveAsOptions);
                                        }
                                    }
                                }
                                //Close the family
                                famDoc.Close(false);
                            }
                            else
                            {
                                continue;
                            }
                            //Step forward the progress bar
                            uiForm.adminFamiliesBAPProgressBar.PerformStep();
                        }
                    }
                    catch
                    {
                        MessageBox.Show("The family could not be opened, likely due to being saved in a newer version of Revit");
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                //Clean up the backups when done
                GeneralOperations.CleanRfaBackups(uiForm.adminFamiliesBAPFamilyDirectory);
            }
            uiForm.adminFamiliesBAPProgressBar.Visible = false;
            uiForm.adminFamiliesBAPDoneLabel.Visible   = true;
            uiForm.Update();
        }