Ejemplo n.º 1
0
        //Energy Analysis

        public void EnergyAnalysis()
        {
            // Collect space and surface data from the building's analytical thermal model
            EnergyAnalysisDetailModelOptions options = new EnergyAnalysisDetailModelOptions();

            options.Tier            = EnergyAnalysisDetailModelTier.Final; // include constructions, schedules, and non-graphical data in the computation of the energy analysis model
            options.EnergyModelType = EnergyModelType.SpatialElement;      // Energy model based on rooms or spaces
            options.EnergyModelType = EnergyModelType.BuildingElement;

            EnergyAnalysisDetailModel   eadm   = EnergyAnalysisDetailModel.Create(doc, options); // Create a new energy analysis detailed model from the physical model
            IList <EnergyAnalysisSpace> spaces = eadm.GetAnalyticalSpaces();
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("Spaces: " + spaces.Count);
            foreach (EnergyAnalysisSpace space in spaces)
            {
                SpatialElement spatialElement   = doc.GetElement(space.CADObjectUniqueId) as SpatialElement;
                ElementId      spatialElementId = spatialElement == null ? ElementId.InvalidElementId : spatialElement.Id;
                builder.AppendLine("   >>> " + space.SpaceName + " related to " + spatialElementId);
                IList <EnergyAnalysisSurface> surfaces = space.GetAnalyticalSurfaces();
                builder.AppendLine("       has " + surfaces.Count + " surfaces.");
                foreach (EnergyAnalysisSurface surface in surfaces)
                {
                    builder.AppendLine("            +++ Surface from " + surface.OriginatingElementDescription);
                }
            }
            TaskDialog.Show("EAM", builder.ToString());
        }
Ejemplo n.º 2
0
        public static bool TogbXML(this Document document, string path)
        {
            if (document == null || document.IsFamilyDocument || string.IsNullOrWhiteSpace(path))
            {
                return(false);
            }

            bool result = true;

            try
            {
                using (Transaction transaction = new Transaction(document, "Export gbXML"))
                {
                    transaction.Start();

                    EnergyAnalysisDetailModel energyAnalysisDetailModel = null;

                    using (SubTransaction subTransaction = new SubTransaction(document))
                    {
                        subTransaction.Start();
                        energyAnalysisDetailModel = EnergyAnalysisDetailModel.GetMainEnergyAnalysisDetailModel(document);
                        if (energyAnalysisDetailModel != null && energyAnalysisDetailModel.IsValidObject)
                        {
                            document.Delete(energyAnalysisDetailModel.Id);
                        }
                        subTransaction.Commit();
                    }

                    //Reseting Project Base Point
                    IEnumerable <Element> elements = new FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_ProjectBasePoint);
                    foreach (Element aElement in elements)
                    {
                        if (aElement.Pinned)
                        {
                            aElement.Pinned = false;
                        }

                        Parameter parameter = null;

                        parameter = aElement.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM);
                        if (parameter != null && !parameter.IsReadOnly)
                        {
                            parameter.Set(0.0);
                        }

                        parameter = aElement.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM);
                        if (parameter != null && !parameter.IsReadOnly)
                        {
                            parameter.Set(0.0);
                        }

                        parameter = aElement.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM);
                        if (parameter != null && !parameter.IsReadOnly)
                        {
                            parameter.Set(0.0);
                        }

                        parameter = aElement.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM);
                        if (parameter != null && !parameter.IsReadOnly)
                        {
                            parameter.Set(0.0);
                        }

                        parameter = aElement.get_Parameter(BuiltInParameter.BASEPOINT_ANGLETON_PARAM);
                        if (parameter != null && !parameter.IsReadOnly)
                        {
                            parameter.Set(0.0);
                        }
                    }


                    EnergyAnalysisDetailModelOptions energyAnalysisDetailModelOptions = new EnergyAnalysisDetailModelOptions();
                    energyAnalysisDetailModelOptions.Tier                   = EnergyAnalysisDetailModelTier.SecondLevelBoundaries;
                    energyAnalysisDetailModelOptions.EnergyModelType        = EnergyModelType.SpatialElement;
                    energyAnalysisDetailModelOptions.ExportMullions         = true;
                    energyAnalysisDetailModelOptions.IncludeShadingSurfaces = true;
                    energyAnalysisDetailModelOptions.SimplifyCurtainSystems = false;

                    EnergyDataSettings energyDataSettings = EnergyDataSettings.GetFromDocument(document);
                    energyDataSettings.ExportComplexity = gbXMLExportComplexity.ComplexWithMullionsAndShadingSurfaces;
                    energyDataSettings.ExportDefaults   = false;
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    energyDataSettings.SliverSpaceTolerance = UnitUtils.ConvertToInternalUnits(5, DisplayUnitType.DUT_MILLIMETERS);
#else
                    energyDataSettings.SliverSpaceTolerance = UnitUtils.ConvertToInternalUnits(5, UnitTypeId.Millimeters);
#endif

                    energyDataSettings.AnalysisType = AnalysisMode.BuildingElements;
                    energyDataSettings.EnergyModel  = false;

                    energyAnalysisDetailModel = EnergyAnalysisDetailModel.Create(document, energyAnalysisDetailModelOptions);

                    GBXMLExportOptions gBXMLExportOptions = new GBXMLExportOptions();
                    gBXMLExportOptions.ExportEnergyModelType = ExportEnergyModelType.SpatialElement;

                    if (!document.Export(System.IO.Path.GetDirectoryName(path), System.IO.Path.GetFileName(path), gBXMLExportOptions))
                    {
                        result = false;
                    }

                    transaction.RollBack();
                }
            }
            catch (System.Exception Exception)
            {
                result = false;
            }

            return(result);
        }
        /// <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;
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="doc">Revit Document</param>
 public EnergyAnalysisModel(Document doc)
 {
     RevitDoc  = doc;
     m_options = new EnergyAnalysisDetailModelOptions();
 }
        /// <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();
            }
        }
Ejemplo n.º 6
0
        /***************************************************/
        /****               Public Methods              ****/
        /***************************************************/

        public static List <IBHoMObject> EnergyAnalysisModelFromRevit(this EnergyAnalysisDetailModel energyAnalysisModel, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            if (energyAnalysisModel.Document.IsLinked)
            {
                BH.Engine.Reflection.Compute.RecordError($"It is not allowed to pull the energy analysis model from linked models - please open the document {energyAnalysisModel.Document.PathName} and pull directly from it instead.");
                return(null);
            }

            settings = settings.DefaultIfNull();

            ElementId          modelId = energyAnalysisModel.Id;
            List <IBHoMObject> result  = refObjects.GetValues <IBHoMObject>(energyAnalysisModel.Id);

            if (result != null)
            {
                return(result);
            }

            Document document = energyAnalysisModel.Document;

            ProjectInfo projectInfo = new FilteredElementCollector(document).OfClass(typeof(ProjectInfo)).FirstOrDefault() as ProjectInfo;

            if (projectInfo == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Project info of a document has not been found.");
            }
            else
            {
                projectInfo.BuildingFromRevit(settings, refObjects);
            }

            using (Transaction transaction = new Transaction(document, "GetAnalyticalModel"))
            {
                transaction.Start();

                FailureHandlingOptions failureHandlingOptions = transaction.GetFailureHandlingOptions();
                failureHandlingOptions.SetFailuresPreprocessor(new WarningSwallower());
                transaction.SetFailureHandlingOptions(failureHandlingOptions);

                EnergyAnalysisDetailModelOptions energyAnalysisDetailModelOptions = new EnergyAnalysisDetailModelOptions();
                energyAnalysisDetailModelOptions.Tier                   = EnergyAnalysisDetailModelTier.SecondLevelBoundaries;
                energyAnalysisDetailModelOptions.EnergyModelType        = EnergyModelType.SpatialElement;
                energyAnalysisDetailModelOptions.ExportMullions         = true;
                energyAnalysisDetailModelOptions.IncludeShadingSurfaces = true;
                energyAnalysisDetailModelOptions.SimplifyCurtainSystems = false;

                EnergyDataSettings energyDataSettings = EnergyDataSettings.GetFromDocument(document);
                energyDataSettings.ExportComplexity     = gbXMLExportComplexity.ComplexWithMullionsAndShadingSurfaces;
                energyDataSettings.ExportDefaults       = false;
                energyDataSettings.SliverSpaceTolerance = Convert.FromSI(0.005, UnitType.UT_Length);
                energyDataSettings.AnalysisType         = AnalysisMode.BuildingElements;
                energyDataSettings.EnergyModel          = false;

                //Reseting Project Base Point
                IEnumerable <Element> elements = new FilteredElementCollector(document).OfCategory(Autodesk.Revit.DB.BuiltInCategory.OST_ProjectBasePoint);
                foreach (Element element in elements)
                {
                    if (element.Pinned)
                    {
                        element.Pinned = false;
                    }

                    Parameter parameter = null;

                    parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM);
                    if (parameter != null && !parameter.IsReadOnly)
                    {
                        parameter.Set(0.0);
                    }

                    parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM);
                    if (parameter != null && !parameter.IsReadOnly)
                    {
                        parameter.Set(0.0);
                    }

                    parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM);
                    if (parameter != null && !parameter.IsReadOnly)
                    {
                        parameter.Set(0.0);
                    }

                    parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM);
                    if (parameter != null && !parameter.IsReadOnly)
                    {
                        parameter.Set(0.0);
                    }

                    parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_ANGLETON_PARAM);
                    if (parameter != null && !parameter.IsReadOnly)
                    {
                        parameter.Set(0.0);
                    }
                }

                //AnalyticalSpaces
                energyAnalysisModel = EnergyAnalysisDetailModel.Create(document, energyAnalysisDetailModelOptions);
                IList <EnergyAnalysisSpace> energyAnalysisSpaces = energyAnalysisModel.GetAnalyticalSpaces();
                Dictionary <string, EnergyAnalysisSurface> energyAnalsyisSurfaces = new Dictionary <string, EnergyAnalysisSurface>();
                foreach (EnergyAnalysisSpace energyAnalysisSpace in energyAnalysisSpaces)
                {
                    try
                    {
                        Space space = energyAnalysisSpace.SpaceFromRevit(settings, refObjects);

                        foreach (EnergyAnalysisSurface energyAnalysisSurface in energyAnalysisSpace.GetAnalyticalSurfaces())
                        {
                            if (!energyAnalsyisSurfaces.ContainsKey(energyAnalysisSurface.SurfaceName))
                            {
                                energyAnalsyisSurfaces.Add(energyAnalysisSurface.SurfaceName, energyAnalysisSurface);
                            }
                        }
                    }
                    catch
                    {
                        energyAnalysisSpace.ElementCouldNotBeQueriedWarning();
                    }
                }

                //EnergyAnalysisSurfaces
                foreach (KeyValuePair <string, EnergyAnalysisSurface> kvp in energyAnalsyisSurfaces)
                {
                    try
                    {
                        oM.Environment.Elements.Panel panel = kvp.Value.EnvironmentPanelFromRevit(settings, refObjects);

                        List <IBHoMObject> hostedBHoMObjects = new List <IBHoMObject>();
                        foreach (EnergyAnalysisOpening energyAnalysisOpening in kvp.Value.GetAnalyticalOpenings())
                        {
                            oM.Environment.Elements.Opening opening = energyAnalysisOpening.OpeningFromRevit(settings, refObjects);
                            panel.Openings.Add(opening);
                        }
                    }
                    catch
                    {
                        kvp.Value.ElementCouldNotBeQueriedWarning();
                    }
                }

                //AnalyticalShadingSurfaces
                IList <EnergyAnalysisSurface> analyticalShadingSurfaces = energyAnalysisModel.GetAnalyticalShadingSurfaces();
                foreach (EnergyAnalysisSurface energyAnalysisSurface in analyticalShadingSurfaces)
                {
                    try
                    {
                        oM.Environment.Elements.Panel panel = energyAnalysisSurface.EnvironmentPanelFromRevit(settings, refObjects);

                        List <IBHoMObject> hostedBHoMObjects = new List <IBHoMObject>();
                        foreach (EnergyAnalysisOpening energyOpening in energyAnalysisSurface.GetAnalyticalOpenings())
                        {
                            oM.Environment.Elements.Opening opening = energyOpening.OpeningFromRevit(settings, refObjects);
                            panel.Openings.Add(opening);
                        }
                    }
                    catch
                    {
                        energyAnalysisSurface.ElementCouldNotBeQueriedWarning();
                    }
                }

                transaction.RollBack();
            }

            //Levels
            IEnumerable <Level> levels = new FilteredElementCollector(document).OfClass(typeof(Level)).Cast <Level>();

            foreach (Level level in levels)
            {
                level.LevelFromRevit(settings, refObjects);
            }

            result = new List <IBHoMObject>();
            foreach (List <IBHoMObject> bhomObjects in refObjects.Values)
            {
                if (bhomObjects != null)
                {
                    result.AddRange(bhomObjects);
                }
            }

            refObjects.AddOrReplace(modelId, result);
            return(result);
        }
        /// <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();
            }
        }
        public static Dictionary<string, object> CreateByMassLevels(AbstractFamilyInstance MassFamilyInstance, List<Revit.Elements.Element> Levels)
        {
            //local varaibles
            Document RvtDoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument.Document;
            EnergyAnalysisDetailModel em = null;

            #region Mass Floors and Energy Model
            //create mass floors
            try
            {
                TransactionManager.Instance.EnsureInTransaction(RvtDoc);
                foreach (var l in Levels)
                {
                    MassInstanceUtils.AddMassLevelDataToMassInstance(RvtDoc, MassFamilyInstance.InternalElement.Id, l.InternalElement.Id);
                }
                TransactionManager.Instance.TransactionTaskDone();
            }
            catch (Exception)
            {
                throw new Exception("Something went wrong when trying to create mass floors.");
            }

            //enable the analytical model in the document if it isn't already
            try
            {
                ActivateEnergyModel(RvtDoc);
            }
            catch (Exception)
            {
                throw new Exception("Something went wrong when trying to enable the energy model.");
            }

            //try to create an energy analysis model in the document
            try
            {
                TransactionManager.Instance.EnsureInTransaction(RvtDoc);
                EnergyAnalysisDetailModelOptions opt = new EnergyAnalysisDetailModelOptions();
                opt.Tier = EnergyAnalysisDetailModelTier.NotComputed;
                em = EnergyAnalysisDetailModel.Create(RvtDoc, opt);
                TransactionManager.Instance.TransactionTaskDone();
                DocumentManager.Regenerate();
            }
            catch (Exception)
            {
                throw new Exception("Something went wrong when trying to create an energy model from your mass.");
            }
            #endregion

            #region Output Zone and Surface IDs
            //ok now we should be able to get all of the zones and surfaces associated
            //with our mass, and output them for use downstream

            //get the id of the analytical model associated with that mass
            Autodesk.Revit.DB.ElementId myEnergyModelId = MassEnergyAnalyticalModel.GetMassEnergyAnalyticalModelIdForMassInstance(RvtDoc, MassFamilyInstance.InternalElement.Id);
            MassEnergyAnalyticalModel mea = (MassEnergyAnalyticalModel)RvtDoc.GetElement(myEnergyModelId);

            //if mea is null, we should throw a good error message.  Seems to be working in Revit now that we are regenerating.
            if (mea == null)
            {
                throw new Exception("Could not get the MassEnergyAnalyticalModel from the mass.");
            }

            //get the zone ids from our Mass's MassEnergyAnalyticalModel object
            //we'll use these to draw zones in another component - not sure if we can use them to drive opening / shading params
            List<Autodesk.Revit.DB.ElementId> zoneIds = mea.GetMassZoneIds().ToList();
            //loop over the output lists, and wrap them in our ElementId wrapper class
            List<ElementId> outZoneIds = zoneIds.Select(e => new ElementId(e.IntegerValue)).ToList();

            #endregion

            return new Dictionary<string, object>
            {
                {"MassFamilyInstance", MassFamilyInstance},
                {"ZoneIds", outZoneIds}
            };
        }
        public static Dictionary <string, object> CreateEnergyModelFromMassAndLevels(AbstractFamilyInstance MassFamilyInstance, List <Revit.Elements.Element> Levels)
        {
            //local varaibles
            Document RvtDoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument.Document;
            EnergyAnalysisDetailModel em = null;

            #region Mass Floors and Energy Model
            //create mass floors
            try
            {
                TransactionManager.Instance.EnsureInTransaction(RvtDoc);
                foreach (var l in Levels)
                {
                    MassInstanceUtils.AddMassLevelDataToMassInstance(RvtDoc, MassFamilyInstance.InternalElement.Id, l.InternalElement.Id);
                }
                TransactionManager.Instance.TransactionTaskDone();
            }
            catch (Exception)
            {
                throw new Exception("Something went wrong when trying to create mass floors.");
            }

            //enable the analytical model in the document if it isn't already
            try
            {
                ActivateEnergyModel(RvtDoc);
            }
            catch (Exception)
            {
                throw new Exception("Something went wrong when trying to enable the energy model.");
            }

            //try to create an energy analysis model in the document
            try
            {
                TransactionManager.Instance.EnsureInTransaction(RvtDoc);
                EnergyAnalysisDetailModelOptions opt = new EnergyAnalysisDetailModelOptions();
                opt.Tier = EnergyAnalysisDetailModelTier.NotComputed;
                em       = EnergyAnalysisDetailModel.Create(RvtDoc, opt);
                TransactionManager.Instance.TransactionTaskDone();
                DocumentManager.Regenerate();
            }
            catch (Exception)
            {
                throw new Exception("Something went wrong when trying to create an energy model from your mass.");
            }
            #endregion

            #region Output Zone and Surface IDs
            //ok now we should be able to get all of the zones and surfaces associated
            //with our mass, and output them for use downstream


            //get the id of the analytical model associated with that mass
            Autodesk.Revit.DB.ElementId myEnergyModelId = MassEnergyAnalyticalModel.GetMassEnergyAnalyticalModelIdForMassInstance(RvtDoc, MassFamilyInstance.InternalElement.Id);
            MassEnergyAnalyticalModel   mea             = (MassEnergyAnalyticalModel)RvtDoc.GetElement(myEnergyModelId);

            //if mea is null, we should throw a good error message.  Seems to be working in Revit now that we are regenerating.
            if (mea == null)
            {
                throw new Exception("Could not get the MassEnergyAnalyticalModel from the mass.");
            }

            //get the zone ids from our Mass's MassEnergyAnalyticalModel object
            //we'll use these to draw zones in another component - not sure if we can use them to drive opening / shading params
            List <Autodesk.Revit.DB.ElementId> zoneIds = mea.GetMassZoneIds().ToList();
            //loop over the output lists, and wrap them in our ElementId wrapper class
            List <ElementId> outZoneIds = zoneIds.Select(e => new ElementId(e.IntegerValue)).ToList();

            List <ElementId> outWallSurfaceIds = Helper.GetSurfaceIdsFromMassEnergyAnalyticalModelBasedOnType(mea, "Mass Exterior Wall");
            List <ElementId> outRoofSurfaceIds = Helper.GetSurfaceIdsFromMassEnergyAnalyticalModelBasedOnType(mea, "Mass Roof");

            #endregion

            return(new Dictionary <string, object>
            {
                { "MassFamilyInstance", MassFamilyInstance },
                { "ZoneIds", outZoneIds },
                { "WallSurfaceIds", outWallSurfaceIds },
                { "RoofSurfaceIds", outRoofSurfaceIds }
            });
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="doc">Revit Document</param>
 public EnergyAnalysisModel(Document doc)
 {
     RevitDoc = doc;
     m_options = new EnergyAnalysisDetailModelOptions();
 }
Ejemplo n.º 11
0
        public static AnalyticalModel ToSAM_AnalyticalModel(this Document document, ConvertSettings convertSettings)
        {
            if (document == null)
            {
                return(null);
            }

            ProjectInfo projectInfo = document.ProjectInformation;

            AnalyticalModel result = convertSettings?.GetObject <AnalyticalModel>(projectInfo?.Id);

            if (result != null)
            {
                return(result);
            }

            Core.Location location = Core.Revit.Query.Location(document);
            Address       address  = null;

            if (projectInfo != null)
            {
                address = new Address(Guid.NewGuid(), projectInfo.BuildingName, projectInfo.Address, null, null, CountryCode.Undefined);
            }

            AdjacencyCluster adjacencyCluster = new AdjacencyCluster();

            EnergyAnalysisDetailModelOptions energyAnalysisDetailModelOptions = new EnergyAnalysisDetailModelOptions();

            energyAnalysisDetailModelOptions.Tier                   = EnergyAnalysisDetailModelTier.SecondLevelBoundaries;
            energyAnalysisDetailModelOptions.EnergyModelType        = EnergyModelType.SpatialElement;
            energyAnalysisDetailModelOptions.ExportMullions         = true;
            energyAnalysisDetailModelOptions.IncludeShadingSurfaces = true;
            energyAnalysisDetailModelOptions.SimplifyCurtainSystems = false;

            EnergyDataSettings energyDataSettings = EnergyDataSettings.GetFromDocument(document);

            energyDataSettings.ExportComplexity = gbXMLExportComplexity.ComplexWithMullionsAndShadingSurfaces;
            energyDataSettings.ExportDefaults   = false;
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
            energyDataSettings.SliverSpaceTolerance = UnitUtils.ConvertToInternalUnits(0.005, DisplayUnitType.DUT_METERS);
#else
            energyDataSettings.SliverSpaceTolerance = UnitUtils.ConvertToInternalUnits(0.005, UnitTypeId.Meters);
#endif
            energyDataSettings.AnalysisType = AnalysisMode.BuildingElements;
            energyDataSettings.EnergyModel  = false;

            //Reseting Project Base Point
            IEnumerable <Element> elements = new FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_ProjectBasePoint);
            foreach (Element element in elements)
            {
                if (element.Pinned)
                {
                    element.Pinned = false;
                }

                Parameter parameter = null;

                parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM);
                if (parameter != null && !parameter.IsReadOnly)
                {
                    parameter.Set(0.0);
                }

                parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM);
                if (parameter != null && !parameter.IsReadOnly)
                {
                    parameter.Set(0.0);
                }

                parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM);
                if (parameter != null && !parameter.IsReadOnly)
                {
                    parameter.Set(0.0);
                }

                parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM);
                if (parameter != null && !parameter.IsReadOnly)
                {
                    parameter.Set(0.0);
                }

                parameter = element.get_Parameter(BuiltInParameter.BASEPOINT_ANGLETON_PARAM);
                if (parameter != null && !parameter.IsReadOnly)
                {
                    parameter.Set(0.0);
                }
            }

            //AnalyticalSpaces
            EnergyAnalysisDetailModel   energyAnalysisDetailModel         = EnergyAnalysisDetailModel.Create(document, energyAnalysisDetailModelOptions);
            IList <EnergyAnalysisSpace> energyAnalysisSpaces              = energyAnalysisDetailModel.GetAnalyticalSpaces();
            Dictionary <string, Tuple <Panel, List <Space> > > dictionary = new Dictionary <string, Tuple <Panel, List <Space> > >();
            foreach (EnergyAnalysisSpace energyAnalysisSpace in energyAnalysisSpaces)
            {
                try
                {
                    if (energyAnalysisSpace.Area <= Core.Tolerance.MacroDistance)
                    {
                        continue;
                    }

                    Space space = energyAnalysisSpace.ToSAM(convertSettings);
                    if (space == null)
                    {
                        continue;
                    }

                    Shell shell = Geometry.Revit.Convert.ToSAM(energyAnalysisSpace.GetClosedShell());
                    if (shell == null)
                    {
                        continue;
                    }

                    adjacencyCluster.AddObject(space);

                    foreach (EnergyAnalysisSurface energyAnalysisSurface in energyAnalysisSpace.GetAnalyticalSurfaces())
                    {
                        Tuple <Panel, List <Space> > tuple;
                        if (!dictionary.TryGetValue(energyAnalysisSurface.SurfaceName, out tuple))
                        {
                            Panel panel = energyAnalysisSurface.ToSAM(convertSettings, shell);
                            if (panel == null)
                            {
                                continue;
                            }

                            tuple = new Tuple <Panel, List <Space> >(panel, new List <Space>());
                            dictionary[energyAnalysisSurface.SurfaceName] = tuple;
                        }

                        tuple.Item2.Add(space);
                    }
                }
                catch
                {
                }
            }

            #region Additional Checks (WIP)
            //Additional Check for wrongly recoginzed internal panels (WIP)
            List <Tuple <string, Panel, Space, Face3D> > tuples_External = new List <Tuple <string, Panel, Space, Face3D> >();
            foreach (KeyValuePair <string, Tuple <Panel, List <Space> > > keyValuePair in dictionary)
            {
                Tuple <Panel, List <Space> > tuple = keyValuePair.Value;
                if (tuple.Item1 != null && tuple.Item2 != null && tuple.Item2.Count == 1)
                {
                    Face3D face3D = tuple.Item1.GetFace3D();
                    if (face3D != null)
                    {
                        tuples_External.Add(new Tuple <string, Panel, Space, Face3D>(keyValuePair.Key, tuple.Item1, tuple.Item2[0], face3D));
                    }
                }
            }

            while (tuples_External.Count > 0)
            {
                Tuple <string, Panel, Space, Face3D> tuple = tuples_External[0];
                tuples_External.RemoveAt(0);

                Point3D point3D = tuple.Item4.InternalPoint3D();
                if (point3D == null)
                {
                    continue;
                }

                List <Tuple <string, Panel, Space, Face3D> > tuples_Overlap = tuples_External.FindAll(x => x.Item4.Inside(point3D));
                if (tuples_Overlap.Count != 1)
                {
                    continue;
                }

                tuples_Overlap.Add(tuple);

                tuples_Overlap.Sort((x, y) => y.Item4.GetArea().CompareTo(x.Item4.GetArea()));

                tuple = tuples_Overlap[0];
                Tuple <string, Panel, Space, Face3D> tuple_Overlap = tuples_Overlap[1];

                dictionary[tuple.Item1].Item2.Add(tuple_Overlap.Item3);
                dictionary[tuple_Overlap.Item1] = new Tuple <Panel, List <Space> >(Analytical.Create.Panel(dictionary[tuple_Overlap.Item1].Item1, PanelType.Shade), null);
                int index = tuples_External.IndexOf(tuple_Overlap);
                if (index != -1)
                {
                    tuples_External.RemoveAt(index);
                }
            }
            #endregion

            foreach (Tuple <Panel, List <Space> > tuple in dictionary.Values)
            {
                Panel panel = tuple.Item1;

                adjacencyCluster.AddObject(panel);
                tuple.Item2?.ForEach(x => adjacencyCluster.AddRelation(x, panel));
            }

            //AnalyticalShadingSurfaces
            IList <EnergyAnalysisSurface> analyticalShadingSurfaces = energyAnalysisDetailModel.GetAnalyticalShadingSurfaces();
            foreach (EnergyAnalysisSurface energyAnalysisSurface in analyticalShadingSurfaces)
            {
                try
                {
                    Panel panel = energyAnalysisSurface.ToSAM(convertSettings);
                    if (panel == null)
                    {
                        continue;
                    }

                    panel = Analytical.Create.Panel(panel, PanelType.Shade);

                    adjacencyCluster.AddObject(panel);
                }
                catch
                {
                }
            }

            adjacencyCluster.MapZones();

            IEnumerable <IMaterial> materials       = Analytical.Query.Materials(adjacencyCluster, Analytical.ActiveSetting.Setting.GetValue <MaterialLibrary>(AnalyticalSettingParameter.DefaultMaterialLibrary));
            MaterialLibrary         materialLibrary = Core.Create.MaterialLibrary("Default Material Library", materials);

            IEnumerable <Profile> profiles       = Analytical.Query.Profiles(adjacencyCluster, Analytical.ActiveSetting.Setting.GetValue <ProfileLibrary>(AnalyticalSettingParameter.DefaultProfileLibrary));
            ProfileLibrary        profileLibrary = new ProfileLibrary("Default Profile Library", profiles);

            result = new AnalyticalModel(document.Title, null, location, address, adjacencyCluster, materialLibrary, profileLibrary);
            result.UpdateParameterSets(document.ProjectInformation, ActiveSetting.Setting.GetValue <TypeMap>(Core.Revit.ActiveSetting.Name.ParameterMap));

            convertSettings?.Add(projectInfo.Id, result);

            return(result);
        }