示例#1
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="dataAccess">
        /// The DA object is used to retrieve from inputs and store in outputs.
        /// </param>
        protected override void SolveInstance(IGH_DataAccess dataAccess)
        {
            GH_ObjectWrapper objectWrapper = null;

            if (!dataAccess.GetData(0, ref objectWrapper) || objectWrapper.Value == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Invalid data");
                return;
            }

            Autodesk.Revit.DB.Level level = null;

            Document document = RhinoInside.Revit.Revit.ActiveDBDocument;

            if (document == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cannot access Revit Document");
                return;
            }

            dynamic obj = objectWrapper.Value;

            if (obj is GH_Integer)
            {
                ElementId elementId = new ElementId(((GH_Integer)obj).Value);
                if (elementId == null || elementId == ElementId.InvalidElementId)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cannot access Element");
                    return;
                }
                level = document.GetElement(elementId) as Autodesk.Revit.DB.Level;
            }
            else if (obj is GH_String)
            {
                string @string = ((GH_String)obj).Value;
                if (@string.Length > 37)
                {
                    @string = @string.Substring(37);
                }

                level = document.GetElement(@string) as Autodesk.Revit.DB.Level;
            }
            else if (obj.GetType().GetProperty("Id") != null)
            {
                ElementId aId = obj.Id as ElementId;
                level = document.GetElement(aId) as Autodesk.Revit.DB.Level;
            }

            if (level == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Cannot access Level");
                return;
            }

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

            Autodesk.Revit.DB.Level level_High = Core.Revit.Query.HighLevel(level);
            double elevation_High = double.NaN;

            if (level_High != null)
            {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                elevation_High = UnitUtils.ConvertFromInternalUnits(level_High.Elevation, DisplayUnitType.DUT_METERS);
#else
                elevation_High = UnitUtils.ConvertFromInternalUnits(level_High.Elevation, UnitTypeId.Meters);
#endif
            }


            Autodesk.Revit.DB.Level level_Low = Core.Revit.Query.LowLevel(level);
            double elevation_Low = double.NaN;
            if (level_Low != null)
            {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                elevation_Low = UnitUtils.ConvertFromInternalUnits(level_Low.Elevation, DisplayUnitType.DUT_METERS);
#else
                elevation_Low = UnitUtils.ConvertFromInternalUnits(level_Low.Elevation, UnitTypeId.Meters);
#endif
            }

            dataAccess.SetData(0, level_High);
            dataAccess.SetData(1, new GH_Number(elevation_High));
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
            dataAccess.SetData(2, new GH_Number(UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS)));
#else
            dataAccess.SetData(2, new GH_Number(UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters)));
#endif

            dataAccess.SetData(3, level_Low);
            dataAccess.SetData(4, new GH_Number(elevation_Low));
        }
示例#2
0
        public bool ConstructSVLCenterlineDXFAlignment(NFFGuidableAlignmentEntity alignment,
                                                       out DesignProfilerRequestResult calcResult, out MemoryStream ms)
        {
            ms = null;
            if ((calcResult = Validate(alignment)) != DesignProfilerRequestResult.OK)
            {
                return(false);
            }

            DXF = new DXFFile();
            DXF.Layers.Add("B");

            // Run through the entities in the alignment and add them to the DXF file
            for (var I = 0; I < alignment.Entities.Count; I++)
            {
                AddEntityToDXF(alignment.Entities[I]);
            }

            // Construct the stationing text entities along the alignment
            var StationIncrement = AlignmentLabelingInterval;
            var CurrentStation   = alignment.StartStation;

            while (CurrentStation <= alignment.EndStation + 0.001)
            {
                alignment.ComputeXY(CurrentStation, 0, out var X1, out var Y1);
                alignment.ComputeXY(CurrentStation, -1, out var X2, out var Y2);

                GeometryUtils.RectToPolar(Y1, X1, Y2, X2, out var textOrientation, out _);

                DXF.Entities.Add(new DXFTextEntity("B",
                                                   kAlignmentCenterLineColor,
                                                   X1, Y1, Consts.NullDouble,
                                                   $"{CurrentStation / UnitUtils.DistToMeters(Units):F2}",
                                                   textOrientation - (Math.PI / 2),
                                                   2,
                                                   "Arial",
                                                   //[],
                                                   //0,
                                                   0, 0));

                if (CurrentStation + StationIncrement <= alignment.EndStation)
                {
                    CurrentStation = CurrentStation + StationIncrement;
                }
                else if (CurrentStation > alignment.EndStation - 0.001)
                {
                    break;
                }
                else
                {
                    CurrentStation = alignment.EndStation;
                }
            }

            if (DXF.Entities.Count > 0)
            {
                ms = new MemoryStream();
                using var writer = new StreamWriter(ms);
                DXF.SaveToFile(writer);
            }

            calcResult = DesignProfilerRequestResult.OK;

            return(true);
        }
示例#3
0
 public static double DXFDistance(double value, DistanceUnitsType outputUnits)
 {
     // Takes a value in SI units (ie: meters) and converts it to the project units for writing out to a DXF file
     return(value / UnitUtils.DistToMeters(outputUnits));
 }
        /// <summary>
        /// Generate Viewpoint
        /// </summary>
        /// <param name="elemCheck"></param>
        /// <returns></returns>
        private VisualizationInfo generateViewpoint(int elemCheck)
        {
            try
            {
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                VisualizationInfo v = new VisualizationInfo();

                XYZ    centerIMP = new XYZ();
                string type      = "";
                double zoomValue = 1;

                if (uidoc.ActiveView.ViewType != ViewType.ThreeD) //is a 2D view
                {
                    XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                    XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];
                    v.SheetCamera             = new SheetCamera();
                    v.SheetCamera.SheetID     = uidoc.ActiveView.Id.IntegerValue;
                    v.SheetCamera.TopLeft     = new IssueTracker.Data.Point(TL.X, TL.Y, TL.Z);
                    v.SheetCamera.BottomRight = new IssueTracker.Data.Point(BR.X, BR.Y, BR.Z);
                }
                else
                {
                    View3D view3D = (View3D)uidoc.ActiveView;
                    if (!view3D.IsPerspective) //IS ORTHO
                    {
                        XYZ TL = uidoc.GetOpenUIViews()[0].GetZoomCorners()[0];
                        XYZ BR = uidoc.GetOpenUIViews()[0].GetZoomCorners()[1];

                        double xO = (TL.X + BR.X) / 2;
                        double yO = (TL.Y + BR.Y) / 2;
                        double zO = (TL.Z + BR.Z) / 2;
                        //converto to METERS
                        centerIMP = new XYZ(xO, yO, zO);
                        double dist            = TL.DistanceTo(BR) / 2; //custom value to get solibri zoom value from Corners of Revit UiView
                        XYZ    diagVector      = TL.Subtract(BR);
                        double customZoomValue = (ProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;

                        zoomValue = UnitUtils.ConvertFromInternalUnits(dist * Math.Sin(diagVector.AngleTo(view3D.RightDirection)), DisplayUnitType.DUT_METERS) * customZoomValue;
                        type      = "OrthogonalCamera";
                    }
                    else // it is a perspective view
                    {
                        centerIMP = uidoc.ActiveView.Origin;
                        type      = "PerspectiveCamera";
                        zoomValue = 45;
                    }
                    ViewOrientation3D t = ConvertBasePoint(centerIMP, uidoc.ActiveView.ViewDirection, uidoc.ActiveView.UpDirection, false);
                    XYZ c  = t.EyePosition;
                    XYZ vi = t.ForwardDirection;
                    XYZ up = t.UpDirection;

                    if (type == "OrthogonalCamera")
                    {
                        v.OrthogonalCamera = new OrthogonalCamera();
                        v.OrthogonalCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.OrthogonalCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.OrthogonalCamera.ViewToWorldScale  = zoomValue;
                    }
                    else
                    {
                        v.PerspectiveCamera = new PerspectiveCamera();
                        v.PerspectiveCamera.CameraViewPoint.X = UnitUtils.ConvertFromInternalUnits(c.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Y = UnitUtils.ConvertFromInternalUnits(c.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraViewPoint.Z = UnitUtils.ConvertFromInternalUnits(c.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.X  = UnitUtils.ConvertFromInternalUnits(up.X, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Y  = UnitUtils.ConvertFromInternalUnits(up.Y, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraUpVector.Z  = UnitUtils.ConvertFromInternalUnits(up.Z, DisplayUnitType.DUT_METERS);
                        v.PerspectiveCamera.CameraDirection.X = UnitUtils.ConvertFromInternalUnits(vi.X, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Y = UnitUtils.ConvertFromInternalUnits(vi.Y, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.CameraDirection.Z = UnitUtils.ConvertFromInternalUnits(vi.Z, DisplayUnitType.DUT_METERS) * -1;
                        v.PerspectiveCamera.FieldOfView       = zoomValue;
                    }
                }


                //COMPONENTS PART
                FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                System.Collections.Generic.ICollection <ElementId> collection = null;

                if (elemCheck == 0)
                {
                    collection = collector.ToElementIds();
                }
                else if (elemCheck == 1)
                {
                    collection = uidoc.Selection.GetElementIds();
                }

                if (null != collection && collection.Any())
                {
                    v.Components = new IssueTracker.Data.Component[collection.Count];
                    for (var i = 0; i < collection.Count; i++)
                    {
                        Guid   guid    = ExportUtils.GetExportId(doc, collection.ElementAt(i));
                        string ifcguid = IfcGuid.ToIfcGuid(guid).ToString();
                        ;
                        v.Components[i] = new Case.IssueTracker.Data.Component(doc.Application.VersionName, collection.ElementAt(i).ToString(), ifcguid);
                    }
                }

                return(v);
            }
            catch (System.Exception ex1)
            {
                TaskDialog.Show("Error!", "exception: " + ex1);
            }
            return(null);
        }
示例#5
0
 private double ScaleToNative(double value, DisplayUnitType units)
 {
     return(UnitUtils.ConvertToInternalUnits(value, units));
 }
示例#6
0
        // TODO: Wall to Speckle
        // TODO: Set levels, heights, etc.
        // Does not go through nicely from revit to revit
        public static SpeckleElementsClasses.Wall ToSpeckle(this Autodesk.Revit.DB.Wall myWall)
        {
            var speckleWall = new SpeckleElementsClasses.Wall();

            speckleWall.baseCurve = SpeckleCore.Converter.Serialise(((LocationCurve)myWall.Location).Curve) as SpeckleObject;

            var heightParam = myWall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);
            var heightValue = heightParam.AsDouble();
            var height      = UnitUtils.ConvertFromInternalUnits(heightValue, heightParam.DisplayUnitType);

            speckleWall.height = heightValue / Scale;

            var offsetParam = myWall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
            var offsetValue = offsetParam.AsDouble();
            var offset      = UnitUtils.ConvertFromInternalUnits(offsetValue, offsetParam.DisplayUnitType);

            speckleWall.offset = offsetValue / Scale;

            speckleWall.wallType = myWall.WallType.Name;

            var level = (Level)Doc.GetElement(myWall.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT).AsElementId());

            speckleWall.baseLevel = level.ToSpeckle();

            try
            {
                var topLevel = (Level)Doc.GetElement(myWall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE).AsElementId());
                speckleWall.topLevel = topLevel.ToSpeckle();
            }
            catch (Exception e) { }

            speckleWall.parameters     = GetElementParams(myWall);
            speckleWall.typeParameters = GetElementTypeParams(myWall);

            var grid = myWall.CurtainGrid;

            // TODO: Should move maybe in base class defintion
            speckleWall.Properties["__flipped"] = myWall.Flipped;

            speckleWall.ApplicationId = myWall.UniqueId;
            speckleWall.elementId     = myWall.Id.ToString();
            speckleWall.GenerateHash();

            // meshing for walls in case they are curtain grids
            if (grid != null)
            {
                var mySolids = new List <Solid>();
                foreach (ElementId panelId in grid.GetPanelIds())
                {
                    mySolids.AddRange(GetElementSolids(Doc.GetElement(panelId)));
                }
                foreach (ElementId mullionId in grid.GetMullionIds())
                {
                    mySolids.AddRange(GetElementSolids(Doc.GetElement(mullionId)));
                }
                (speckleWall.Faces, speckleWall.Vertices) = GetFaceVertexArrFromSolids(mySolids);
            }
            else
            {
                (speckleWall.Faces, speckleWall.Vertices) = GetFaceVertexArrayFromElement(myWall, new Options()
                {
                    DetailLevel = ViewDetailLevel.Fine, ComputeReferences = false
                });
            }

            return(speckleWall);
        }
示例#7
0
        /// <summary>
        /// Given the filter in use by a stream returns the document elements that match it.
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        private List <Element> GetSelectionFilterObjects(ISelectionFilter filter)
        {
            var doc = CurrentDoc.Document;

            var selection = new List <Element>();

            switch (filter.Name)
            {
            case "Category":
                var catFilter  = filter as ListSelectionFilter;
                var bics       = new List <BuiltInCategory>();
                var categories = ConnectorRevitUtils.GetCategories(doc);
                IList <ElementFilter> elementFilters = new List <ElementFilter>();

                foreach (var cat in catFilter.Selection)
                {
                    elementFilters.Add(new ElementCategoryFilter(categories[cat].Id));
                }

                var categoryFilter = new LogicalOrFilter(elementFilters);

                selection = new FilteredElementCollector(doc)
                            .WhereElementIsNotElementType()
                            .WhereElementIsViewIndependent()
                            .WherePasses(categoryFilter).ToList();
                return(selection);

            case "View":
                var viewFilter = filter as ListSelectionFilter;

                var views = new FilteredElementCollector(doc)
                            .WhereElementIsNotElementType()
                            .OfClass(typeof(View))
                            .Where(x => viewFilter.Selection.Contains(x.Name));

                foreach (var view in views)
                {
                    var ids = selection.Select(x => x.UniqueId);

                    var viewElements = new FilteredElementCollector(doc, view.Id)
                                       .WhereElementIsNotElementType()
                                       .WhereElementIsViewIndependent()
                                       .Where(x => x.IsPhysicalElement())
                                       .Where(x => !ids.Contains(x.UniqueId)) //exclude elements already added from other views
                                       .ToList();

                    selection.AddRange(viewElements);
                }
                return(selection);

            case "Project Info":
                var projectInfoFilter = filter as ListSelectionFilter;

                if (projectInfoFilter.Selection.Contains("Project Info"))
                {
                    selection.Add(doc.ProjectInformation);
                }

                if (projectInfoFilter.Selection.Contains("Views 2D"))
                {
                    selection.AddRange(new FilteredElementCollector(doc)
                                       .WhereElementIsNotElementType()
                                       .OfCategory(BuiltInCategory.OST_Views)
                                       .Cast <View>()
                                       .Where(x => x.ViewType == ViewType.CeilingPlan ||
                                              x.ViewType == ViewType.FloorPlan ||
                                              x.ViewType == ViewType.Elevation ||
                                              x.ViewType == ViewType.Section)
                                       .ToList());
                }

                if (projectInfoFilter.Selection.Contains("Views 3D"))
                {
                    selection.AddRange(new FilteredElementCollector(doc)
                                       .WhereElementIsNotElementType()
                                       .OfCategory(BuiltInCategory.OST_Views)
                                       .Cast <View>()
                                       .Where(x => x.ViewType == ViewType.ThreeD)
                                       .ToList());
                }

                if (projectInfoFilter.Selection.Contains("Levels"))
                {
                    selection.AddRange(new FilteredElementCollector(doc)
                                       .WhereElementIsNotElementType()
                                       .OfCategory(BuiltInCategory.OST_Levels).ToList());
                }

                if (projectInfoFilter.Selection.Contains("Families & Types"))
                {
                    //get all the elementtypes of the categories we support
                    var allCategoryFilter = new LogicalOrFilter(ConnectorRevitUtils.GetCategories(doc).Select(x => new ElementCategoryFilter(x.Value.Id)).Cast <ElementFilter>().ToList());

                    selection.AddRange(new FilteredElementCollector(doc)
                                       .WhereElementIsElementType()
                                       .WherePasses(allCategoryFilter).ToList());
                }
                return(selection);

            case "Parameter":
                try
                {
                    var propFilter = filter as PropertySelectionFilter;
                    var query      = new FilteredElementCollector(doc)
                                     .WhereElementIsNotElementType()
                                     .WhereElementIsNotElementType()
                                     .WhereElementIsViewIndependent()
                                     .Where(x => x.IsPhysicalElement())
                                     .Where(fi => fi.LookupParameter(propFilter.PropertyName) != null);

                    propFilter.PropertyValue = propFilter.PropertyValue.ToLowerInvariant();

                    switch (propFilter.PropertyOperator)
                    {
                    case "equals":
                        query = query.Where(fi =>
                                            GetStringValue(fi.LookupParameter(propFilter.PropertyName)) == propFilter.PropertyValue);
                        break;

                    case "contains":
                        query = query.Where(fi =>
                                            GetStringValue(fi.LookupParameter(propFilter.PropertyName)).Contains(propFilter.PropertyValue));
                        break;

                    case "is greater than":
                        query = query.Where(fi => UnitUtils.ConvertFromInternalUnits(
                                                fi.LookupParameter(propFilter.PropertyName).AsDouble(),
                                                fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) >
                                            double.Parse(propFilter.PropertyValue));
                        break;

                    case "is less than":
                        query = query.Where(fi => UnitUtils.ConvertFromInternalUnits(
                                                fi.LookupParameter(propFilter.PropertyName).AsDouble(),
                                                fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) <
                                            double.Parse(propFilter.PropertyValue));
                        break;
                    }

                    selection = query.ToList();
                }
                catch (Exception e)
                {
                    Log.CaptureException(e);
                }
                return(selection);
            }

            return(selection);
        }
示例#8
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="revit">The revit application.</param>
        public STLExportForm(Autodesk.Revit.UI.UIApplication revit)
        {
            InitializeComponent();
            m_Revit = revit;

            // get new data generator
            m_Generator = new DataGenerator(m_Revit.Application, m_Revit.ActiveUIDocument.Document, m_Revit.ActiveUIDocument.Document.ActiveView);

            // scan for categories to populate category list
            m_CategoryList = m_Generator.ScanCategories(true);

            foreach (Category category in m_CategoryList.Values)
            {
                TreeNode treeNode = GetChildNode(category, m_Revit.ActiveUIDocument.Document.ActiveView);
                if (treeNode != null)
                {
                    tvCategories.Nodes.Add(treeNode);
                }
            }

            string unitName = "Use Internal: Feet";

            m_DisplayUnits.Add(unitName, DisplayUnitType.DUT_UNDEFINED);
            int selectedIndex = comboBox_DUT.Items.Add(unitName);

            if (m_SelectedDUT == DisplayUnitType.DUT_UNDEFINED)
            {
                comboBox_DUT.SelectedIndex = selectedIndex;
            }

            Units           currentUnits = m_Revit.ActiveUIDocument.Document.GetUnits();
            DisplayUnitType currentDut   = currentUnits.GetFormatOptions(UnitType.UT_Length).DisplayUnits;

            unitName = "Use Current: " + LabelUtils.GetLabelFor(currentDut);
            m_DisplayUnits.Add(unitName, currentDut);
            selectedIndex = comboBox_DUT.Items.Add(unitName);
            if (m_SelectedDUT == currentDut)
            {
                comboBox_DUT.SelectedIndex = selectedIndex;
            }

            foreach (DisplayUnitType dut in UnitUtils.GetValidDisplayUnits(UnitType.UT_Length))
            {
                if (currentDut == dut)
                {
                    continue;
                }
                unitName = LabelUtils.GetLabelFor(dut);
                m_DisplayUnits.Add(unitName, dut);
                selectedIndex = comboBox_DUT.Items.Add(unitName);
                if (m_SelectedDUT == dut)
                {
                    comboBox_DUT.SelectedIndex = selectedIndex;
                }
            }

            // initialize the UI differently for Families
            if (revit.ActiveUIDocument.Document.IsFamilyDocument)
            {
                cbIncludeLinked.Enabled = false;
                tvCategories.Enabled    = false;
                btnCheckAll.Enabled     = false;
                btnCheckNone.Enabled    = false;
            }
        }
        public void CheckModelDoors(Document doc, Application app)
        {
            #region Set Collector and Filter

            /*
             * // set collector
             * FilteredElementCollector collector = new FilteredElementCollector(doc);
             * // set filter
             * ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Doors);
             */
            #endregion

            var doorCollector = new FilteredElementCollector(doc).OfClass(typeof(FamilyInstance));
            // FilteredElementCollector a = new FilteredElementCollector(doc).OfClass(typeof(SpatialElement));

            doorCollector.OfCategory(BuiltInCategory.OST_Doors);
            IList <Element> doorList = doorCollector.ToElements();


            #region Set Filter on Collector
            // set filter on the collector
            //IList<Element> typedoors = collector.WherePasses(filter).WhereElementIsElementType().ToElements();
            //IList<Element> instdoors = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();
            #endregion

            #region Get Doors and Check their Width

            List <Double>    passedDoors  = new List <Double>();
            List <Double>    failedDoors  = new List <Double>();
            List <ElementId> failedDoorId = new List <ElementId>();
            List <ElementId> passedDoorId = new List <ElementId>();

            foreach (Element door in doorList)
            {
                //Instance param
                Parameter doorInstparam = door.get_Parameter(BuiltInParameter.DOOR_WIDTH);
                //string InstStorage = doorInstparam.StorageType.ToString();
                //Parameter parameter = door.LookupParameter("width");

                double doorInstWidth = (doorInstparam.HasValue) ? doorInstparam.AsDouble() : 0;
                //double doorWidthParam = parameter.AsDouble();

                //type param
                ElementId   doorTypeId    = door.GetTypeId();
                ElementType doorType      = (ElementType)doc.GetElement(doorTypeId);
                Parameter   doorTypeParam = doorType.get_Parameter(BuiltInParameter.FAMILY_WIDTH_PARAM);

                //string typeStorage = doorInstparam.StorageType.ToString();

                double doorTypeWidth = (doorTypeParam.HasValue) ? doorTypeParam.AsDouble() : 0;


                double doorInstWidthmm = UnitUtils.ConvertFromInternalUnits(doorInstWidth, DisplayUnitType.DUT_MILLIMETERS);
                double doorTypeWidthmm = UnitUtils.ConvertFromInternalUnits(doorTypeWidth, DisplayUnitType.DUT_MILLIMETERS);

                double ttldoorWidth = new double();
                if (doorInstWidthmm == 0)
                {
                    ttldoorWidth = doorTypeWidthmm;
                }
                else
                {
                    ttldoorWidth = doorInstWidthmm;
                }

                if (ttldoorWidth <= 800)
                {
                    ElementId faildoorId = door.GetTypeId();
                    failedDoorId.Add(faildoorId);
                    failedDoors.Add(ttldoorWidth);
                }
                else
                {
                    ElementId passdoorId = door.GetTypeId();
                    passedDoorId.Add(passdoorId);
                    passedDoors.Add(ttldoorWidth);
                }
            }

            #endregion

            #region Write to text file
            //if ((!File.Exists("FailedDoors.txt")))
            //{
            StreamWriter File = new StreamWriter("FailedDoors.txt");
            for (int i = 0; i < failedDoors.Count; i++)
            {
                string fdtxt = "The Door Width is " + failedDoors[i];
                File.WriteLine(fdtxt);
                string fdIdtxt = "The Door Id is " + failedDoorId[i];
                File.WriteLine(fdIdtxt);
                File.WriteLine("++++++++++++++++++++++++++++++");
            }

            File.Close();

            StreamWriter file = new StreamWriter("PassedDoors.txt");
            for (int i = 0; i < passedDoors.Count; i++)
            {
                string pdtxt = "The Door Width is " + passedDoors[i];
                File.WriteLine(pdtxt);
                string pdIdtxt = "The Door Id is " + passedDoorId[i];
                File.WriteLine(pdIdtxt);
                File.WriteLine("++++++++++++++++++++++++++++++");
            }

            file.Close();

            //}
            #endregion


            TaskDialog.Show("Door Width", "The failed Doors are saved in a text file");
        }
示例#10
0
        public static List <Shell> Shells(this Document document, IEnumerable <Autodesk.Revit.DB.Mechanical.Space> spaces = null, double offset = 0.1, double snapTolerance = Core.Tolerance.MacroDistance, double tolerance = Core.Tolerance.Distance)
        {
            if (document == null)
            {
                return(null);
            }

            //Collecting Space list
            List <Autodesk.Revit.DB.Mechanical.Space> spaces_Temp = new FilteredElementCollector(document).OfCategory(BuiltInCategory.OST_MEPSpaces).Cast <Autodesk.Revit.DB.Mechanical.Space>().ToList();

            if (spaces != null)
            {
                List <Autodesk.Revit.DB.Mechanical.Space> spaces_New = new List <Autodesk.Revit.DB.Mechanical.Space>();
                foreach (Autodesk.Revit.DB.Mechanical.Space space in spaces)
                {
                    int index = spaces_Temp.FindIndex(x => x.Id.IntegerValue == space.Id.IntegerValue);
                    if (index != -1)
                    {
                        spaces_New.Add(spaces_Temp[index]);
                    }
                }
                spaces_Temp = spaces_New;
            }

            if (spaces_Temp == null || spaces_Temp.Count == 0)
            {
                return(null);
            }

            //Dictionary of bottom elevations and tuples (top elevation, location 2D, Space) (Metric Units)
            Dictionary <double, List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > > dictionary = new Dictionary <double, List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > >();

            //Space cut elevations (Imperial Units)
            HashSet <double> cutElevations = new HashSet <double>();

            //Collecting Spaces data
            foreach (Autodesk.Revit.DB.Mechanical.Space space in spaces_Temp)
            {
                XYZ xyz = (space.Location as LocationPoint)?.Point;
                if (xyz == null)
                {
                    continue;
                }

                double elevation_Top = double.NaN;

                Parameter parameter = space.get_Parameter(BuiltInParameter.ROOM_UPPER_LEVEL);
                if (parameter != null && parameter.HasValue)
                {
                    ElementId elementId = parameter.AsElementId();
                    if (elementId != null && elementId != ElementId.InvalidElementId)
                    {
                        Level level = document.GetElement(elementId) as Level;
                        if (level != null)
                        {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                            elevation_Top = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS);
#else
                            elevation_Top = UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters);
#endif
                        }
                    }
                }

                BoundingBoxXYZ boundingBoxXYZ = space.get_BoundingBox(null);

                if (double.IsNaN(elevation_Top) && boundingBoxXYZ != null)
                {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    elevation_Top = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Max.Z, DisplayUnitType.DUT_METERS);
#else
                    elevation_Top = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Max.Z, UnitTypeId.Meters);
#endif
                }

                double elevation_Bottom = double.NaN;

                if (boundingBoxXYZ != null)
                {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    elevation_Bottom = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Min.Z, DisplayUnitType.DUT_METERS);
#else
                    elevation_Bottom = UnitUtils.ConvertFromInternalUnits(boundingBoxXYZ.Min.Z, UnitTypeId.Meters);
#endif
                }


                if (double.IsNaN(elevation_Bottom))
                {
                    ElementId elementId = space.LevelId;
                    if (elementId != null && elementId != ElementId.InvalidElementId)
                    {
                        Level level = document.GetElement(elementId) as Level;
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                        elevation_Bottom = UnitUtils.ConvertFromInternalUnits(level.Elevation, DisplayUnitType.DUT_METERS);
#else
                        elevation_Bottom = UnitUtils.ConvertFromInternalUnits(level.Elevation, UnitTypeId.Meters);
#endif
                    }
                }

                Point3D point3D = Geometry.Revit.Convert.ToSAM(xyz);
                if (point3D == null)
                {
                    continue;
                }

                Geometry.Planar.Point2D point2D = Geometry.Spatial.Plane.WorldXY.Convert(point3D);
                if (point2D == null)
                {
                    continue;
                }

#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                cutElevations.Add(UnitUtils.ConvertToInternalUnits(elevation_Bottom + offset, DisplayUnitType.DUT_METERS));
#else
                cutElevations.Add(UnitUtils.ConvertToInternalUnits(elevation_Bottom + offset, UnitTypeId.Meters));
#endif

                if (!dictionary.TryGetValue(elevation_Bottom, out List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > tuples))
                {
                    tuples = new List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> >();
                    dictionary[elevation_Bottom] = tuples;
                }
                tuples.Add(new Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space>(elevation_Top, point2D, space));
            }

            //Collecting Revit Walls
            List <Autodesk.Revit.DB.Wall> walls = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.Wall)).Cast <Autodesk.Revit.DB.Wall>().ToList();
            if (walls == null || walls.Count == 0)
            {
                return(null);
            }

            //Converting Revit Walls to SAM Panels
            List <Panel> panels = new List <Panel>();
            foreach (Autodesk.Revit.DB.Wall wall in walls)
            {
                BoundingBoxXYZ boundingBoxXYZ = wall?.get_BoundingBox(null);
                if (boundingBoxXYZ == null)
                {
                    continue;
                }

                bool valid = false;
                foreach (double cutElevation in cutElevations)
                {
                    if (boundingBoxXYZ.Max.Z >= cutElevation && boundingBoxXYZ.Min.Z <= cutElevation)
                    {
                        valid = true;
                        break;
                    }
                }

                if (!valid)
                {
                    continue;
                }

                List <Panel> panels_Wall = wall.ToSAM(new Core.Revit.ConvertSettings(true, false, false));
                if (panels_Wall == null || panels_Wall.Count == 0)
                {
                    continue;
                }

                panels.AddRange(panels_Wall);
            }

            if (panels == null || panels.Count == 0)
            {
                return(null);
            }

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

            //Inerating through elevations and Spaces data
            foreach (KeyValuePair <double, List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > > keyValuePair in dictionary)
            {
                double elevation_Bottom = keyValuePair.Key;
                double elevation_Cut    = elevation_Bottom + offset;

                Geometry.Spatial.Plane plane_Cut = Geometry.Spatial.Plane.WorldXY.GetMoved(new Vector3D(0, 0, elevation_Cut)) as Geometry.Spatial.Plane;

                List <Geometry.Planar.Segment2D> segment2Ds = new List <Geometry.Planar.Segment2D>();
                foreach (Panel panel in panels)
                {
                    IClosedPlanar3D closedPlanar3D = panel?.GetFace3D()?.GetExternalEdge3D();
                    if (closedPlanar3D == null)
                    {
                        continue;
                    }

                    PlanarIntersectionResult planarIntersectionResult = plane_Cut.PlanarIntersectionResult(closedPlanar3D);
                    if (planarIntersectionResult == null || !planarIntersectionResult.Intersecting)
                    {
                        continue;
                    }

                    List <Geometry.Planar.ISegmentable2D> segmentable2Ds_Temp = planarIntersectionResult.GetGeometry2Ds <Geometry.Planar.ISegmentable2D>();
                    if (segmentable2Ds_Temp == null || segmentable2Ds_Temp.Count == 0)
                    {
                        continue;
                    }

                    segmentable2Ds_Temp?.ForEach(x => segment2Ds.AddRange(x.GetSegments()));
                }

                if (panels == null || panels.Count == 0)
                {
                    continue;
                }

                segment2Ds = Geometry.Planar.Query.Split(segment2Ds, tolerance);

                segment2Ds = Geometry.Planar.Query.Snap(segment2Ds, true, snapTolerance);

                List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> > tuples_Polygon2D = Geometry.Planar.Create.Polygon2Ds(segment2Ds)?.ConvertAll(x => new Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D>(x.GetBoundingBox(tolerance), x));
                if (tuples_Polygon2D == null || tuples_Polygon2D.Count == 0)
                {
                    continue;
                }

                Geometry.Spatial.Plane plane_Bottom = Geometry.Spatial.Plane.WorldXY.GetMoved(new Vector3D(0, 0, elevation_Bottom)) as Geometry.Spatial.Plane;

                List <Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> > tuples_Space = keyValuePair.Value;
                while (tuples_Space.Count > 0)
                {
                    Tuple <double, Geometry.Planar.Point2D, Autodesk.Revit.DB.Mechanical.Space> tuple = tuples_Space[0];
                    tuples_Space.RemoveAt(0);

                    Geometry.Spatial.Plane plane_Top = Geometry.Spatial.Plane.WorldXY.GetMoved(new Vector3D(0, 0, tuple.Item1)) as Geometry.Spatial.Plane;

                    Geometry.Planar.Point2D point2D = tuple.Item2;

                    List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> > tuples_Polygon2D_External = tuples_Polygon2D.FindAll(x => x.Item1.Inside(point2D, tolerance)).FindAll(x => x.Item2.Inside(point2D, tolerance));
                    tuples_Polygon2D_External.Sort((x, y) => x.Item1.GetArea().CompareTo(y.Item1.GetArea()));

                    Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> tuple_Polygon2D_External = tuples_Polygon2D_External.FirstOrDefault();
                    if (tuple_Polygon2D_External == null)
                    {
                        continue;
                    }

                    List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> > tuples_Polygon2D_Internal = new List <Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> >();
                    foreach (Tuple <Geometry.Planar.BoundingBox2D, Geometry.Planar.Polygon2D> tuple_Polygon2D in tuples_Polygon2D)
                    {
                        if (tuple_Polygon2D == tuple_Polygon2D_External)
                        {
                            continue;
                        }

                        if (tuple_Polygon2D_External.Item1.Inside(tuple_Polygon2D.Item1, tolerance) && tuple_Polygon2D_External.Item2.Inside(tuple_Polygon2D.Item2, tolerance))
                        {
                            tuples_Polygon2D_Internal.Add(tuple_Polygon2D);
                        }
                    }

                    List <Geometry.Planar.Face2D> face2Ds = Geometry.Planar.Query.Difference(new Geometry.Planar.Face2D(tuple_Polygon2D_External.Item2), tuples_Polygon2D_Internal.ConvertAll(x => new Geometry.Planar.Face2D(x.Item2)), tolerance);
                    if (face2Ds == null || face2Ds.Count == 0)
                    {
                        continue;
                    }


                    foreach (Geometry.Planar.Face2D face2D in face2Ds)
                    {
                        tuples_Space.RemoveAll(x => face2D.Inside(x.Item2, tolerance));
                    }

                    List <Face3D> face3Ds = new List <Face3D>();
                    face3Ds.AddRange(face2Ds.ConvertAll(x => new Face3D(plane_Bottom, x)));
                    face3Ds.AddRange(face2Ds.ConvertAll(x => new Face3D(plane_Top, x)));

                    List <Shell> shells_Temp = Geometry.Spatial.Create.Shells(face3Ds, new double[] { elevation_Bottom }, offset, snapTolerance: snapTolerance, tolerance_Distance: tolerance);
                    if (shells_Temp == null || shells_Temp.Count == 0)
                    {
                        continue;
                    }

                    result.AddRange(shells_Temp);
                }
            }

            return(result);
        }
示例#11
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private FamilyInstance Connect(Transaction docTrans, Connector conCabinet, Connector conConduit)
        {
            // 找到设备的底面

            XYZ cabLocation = conCabinet.Origin;

            PlanarFace bottomFace = GeoHelper.GetBottomPlanarFace(_cabinet.MepInstance);
            double     bottomZ    = bottomFace.Origin.Z;

            // 根据线管的位置与方向,以及设备中连接件的位置,得到此线管发出的射线与设备连接件的某竖向平面的交点
            XYZ rayPoint = GetRayPoint(conConduit.CoordinateSystem, conCabinet.CoordinateSystem);

            XYZ verticalConduitTop    = new XYZ(rayPoint.X, rayPoint.Y, cabLocation.Z);
            XYZ verticalConduitBottom = new XYZ(rayPoint.X, rayPoint.Y, bottomZ);


            // 判断是否能够成功地生成弯头
            // (因为如果不能成功生成,在API的代码中也不会报错,而只是在Transaction.Commit时弹出一个消息框)
            double?outDiamter = _conduit.GetConduitOuterDiameter();

            if (outDiamter == null)
            {
                throw new NullReferenceException("在线管中未找到参数“外径”");
            }

            // ------------------------------------------------
            // 要生成弯头所需要的最小的弯曲半径,如果弯头的半径大于此值,则不能成功生成弯头。

            // 在生成弯头时,两边的线管如果被截断,则其截断后的长度不能为负,也不能为零,至少还要剩3mm(2.5 mm都不行)。
            double minLengthOfVerticalConduit = UnitUtils.ConvertToInternalUnits(5, DisplayUnitType.DUT_MILLIMETERS);
            // 弯头对象除了圆弧段以外,其两端还各有一个线管段,其长度 = 线管外径。
            double allowableRadius = cabLocation.Z - conConduit.Origin.Z - outDiamter.Value - minLengthOfVerticalConduit;

            double allowableRatio = allowableRadius / outDiamter.Value;

            // ------------------------------------------------

            double?ratioInFamily = GetElbowRadiusRatio(docTrans, _conduit.ConduitIns);

            if (ratioInFamily == null)
            {
                throw new NullReferenceException("在线管中没有找到匹配的弯头对象");
            }

            if (allowableRatio < ratioInFamily)
            {
                throw new InvalidOperationException(message: "线管当前所使用的弯头中的弯曲半径值过大,不能正常地生成弯头。" +
                                                    "请换用其他的弯头,或者将将弯头中的实例参数“弯曲半径”由“管件外径 * " + ratioInFamily +
                                                    "”修改为“管件外径 * " + allowableRatio + "”或更小的值。");
            }

            // 生成设备内部的竖向线管
            Conduit    cd    = Conduit.Create(_doc, _conduit.ConduitIns.GetTypeId(), verticalConduitBottom, verticalConduitTop, ElementId.InvalidElementId);
            MEPConduit mepCd = new MEPConduit(cd);
            // 调整线管直径到与选择的线管直径相同
            double?diameter = _conduit.GetConduitDiameter();

            if (diameter == null)
            {
                throw new NullReferenceException("在线管中未找到参数“直径(公称尺寸)”");
            }
            mepCd.SetConduitDiameter(diameter.Value);

            //
            Connector conn_vert = cd.ConnectorManager.Lookup(0);

            // 生成弯头
            FamilyInstance elbow = _doc.Create.NewElbowFitting(conn_vert, conConduit);

            return(elbow);
        }
示例#12
0
        //The main method to excute.
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            #region Build the basic and filter the selection
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Autodesk.Revit.ApplicationServices.Application app = uiapp.Application;
            Document doc = uidoc.Document;

            // Access current selection
            Selection sel = uidoc.Selection;
            FilteredElementCollector col;
            // Retrieve elements from database£¨only choose room)
            try
            {
                col = new FilteredElementCollector(doc, sel.GetElementIds())
                      .WhereElementIsNotElementType()
                      .OfCategory(BuiltInCategory.OST_Rooms);
            }
            catch (Autodesk.Revit.Exceptions.ArgumentException ae)
            {
                TaskDialog.Show("Warning", "Please select at least one room.\n"
                                + "Detail:" + ae.Message);
                return(Result.Failed);
            }

            #endregion

            #region Confirm selection.result in tdResult.
            // Write all the roomname into a string to confirm with the user.
            if (col.Count() == 0)
            {
                TaskDialog.Show("Warning", "No room is selected." +
                                "This commend operates based on room.");
                return(Result.Failed);
            }

            string confirmMessage = "The following rooms are choosen, confirm?\n";
            foreach (Element currentRoom in col)
            {
                Room roome = currentRoom as Room;
                confirmMessage = confirmMessage + roome.Name + "\n";
            }

            //Pop up a dialog to confirm selection.
            TaskDialogResult tdResult =
                TaskDialog.Show("Revit", confirmMessage,
                                TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No);
            if (tdResult == TaskDialogResult.No)
            {
                return(Result.Failed);
            }
            #endregion

            #region Load the family(into "panelRfa""basePanelSymbol")
            //Set directory for the family
            family_folder = Path.GetDirectoryName(doc.PathName);
            //check if the family already exist in the project
            Family panelRfa = FindElementByName
                                  (doc, typeof(Family), panelFamilyName) as Family;
            if (panelRfa == null)
            {
                //check for the file to load.
                if (!File.Exists(FamilyPath))
                {
                    TaskDialog.Show("Waning",
                                    "Please ensure the PanelAuto.rfa is " +
                                    "in the same folder with current project.");
                    return(Result.Failed);
                }
                using (Transaction tx = new Transaction(doc)){
                    tx.Start("Load PanelAuto.Rfa");
                    doc.LoadFamily(FamilyPath, out panelRfa);
                    tx.Commit();
                }
            }
            ISet <ElementId> typeId          = panelRfa.GetFamilySymbolIds();
            FamilySymbol     basePanelSymbol = doc
                                               .GetElement(typeId.FirstOrDefault()) as FamilySymbol;
            #endregion

            #region Ask for custom input
            double DistanceToWall = 0;
            double UnitWidth      = 0;
            //Show a dialog to ask input from user.
            using (InputForm input = new InputForm()){
                if (!(input.ShowDialog() == DialogResult.OK))
                {
                    return(Result.Failed);
                }
                DistanceToWall = UnitUtils.ConvertToInternalUnits
                                     ((double)input.DistanceToWall.Value, DisplayUnitType.DUT_MILLIMETERS);
                UnitWidth = UnitUtils.ConvertToInternalUnits
                                ((double)input.UnitWidth.Value, DisplayUnitType.DUT_MILLIMETERS);
            }
            #endregion

            #region The main work.
            using (Transaction tx = new Transaction(doc))
            {
                tx.Start("Create the panels");
                //Store all the boundary segments of a room.
                List <EdgeSegment> roomSegments = new List <EdgeSegment>();
                //Store all the Id of the panels created.
                List <ElementId> PanelIds = new List <ElementId>();

                //Loop through each room
                foreach (Element currentRoom in col)
                {
                    //Clear the data for the new room.
                    roomSegments.Clear();
                    PanelIds.Clear();

                    //Step1-Get the raw data of each wall.
                    roomSegments = GetRawData(currentRoom as Room, DistanceToWall, UnitWidth);

                    foreach (EdgeSegment eSegment in roomSegments)
                    {
                        //Step2-Create ranges.In one range panels have same height
                        //and are horizontally spread as evenly as possible
                        if (!eSegment.NoPanel)
                        {
                            eSegment.DivideToPanelRange();
                        }
                        //Step3-Create construction daga for each panel.
                        foreach (PanelRange pR in eSegment.ranges)
                        {
                            eSegment.panels.AddRange
                                (pR.CreatePanelDatas(UnitWidth, DistanceToWall));
                        }

                        #region for demostration(while working)
                        //XYZ normal = wall.normal;
                        //XYZ origin = wall.start;
                        //Plane plane = Plane.CreateByNormalAndOrigin(normal, origin);
                        //SketchPlane sP = SketchPlane.Create(doc, plane);
                        //foreach (PanelRange pRange in wall.ranges)
                        //{
                        //    doc.Create.NewModelCurveArray(pRange.GetRangeCurves(), sP);
                        //}
                        #endregion

                        //Step 4-Create the panel instances.
                        foreach (PanelData pData in eSegment.panels)
                        {
                            #region Only for demo while working

                            /*
                             * Plane tempP = Plane.CreateByNormalAndOrigin(pData.PaNormal, pData.PaOrigin);
                             * SketchPlane sP = SketchPlane.Create(doc, tempP);
                             * XYZ T = new XYZ(-pData.PaNormal.Y, pData.PaNormal.X, 0);
                             * XYZ dl = pData.PaOrigin + 0.5 * pData.PaWidth * T;
                             * XYZ dr = pData.PaOrigin - 0.5 * pData.PaWidth * T;
                             * Transform up = Transform.CreateTranslation(new XYZ(0, 0, pData.PaHeight));
                             * XYZ ul = up.OfPoint(dl);
                             * XYZ ur = up.OfPoint(dr);
                             * Line l1 = Line.CreateBound(dl, ul);
                             * Line l2 = Line.CreateBound(dr, ur);
                             * doc.Create.NewModelCurve(l1, sP);
                             * doc.Create.NewModelCurve(l2, sP);
                             */
                            #endregion

                            #region Create the panels

                            //Convert the panelWidth and Height into mm
                            //And create the name for the panel.
                            int panelW_mm = (int)Math.Round(UnitUtils.ConvertFromInternalUnits
                                                                (pData.PaWidth, DisplayUnitType.DUT_MILLIMETERS));
                            int panelH_mm = (int)Math.Round(UnitUtils.ConvertFromInternalUnits
                                                                (pData.PaHeight, DisplayUnitType.DUT_MILLIMETERS));
                            string panelName = "P" + panelW_mm + "-" + panelH_mm;

                            //Check if this type already exist
                            FamilySymbol currentPanelSymbol = FindElementByName
                                                                  (doc, typeof(FamilySymbol), panelName) as FamilySymbol;
                            if (currentPanelSymbol == null)
                            {
                                //Create a new one
                                currentPanelSymbol = basePanelSymbol.Duplicate(panelName) as FamilySymbol;
                                //modify the size of new symbol
                                currentPanelSymbol.GetParameters("Height")[0].Set(pData.PaHeight);
                                currentPanelSymbol.GetParameters("Width")[0].Set(pData.PaWidth);
                            }

                            //Create the actual instance
                            FamilyInstance currentInst = doc.Create.NewFamilyInstance
                                                             (pData.PaOrigin, currentPanelSymbol, StructuralType.NonStructural);
                            //Rotate the instance to correct direction
                            Line axis = Line.CreateBound(pData.PaOrigin, pData.PaOrigin + XYZ.BasisZ);
                            //The AngleOnPlaneTo will create the angle from 0 to 2Pi
                            double angle = new XYZ(0, -1, 0).AngleOnPlaneTo(pData.PaNormal, new XYZ(0, 0, 1));
                            ElementTransformUtils.RotateElement(doc, currentInst.Id, axis, angle);
                            //log the panel id
                            PanelIds.Add(currentInst.Id);
                            #endregion
                        }
                    }
                    //Group the panels of the same room.
                    Group group = doc.Create.NewGroup(PanelIds);
                }
                tx.Commit();
            }
            #endregion

            return(Result.Succeeded);
        }
示例#13
0
        public List <EdgeSegment> GetRawData(Room room,
                                             double DistanceToWall, double UnitWidth)
        {
            //Used to store the wall object.
            List <EdgeSegment> rSegments = new List <EdgeSegment>();

            #region The basics and datas
            const double er  = 0.0001;//used for error correction.
            Document     doc = room.Document;
            Autodesk.Revit.ApplicationServices.Application app = doc.Application;
            //get the level height of floor and ceiling
            //!!!!!current not consider different ceiling height or floor.Need improving.
            double levelC = room.ClosedShell.GetBoundingBox().Max.Z;
            double levelF = room.ClosedShell.GetBoundingBox().Min.Z;
            //Custom input data.
            double dist2W = DistanceToWall;
            double unitW  = UnitWidth;
            #endregion

            //get the boundary segments list
            IList <IList <BoundarySegment> > boundarys =
                room.GetBoundarySegments(new SpatialElementBoundaryOptions());

            //Loop through all the wall segment needed to oprate on
            //first layer is each boundary loop(in case a room has multiple boundaries)
            foreach (IList <BoundarySegment> groupSegments in boundarys)
            {
                //The stack is for the segments(one wall can be several segments)
                //The queue is for the wall after merging the segments.
                Stack <EdgeSegment> eSegments       = new Stack <EdgeSegment>();
                List <EdgeSegment>  eSegmentsMerged = new List <EdgeSegment>();

                //Second layer is the actual segment
                //in this loop process each segment opening info and log them
                foreach (BoundarySegment segment in groupSegments)
                {
                    #region Create the object,get the inner edge of a wall segment
                    EdgeSegment theSeg = new EdgeSegment();
                    Curve       segCrv = segment.GetCurve();
                    XYZ         start  = segCrv.GetEndPoint(0);
                    XYZ         end    = segCrv.GetEndPoint(1);
                    XYZ         normal;
                    theSeg.levelC = levelC;
                    theSeg.levelF = levelF;
                    theSeg.start  = new XYZ(start.X, start.Y, levelF);
                    theSeg.end    = new XYZ(end.X, end.Y, levelF);
                    #endregion

                    //The boundary segment may not be a wall
                    Element wallOrNot = doc.GetElement(segment.ElementId);

                    #region Seperate different category(Wall,Column or others)
                    Categories docCat   = doc.Settings.Categories;
                    ElementId  idColumn = docCat.get_Item(BuiltInCategory.OST_Columns).Id;
                    ElementId  idWall   = docCat.get_Item(BuiltInCategory.OST_Walls).Id;
                    //Case 1-A column or the end of a single wall.
                    if ((wallOrNot == null) || (wallOrNot.Category.Id.Equals(idColumn)))
                    {
                        //The room segments always search counterclockwise
                        //Thus compute the normal as follow
                        //Other data is not needed.Treat it as a full wall.
                        XYZ line = end - start;
                        normal        = new XYZ(-line.Y, line.X, 0);
                        theSeg.normal = normal / normal.GetLength();
                        eSegments.Push(theSeg);
                        continue;
                    }
                    //Case 2-Not column or wall.(Most likely curtain)Mark as noPanel.
                    if (!(wallOrNot.Category.Id.Equals(idWall)))
                    {
                        theSeg.NoPanel = true;
                        eSegments.Push(theSeg);
                        continue;
                    }
                    //Case 3-Walls
                    Wall theWall = wallOrNot as Wall;
                    #endregion

                    #region Get the sideface of a wall and get the profile curves
                    IList <Reference> sideFaces =
                        HostObjectUtils.GetSideFaces(theWall, ShellLayerType.Exterior);
                    //get the real face(why so long???)
                    Face face = doc.GetElement(sideFaces[0])
                                .GetGeometryObjectFromReference(sideFaces[0]) as Face;
                    //get edge loops as curveloops
                    IList <CurveLoop> openLoops = face.GetEdgesAsCurveLoops();
                    #endregion

                    //Some basic properties of the face.
                    normal = face.ComputeNormal(new UV(0, 0));
                    Plane plane = Plane.CreateByNormalAndOrigin(normal, start);

                    #region Check if curves are on the inner plane or not.
                    //(Might be on the other side of the wall)
                    //Log the correction vector in correction.
                    Curve checkCurve = openLoops[0].GetEnumerator().Current;
                    plane.Project(checkCurve.GetEndPoint(1), out UV uv, out double dist);
                    Transform correction = Transform.CreateTranslation(new XYZ(0, 0, 0));
                    if (dist > er) //Same wired reason.See "const double er" up front.
                    {
                        normal     = -normal;
                        correction = Transform.CreateTranslation(dist * normal);
                        plane      = Plane.CreateByNormalAndOrigin(normal, start);
                    }
                    #endregion

                    //Store all the endpoints and horizontal curves.
                    List <XYZ>   points = new List <XYZ>();
                    List <Curve> hoCrvs = new List <Curve>();
                    foreach (CurveLoop curveloop in openLoops)
                    {
                        foreach (Curve curve in curveloop)
                        {
                            points.Add(correction.OfPoint(curve.GetEndPoint(0)));
                            //If curve is horizontal,and in the middle range,log it
                            double cSz = curve.GetEndPoint(0).Z;
                            double cEz = curve.GetEndPoint(1).Z;
                            if ((Math.Abs(cSz - cEz) < er) && (cSz > levelF + er) && (cSz < levelC - er))
                            {
                                hoCrvs.Add(curve.CreateTransformed(correction));
                            }
                        }
                    }

                    #region Sort pts according to curve direction
                    var tempPts = from point in points
                                  where ((point.Z > levelF + er) && (point.Z < levelC - er))
                                  select new XYZ(point.X, point.Y, levelF);
                    List <XYZ> relayPts = tempPts.ToList <XYZ>();
                    relayPts.Add(start); relayPts.Add(end);
                    var sortPt = from point in relayPts
                                 where (segCrv.Distance(point) < er)
                                 orderby(point - start).GetLength()
                                 select point;
                    List <XYZ> sortPtList = sortPt
                                            .Distinct(new PtEqualComparer())
                                            .ToList <XYZ>();
                    if (!(sortPtList[0] == start))
                    {
                        sortPtList.Reverse();
                    }
                    sortPtList.RemoveAt(sortPtList.Count - 1);
                    sortPtList.RemoveAt(0);
                    #endregion

                    #region log the data
                    theSeg.crvList = hoCrvs;
                    theSeg.ptList  = sortPtList;
                    theSeg.normal  = normal;
                    #endregion

                    //Find insert element(and project on plane)
                    List <ElementId> insertIds = theWall
                                                 .FindInserts(true, true, true, true).Distinct().ToList();
                    foreach (ElementId eId in insertIds)
                    {
                        Element        currentRoom = doc.GetElement(eId);
                        BoundingBoxXYZ box         = currentRoom.get_Geometry(new Options()).GetBoundingBox();
                        XYZ            ept         = 0.5 * (box.Max + box.Min);
                        XYZ            v           = ept - plane.Origin;
                        double         signedDist  = plane.Normal.DotProduct(v);
                        XYZ            eptnew      = ept - signedDist * normal;
                        theSeg.insertPts.Add(eptnew);
                    }

                    //Push to the stack.
                    eSegments.Push(theSeg);
                }

                #region Merge from segments to walls...
                //Merge the segments that are on same curve.
                int         segNum = eSegments.Count;
                EdgeSegment sNew;
                for (int i = 1; i < segNum; i++)
                {
                    EdgeSegment s1 = eSegments.Pop();
                    EdgeSegment s2 = eSegments.Pop();
                    if (!(s2.MergeWith(s1, out sNew)))
                    {
                        eSegmentsMerged.Add(s1);
                    }
                    eSegments.Push(sNew);
                }

                //Compare the final one to the first one again
                EdgeSegment sf1 = eSegmentsMerged[0];
                EdgeSegment sf2 = eSegments.Pop();
                if (sf2.MergeWith(sf1, out sNew))
                {
                    eSegmentsMerged.RemoveAt(0);
                }
                eSegmentsMerged.Add(sNew);
                //Because the use of stack,the order need to be reversed back.
                eSegmentsMerged.Reverse();
                #endregion

                #region Set the offset for each corner according to dist2W
                int wallNum = eSegmentsMerged.Count;
                eSegmentsMerged.Add(eSegmentsMerged[0]);
                for (int i = 0; i < wallNum; i++)
                {
                    EdgeSegment SegCur = eSegmentsMerged[i];
                    EdgeSegment SegAft = eSegmentsMerged[i + 1];
                    double      angle  = SegCur.unitV.AngleOnPlaneTo(SegAft.unitV, XYZ.BasisZ);
                    SegCur.end   -= Math.Tan(0.5 * angle) * dist2W * SegCur.unitV;
                    SegAft.start += Math.Tan(0.5 * angle) *
                                    (dist2W + UnitUtils.ConvertToInternalUnits(10, DisplayUnitType.DUT_MILLIMETERS)) *
                                    SegAft.unitV;
                }
                eSegmentsMerged.RemoveAt(eSegmentsMerged.Count - 1);
                #endregion

                rSegments.AddRange(eSegmentsMerged);
            }

            return(rSegments);
        }
示例#14
0
        private String GetWalls()
        {
            String tString = "";

            //List<Element> walls = new FilteredElementCollector(doc)
            //        .OfClass(typeof(Wall)).WhereElementIsNotElementType().ToElements().ToList();

            walls = new FilteredElementCollector(doc)
                    .WhereElementIsNotElementType().WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_Walls)).ToElements();

            tString += NL + NL + "# WALLS";

            foreach (Element e in walls)
            {
                if (e is FamilyInstance)
                {
                    string URI = Util.CreateURI(e, Namespace).Replace(Namespace, "inst:");

                    ElementDict.Add(e.Id, URI);

                    tString +=
                        NL + NL + $"{URI}" +
                        NLT + $"a bot:Element ;" +
                        NLT + $"a beo:Wall ;" +
                        NLT + $"props:geometryType \"FamilyInstance\" ;" +
                        NLT + $"props:revitId \"{e.Id}\" ;" +
                        NLT + $"props:ifcGuid \"{e.GetGUID()}\" ;" +
                        NLT + $"props:uuid \"{e.GetUUID()}\" .";
                }
                else
                {
                    Wall wall = e as Wall;

                    //string URI = Parameters.GenerateURIifNotExist(doc, e).Replace(Namespace, "inst:");
                    string URI = Util.CreateURI(e, Namespace).Replace(Namespace, "inst:");

                    String wallType = doc.GetElement(wall.GetTypeId()).Name.ToString();
                    //string typeURI = "inst:" + Util.TypeNameToId(wallType);

                    ElementDict.Add(e.Id, URI);

                    // Append classes to
                    tString +=
                        NL + NL + $"{URI}" +
                        NLT + $"a bot:Element ;" +
                        NLT + $"a beo:Wall ;" +
                        NLT + $"props:geometryType \"Solid\" ;" +
                        NLT + $"props:revitId \"{e.Id}\" ;" +
                        NLT + $"props:ifcGuid \"{e.GetGUID()}\" ;" +
                        NLT + $"props:uuid \"{e.GetUUID()}\" ;";

                    string width       = Math.Round(UnitUtils.ConvertFromInternalUnits(wall.Width, Autodesk.Revit.DB.DisplayUnitType.DUT_MILLIMETERS), 2).ToString().Replace(",", ".");
                    double curveLength = wall.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH).AsDouble();
                    string length      = Math.Round(UnitUtils.ConvertFromInternalUnits(curveLength, Autodesk.Revit.DB.DisplayUnitType.DUT_MILLIMETERS), 2).ToString().Replace(",", ".");

                    width  = $"\"{width}\"^^xsd:decimal";
                    length = $"\"{length}\"^^xsd:decimal";
                    string name = $"{e.Name}";

                    tString += NLT + $"props:identityDataName \"{name}\" ;";
                    tString += NLT + $"props:dimensionsWidth {width} ;";
                    tString += NLT + $"props:dimensionsLength {length} ;";

                    //testString += Util.GetFacesAndEdges(wall) + NL;
                    tString += NLT + $"bot:hasSimple3DModel \"\"\"{Util.GetFacesAndEdges(wall, true)}\"\"\" .";
                }
            }

            return(tString);
        }
示例#15
0
        /// <summary>
        /// Given the filter in use by a stream returns the document elements that match it
        /// </summary>
        /// <returns></returns>
        private IEnumerable <SpeckleObject> GetSelectionFilterObjects(ISelectionFilter filter, string clientId, string streamId)
        {
            var doc = CurrentDoc.Document;
            IEnumerable <SpeckleObject> objects = new List <SpeckleObject>();

            var selectionIds = new List <string>();

            if (filter.Name == "Selection")
            {
                var selFilter = filter as ElementsSelectionFilter;
                selectionIds = selFilter.Selection;
            }
            else if (filter.Name == "Category")
            {
                var catFilter  = filter as ListSelectionFilter;
                var bics       = new List <BuiltInCategory>();
                var categories = Globals.GetCategories(doc);
                IList <ElementFilter> elementFilters = new List <ElementFilter>();

                foreach (var cat in catFilter.Selection)
                {
                    elementFilters.Add(new ElementCategoryFilter(categories[cat].Id));
                }
                LogicalOrFilter categoryFilter = new LogicalOrFilter(elementFilters);

                selectionIds = new FilteredElementCollector(doc)
                               .WhereElementIsNotElementType()
                               .WhereElementIsViewIndependent()
                               .WherePasses(categoryFilter)
                               .Select(x => x.UniqueId).ToList();
            }
            else if (filter.Name == "View")
            {
                var viewFilter = filter as ListSelectionFilter;

                var views = new FilteredElementCollector(doc)
                            .WhereElementIsNotElementType()
                            .OfClass(typeof(View))
                            .Where(x => viewFilter.Selection.Contains(x.Name));

                foreach (var view in views)
                {
                    var ids = new FilteredElementCollector(doc, view.Id)
                              .WhereElementIsNotElementType()
                              .WhereElementIsViewIndependent()
                              .Where(x => x.IsPhysicalElement())
                              .Select(x => x.UniqueId).ToList();

                    selectionIds = selectionIds.Union(ids).ToList();
                }
            }
            else if (filter.Name == "Parameter")
            {
                try
                {
                    var propFilter = filter as PropertySelectionFilter;
                    var query      = new FilteredElementCollector(doc)
                                     .WhereElementIsNotElementType()
                                     .WhereElementIsNotElementType()
                                     .WhereElementIsViewIndependent()
                                     .Where(x => x.IsPhysicalElement())
                                     .Where(fi => fi.LookupParameter(propFilter.PropertyName) != null);

                    propFilter.PropertyValue = propFilter.PropertyValue.ToLowerInvariant();

                    switch (propFilter.PropertyOperator)
                    {
                    case "equals":
                        query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)) == propFilter.PropertyValue);
                        break;

                    case "contains":
                        query = query.Where(fi => GetStringValue(fi.LookupParameter(propFilter.PropertyName)).Contains(propFilter.PropertyValue));
                        break;

                    case "is greater than":
                        query = query.Where(fi => UnitUtils.ConvertFromInternalUnits(
                                                fi.LookupParameter(propFilter.PropertyName).AsDouble(),
                                                fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) > double.Parse(propFilter.PropertyValue));
                        break;

                    case "is less than":
                        query = query.Where(fi => UnitUtils.ConvertFromInternalUnits(
                                                fi.LookupParameter(propFilter.PropertyName).AsDouble(),
                                                fi.LookupParameter(propFilter.PropertyName).DisplayUnitType) < double.Parse(propFilter.PropertyValue));
                        break;

                    default:
                        break;
                    }

                    selectionIds = query.Select(x => x.UniqueId).ToList();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }

            // LOCAL STATE management
            objects = selectionIds.Select(id =>
            {
                var temp = new SpeckleObject();
                temp.Properties["revitUniqueId"] = id;
                temp.Properties["__type"]        = "Sent Object";
                return(temp);
            });


            var myStream = LocalState.FirstOrDefault(st => st.StreamId == streamId);

            myStream.Objects.Clear();
            myStream.Objects.AddRange(objects);

            var myClient = ClientListWrapper.clients.FirstOrDefault(cl => (string)cl._id == (string)clientId);

            myClient.objects = JsonConvert.DeserializeObject <dynamic>(JsonConvert.SerializeObject(myStream.Objects));

            // Persist state and clients to revit file
            Queue.Add(new Action(() =>
            {
                using (Transaction t = new Transaction(CurrentDoc.Document, "Update local storage"))
                {
                    t.Start();
                    SpeckleStateManager.WriteState(CurrentDoc.Document, LocalState);
                    SpeckleClientsStorageManager.WriteClients(CurrentDoc.Document, ClientListWrapper);
                    t.Commit();
                }
            }));
            Executor.Raise();
            var plural = objects.Count() == 1 ? "" : "s";

            if (objects.Count() != 0)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = clientId,
                    expired = true,
                    objects = myClient.objects,
                    //message = $"You have added {objects.Count()} object{plural} to this sender."
                }));
            }

            return(objects);
        }
示例#16
0
 /// <summary>
 /// Method to convert length units to Internal Units
 /// </summary>
 /// <param name="number"></param>
 /// <param name="dUT"></param>
 /// <returns></returns>
 public static double LengthUnitToInternal(double number, DisplayUnitType dUT)
 {
     return(UnitUtils.ConvertToInternalUnits(number, dUT));
 }
示例#17
0
        // NOTE: This is actually triggered when clicking "Push!"
        // TODO: Orchestration
        // Create buckets, send sequentially, notify ui re upload progress
        // NOTE: Problems with local context and cache: we seem to not sucesffuly pass through it
        // perhaps we're not storing the right sent object (localcontext.addsentobject)
        public override void PushSender(string args)
        {
            var client = JsonConvert.DeserializeObject <dynamic>(args);

            //if it's a category or property filter we need to refresh the list of objects
            //if it's a selection filter just use the objects that were stored previously
            ISelectionFilter            filter  = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(client.filter), GetFilterType(client.filter.Type.ToString()));
            IEnumerable <SpeckleObject> objects = new List <SpeckleObject>();

            objects = GetSelectionFilterObjects(filter, client._id.ToString(), client.streamId.ToString());

            var apiClient = new SpeckleApiClient((string)client.account.RestApi)
            {
                AuthToken = (string)client.account.Token
            };

            var convertedObjects = new List <SpeckleObject>();
            var placeholders     = new List <SpeckleObject>();

            var units = CurrentDoc.Document.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits.ToString().ToLowerInvariant().Replace("dut_", "");

            InjectScaleInKits(GetScale(units)); // this is used for feet to sane units conversion.

            int  i = 0;
            long currentBucketSize = 0;
            var  errorMsg          = "";
            var  failedToConvert   = 0;
            var  errors            = new List <SpeckleError>();

            foreach (var obj in objects)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = (string)client._id,
                    loading = true,
                    isLoadingIndeterminate = false,
                    loadingProgress        = 1f * i++ / objects.Count() * 100,
                    loadingBlurb           = string.Format("Converting and uploading objects: {0} / {1}", i, objects.Count())
                }));

                var     id           = 0;
                Element revitElement = null;
                try
                {
                    revitElement = CurrentDoc.Document.GetElement((string)obj.Properties["revitUniqueId"]);
                    id           = revitElement.Id.IntegerValue;
                }
                catch (Exception e)
                {
                    errors.Add(new SpeckleError {
                        Message = "Could not retrieve element", Details = e.Message
                    });
                    continue;
                }

                try
                {
                    var conversionResult = SpeckleCore.Converter.Serialise(new List <object>()
                    {
                        revitElement
                    });
                    var byteCount = Converter.getBytes(conversionResult).Length;
                    currentBucketSize += byteCount;

                    if (byteCount > 2e6)
                    {
                        errors.Add(new SpeckleError {
                            Message = "Element is too big to be sent", Details = $"Element {id} is bigger than 2MB, it will be skipped"
                        });
                        continue;
                    }

                    convertedObjects.AddRange(conversionResult);

                    if (currentBucketSize > 5e5 || i >= objects.Count()) // aim for roughly 500kb uncompressed
                    {
                        LocalContext.PruneExistingObjects(convertedObjects, apiClient.BaseUrl);

                        try
                        {
                            var chunkResponse = apiClient.ObjectCreateAsync(convertedObjects).Result.Resources;
                            int m             = 0;
                            foreach (var objConverted in convertedObjects)
                            {
                                objConverted._id = chunkResponse[m++]._id;
                                placeholders.Add(new SpecklePlaceholder()
                                {
                                    _id = objConverted._id
                                });
                                if (objConverted.Type != "Placeholder")
                                {
                                    LocalContext.AddSentObject(objConverted, apiClient.BaseUrl);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            errors.Add(new SpeckleError {
                                Message = $"Failed to send {convertedObjects.Count} objects", Details = e.Message
                            });
                        }
                        currentBucketSize = 0;
                        convertedObjects  = new List <SpeckleObject>(); // reset the chunkness
                    }
                }
                catch (Exception e)
                {
                    failedToConvert++;
                    errors.Add(new SpeckleError {
                        Message = $"Failed to convert {revitElement.Name}", Details = $"Element id: {id}"
                    });

                    //NotifyUi("update-client", JsonConvert.SerializeObject(new
                    //{
                    //  _id = (string)client._id,
                    //  errors = "Failed to convert " + failedConvert + " objects."
                    //}));
                }
            }

            if (errors.Any())
            {
                if (failedToConvert > 0)
                {
                    errorMsg += string.Format("Failed to convert {0} objects ",
                                              failedToConvert,
                                              failedToConvert == 1 ? "" : "s");
                }
                else
                {
                    errorMsg += string.Format("There {0} {1} error{2} ",
                                              errors.Count() == 1 ? "is" : "are",
                                              errors.Count(),
                                              errors.Count() == 1 ? "" : "s");
                }


                errorMsg += "<nobr>" + Globals.GetRandomSadFace() + "</nobr>";
            }

            var myStream = new SpeckleStream()
            {
                Objects = placeholders
            };

            var ug        = UnitUtils.GetUnitGroup(UnitType.UT_Length);
            var baseProps = new Dictionary <string, object>();

            baseProps["units"] = units;

            baseProps["unitsDictionary"] = GetAndClearUnitDictionary();

            myStream.BaseProperties = baseProps;
            //myStream.BaseProperties =  JsonConvert.SerializeObject(baseProps);

            NotifyUi("update-client", JsonConvert.SerializeObject(new
            {
                _id     = (string)client._id,
                loading = true,
                isLoadingIndeterminate = true,
                loadingBlurb           = "Updating stream."
            }));

            var response = apiClient.StreamUpdateAsync((string)client.streamId, myStream).Result;

            var plural = objects.Count() == 1 ? "" : "s";

            NotifyUi("update-client", JsonConvert.SerializeObject(new
            {
                _id          = (string)client._id,
                loading      = false,
                loadingBlurb = "",
                message      = $"Done sending {objects.Count()} object{plural}.",
                errorMsg,
                errors
            }));

            SpeckleTelemetry.RecordStreamUpdated("Revit");
        }
示例#18
0
        public static HostObject ToRevit(this Panel panel, Document document, Core.Revit.ConvertSettings convertSettings)
        {
            Geometry.Spatial.Face3D face3D = panel?.GetFace3D();
            if (face3D == null)
            {
                return(null);
            }

            HostObject result = convertSettings?.GetObject <HostObject>(panel.Guid);

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

            PanelType panelType = panel.PanelType;

            Geometry.Spatial.Vector3D normal = panel.Normal;

            HostObjAttributes hostObjAttributes = panel.Construction.ToRevit(document, panelType, normal, convertSettings);

            if (hostObjAttributes == null)
            {
                hostObjAttributes = Analytical.Query.DefaultConstruction(panelType)?.ToRevit(document, panelType, normal, convertSettings); //Default Construction
            }
            BuiltInParameter[] builtInParameters = null;
            if (hostObjAttributes is Autodesk.Revit.DB.WallType)
            {
                double lowElevation = panel.LowElevation();

                Level level = document.LowLevel(lowElevation);

                Autodesk.Revit.DB.Wall wall = ToRevit_Wall(face3D, document, (Autodesk.Revit.DB.WallType)hostObjAttributes, level);
                if (wall == null)
                {
                    return(result);
                }

                //List<Curve> curveList = new List<Curve>();
                //foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D in face3D.GetEdge3Ds())
                //{
                //    if (Geometry.Spatial.Query.Clockwise(closedPlanar3D))
                //        closedPlanar3D.Reverse();

                //    List<Line> lines = closedPlanar3D.ToRevit();
                //    if (lines == null)
                //        continue;

                //    curveList.AddRange(lines);
                //}

                //if (curveList == null || curveList.Count == 0)
                //    return null;

                //double lowElevation = panel.LowElevation();

                //Level level = document.LowLevel(lowElevation);
                //if (level == null)
                //    return null;

                //Wall wall = Wall.Create(document, curveList, hostObjAttributes.Id, level.Id, false, panel.Normal.ToRevit(false));

                Parameter parameter = null;

                parameter = wall.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE);
                if (parameter != null)
                {
                    parameter.Set(ElementId.InvalidElementId);
                }

                parameter = wall.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);
                if (parameter != null)
                {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    double height = UnitUtils.ConvertToInternalUnits((panel.HighElevation() - lowElevation), DisplayUnitType.DUT_METERS);
#else
                    double height = UnitUtils.ConvertToInternalUnits((panel.HighElevation() - lowElevation), UnitTypeId.Meters);
#endif


                    parameter.Set(height);
                }

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

                if (Math.Abs(lowElevation - levelElevation) > Core.Tolerance.MacroDistance)
                {
                    parameter = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                    if (parameter != null)
                    {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                        parameter.Set(UnitUtils.ConvertToInternalUnits(lowElevation - levelElevation, DisplayUnitType.DUT_METERS));
#else
                        parameter.Set(UnitUtils.ConvertToInternalUnits(lowElevation - levelElevation, UnitTypeId.Meters));
#endif
                    }
                }

                builtInParameters = new BuiltInParameter[] { BuiltInParameter.WALL_BASE_CONSTRAINT, BuiltInParameter.WALL_BASE_OFFSET, BuiltInParameter.WALL_HEIGHT_TYPE, BuiltInParameter.WALL_USER_HEIGHT_PARAM, BuiltInParameter.WALL_KEY_REF_PARAM };
                result            = wall;
            }
            else if (hostObjAttributes is Autodesk.Revit.DB.FloorType)
            {
                Geometry.Spatial.IClosedPlanar3D closedPlanar3D_External = face3D.GetExternalEdge3D();
                if (!(closedPlanar3D_External is Geometry.Spatial.ICurvable3D))
                {
                    return(null);
                }

                double elevation = panel.LowElevation();
                Level  level     = document.HighLevel(elevation);

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

                CurveArray curveArray_Sloped = new CurveArray();
                CurveArray curveArray_Plane  = new CurveArray();

                Geometry.Spatial.IClosedPlanar3D closedPlanar3D = face3D.GetExternalEdge3D();
                if (!(closedPlanar3D is Geometry.Spatial.ICurvable3D))
                {
                    return(null);
                }

                List <Geometry.Spatial.Segment3D> segment3Ds = Geometry.Revit.Query.Segment3Ds(closedPlanar3D);
                if (segment3Ds == null || segment3Ds.Count == 0)
                {
                    return(null);
                }

                foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds)
                {
                    curveArray_Sloped.Append(segment3D.ToRevit_Line());

                    Geometry.Spatial.Segment3D segment3D_Temp = Geometry.Spatial.Query.Project(plane, segment3D);
                    if (segment3D_Temp == null)
                    {
                        continue;
                    }

                    curveArray_Plane.Append(segment3D_Temp.ToRevit_Line());
                }

#if Revit2017 || Revit2018 || Revit2019 || Revit2020 || Revit2021
                Autodesk.Revit.DB.Floor floor = document.Create.NewFloor(curveArray_Plane, hostObjAttributes as Autodesk.Revit.DB.FloorType, level, false);
#else
                CurveLoop curveLoop = new CurveLoop();
                foreach (Curve curve in curveArray_Plane)
                {
                    curveLoop.Append(curve);
                }

                Autodesk.Revit.DB.Floor floor = Autodesk.Revit.DB.Floor.Create(document, new CurveLoop[] { curveLoop }, hostObjAttributes.Id, level.Id);
#endif

                if (floor != null)
                {
                    floor.ChangeTypeId(hostObjAttributes.Id);

                    List <Geometry.Spatial.IClosedPlanar3D> closedPlanar3Ds_Internal = face3D.GetInternalEdge3Ds();
                    if (closedPlanar3Ds_Internal != null && closedPlanar3Ds_Internal.Count > 0)
                    {
                        //Requires to be regenerated before inserting openings
                        //https://thebuildingcoder.typepad.com/blog/2013/07/create-a-floor-with-an-opening-or-complex-boundary.html
                        document.Regenerate();

                        foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D_Internal in face3D.GetInternalEdge3Ds())
                        {
                            List <Geometry.Spatial.Segment3D> segment3Ds_Internal = Geometry.Revit.Query.Segment3Ds(closedPlanar3D_Internal);
                            if (segment3Ds_Internal == null || segment3Ds_Internal.Count == 0)
                            {
                                continue;
                            }

                            curveArray_Plane = new CurveArray();
                            //foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds)
                            foreach (Geometry.Spatial.Segment3D segment3D in segment3Ds_Internal)
                            {
                                curveArray_Sloped.Append(segment3D.ToRevit_Line());

                                Geometry.Spatial.Segment3D segment3D_Temp = Geometry.Spatial.Query.Project(plane, segment3D);
                                if (segment3D_Temp == null)
                                {
                                    continue;
                                }

                                curveArray_Plane.Append(segment3D_Temp.ToRevit_Line());
                            }

                            Opening opening = document.Create.NewOpening(floor, curveArray_Plane, true);
                        }
                    }
                }

                if (floor != null)
                {
                    document.Regenerate();

                    SlabShapeEditor slabShapeEditor = floor.SlabShapeEditor;
                    if (slabShapeEditor != null)
                    {
                        slabShapeEditor.ResetSlabShape();

                        foreach (Curve curve in curveArray_Sloped)
                        {
                            XYZ xYZ = curve.GetEndPoint(0);
                            slabShapeEditor.DrawPoint(xYZ);
                        }
                    }
                }

                builtInParameters = new BuiltInParameter[] { BuiltInParameter.LEVEL_PARAM };
                result            = floor;
            }
            else if (hostObjAttributes is Autodesk.Revit.DB.RoofType)
            {
                CurveArray curveArray = new CurveArray();
                foreach (Geometry.Spatial.IClosedPlanar3D closedPlanar3D in face3D.GetEdge3Ds())
                {
                    List <Geometry.Spatial.Segment3D> segment3Ds = Geometry.Revit.Query.Segment3Ds(closedPlanar3D);
                    if (segment3Ds == null || segment3Ds.Count == 0)
                    {
                        return(null);
                    }

                    segment3Ds.ForEach(x => curveArray.Append(x.ToRevit_Line()));
                }

                Level  level          = document.HighLevel(panel.LowElevation());
                double levelElevation = level.Elevation;

                ModelCurveArray modelCurveArray = new ModelCurveArray();
                RoofBase        roofBase        = document.Create.NewFootPrintRoof(curveArray, level, hostObjAttributes as Autodesk.Revit.DB.RoofType, out modelCurveArray);

                Parameter parameter = roofBase.get_Parameter(BuiltInParameter.ROOF_UPTO_LEVEL_PARAM);
                if (parameter != null)
                {
                    parameter.Set(ElementId.InvalidElementId);
                }

                SlabShapeEditor slabShapeEditor = roofBase.SlabShapeEditor;
                if (slabShapeEditor != null)
                {
                    slabShapeEditor.ResetSlabShape();

                    foreach (Curve curve in curveArray)
                    {
                        XYZ xYZ = curve.GetEndPoint(0);
                        //if (Math.Abs(xYZ.Z - levelElevation) > Core.Tolerance.MicroDistance)
                        slabShapeEditor.DrawPoint(xYZ);
                    }
                }

                builtInParameters = new BuiltInParameter[] { BuiltInParameter.ROOF_LEVEL_OFFSET_PARAM, BuiltInParameter.ROOF_BASE_LEVEL_PARAM, BuiltInParameter.ROOF_UPTO_LEVEL_PARAM };
                result            = roofBase;
            }

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

            List <Aperture> apertures = panel.Apertures;
            if (apertures != null)
            {
                if (result is Autodesk.Revit.DB.Wall && ((Autodesk.Revit.DB.Wall)result).WallType.Kind == WallKind.Curtain)
                {
                }
                else
                {
                    foreach (Aperture aperture in apertures)
                    {
                        Geometry.Spatial.Plane plane_Aperture = aperture?.PlanarBoundary3D?.Plane;
                        if (plane_Aperture == null)
                        {
                            continue;
                        }

                        //bool flipHand = !plane_Panel.AxisX.SameHalf(plane_Aperture.AxisX);
                        //bool flipFacing = !plane_Panel.Normal.SameHalf(plane_Aperture.Normal);

                        FamilyInstance failyInstance_Aperture = aperture.ToRevit(document, result, convertSettings);
                    }
                }
            }

            if (convertSettings.ConvertParameters)
            {
                Core.Revit.Modify.SetValues(result, panel, builtInParameters);
                Core.Revit.Modify.SetValues(result, panel, ActiveSetting.Setting);

                Core.Revit.Modify.SetJson(result, panel.ToJObject()?.ToString());
            }
            //TODO: Implement proper log
            //System.IO.File.AppendAllText(@"C:\Users\DengusiakM\Desktop\SAM\2020-04-16 floorbug\LOG.txt", string.Format("{0}\t{1}\t{2}\n", DateTime.Now.ToString(), panel.Guid, panel.Name));

            convertSettings?.Add(panel.Guid, result);

            return(result);
        }
示例#19
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            var uidoc = commandData.Application.ActiveUIDocument;
            var doc   = uidoc.Document;

            //Get document file Link
            //var link = new FilteredElementCollector(doc).OfType<RevitLinkInstance>().FirstOrDefault(l => l.Name == "test.rvt");
            //var linkdoc = link.GetLinkDocument();

            var foundations = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFoundation)
                              .WhereElementIsNotElementType()
                              .ToElements();

            foreach (var foundation in foundations)
            {
                //var otp = new Options();
                //otp.DetailLevel = ViewDetailLevel.Fine;
                //var geoElement = foundation.get_Geometry(otp);
                //var instance = geoElement.Cast<GeometryObject>().OfType<GeometryInstance>().Select(i => i.GetInstanceGeometry()).ToList();
                //var solids = geoElement.Cast<GeometryObject>().Concat(instance).OfType<Solid>().Where(s => s.Volume > 0 && s.Faces.Size > 0).ToList();

                //Declare variable
                double offsetTop = 1000;
                offsetTop = UnitUtils.Convert(offsetTop, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET);
                double offsetBot = -100;
                offsetBot = UnitUtils.Convert(offsetBot, DisplayUnitType.DUT_MILLIMETERS, DisplayUnitType.DUT_DECIMAL_FEET);

                var solids = GetTargetSolids(foundation);
                var solid  = solids.OrderByDescending(s => s.Volume).FirstOrDefault();

                var botFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1);
                var offsetbotFace = CurveLoop.CreateViaOffset(botFace.GetEdgesAsCurveLoops().FirstOrDefault(), offsetBot, botFace.FaceNormal);

                var topFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == 1);
                var offsettopFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), offsetTop, topFace.FaceNormal);

                var fdoc = commandData.Application.Application.NewFamilyDocument(@"C:\ProgramData\Autodesk\RVT 2020\Family Templates\English\Metric Generic Model.rft");
                using (Transaction tran = new Transaction(fdoc, "new Blend"))
                {
                    tran.Start();
                    var plan        = Plane.CreateByNormalAndOrigin(XYZ.BasisZ, botFace.Origin);
                    var sketchPlane = SketchPlane.Create(fdoc, plan);
                    var top         = ConvertLoopToArray(offsettopFace);
                    var baseface    = ConvertLoopToArray(botFace.GetEdgesAsCurveLoops().FirstOrDefault());
                    var blend       = fdoc.FamilyCreate.NewBlend(true, top, baseface, sketchPlane);
                    blend.LookupParameter("Second End").Set(Math.Abs(blend.LookupParameter("Second End").AsDouble()));
                    //CreateBlend(fdoc, null);
                    tran.Commit();
                }
                fdoc.SaveAs($"{Path.GetTempPath()}{foundation.Id.ToString()}-{Guid.NewGuid().ToString()}.rfa");
                Family family = fdoc.LoadFamily(doc);
                fdoc.Close();
                using (Transaction tran = new Transaction(doc, "new void"))
                {
                    tran.Start();
                    //offsetFace.ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                    //botFace.GetEdgesAsCurveLoops().FirstOrDefault().ToList().ForEach(f => doc.Create.NewModelCurve(f, SketchPlane.Create(doc, Plane.CreateByThreePoints(f.GetEndPoint(0), f.GetEndPoint(1), new XYZ(0, 0, 1)))));
                    var symbol = doc.GetElement(family.GetFamilySymbolIds().FirstOrDefault()) as FamilySymbol;
                    symbol.Activate();
                    doc.Create.NewFamilyInstance(XYZ.Zero, symbol, Autodesk.Revit.DB.Structure.StructuralType.Footing);
                    tran.Commit();
                }
            }
            return(Result.Succeeded);
        }
示例#20
0
 public static void MoveUnitToBottomLeftSideOfEnemy(SpriteRectangleColliderData SelfSpriteCollider, GameObject EnemyGO, GameObject ThisGO, float speed)
 {
     ThisGO.transform.position = Vector2.MoveTowards(ThisGO.transform.position, UnitUtils.LeftOfEnemyPositionRelativeToSelfSpriteColliderSize(SelfSpriteCollider, EnemyGO), Time.deltaTime * speed);
 }
示例#21
0
        public static (Dictionary <string, List <double> >, Dictionary <ElementId, List <double> >, Dictionary <ElementId, Dictionary <string, double> >) BureauLot(List <Document> docs)
        {
            // creation des dicos
            Dictionary <string, List <double> >    dicolotsurface             = new Dictionary <string, List <double> >();                  // LOT ET SURFACE BUREAU ET REUNION
            Dictionary <ElementId, List <double> > dicolevelsurface           = new Dictionary <ElementId, List <double> >();               // ETAGE ET SURFACE BUREAU ET REUNION
            Dictionary <ElementId, Dictionary <string, double> > dicolotlevel = new Dictionary <ElementId, Dictionary <string, double> >(); // ETAGE ET DICO LOT ET SURFACE

            //Liste pour compte 1 seule fois chaque piece
            List <int> pieceids = new List <int>();

            //On liste les erreurs
            int           nombreerreur  = 0;
            List <string> messageerreur = new List <string>();

            //On passe tous les documents
            foreach (Document doc in docs)
            {
                FilteredElementCollector pieces = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).WhereElementIsNotElementType();
                foreach (Element piece in pieces)
                {
                    try
                    {
                        //on check si la piece a deja ete compté
                        if (pieceids.Contains(piece.Id.IntegerValue))
                        {
                            continue;
                        }
                        // on check que le parametre "Service" n'est pas nul
                        if (piece.get_Parameter(BuiltInParameter.ROOM_DEPARTMENT) == null)
                        {
                            nombreerreur += 1;
                            continue;
                        }

                        string lotpiece = piece.get_Parameter(BuiltInParameter.ROOM_DEPARTMENT).AsString();
                        //on verifie si le parametre "Service" n'est pas vide
                        if (lotpiece == "")
                        {
                            nombreerreur += 1;
                            continue;
                        }

                        ElementId levelpieceid = piece.LevelId;
                        Element   levelpiece   = doc.GetElement(levelpieceid);
                        double    surfacepiece = piece.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble();
                        surfacepiece = UnitUtils.ConvertFromInternalUnits(surfacepiece, DisplayUnitType.DUT_SQUARE_METERS);
                        surfacepiece = Math.Round(surfacepiece, 2);
                        string nompiece = piece.Name;

                        //ANALYSE
                        //NOUVEAU LOT DE PIECE POUR SURFACE LOT ET BUREAU
                        if (dicolotsurface.ContainsKey(lotpiece) == false)
                        {
                            List <double> listetriplezero = new List <double> {
                                0.00, 0.00, 0.00
                            };
                            dicolotsurface.Add(lotpiece, listetriplezero);
                            dicolotsurface[lotpiece][0] += surfacepiece;
                            //SI LA PIECE EST UN BUREAU
                            if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau"))
                            {
                                dicolotsurface[lotpiece][1] += surfacepiece;
                            }
                            //SI LA PIECE EST UNE SALLE DE REUNION
                            else if (nompiece.Contains("reunion") | nompiece.Contains("REUNION") | nompiece.Contains("réunion"))
                            {
                                dicolotsurface[lotpiece][2] += surfacepiece;
                            }
                        }

                        //LOT DEJA VU
                        else
                        {
                            //
                            dicolotsurface[lotpiece][0] += surfacepiece;
                            if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau"))
                            {
                                dicolotsurface[lotpiece][1] += surfacepiece;
                            }
                            else if (nompiece.Contains("réunion") | nompiece.Contains("REUNION") | nompiece.Contains("reunion"))
                            {
                                dicolotsurface[lotpiece][2] += surfacepiece;
                            }
                        }
                        // SI NOUVEL ETAGE DICO SURFACE ETAGE ET BUREAU REU
                        if (dicolevelsurface.ContainsKey(levelpieceid) == false)
                        {
                            List <double> listedoublezero = new List <double> {
                                0.00, 0.00
                            };
                            dicolevelsurface.Add(levelpieceid, listedoublezero);
                            if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau"))
                            {
                                dicolevelsurface[levelpieceid][0] += surfacepiece;
                            }
                            else if (nompiece.Contains("reunion") | nompiece.Contains("REUNION") | nompiece.Contains("réunion"))
                            {
                                dicolevelsurface[levelpieceid][1] += surfacepiece;
                            }
                        }
                        else
                        {
                            if (nompiece.Contains("BUREAU") | nompiece.Contains("Bureau") | nompiece.Contains("bureau"))
                            {
                                dicolevelsurface[levelpieceid][0] += surfacepiece;
                            }
                            else if (nompiece.Contains("reunion") | nompiece.Contains("REUNION") | nompiece.Contains("réunion"))
                            {
                                dicolevelsurface[levelpieceid][1] += surfacepiece;
                            }
                        }
                        // SURFACE ETAGE LOT
                        if (dicolotlevel.ContainsKey(levelpieceid) == false)
                        {
                            Dictionary <string, double> nvletage = new Dictionary <string, double>();
                            nvletage.Add(lotpiece, surfacepiece);
                            dicolotlevel.Add(levelpieceid, nvletage);
                        }
                        else
                        {
                            if (dicolotlevel[levelpieceid].ContainsKey(lotpiece))
                            {
                                dicolotlevel[levelpieceid][lotpiece] += surfacepiece;
                            }
                            else
                            {
                                dicolotlevel[levelpieceid].Add(lotpiece, surfacepiece);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        string meser = e.Message;
                        if (messageerreur.Contains(meser) != true)
                        {
                            messageerreur.Add(meser);
                        }
                        nombreerreur += 1;
                    }
                }
            }

            if (nombreerreur != 0)
            {
                foreach (string erreur in messageerreur)
                {
                    TaskDialog.Show("Erreur lors de la récupération des pièces", " Message d'erreur :" + Environment.NewLine + string.Format("{0}", erreur));
                }
            }
            return(dicolotsurface, dicolevelsurface, dicolotlevel);
        }
示例#22
0
        public static ForgeTypeId UnitTypeId(this ForgeTypeId specTypeId)
        {
            if (specTypeId == SpecTypeId.Number)
            {
                return(null);
            }

            IEnumerable <ForgeTypeId> unitTypeIds = UnitUtils.GetValidUnits(specTypeId);

            if (unitTypeIds == null || unitTypeIds.Count() == 0)
            {
                return(null);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Meters))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Meters);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Kilograms))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Kilograms);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Celsius))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Celsius);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Amperes))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Amperes);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Watts))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Watts);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.WattsPerCubicMeter))
            {
                return(Autodesk.Revit.DB.UnitTypeId.WattsPerCubicMeter);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.WattsPerMeterKelvin))
            {
                return(Autodesk.Revit.DB.UnitTypeId.WattsPerMeterKelvin);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.WattsPerSquareMeterKelvin))
            {
                return(Autodesk.Revit.DB.UnitTypeId.WattsPerSquareMeterKelvin);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.CubicMeters))
            {
                return(Autodesk.Revit.DB.UnitTypeId.CubicMeters);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.SquareMeters))
            {
                return(Autodesk.Revit.DB.UnitTypeId.SquareMeters);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.CubicMetersPerSecond))
            {
                return(Autodesk.Revit.DB.UnitTypeId.CubicMetersPerSecond);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.WattsPerSquareMeter))
            {
                return(Autodesk.Revit.DB.UnitTypeId.WattsPerSquareMeter);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Volts))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Volts);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.KilogramsForce))
            {
                return(Autodesk.Revit.DB.UnitTypeId.KilogramsForce);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Lux))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Lux);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Lumens))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Lumens);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.Pascals))
            {
                return(Autodesk.Revit.DB.UnitTypeId.Pascals);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.PascalsPerMeter))
            {
                return(Autodesk.Revit.DB.UnitTypeId.PascalsPerMeter);
            }

            if (unitTypeIds.Contains(Autodesk.Revit.DB.UnitTypeId.KilogramsPerCubicMeter))
            {
                return(Autodesk.Revit.DB.UnitTypeId.KilogramsPerCubicMeter);
            }

            return(null);
        }
示例#23
0
 private double ScaleToNative(double value, string units)
 {
     return(UnitUtils.ConvertToInternalUnits(value, UnitsToNative(units)));
 }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            _uiapp = commandData.Application;
            _uidoc = _uiapp.ActiveUIDocument;
            _doc   = _uidoc.Document;
            try
            {
                // Get list of all structural levels
                IList <Level> strLevels = GetAllLevels(_doc, true, true);
                if (strLevels.Count == 0)
                {
                    return(Result.Cancelled);
                }

                // Get list of all CAD files
                IList <ImportInstance> cadFileLinksList = GetAllCADFiles(_doc);
                if (cadFileLinksList.Count == 0)
                {
                    return(Result.Cancelled);
                }

                // Get list of all views
                IList <ViewPlan> viewPlanList = GetAllStructuralPlans(_doc, true);
                if (viewPlanList.Count == 0)
                {
                    return(Result.Cancelled);
                }

                // Set offset to -0.1m for each CAD file
                foreach (ImportInstance cad in cadFileLinksList)
                {
                    using (Transaction tx = new Transaction(_doc, "Set offset for each CAD file"))
                    {
                        tx.Start();
                        cad.get_Parameter(BuiltInParameter.IMPORT_BASE_LEVEL_OFFSET).Set(
                            UnitUtils.Convert(-0.1, DisplayUnitType.DUT_METERS, DisplayUnitType.DUT_DECIMAL_FEET));
                        tx.Commit();
                    }
                }

                foreach (ViewPlan view in viewPlanList)
                {
                    Level viewLvl = view.GenLevel;
                    Level supLvl  = strLevels.Where(lvl => lvl.Elevation > viewLvl.Elevation).OrderBy(l => l.Elevation).FirstOrDefault();
                    using (Transaction tx = new Transaction(_doc))
                    {
                        tx.Start("Underlay Range");
                        if (supLvl != null)
                        {
                            view.SetUnderlayRange(viewLvl.Id, supLvl.Id);
                        }
                        else
                        {
                            view.SetUnderlayBaseLevel(viewLvl.Id);
                        }
                        tx.Commit();
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception e)
            {
                message = e.Message;
                return(Result.Failed);
            }
        }
示例#25
0
 private double ScaleToSpeckle(double value)
 {
     return(UnitUtils.ConvertFromInternalUnits(value, RevitLengthTypeId));
 }
示例#26
0
 private System.Windows.Media.Media3D.Vector3D ConvertToDisplayUnits(System.Windows.Media.Media3D.Vector3D v)
 {
     return(new System.Windows.Media.Media3D.Vector3D(UnitUtils.ConvertFromInternalUnits(v.X, BIM.OpenFOAMExport.Exporter.Instance.settings.Units), UnitUtils.ConvertFromInternalUnits(v.Y, BIM.OpenFOAMExport.Exporter.Instance.settings.Units), UnitUtils.ConvertFromInternalUnits(v.Z, BIM.OpenFOAMExport.Exporter.Instance.settings.Units)));
 }
示例#27
0
文件: Utilits.cs 项目: veabim/veabim
 /// <summary>
 /// Перевод вольтампер в число
 /// </summary>
 public static double VA_D(double va)
 {
     return(UnitUtils.ConvertFromInternalUnits(va, DisplayUnitType.DUT_KILOVOLT_AMPERES));
 }
示例#28
0
        public void ExportDataHydro()
        {
            ExternalCommandData revit = Transfer.revit;
            UIApplication       uiApp = revit.Application;
            Document            doc   = uiApp.ActiveUIDocument.Document;
            Selection           sel   = uiApp.ActiveUIDocument.Selection;

            List <BuiltInCategory> listCategories = new List <BuiltInCategory>()
            {
                BuiltInCategory.OST_PipeCurves,
                BuiltInCategory.OST_PipeFitting,
                BuiltInCategory.OST_PipeAccessory,
                BuiltInCategory.OST_FlexPipeCurves
            };

            LibCategories  libCategories = new LibCategories();
            List <Element> listElements  = libCategories.AllElnewe(doc, listCategories).ToList();

            if (listElements[0].LookupParameter("entools_number") == null)
            {
                TaskDialog.Show("Error", "Parameter entools_number missing.");

                return;
            }

            listElements = listElements.OrderBy(x => int.Parse(x.LookupParameter("entools_number").AsValueString())).ToList();

            const BuiltInParameter bipSyst          = BuiltInParameter.RBS_DUCT_PIPE_SYSTEM_ABBREVIATION_PARAM;
            const BuiltInParameter bipDiameterInner = BuiltInParameter.RBS_PIPE_INNER_DIAM_PARAM;
            const BuiltInParameter bipLength        = BuiltInParameter.CURVE_ELEM_LENGTH;
            const BuiltInParameter bipSize          = BuiltInParameter.RBS_CALCULATED_SIZE;
            const BuiltInParameter minSize          = BuiltInParameter.RBS_PIPE_SIZE_MINIMUM;
            const BuiltInParameter maxSize          = BuiltInParameter.RBS_PIPE_SIZE_MAXIMUM;

            var listId     = new List <object>();
            var listName   = new List <object>();
            var listType   = new List <object>();
            var listDo     = new List <object>();
            var listDi     = new List <object>();
            var listLength = new List <object>();
            var listKvs    = new List <object>();

            try
            {
                Reference selection = sel.PickObject(ObjectType.Element, "Select element of system");
                Element   element   = doc.GetElement(selection);

                string stype   = element.get_Parameter(bipSyst).AsString();
                string i       = string.Empty;
                string getType = string.Empty;
                double getLen;
                double dinner;
                string size    = string.Empty;
                string minsize = string.Empty;
                string maxsize = string.Empty;
                string id      = string.Empty;

                listElements = listElements.Where(x => x.get_Parameter(bipSyst).AsString() == stype).ToList();

                foreach (Element pipe in listElements)
                {
                    if (pipe.LookupParameter("entools_number") == null)
                    {
                        TaskDialog.Show("Error", "Parameter entools_number missing.");
                        break;
                    }
                    else
                    {
                        getType = pipe.get_Parameter(bipSyst).AsString();
                        i       = pipe.LookupParameter("entools_number").AsValueString();
                        size    = pipe.get_Parameter(bipSize).AsString();

                        Category        category        = pipe.Category;
                        BuiltInCategory builtInCategory = (BuiltInCategory)category.Id.IntegerValue;

                        if (builtInCategory == BuiltInCategory.OST_PipeCurves)
                        {
                            id     = pipe.Id.ToString();
                            getLen = pipe.get_Parameter(bipLength).AsDouble();
                            dinner = pipe.get_Parameter(bipDiameterInner).AsDouble();
                            getLen = Math.Round(UnitUtils.ConvertFromInternalUnits(getLen, DisplayUnitType.DUT_MILLIMETERS), 0);
                            dinner = Math.Round(UnitUtils.ConvertFromInternalUnits(dinner, DisplayUnitType.DUT_MILLIMETERS), 1);

                            listName.Add(getType + ":" + i.ToString());
                            listId.Add(pipe.Id.ToString());
                            listType.Add("PIP");
                            listDo.Add(size.Replace('.', ','));
                            listDi.Add(dinner.ToString().Replace('.', ','));
                            listLength.Add(getLen.ToString().Replace('.', ','));
                            listKvs.Add(pipe.LookupParameter("entools_kvse").AsValueString());
                        }

                        if (builtInCategory == BuiltInCategory.OST_PipeFitting)
                        {
                            minsize = pipe.get_Parameter(minSize).AsValueString();
                            maxsize = pipe.get_Parameter(maxSize).AsValueString();
                            listName.Add(getType + ":" + i.ToString());
                            listId.Add(pipe.Id.ToString());
                            listType.Add("FIT");
                            listDo.Add(maxsize.Replace('.', ',') + "-" + minsize.Replace('.', ','));
                            listDi.Add(minsize.Replace('.', ','));
                            listLength.Add("-");
                            listKvs.Add(pipe.LookupParameter("entools_kvse").AsValueString());
                        }

                        if (builtInCategory == BuiltInCategory.OST_PipeAccessory)
                        {
                            listName.Add(getType + ":" + i.ToString());
                            listId.Add(pipe.Id.ToString());
                            listType.Add("ACC");
                            listDo.Add(size);
                            listDi.Add("-");
                            listLength.Add("-");
                            listKvs.Add(pipe.LookupParameter("entools_kvse").AsValueString());
                        }

                        if (builtInCategory == BuiltInCategory.OST_FlexPipeCurves)
                        {
                            getLen = pipe.get_Parameter(bipLength).AsDouble();
                            dinner = pipe.get_Parameter(bipDiameterInner).AsDouble();
                            getLen = Math.Round(UnitUtils.ConvertFromInternalUnits(getLen, DisplayUnitType.DUT_MILLIMETERS), 0);
                            dinner = Math.Round(UnitUtils.ConvertFromInternalUnits(dinner, DisplayUnitType.DUT_MILLIMETERS), 1);

                            listName.Add(getType + ":" + i.ToString());
                            listId.Add(pipe.Id.ToString());
                            listType.Add("FLE");
                            listDo.Add(size.Replace('.', ','));
                            listDi.Add(dinner.ToString());
                            listLength.Add(getLen.ToString());
                            listKvs.Add("-");
                        }
                    }
                }

                ExportGD(listName, listType, listId, listDo, listDi, listLength, listKvs);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
                TaskDialog.Show("Report", "Canceled");
            }
        }
示例#29
0
        public void ExportLinkedDocuments(Autodesk.Revit.DB.Document document, string fileName, Dictionary <ElementId, string> linksGUIDsCache, IFCExportOptions exportOptions)
        {
            // get the extension
            int index = fileName.LastIndexOf('.');

            if (index <= 0)
            {
                return;
            }
            string sExtension = fileName.Substring(index);

            fileName = fileName.Substring(0, index);

            // get all the revit link instances
            FilteredElementCollector collector        = new FilteredElementCollector(document);
            ElementFilter            elementFilter    = new ElementClassFilter(typeof(RevitLinkInstance));
            List <RevitLinkInstance> rvtLinkInstances = collector.WherePasses(elementFilter).Cast <RevitLinkInstance>().ToList();

            IDictionary <String, int> rvtLinkNamesDict = new Dictionary <String, int>();
            IDictionary <String, List <RevitLinkInstance> > rvtLinkNamesToInstancesDict = new Dictionary <String, List <RevitLinkInstance> >();

            try
            {
                // get the link types
                foreach (RevitLinkInstance rvtLinkInstance in rvtLinkInstances)
                {
                    // get the instance
                    if (rvtLinkInstance == null)
                    {
                        continue;
                    }

                    // check the cache
                    if (linksGUIDsCache.Keys.Contains(rvtLinkInstance.Id) == false)
                    {
                        continue;
                    }

                    // get the link document
                    Document linkDocument = rvtLinkInstance.GetLinkDocument();
                    if (linkDocument == null)
                    {
                        continue;
                    }

                    // get the link file path and name
                    String    linkPathName          = "";
                    Parameter originalFileNameParam = linkDocument.ProjectInformation.get_Parameter("Original IFC File Name");
                    if (originalFileNameParam != null && originalFileNameParam.StorageType == StorageType.String)
                    {
                        linkPathName = originalFileNameParam.AsString();
                    }
                    else
                    {
                        linkPathName = linkDocument.PathName;
                    }

                    // get the link file name
                    String linkFileName = "";
                    index = linkPathName.LastIndexOf("\\");
                    if (index > 0)
                    {
                        linkFileName = linkPathName.Substring(index + 1);
                    }
                    else
                    {
                        linkFileName = linkDocument.Title;
                    }

                    // remove the extension
                    index = linkFileName.LastIndexOf('.');
                    if (index > 0)
                    {
                        linkFileName = linkFileName.Substring(0, index);
                    }

                    // add to names count dictionary
                    if (!rvtLinkNamesDict.Keys.Contains(linkFileName))
                    {
                        rvtLinkNamesDict.Add(linkFileName, 0);
                    }
                    rvtLinkNamesDict[linkFileName]++;

                    // add to names instances dictionary
                    if (!rvtLinkNamesToInstancesDict.Keys.Contains(linkPathName))
                    {
                        rvtLinkNamesToInstancesDict.Add(linkPathName, new List <RevitLinkInstance>());
                    }
                    rvtLinkNamesToInstancesDict[linkPathName].Add(rvtLinkInstance);
                }
            }
            catch
            {
            }

            // get the link instances
            // We will keep track of the instances we can't export.
            // Reasons we can't export:
            // 1. The path for the linked instance doesn't exist.
            // 2. Couldn't create a temporary document for exporting the linked instance.
            // 3. The document for the linked instance can't be found.
            // 4. The linked instance is mirrored, non-conformal, or scaled.
            IList <string>    pathDoesntExist   = new List <string>();
            IList <string>    noTempDoc         = new List <string>();
            IList <ElementId> cantFindDoc       = new List <ElementId>();
            IList <ElementId> nonConformalInst  = new List <ElementId>();
            IList <ElementId> scaledInst        = new List <ElementId>();
            IList <ElementId> instHasReflection = new List <ElementId>();

            foreach (String linkPathName in rvtLinkNamesToInstancesDict.Keys)
            {
                // get the name of the copy
                String linkPathNameCopy = System.IO.Path.GetTempPath();
                index = linkPathName.LastIndexOf("\\");
                if (index > 0)
                {
                    linkPathNameCopy += linkPathName.Substring(index + 1);
                }
                else
                {
                    linkPathNameCopy += linkPathName;
                }
                index = linkPathNameCopy.LastIndexOf('.');
                if (index <= 0)
                {
                    index = linkPathNameCopy.Length;
                }
                linkPathNameCopy = linkPathNameCopy.Insert(index, " - Copy");
                int i = 1;
                while (File.Exists(linkPathNameCopy))
                {
                    linkPathNameCopy = linkPathNameCopy.Insert(index, "(" + (++i).ToString() + ")");
                }

                // copy the file
                File.Copy(linkPathName, linkPathNameCopy);
                if (!File.Exists(linkPathNameCopy))
                {
                    pathDoesntExist.Add(linkPathName);
                    continue;
                }

                // open the document
                Document documentCopy = null;
                try
                {
                    if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip"))
                    {
                        documentCopy = document.Application.OpenIFCDocument(linkPathNameCopy);
                    }
                    else
                    {
                        documentCopy = document.Application.OpenDocumentFile(linkPathNameCopy);
                    }
                }
                catch
                {
                    documentCopy = null;
                }

                if (documentCopy == null)
                {
                    noTempDoc.Add(linkPathName);
                    continue;
                }

                // get the link document unit scale
                DisplayUnitType dutLink = documentCopy.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;
                double          lengthScaleFactorLink = UnitUtils.ConvertFromInternalUnits(1.0, dutLink);

                // get the link instances
                List <RevitLinkInstance> currRvtLinkInstances = rvtLinkNamesToInstancesDict[linkPathName];
                IList <string>           serTransforms        = new List <string>();
                IList <string>           linkFileNames        = new List <string>();

                foreach (RevitLinkInstance currRvtLinkInstance in currRvtLinkInstances)
                {
                    // Nothing to report if the element itself is null.
                    if (currRvtLinkInstance == null)
                    {
                        continue;
                    }

                    // get the link document
                    Document linkDocument = currRvtLinkInstance.GetLinkDocument();
                    if (linkDocument == null)
                    {
                        cantFindDoc.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    // get the link transform
                    Transform tr = currRvtLinkInstance.GetTransform();

                    // We can't handle non-conformal, scaled, or mirrored transforms.
                    if (!tr.IsConformal)
                    {
                        nonConformalInst.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    if (tr.HasReflection)
                    {
                        instHasReflection.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    if (!MathUtil.IsAlmostEqual(tr.Determinant, 1.0))
                    {
                        scaledInst.Add(currRvtLinkInstance.Id);
                        continue;
                    }

                    // get the link file path and name
                    String linkFileName = "";
                    index = linkPathName.LastIndexOf("\\");
                    if (index > 0)
                    {
                        linkFileName = linkPathName.Substring(index + 1);
                    }
                    else
                    {
                        linkFileName = linkDocument.Title;
                    }

                    // remove the extension
                    index = linkFileName.LastIndexOf('.');
                    if (index > 0)
                    {
                        linkFileName = linkFileName.Substring(0, index);
                    }

                    //if link was an IFC file then make a different formating to the file name
                    if ((linkPathName.Length >= 4 && linkPathName.Substring(linkPathName.Length - 4).ToLower() == ".ifc") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifcxml") ||
                        (linkPathName.Length >= 7 && linkPathName.Substring(linkPathName.Length - 7).ToLower() == ".ifczip"))
                    {
                        String fName = fileName;

                        //get output path and add to the new file name
                        index = fName.LastIndexOf("\\");
                        if (index > 0)
                        {
                            fName = fName.Substring(0, index + 1);
                        }
                        else
                        {
                            fName = "";
                        }

                        //construct IFC file name
                        linkFileName = fName + linkFileName + "-";

                        //add guid
                        linkFileName += linksGUIDsCache[currRvtLinkInstance.Id];
                    }
                    else
                    {
                        // check if there are multiple instances with the same name
                        bool bMultiple = (rvtLinkNamesDict[linkFileName] > 1);

                        // add the path
                        linkFileName = fileName + "-" + linkFileName;

                        // add the guid
                        if (bMultiple)
                        {
                            linkFileName += "-";
                            linkFileName += linksGUIDsCache[currRvtLinkInstance.Id];
                        }
                    }

                    // add the extension
                    linkFileName += sExtension;

                    linkFileNames.Add(linkFileName);

                    // scale the transform origin
                    tr.Origin *= lengthScaleFactorLink;

                    // serialize transform
                    serTransforms.Add(SerializeTransform(tr));
                }

                // IFC export requires an open transaction, although no changes should be made
                Transaction transaction = new Transaction(documentCopy, "Export IFC Link");
                transaction.Start();
                FailureHandlingOptions failureOptions = transaction.GetFailureHandlingOptions();
                failureOptions.SetClearAfterRollback(false);
                transaction.SetFailureHandlingOptions(failureOptions);

                // export
                try
                {
                    int numLinkInstancesToExport = linkFileNames.Count;
                    exportOptions.AddOption("NumberOfExportedLinkInstances", numLinkInstancesToExport.ToString());

                    for (int ii = 0; ii < numLinkInstancesToExport; ii++)
                    {
                        string optionName = (ii == 0) ? "ExportLinkInstanceTransform" : "ExportLinkInstanceTransform" + (ii + 1).ToString();
                        exportOptions.AddOption(optionName, serTransforms[ii]);

                        // Don't pass in file name for the first link instance.
                        if (ii == 0)
                        {
                            continue;
                        }

                        optionName = "ExportLinkInstanceFileName" + (ii + 1).ToString();
                        exportOptions.AddOption(optionName, linkFileNames[ii]);
                    }

                    // Pass in the first value; the rest will  be in the options.
                    String path_     = Path.GetDirectoryName(linkFileNames[0]);
                    String fileName_ = Path.GetFileName(linkFileNames[0]);
                    bool   result    = documentCopy.Export(path_, fileName_, exportOptions); // pass in the options here
                }
                catch
                {
                }

                // rollback the transaction
                transaction.RollBack();

                // close the document
                documentCopy.Close(false);

                // delete the copy
                try
                {
                    File.Delete(linkPathNameCopy);
                }
                catch
                {
                }

                // Show user errors, if any.
                int numBadInstances = pathDoesntExist.Count + noTempDoc.Count + cantFindDoc.Count + nonConformalInst.Count
                                      + scaledInst.Count + instHasReflection.Count;
                if (numBadInstances > 0)
                {
                    using (TaskDialog taskDialog = new TaskDialog(Properties.Resources.IFCExport))
                    {
                        taskDialog.MainInstruction = string.Format(Properties.Resources.LinkInstanceExportErrorMain, numBadInstances);
                        taskDialog.MainIcon        = TaskDialogIcon.TaskDialogIconWarning;
                        taskDialog.TitleAutoPrefix = false;

                        string expandedContent = "";
                        AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportErrorPath, pathDoesntExist);
                        AddExpandedStringContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantCreateDoc, noTempDoc);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportCantFindDoc, cantFindDoc);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportNonConformal, nonConformalInst);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportScaled, scaledInst);
                        AddExpandedElementIdContent(ref expandedContent, Properties.Resources.LinkInstanceExportHasReflection, instHasReflection);

                        taskDialog.ExpandedContent = expandedContent;
                        TaskDialogResult result = taskDialog.Show();
                    }
                }
            }
        }
        /// <summary>
        /// Get triangles in a solid with transform.
        /// </summary>
        /// <param name="solid">The solid contains triangulars</param>
        /// <param name="transform">The transformation.</param>
        private void GetTriangular(Document document, Solid solid, Transform transform)
        {
            // a solid has many faces
            FaceArray faces        = solid.Faces;
            bool      hasTransform = (null != transform);

            if (0 == faces.Size)
            {
                return;
            }

            foreach (Face face in faces)
            {
                if (face.Visibility != Visibility.Visible)
                {
                    continue;
                }
                Mesh mesh = face.Triangulate();
                if (null == mesh)
                {
                    continue;
                }

                m_TriangularNumber += mesh.NumTriangles;

                PlanarFace planarFace = face as PlanarFace;

                // write face to stl file
                // a face has a mesh, all meshes are made of triangles
                for (int ii = 0; ii < mesh.NumTriangles; ii++)
                {
                    MeshTriangle          triangular = mesh.get_Triangle(ii);
                    double[]              xyz        = new double[9];
                    Autodesk.Revit.DB.XYZ normal     = new Autodesk.Revit.DB.XYZ();
                    try
                    {
                        Autodesk.Revit.DB.XYZ[] triPnts = new Autodesk.Revit.DB.XYZ[3];
                        for (int n = 0; n < 3; ++n)
                        {
                            double x, y, z;
                            Autodesk.Revit.DB.XYZ point = triangular.get_Vertex(n);
                            if (hasTransform)
                            {
                                point = transform.OfPoint(point);
                            }
                            if (m_Settings.ExportSharedCoordinates)
                            {
                                ProjectPosition ps = document.ActiveProjectLocation.GetProjectPosition(point);
                                x = ps.EastWest;
                                y = ps.NorthSouth;
                                z = ps.Elevation;
                            }
                            else
                            {
                                x = point.X;
                                y = point.Y;
                                z = point.Z;
                            }
                            if (!m_Settings.Units.Empty())
                            {
                                xyz[3 * n]     = UnitUtils.ConvertFromInternalUnits(x, m_Settings.Units);
                                xyz[3 * n + 1] = UnitUtils.ConvertFromInternalUnits(y, m_Settings.Units);
                                xyz[3 * n + 2] = UnitUtils.ConvertFromInternalUnits(z, m_Settings.Units);
                            }
                            else
                            {
                                xyz[3 * n]     = x;
                                xyz[3 * n + 1] = y;
                                xyz[3 * n + 2] = z;
                            }

                            var mypoint = new XYZ(xyz[3 * n], xyz[3 * n + 1], xyz[3 * n + 2]);
                            triPnts[n] = mypoint;
                        }

                        Autodesk.Revit.DB.XYZ pnt1 = triPnts[1] - triPnts[0];
                        normal = pnt1.CrossProduct(triPnts[2] - triPnts[1]);
                    }
                    catch (Exception ex)
                    {
                        m_TriangularNumber--;
                        STLDialogManager.ShowDebug(ex.Message);
                        continue;
                    }

                    if (m_Writer is SaveDataAsBinary && m_Settings.ExportColor)
                    {
                        Material material = document.GetElement(face.MaterialElementId) as Material;
                        if (material != null)
                        {
                            ((SaveDataAsBinary)m_Writer).Color = material.Color;
                        }
                    }

                    m_Writer.WriteSection(normal, xyz);
                }
            }
        }