private static void SetParameterValue(
            Element element, Parameter parameter, NumerateData numerateData, int markNumber, bool isInstanceParameter)
        {
            if (element.GroupId != ElementId.InvalidElementId &&
                parameter.Definition is InternalDefinition internalDefinition &&
                isInstanceParameter)
            {
                // Параметр в группе меняем без разгруппировки, если:
                // 1 - это стандартный параметр "Марка"
                // 2 - это общий параметр проекта с включенным свойством "Значения могут меняться по экземплярам групп"
                if (!internalDefinition.VariesAcrossGroups &&
                    internalDefinition.BuiltInParameter != BuiltInParameter.ALL_MODEL_MARK)
                {
                    // Невозможно изменить параметр экземпляра у элемента, расположенного в группе, если у параметра не
                    // включено свойство "Значения могут меняться по экземплярам групп" или это не системный параметр "Марка"
                    throw new ArgumentException(Language.GetItem(LangItem, "h16"));
                }
            }

            if (numerateData.Parameter.IsNumeric)
            {
                if (parameter.StorageType == StorageType.Integer)
                {
                    parameter.Set(markNumber);
                }
                else if (parameter.StorageType == StorageType.Double)
                {
#if R2017 || R2018 || R2019 || R2020
                    parameter.Set(UnitUtils.ConvertToInternalUnits(markNumber, parameter.DisplayUnitType));
#else
                    parameter.Set(UnitUtils.ConvertToInternalUnits(markNumber, parameter.GetUnitTypeId()));
#endif
                }
            }
            else
            {
                parameter.Set($"{numerateData.Prefix}{string.Format(numerateData.Format, markNumber)}{numerateData.Suffix}");
            }
        }
Example #2
0
        public void MoveWallsUp()
        {
            var walls = fixture.Walls.Where(x => x.Id.IntegerValue != 346573);

            xru.RunInTransaction(() =>
            {
                foreach (var wall in walls)
                {
                    var param      = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                    var baseOffset = UnitUtils.ConvertToInternalUnits(2000, param.DisplayUnitType);
                    param.Set(baseOffset);
                }
            }, fixture.Doc)
            .Wait(); // Important! Wait for action to finish

            foreach (var wall in walls)
            {
                var param      = wall.get_Parameter(BuiltInParameter.WALL_BASE_OFFSET);
                var baseOffset = UnitUtils.ConvertFromInternalUnits(param.AsDouble(), param.DisplayUnitType);
                Assert.Equal(2000, baseOffset);
            }
        }
            private static void CreateDimensions(
                FilledRegion filledRegion,
                XYZ dimensionDirection)
            {
                var document = filledRegion.Document;

                var view = (View)document.GetElement(
                    filledRegion.OwnerViewId);

                var edgesDirection = dimensionDirection.CrossProduct(
                    view.ViewDirection);

                var edges = FindRegionEdges(filledRegion)
                            .Where(x => IsEdgeDirectionSatisfied(x, edgesDirection))
                            .ToList();

                if (edges.Count < 2)
                {
                    return;
                }

                var shift = UnitUtils.ConvertToInternalUnits(
                    -10 * view.Scale, DisplayUnitType.DUT_MILLIMETERS)
                            * edgesDirection;

                var dimensionLine = Line.CreateUnbound(
                    filledRegion.get_BoundingBox(view).Min
                    + shift, dimensionDirection);

                var references = new ReferenceArray();

                foreach (var edge in edges)
                {
                    references.Append(edge.Reference);
                }

                document.Create.NewDimension(view, dimensionLine,
                                             references);
            }
Example #4
0
        /// <summary>
        /// Aplies the slope in a determined FootPrintRoof.
        /// </summary>
        /// <param name="overhang">The overhang value.</param>
        /// <param name="slope">The slope of the roof</param>
        /// <param name="slopeDirection">The vector that represents the directions that the slope should be applied.</param>
        /// <param name="footPrintRoof">The Roof</param>
        /// <param name="footPrintToModelCurveMapping">The ModelCurveArray generated with the roof instance.</param>
        private static void ApplySlope(double overhang, double slope, XYZ slopeDirection, FootPrintRoof footPrintRoof, ModelCurveArray footPrintToModelCurveMapping)
        {
            ModelCurveArrayIterator iterator = footPrintToModelCurveMapping.ForwardIterator();

            iterator.Reset();

            while (iterator.MoveNext())
            {
                ModelCurve modelCurve     = iterator.Current as ModelCurve;
                Curve      curve          = modelCurve.GeometryCurve;
                XYZ        curveDirection = VectorManipulator.GetCurveDirection(curve);

                if (curveDirection.DotProduct(slopeDirection) == 0)
                {
                    footPrintRoof.set_DefinesSlope(modelCurve, true);
                    footPrintRoof.set_SlopeAngle(modelCurve, slope);
                }

                double elevation = -(overhang - UnitUtils.ConvertToInternalUnits(0.1, UnitTypeId.Meters)) / 3;
                footPrintRoof.set_Offset(modelCurve, elevation);
            }
        }
Example #5
0
        void CreateFloorOri(double x, double y, double hh, double rr)
        {
            double     nx   = UnitUtils.ConvertToInternalUnits(x, DisplayUnitType.DUT_MILLIMETERS);
            double     ny   = UnitUtils.ConvertToInternalUnits(y, DisplayUnitType.DUT_MILLIMETERS);
            double     nh   = UnitUtils.ConvertToInternalUnits(hh, DisplayUnitType.DUT_MILLIMETERS);
            double     nrr  = UnitUtils.ConvertToInternalUnits(rr, DisplayUnitType.DUT_MILLIMETERS);
            CurveArray cur  = new CurveArray();
            Arc        arc1 = Arc.Create(Plane.CreateByNormalAndOrigin(new XYZ(0, 0, 1), new XYZ(nx, ny, hh)), nrr, 0, Math.PI);
            Arc        arc2 = Arc.Create(Plane.CreateByNormalAndOrigin(new XYZ(0, 0, 1), new XYZ(nx, ny, hh)), nrr, Math.PI, Math.PI * 2);

            cur.Append(arc1);
            cur.Append(arc2);
            using (Transaction tran = new Transaction(revitDoc))
            {
                tran.Start("Create floor : ");
                Units u = new Units(UnitSystem.Metric);
                revitDoc.SetUnits(u);
                Floor floor = revitDoc.Create.NewFloor(cur, false);
                //Floor floor = revitDoc.Create.NewFloor(cur,;
                tran.Commit();
            }
        }
Example #6
0
        ////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            if (commandData == null)
            {
                return(Result.Failed);
            }

            UIDocument udoc = commandData.Application.ActiveUIDocument;

            if (udoc.Document.IsFamilyDocument)
            {
                SCaddinsApp.WindowManager.ShowErrorMessageBox("Families not supported", "Solar analysis tools will not work in a family environment.");
                return(Result.Failed);
            }

            var vm = new ViewModels.SolarViewsViewModel(commandData.Application.ActiveUIDocument);

            SCaddinsApp.WindowManager.ShowDialog(vm, null, ViewModels.SolarViewsViewModel.DefaultViewSettings);

            if (vm.CreateAnalysisView)
            {
#if REVIT2021 || REVIT2022 || REVIT2023
                var internalUnitsGridSize = UnitUtils.ConvertToInternalUnits(vm.AnalysisGridSize, UnitTypeId.Millimeters);
#else
                var internalUnitsGridSize = UnitUtils.ConvertToInternalUnits(vm.AnalysisGridSize, DisplayUnitType.DUT_MILLIMETERS);
#endif
                SolarAnalysisManager.CreateTestFaces(vm.FaceSelection, vm.MassSelection, internalUnitsGridSize, udoc, udoc.ActiveView);
            }
            if (vm.DrawSolarRay)
            {
                SolarAnalysisManager.DrawSolarRayAsModelLine(udoc, vm.SolarRayLength);
            }

            return(Result.Succeeded);
        }
Example #7
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try {
                UIDocument uidoc = commandData.Application.ActiveUIDocument;

                Document doc = uidoc.Document;

                FilteredElementCollector collector = new FilteredElementCollector(doc);

                ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_Windows);

                IList <Element> windows = collector.WherePasses(filter).WhereElementIsNotElementType().ToElements();

                foreach (Element ele in windows)
                {
                    Parameter para     = ele.LookupParameter("Head Height");
                    string    storage  = para.StorageType.ToString();
                    double    value    = para.AsDouble();
                    double    newvalue = UnitUtils.ConvertFromInternalUnits(value, DisplayUnitType.DUT_MILLIMETERS);
                    // TaskDialog.Show("Parameters", "Parameter is a " + storage + " with value: " + newvalue.ToString());

                    double setvalue = UnitUtils.ConvertToInternalUnits(2100, DisplayUnitType.DUT_MILLIMETERS);
                    using (Transaction tran = new Transaction(doc, "Set Parameter")) {
                        tran.Start();
                        para.Set(setvalue);
                        tran.Commit();
                    }
                }

                TaskDialog.Show("Windows", windows.Count + " Windows Found!");

                return(Result.Succeeded);
            } catch (Exception ex) {
                TaskDialog.Show("Revit API Sample", "App fail: " + ex.Message);
                return(Result.Failed);
            }
        }
        ////[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            if (commandData == null)
            {
                return(Result.Failed);
            }

            UIDocument udoc = commandData.Application.ActiveUIDocument;

            var vm = new ViewModels.SolarViewsViewModel(commandData.Application.ActiveUIDocument);

            SCaddinsApp.WindowManager.ShowDialog(vm, null, ViewModels.SolarViewsViewModel.DefaultViewSettings);

            if (vm.CreateAnalysisView)
            {
                var internalUnitsGridSize = UnitUtils.ConvertToInternalUnits(vm.AnalysisGridSize, DisplayUnitType.DUT_MILLIMETERS);
                SolarAnalysisManager.CreateTestFaces(vm.FaceSelection, vm.MassSelection, internalUnitsGridSize, udoc, udoc.ActiveView);
            }

            return(Result.Succeeded);
        }
Example #9
0
        public Autodesk.Revit.UI.Result Execute
            (Autodesk.Revit.UI.ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // Get access to the active uidoc and doc
            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = commandData.Application.ActiveUIDocument.Document;

            Autodesk.Revit.UI.Selection.Selection sel = uidoc.Selection;

            try {
                Reference r =
                    sel.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element);
                Element elem = doc.GetElement(r);


                IList <ElementId> elemsWithinBBox = WallJoinerCmd
                                                    .GetWallsIntersectBoundingBox(doc, elem, UnitUtils
                                                                                  .ConvertToInternalUnits(400, DisplayUnitType.DUT_MILLIMETERS))
                                                    .Select(e => e.Id)
                                                    .ToList();

                sel.SetElementIds(elemsWithinBBox);

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (Exception ex) {
                Autodesk.Revit.UI.TaskDialog.Show("Exception",
                                                  string.Format("Message: {0}\nStackTrace: {1}",
                                                                ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Example #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);
        }
Example #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);
        }
Example #12
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument    uidoc            = app.ActiveUIDocument;
                Document      doc              = uidoc.Document;
                SelElementSet m_elementsToHide = SelElementSet.Create();

                List <ElementId> elementsToBeIsolated = new List <ElementId>();
                List <ElementId> elementsToBeHidden   = new List <ElementId>();
                List <ElementId> elementsToBeSelected = new List <ElementId>();


                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z);
                    var CameraViewPoint = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z);
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);


                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        View3D ActiveView3D = doc.ActiveView as View3D;
                        if (!ActiveView3D.IsPerspective)
                        {
                            orthoView = ActiveView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        //try to use default 3D view
                        if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").Any())
                        {
                            orthoView = viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").First();
                        }
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view
                            if (orthoView == null)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = "BCFortho";
                            }

                            orthoView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            orthoView.SetOrientation(orient3d);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = touple.Item2
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;
                    double x       = zoom / customZoomValue;
                    XYZ    m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ    m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }

                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var    zoom   = v.PerspectiveCamera.FieldOfView;
                    double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                    double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                    double factor = z1 - z;

                    var CameraDirection = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z);
                    var CameraUpVector  = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z);
                    XYZ oldO            = ARUP.IssueTracker.Revit.Classes.Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z);
                    var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
                    var orient3d        = ARUP.IssueTracker.Revit.Classes.Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);



                    View3D perspView = null;

                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "BCFpersp").Any())
                    {
                        perspView = viewcollector3D.Where(o => o.Name == "BCFpersp").First();
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = "BCFpersp";
                            }

                            perspView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                            perspView.SetOrientation(orient3d);

                            // turn on the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(1);
                            }
                            // reset far clip offset
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR).HasValue)
                            {
                                Parameter m_farClipOffset = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_OFFSET_FAR);
                                m_farClipOffset.SetValueString("35");
                            }
                            // turn off the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                else if (v.SheetCamera != null)//sheet
                {
                    //using (Transaction trans = new Transaction(uidoc.Document))
                    //{
                    //    if (trans.Start("Open sheet view") == TransactionStatus.Started)
                    //    {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
                    uidoc.RefreshActiveView();

                    //        trans.Commit();
                    //    }
                    //}
                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y,
                                          v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y,
                                          v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                else
                {
                    return;
                }

                //apply BCF clipping planes to Revit section box
                View3D view3D = doc.ActiveView as View3D;
                if (view3D != null)
                {
                    if (v.ClippingPlanes != null)
                    {
                        if (v.ClippingPlanes.Count() > 0)
                        {
                            var result = getBoundingBoxFromClippingPlanes(doc, v.ClippingPlanes);

                            if (result != null)
                            {
                                BoundingBoxXYZ computedBox = result.Item1;
                                Transform      rotate      = result.Item2;

                                using (Transaction trans = new Transaction(uidoc.Document))
                                {
                                    if (trans.Start("Apply Section Box") == TransactionStatus.Started)
                                    {
                                        view3D.IsSectionBoxActive = true;
                                        view3D.SetSectionBox(computedBox);

                                        if (rotate != null)
                                        {
                                            // Transform the View3D's section box with the rotation transform
                                            computedBox.Transform = computedBox.Transform.Multiply(rotate);

                                            // Set the section box back to the view (requires an open transaction)
                                            view3D.SetSectionBox(computedBox);
                                        }
                                    }
                                    trans.Commit();
                                }
                            }
                        }
                    }
                }

                //select/hide elements
                if (v.Components != null && v.Components.Any())
                {
                    if (v.Components.Count > 100)
                    {
                        var result = MessageBox.Show("Too many elements attached. It may take for a while to isolate/select them. Do you want to continue?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        if (result == MessageBoxResult.No)
                        {
                            uidoc.RefreshActiveView();
                            return;
                        }
                    }

                    FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                    System.Collections.Generic.ICollection <ElementId> collection = collector.ToElementIds();
                    foreach (var e in v.Components)
                    {
                        var bcfguid         = IfcGuid.FromIfcGUID(e.IfcGuid);
                        int authoringToolId = string.IsNullOrWhiteSpace(e.AuthoringToolId) ? -1 : int.Parse(e.AuthoringToolId);
                        var ids             = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o) | authoringToolId == Convert.ToInt32(doc.GetElement(o).UniqueId.Substring(37), 16));
                        if (ids.Any())
                        {
                            // handle visibility
                            if (e.Visible)
                            {
                                elementsToBeIsolated.Add(ids.First());
                            }
                            else
                            {
                                elementsToBeHidden.Add(ids.First());
                            }

                            // handle selection
                            if (e.Selected)
                            {
                                elementsToBeSelected.Add(ids.First());
                            }
                        }
                    }

                    if (elementsToBeHidden.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Hide Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.HideElementsTemporary(elementsToBeHidden);
                            }
                            trans.Commit();
                        }
                    }
                    else if (elementsToBeIsolated.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Isolate Elements") == TransactionStatus.Started)
                            {
                                uidoc.ActiveView.IsolateElementsTemporary(elementsToBeIsolated);
                            }
                            trans.Commit();
                        }
                    }

                    if (elementsToBeSelected.Count > 0)
                    {
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Select Elements") == TransactionStatus.Started)
                            {
                                SelElementSet selectedElements = SelElementSet.Create();
                                elementsToBeSelected.ForEach(id => {
                                    selectedElements.Add(doc.GetElement(id));
                                });

                                uidoc.Selection.Elements = selectedElements;
                            }
                            trans.Commit();
                        }
                    }
                }

                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
        //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);
        }
Example #14
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elementSet)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            List <string> liste = new List <string>();

            foreach (RevitLinkInstance instance in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType().ToElements().Cast <RevitLinkInstance>())
            {
                try
                {
                    List <Room> rooms = new FilteredElementCollector(instance.GetLinkDocument()).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_Rooms).Cast <Room>().ToList();

                    if (rooms.Count != 0)
                    {
                        string RVT_link = instance.GetLinkDocument().PathName;
                        liste.Add(RVT_link);
                    }
                }
                catch
                {
                }
            }

            if (liste.Count == 0)
            {
                TaskDialog td = new TaskDialog("Avertissement");
                td.Title       = "Avertissement";
                td.MainIcon    = TaskDialogIcon.TaskDialogIconWarning;
                td.MainContent = "Aucun lien Revit contenant des pièces n'est chargé dans le projet actif.";
                td.Show();
                return(Result.Cancelled);
            }

            Space_Creator form = new Space_Creator(doc);

            if (form.DialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return(Result.Cancelled);
            }

            if (DialogResult.OK == form.ShowDialog())
            {
                List <Level> levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements().Cast <Level>().ToList();

                using (Transaction t = new Transaction(doc, "Créer des espaces à partir des pièces"))
                {
                    t.Start();
                    string filename = form.GetSelectedRVTlink();
                    //var viewFamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast<ViewFamilyType>().FirstOrDefault(x => x.ViewFamily == ViewFamily.ThreeDimensional);
                    //View3D view3D = View3D.CreateIsometric(doc, viewFamilyType.Id);
                    //view3D.Name = "__TEST A EFFACER";
                    //string room_param = "FICHE";
                    //string space_param = "INGP_FICHE";
                    int           unplaced_rooms         = 0;
                    int           unclosed_rooms         = 0;
                    int           redundant_rooms        = 0;
                    int           created_spaces         = 0;
                    List <string> unclosed_rooms_levels  = new List <string>();
                    List <string> redundant_rooms_levels = new List <string>();

                    List <Level> MEP_levels = new List <Level>();
                    MEP_levels = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).WhereElementIsNotElementType().ToElements().Cast <Level>().ToList();

                    foreach (RevitLinkInstance instance in new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_RvtLinks).WhereElementIsNotElementType().ToElements().Cast <RevitLinkInstance>())
                    {
                        Document linkDoc = instance.GetLinkDocument();

                        if (linkDoc != null && Path.GetFileName(linkDoc.PathName) == filename)
                        {
                            List <string> rooms = new List <string>();
                            foreach (Space s in new FilteredElementCollector(doc).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_MEPSpaces).Cast <Space>())
                            {
                                Parameter room_name   = s.get_Parameter(BuiltInParameter.SPACE_ASSOC_ROOM_NAME);
                                Parameter room_number = s.get_Parameter(BuiltInParameter.SPACE_ASSOC_ROOM_NUMBER);
                                rooms.Add(room_name.AsString() + " " + room_number.AsString());
                            }

                            Transform tr = instance.GetTotalTransform();

                            foreach (Room room in new FilteredElementCollector(linkDoc).OfClass(typeof(SpatialElement)).OfCategory(BuiltInCategory.OST_Rooms).Cast <Room>())
                            {
                                if (DistinguishRoom(room) == RoomState.Placed || DistinguishRoom(room) == RoomState.NotEnclosed || DistinguishRoom(room) == RoomState.Redundant)
                                {
                                    Parameter room_name   = room.get_Parameter(BuiltInParameter.ROOM_NAME);
                                    Parameter room_number = room.get_Parameter(BuiltInParameter.ROOM_NUMBER);
                                    //Parameter room_level = room.LookupParameter("Niveau");
                                    LocationPoint point = room.Location as LocationPoint;
                                    XYZ           pt    = new XYZ(point.Point.X, point.Point.Y, point.Point.Z);
                                    pt = tr.OfPoint(pt);

                                    Level level = GetNearestLevel(pt, levels);
                                    Phase phase = doc.GetElement(doc.ActiveView.get_Parameter(BuiltInParameter.VIEW_PHASE).AsElementId()) as Phase;

                                    if (!rooms.Contains(room_name.AsString() + " " + room_number.AsString()))
                                    {
                                        Space space = doc.Create.NewSpace(level, phase, new UV(pt.X, pt.Y));
                                        created_spaces += 1;

                                        if (form.roomData() == true)
                                        {
                                            space.Name   = room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString();
                                            space.Number = room.Number;
                                        }
                                        //space.LookupParameter(space_param).Set(room.LookupParameter(room_param).AsString());
                                        space.BaseOffset = room.BaseOffset;

                                        if (form.spaceGeometry() == true)
                                        {
                                            Parameter limitOffset = space.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET);
                                            if (room.LimitOffset > 0)
                                            {
                                                limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET).AsDouble());
                                            }
                                            if (space.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() != room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble())
                                            {
                                                limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() + room.get_Parameter(BuiltInParameter.ROOM_LOWER_OFFSET).AsDouble());
                                            }
                                        }

                                        if (form.spaceGeometry() == false)
                                        {
                                            Parameter     limitOffset = space.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET);
                                            List <double> distances   = GetDistancesToFloors(doc, doc.ActiveView as View3D, room);
                                            try
                                            {
                                                if (distances[0] < room.BaseOffset)
                                                {
                                                    if (distances[1] < room.BaseOffset)
                                                    {
                                                        //limitOffset.Set(Math.Round(distances[2], 2));
                                                        limitOffset.Set(distances[2]);
                                                    }
                                                    else
                                                    {
                                                        //limitOffset.Set(Math.Round(distances[1], 2));
                                                        limitOffset.Set(distances[1]);
                                                    }
                                                }
                                                else
                                                {
                                                    //limitOffset.Set(Math.Round(distances.First(), 2));
                                                    limitOffset.Set(distances.First());
                                                }

                                                for (int i = 0; i < 10; i++)
                                                {
                                                    if (space.UnboundedHeight < UnitUtils.ConvertToInternalUnits(1.5, DisplayUnitType.DUT_METERS))
                                                    {
                                                        limitOffset.Set(Math.Round(distances[i], 5));
                                                        //limitOffset.Set(distances[i]);
                                                        if (space.UnboundedHeight > UnitUtils.ConvertToInternalUnits(1.5, DisplayUnitType.DUT_METERS))
                                                        {
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            catch
                                            {
                                                if (room.LimitOffset > 0)
                                                {
                                                    limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_UPPER_OFFSET).AsDouble());
                                                }
                                                if (space.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() != room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble())
                                                {
                                                    limitOffset.Set(room.get_Parameter(BuiltInParameter.ROOM_HEIGHT).AsDouble() + room.get_Parameter(BuiltInParameter.ROOM_LOWER_OFFSET).AsDouble());
                                                }
                                            }
                                        }

                                        if (DistinguishRoom(room) == RoomState.Redundant)
                                        {
                                            LocationPoint pt2  = space.Location as LocationPoint;
                                            XYZ           xyz  = new XYZ(0.001, 0, 0);
                                            XYZ           xyz2 = new XYZ(0.001, 0, 0);
                                            pt2.Move(xyz);
                                            pt2.Move(-xyz);
                                        }
                                    }
                                }
                                if (DistinguishRoom(room) == RoomState.NotPlaced)
                                {
                                    unplaced_rooms += 1;
                                }

                                if (DistinguishRoom(room) == RoomState.NotEnclosed)
                                {
                                    unclosed_rooms += 1;
                                    if (!unclosed_rooms_levels.Contains(room.Level.Name))
                                    {
                                        unclosed_rooms_levels.Add(room.Level.Name);
                                    }
                                }
                                if (DistinguishRoom(room) == RoomState.Redundant)
                                {
                                    redundant_rooms += 1;
                                    if (!redundant_rooms_levels.Contains(room.Level.Name))
                                    {
                                        redundant_rooms_levels.Add(room.Level.Name);
                                    }
                                }
                            }
                        }
                    }

                    TaskDialog td = new TaskDialog("Confirmation");
                    td.AllowCancellation = true;
                    td.TitleAutoPrefix   = true;


                    if (created_spaces > 0)
                    {
                        td.Title           = "Confirmation";
                        td.MainInstruction = created_spaces.ToString() + " espaces vont être crées.";

                        if (unclosed_rooms == 0 && redundant_rooms == 0)
                        {
                            td.MainContent = "Confirmer la création ?";
                        }
                        if (unclosed_rooms > 0 && redundant_rooms > 0)
                        {
                            td.MainContent = "dont espaces non fermés : " + unclosed_rooms.ToString() + " (" + string.Join("; ", unclosed_rooms_levels) + ")"
                                             + Environment.NewLine + "dont espaces superflus : " + redundant_rooms.ToString() + " (" + string.Join("; ", redundant_rooms_levels) + ")"
                                             + Environment.NewLine + "Confirmer la création ?";
                        }
                        if (unclosed_rooms > 0 && redundant_rooms == 0)
                        {
                            td.MainContent = "dont espaces non fermés : " + unclosed_rooms.ToString() + " (" + string.Join("; ", unclosed_rooms_levels) + ")"
                                             + Environment.NewLine + "Confirmer la création ?";
                        }
                        if (unclosed_rooms == 0 && redundant_rooms > 0)
                        {
                            td.MainContent = "dont espaces superflus : " + redundant_rooms.ToString() + " (" + string.Join("; ", redundant_rooms_levels) + ")"
                                             + Environment.NewLine + "Confirmer la création ?";
                        }

                        td.CommonButtons = TaskDialogCommonButtons.Cancel | TaskDialogCommonButtons.Ok;
                        TaskDialogResult result = td.Show();
                        if (result == TaskDialogResult.Ok)
                        {
                            t.Commit();
                        }
                        return(Result.Succeeded);
                    }
                }
                return(Result.Succeeded);
            }
            return(Result.Succeeded);
        }
Example #15
0
        public void SampleFail()
        {
            var feet = UnitUtils.ConvertToInternalUnits(3000, DisplayUnitType.DUT_MILLIMETERS);

            Assert.Equal(5, feet);
        }
Example #16
0
 private double ScaleToNative(double value, DisplayUnitType units)
 {
     return(UnitUtils.ConvertToInternalUnits(value, units));
 }
Example #17
0
        /// <summary>
        /// Calculate the max point and the min point of Revit section box based on BCF clipping planes
        /// </summary>
        /// <param name="clippingPlanes">clipping planes from BCF viewpoint</param>
        /// <returns>1: max, 2: min</returns>
        private Tuple <BoundingBoxXYZ, Transform> getBoundingBoxFromClippingPlanes(Document doc, ClippingPlane[] clippingPlanes)
        {
            const double tolerance = 0.0000001;

            if (clippingPlanes.Count() != 6)
            {
                return(null);
            }

            try
            {
                List <ClippingPlane> cPlanes = clippingPlanes.ToList();
                double maxZ, minZ;

                // checking z direction normals
                List <XYZ>           zPoints           = new List <XYZ>();
                List <ClippingPlane> xyClipppingPlanes = new List <ClippingPlane>();
                foreach (ClippingPlane cp in cPlanes)
                {
                    XYZ zDirection = new XYZ(0, 0, 1);
                    XYZ normal     = new XYZ(cp.Direction.X, cp.Direction.Y, cp.Direction.Z);
                    if (normal.IsAlmostEqualTo(zDirection, tolerance) || normal.IsAlmostEqualTo(-zDirection, tolerance))
                    {
                        zPoints.Add(new XYZ(cp.Location.X, cp.Location.Y, cp.Location.Z));
                    }
                    else
                    {
                        xyClipppingPlanes.Add(cp);
                    }
                }
                if (zPoints.Count != 2)
                {
                    return(null);
                }
                else
                {
                    maxZ = zPoints[0].Z > zPoints[1].Z ? zPoints[0].Z : zPoints[1].Z;
                    minZ = zPoints[0].Z < zPoints[1].Z ? zPoints[0].Z : zPoints[1].Z;
                    maxZ = UnitUtils.ConvertToInternalUnits(maxZ, DisplayUnitType.DUT_METERS);
                    minZ = UnitUtils.ConvertToInternalUnits(minZ, DisplayUnitType.DUT_METERS);
                }

                // check if the remaining 4 points are on XY plane
                //if (!xyClipppingPlanes.TrueForAll(cp => (cp.Location.Z < tolerance && cp.Location.Z > -tolerance)))
                //{
                //    return null;
                //}

                // find out lines orthorgonal to self-normal
                List <Autodesk.Revit.DB.Line> linesToBeIntersected = new List <Autodesk.Revit.DB.Line>();
                foreach (ClippingPlane cp in xyClipppingPlanes)
                {
                    XYZ           planeNormal     = new XYZ(cp.Direction.X, cp.Direction.Y, cp.Direction.Z);
                    ClippingPlane othorgonalPlane = xyClipppingPlanes.Find(c => !(
                                                                               new XYZ(c.Direction.X, c.Direction.Y, c.Direction.Z).IsAlmostEqualTo(planeNormal, tolerance)
                                                                               ||
                                                                               new XYZ(c.Direction.X, c.Direction.Y, c.Direction.Z).IsAlmostEqualTo(-planeNormal, tolerance)
                                                                               ));
                    XYZ othorgonalNormal = new XYZ(othorgonalPlane.Direction.X, othorgonalPlane.Direction.Y, othorgonalPlane.Direction.Z);
                    XYZ planeOrigin      = new XYZ(cp.Location.X, cp.Location.Y, 0);

                    linesToBeIntersected.Add(Autodesk.Revit.DB.Line.CreateUnbound(planeOrigin, othorgonalNormal));
                }

                // get intersection results
                List <XYZ> intersectedPoints = new List <XYZ>();
                foreach (Autodesk.Revit.DB.Line line1 in linesToBeIntersected)
                {
                    foreach (Autodesk.Revit.DB.Line line2 in linesToBeIntersected)
                    {
                        if (line1 != line2)
                        {
                            // calculate intersection points
                            double a1 = line1.Direction.Y;
                            double b1 = line1.Direction.X;
                            double a2 = line2.Direction.Y;
                            double b2 = line2.Direction.X;

                            // if not parallel
                            double delta = b1 * a2 - a1 * b2;
                            if (delta > tolerance || delta < -tolerance)
                            {
                                double c1 = a1 * line1.Origin.X - b1 * line1.Origin.Y;
                                double c2 = a2 * line2.Origin.X - b2 * line2.Origin.Y;

                                double deltaX = b1 * c2 - b2 * c1;
                                double deltaY = a1 * c2 - a2 * c1;

                                double intersectionX = deltaX / delta;
                                double intersectionY = deltaY / delta;
                                intersectedPoints.Add(new XYZ(intersectionX, intersectionY, 0));
                            }
                        }
                    }
                }

                // find rightmost, leftmost, topmost, and bottommost points
                XYZ rightmost  = intersectedPoints[0];
                XYZ leftmost   = intersectedPoints[0];
                XYZ topmost    = intersectedPoints[0];
                XYZ bottommost = intersectedPoints[0]; // for non-rotated section box only
                if (intersectedPoints.Count < 4)
                {
                    return(null);
                }
                else
                {
                    foreach (XYZ p in intersectedPoints)
                    {
                        if (p.X > rightmost.X)
                        {
                            rightmost = p;
                        }
                        if (p.X < leftmost.X)
                        {
                            leftmost = p;
                        }
                        if (p.Y > topmost.Y)
                        {
                            topmost = p;
                        }
                        if (p.Y < bottommost.Y)
                        {
                            bottommost = p;
                        }
                    }
                }

                // change the coordinate system from Project to Shared
                rightmost  = ConvertToInteranlAndSharedCoordinate(doc, rightmost);
                leftmost   = ConvertToInteranlAndSharedCoordinate(doc, leftmost);
                topmost    = ConvertToInteranlAndSharedCoordinate(doc, topmost);
                bottommost = ConvertToInteranlAndSharedCoordinate(doc, bottommost);

                // create diagonal and rotation vector
                XYZ horizontalBase = new XYZ(-1, 0, 0);
                Autodesk.Revit.DB.Line diagonal     = Autodesk.Revit.DB.Line.CreateBound(rightmost, leftmost);
                Autodesk.Revit.DB.Line rotationBase = !rightmost.IsAlmostEqualTo(topmost, tolerance) ?
                                                      Autodesk.Revit.DB.Line.CreateBound(rightmost, topmost) :
                                                      Autodesk.Revit.DB.Line.CreateUnbound(new XYZ(0, 0, 0), horizontalBase);

                // return these two guys
                BoundingBoxXYZ bBox = new BoundingBoxXYZ();
                Transform      originalTransform = null;

                // compute a correct section box depending on two conditions
                if (rightmost.IsAlmostEqualTo(topmost, tolerance) ||
                    leftmost.IsAlmostEqualTo(bottommost, tolerance) ||
                    horizontalBase.IsAlmostEqualTo(rotationBase.Direction, tolerance) ||
                    horizontalBase.IsAlmostEqualTo(-rotationBase.Direction, tolerance))
                {  //non-rotated section box
                    XYZ max = new XYZ(
                        rightmost.X,
                        topmost.Y,
                        maxZ
                        );
                    XYZ min = new XYZ(
                        leftmost.X,
                        bottommost.Y,
                        minZ
                        );

                    bBox.Max = max;
                    bBox.Min = min;
                }
                else //rotated section box
                {
                    // calculate rotation angle
                    double angle = horizontalBase.AngleTo(rotationBase.Direction);

                    // create transform
                    Transform transform = Transform.CreateRotationAtPoint(new XYZ(0, 0, 1), angle, rightmost);

                    // rotate it then get the rotated bounding box projection point (i.e., min. of rorated section box)
                    XYZ rotatedMin = diagonal.CreateTransformed(transform).GetEndPoint(1);

                    // create rotated section box with max and min
                    XYZ max = new XYZ(
                        rightmost.X,
                        rightmost.Y,
                        maxZ
                        );
                    XYZ min = new XYZ(
                        rotatedMin.X,
                        rotatedMin.Y,
                        minZ
                        );

                    bBox.Max = max;
                    bBox.Min = min;

                    // rotate back to the original position
                    originalTransform = Transform.CreateRotationAtPoint(new XYZ(0, 0, 1), -angle, max);
                }

                return(new Tuple <BoundingBoxXYZ, Transform>(bBox, originalTransform));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return(null);
            }
        }
Example #18
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));
 }
Example #19
0
        /// <summary>
        /// External Event Implementation
        /// </summary>
        /// <param name="app"></param>
        public void Execute(UIApplication app)
        {
            try
            {
                UIDocument       uidoc            = app.ActiveUIDocument;
                Document         doc              = uidoc.Document;
                SelElementSet    m_elementsToHide = SelElementSet.Create();
                List <ElementId> elementids       = new List <ElementId>();



                // IS ORTHOGONAL
                if (v.OrthogonalCamera != null)
                {
                    if (v.OrthogonalCamera.ViewToWorldScale == null || v.OrthogonalCamera.CameraViewPoint == null || v.OrthogonalCamera.CameraUpVector == null || v.OrthogonalCamera.CameraDirection == null)
                    {
                        return;
                    }
                    //type = "OrthogonalCamera";
                    var zoom            = UnitUtils.ConvertToInternalUnits(v.OrthogonalCamera.ViewToWorldScale, DisplayUnitType.DUT_METERS);
                    var CameraDirection = Utils.GetXYZ(v.OrthogonalCamera.CameraDirection.X, v.OrthogonalCamera.CameraDirection.Y, v.OrthogonalCamera.CameraDirection.Z);
                    var CameraUpVector  = Utils.GetXYZ(v.OrthogonalCamera.CameraUpVector.X, v.OrthogonalCamera.CameraUpVector.Y, v.OrthogonalCamera.CameraUpVector.Z);
                    var CameraViewPoint = Utils.GetXYZ(v.OrthogonalCamera.CameraViewPoint.X, v.OrthogonalCamera.CameraViewPoint.Y, v.OrthogonalCamera.CameraViewPoint.Z);
                    var orient3d        = Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);


                    View3D orthoView = null;
                    //if active view is 3d ortho use it
                    if (doc.ActiveView.ViewType == ViewType.ThreeD)
                    {
                        View3D ActiveView3D = doc.ActiveView as View3D;
                        if (!ActiveView3D.IsPerspective)
                        {
                            orthoView = ActiveView3D;
                        }
                    }
                    if (orthoView == null)
                    {
                        IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                        //try to use default 3D view
                        if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").Any())
                        {
                            orthoView = viewcollector3D.Where(o => o.Name == "{3D}" || o.Name == "BCFortho").First();
                        }
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open orthogonal view") == TransactionStatus.Started)
                        {
                            //create a new 3d ortho view
                            if (orthoView == null)
                            {
                                orthoView      = View3D.CreateIsometric(doc, getFamilyViews(doc).First().Id);
                                orthoView.Name = "BCFortho";
                            }

                            orthoView.SetOrientation(orient3d);
                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = orthoView;
                    //adjust view rectangle

                    // **** CUSTOM VALUE FOR TEKLA **** //
                    // double x = touple.Item2
                    // **** CUSTOM VALUE FOR TEKLA **** //
                    double customZoomValue = (MyProjectSettings.Get("useDefaultZoom", doc.PathName) == "1") ? 1 : 2.5;
                    double x       = zoom / customZoomValue;
                    XYZ    m_xyzTl = uidoc.ActiveView.Origin.Add(uidoc.ActiveView.UpDirection.Multiply(x)).Subtract(uidoc.ActiveView.RightDirection.Multiply(x));
                    XYZ    m_xyzBr = uidoc.ActiveView.Origin.Subtract(uidoc.ActiveView.UpDirection.Multiply(x)).Add(uidoc.ActiveView.RightDirection.Multiply(x));
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }

                else if (v.PerspectiveCamera != null)
                {
                    if (v.PerspectiveCamera.FieldOfView == null || v.PerspectiveCamera.CameraViewPoint == null || v.PerspectiveCamera.CameraUpVector == null || v.PerspectiveCamera.CameraDirection == null)
                    {
                        return;
                    }

                    var    zoom   = v.PerspectiveCamera.FieldOfView;
                    double z1     = 18 / Math.Tan(zoom / 2 * Math.PI / 180); //focale 1
                    double z      = 18 / Math.Tan(25 / 2 * Math.PI / 180);   //focale, da controllare il 18, vedi PDF
                    double factor = z1 - z;

                    var CameraDirection = Utils.GetXYZ(v.PerspectiveCamera.CameraDirection.X, v.PerspectiveCamera.CameraDirection.Y, v.PerspectiveCamera.CameraDirection.Z);
                    var CameraUpVector  = Utils.GetXYZ(v.PerspectiveCamera.CameraUpVector.X, v.PerspectiveCamera.CameraUpVector.Y, v.PerspectiveCamera.CameraUpVector.Z);
                    XYZ oldO            = Utils.GetXYZ(v.PerspectiveCamera.CameraViewPoint.X, v.PerspectiveCamera.CameraViewPoint.Y, v.PerspectiveCamera.CameraViewPoint.Z);
                    var CameraViewPoint = (oldO.Subtract(CameraDirection.Divide(factor)));
                    var orient3d        = Utils.ConvertBasePoint(doc, CameraViewPoint, CameraDirection, CameraUpVector, true);



                    View3D perspView = null;

                    IEnumerable <View3D> viewcollector3D = get3DViews(doc);
                    if (viewcollector3D.Any() && viewcollector3D.Where(o => o.Name == "BCFpersp").Any())
                    {
                        perspView = viewcollector3D.Where(o => o.Name == "BCFpersp").First();
                    }
                    using (Transaction trans = new Transaction(uidoc.Document))
                    {
                        if (trans.Start("Open perspective view") == TransactionStatus.Started)
                        {
                            if (null == perspView)
                            {
                                perspView      = View3D.CreatePerspective(doc, getFamilyViews(doc).First().Id);
                                perspView.Name = "BCFpersp";
                            }

                            perspView.SetOrientation(orient3d);

                            // turn off the far clip plane with standard parameter API
                            if (perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR).HasValue)
                            {
                                Parameter m_farClip = perspView.get_Parameter(BuiltInParameter.VIEWER_BOUND_ACTIVE_FAR);
                                m_farClip.Set(0);
                            }
                            perspView.CropBoxActive  = true;
                            perspView.CropBoxVisible = true;

                            trans.Commit();
                        }
                    }
                    uidoc.ActiveView = perspView;
                }
                else if (v.SheetCamera != null)//sheet
                {
                    //using (Transaction trans = new Transaction(uidoc.Document))
                    //{
                    //    if (trans.Start("Open sheet view") == TransactionStatus.Started)
                    //    {
                    IEnumerable <View> viewcollectorSheet = getSheets(doc, v.SheetCamera.SheetID);
                    if (!viewcollectorSheet.Any())
                    {
                        MessageBox.Show("No Sheet with Id=" + v.SheetCamera.SheetID + " found.");
                        return;
                    }
                    uidoc.ActiveView = viewcollectorSheet.First();
                    uidoc.RefreshActiveView();

                    //        trans.Commit();
                    //    }
                    //}
                    XYZ m_xyzTl = new XYZ(v.SheetCamera.TopLeft.X, v.SheetCamera.TopLeft.Y,
                                          v.SheetCamera.TopLeft.Z);
                    XYZ m_xyzBr = new XYZ(v.SheetCamera.BottomRight.X, v.SheetCamera.BottomRight.Y,
                                          v.SheetCamera.BottomRight.Z);
                    uidoc.GetOpenUIViews().First().ZoomAndCenterRectangle(m_xyzTl, m_xyzBr);
                }
                else
                {
                    return;
                }
                //select/hide elements
                if (v.Components != null && v.Components.Any())
                {
                    FilteredElementCollector collector = new FilteredElementCollector(doc, doc.ActiveView.Id).WhereElementIsNotElementType();
                    System.Collections.Generic.ICollection <ElementId> collection = collector.ToElementIds();
                    foreach (var e in v.Components)
                    {
                        var bcfguid = IfcGuid.FromIfcGUID(e.IfcGuid);
                        var ids     = collection.Where(o => bcfguid == ExportUtils.GetExportId(doc, o));
                        if (ids.Any())
                        {
                            m_elementsToHide.Add(doc.GetElement(ids.First()));
                            elementids.Add(ids.First());
                        }
                    }
                    if (null != m_elementsToHide && !m_elementsToHide.IsEmpty)
                    {
                        //do transaction only if there is something to hide/select
                        using (Transaction trans = new Transaction(uidoc.Document))
                        {
                            if (trans.Start("Apply visibility/selection") == TransactionStatus.Started)
                            {
                                if (MySettings.Get("selattachedelems") == "0")
                                {
                                    uidoc.ActiveView.IsolateElementsTemporary(elementids);
                                }
                                else
                                {
                                    uidoc.Selection.Elements = m_elementsToHide;
                                }
                            }
                            trans.Commit();
                        }
                    }
                }


                uidoc.RefreshActiveView();
            }
            catch (Exception ex)
            {
                TaskDialog.Show("Error!", "exception: " + ex);
            }
        }
Example #20
0
 public static double ToFeet(this double meters)
 {
     return(UnitUtils.ConvertToInternalUnits(meters, DisplayUnitType.DUT_METERS));
 }
Example #21
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);
        }
Example #22
0
        public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.
                                                ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Tracer.Listeners.Add(new System.Diagnostics.EventLogTraceListener("Application"));

            Autodesk.Revit.UI.UIDocument uidoc = commandData.Application.ActiveUIDocument;
            Document doc = uidoc.Document;

            try {
                // Set the minimum wall width
                double minWallWidth = UnitUtils
                                      .ConvertToInternalUnits(400, DisplayUnitType.DUT_MILLIMETERS); // 400mm

                // Select all walls wider than 400 mm
                ElementParameterFilter widthFilter =
                    new ElementParameterFilter(ParameterFilterRuleFactory
                                               .CreateGreaterOrEqualRule(new ElementId(BuiltInParameter.WALL_ATTR_WIDTH_PARAM),
                                                                         minWallWidth, 0.1));

                IList <Wall> walls = new FilteredElementCollector(doc)
                                     .OfClass(typeof(Wall))
                                     .WhereElementIsNotElementType()
                                     .WherePasses(widthFilter)
                                     .Cast <Wall>()
                                     .ToList();

                Tracer.Write("The number of walls in the project: " + walls.Count);

                using (Transaction t = new Transaction(doc, "Join walls")) {
                    FailureHandlingOptions handlingOptions = t.GetFailureHandlingOptions();
                    handlingOptions.SetFailuresPreprocessor(new AllWarningSwallower());
                    t.SetFailureHandlingOptions(handlingOptions);
                    t.Start();

                    foreach (Wall wall in walls)
                    {
                        IList <Element> intrudingWalls =
                            GetWallsIntersectBoundingBox(doc, wall, minWallWidth);

                        Tracer.Write(string.Format("Wall {0} is intersected by {1} walls",
                                                   wall.Id.ToString(), intrudingWalls.Count));

                        foreach (Element elem in intrudingWalls)
                        {
                            if (//((Wall)elem).WallType.Width < minWallWidth ||
                                ((Wall)elem).WallType.Kind == WallKind.Curtain)
                            {
                                continue;
                            }
                            try {
                                if (!JoinGeometryUtils.AreElementsJoined(doc, wall, elem))
                                {
                                    JoinGeometryUtils.JoinGeometry(doc, wall, elem);
                                }
                            }
                            catch (Exception ex) {
                                Tracer.Write(string.Format("{0}\nWall: {1} cannot be joined to {2}",
                                                           ex.Message, wall.Id.ToString(), elem.Id.ToString()));
                                continue;
                            }
                        }
                    }
                    t.Commit();
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Autodesk.Revit.Exceptions.OperationCanceledException) {
                return(Autodesk.Revit.UI.Result.Cancelled);
            }
            catch (Exception ex) {
                Tracer.Write(string.Format("{0}\n{1}",
                                           ex.Message, ex.StackTrace));
                return(Autodesk.Revit.UI.Result.Failed);
            }
        }
Example #23
0
 private double ScaleToNative(double value, string units)
 {
     return(UnitUtils.ConvertToInternalUnits(value, UnitsToNative(units)));
 }
Example #24
0
        private static Autodesk.Revit.DB.Wall CopyWall(Autodesk.Revit.DB.WallType wallType, Autodesk.Revit.DB.Wall Wall, Level level_Bottom, Level level_Top, Dictionary <ElementId, List <FamilyInstance> > dictionary_Hosts, Dictionary <BuiltInCategory, FamilySymbol> dictionary_Symbols)
        {
            if (wallType == null || Wall == null)
            {
                return(null);
            }

            if (!(Wall.Location is LocationCurve))
            {
                return(null);
            }

            LocationCurve locationCurve = Wall.Location as LocationCurve;

            Document document = wallType.Document;

            Autodesk.Revit.DB.Wall result = Autodesk.Revit.DB.Wall.Create(wallType.Document, locationCurve.Curve, level_Bottom.Id, false);

            result.WallType = wallType;

            //FamilyInstance aFamilyInstance = aDocument.Create.NewFamilyInstance(aLocationCurve.Curve, ElementType, Level_Bottom, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);
            if (result == null)
            {
                return(null);
            }

            if (Wall.Flipped != result.Flipped)
            {
                result.Flip();
            }

            Parameter parameter = null;

            if (level_Top.Elevation > level_Bottom.Elevation)
            {
                parameter = result.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE);
                if (parameter != null)
                {
                    parameter.Set(level_Top.Id);
                }
            }
            else
            {
                parameter = result.get_Parameter(BuiltInParameter.WALL_USER_HEIGHT_PARAM);
                if (parameter != null && !parameter.IsReadOnly)
                {
#if Revit2017 || Revit2018 || Revit2019 || Revit2020
                    parameter.Set(UnitUtils.ConvertToInternalUnits(2000, DisplayUnitType.DUT_MILLIMETERS));
#else
                    parameter.Set(UnitUtils.ConvertToInternalUnits(2000, UnitTypeId.Millimeters));
#endif
                }
            }

            parameter = result.get_Parameter(BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS);
            if (parameter != null)
            {
                parameter.Set(Wall.Id.IntegerValue.ToString());
            }

            document.Regenerate();

            AddHosts(result, Wall.Id, dictionary_Hosts, dictionary_Symbols);

            return(result);
        }
Example #25
0
        public static bool TogbXML(this Document document, string path)
        {
            if (document == null || document.IsFamilyDocument || string.IsNullOrWhiteSpace(path))
            {
                return(false);
            }

            bool result = true;

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

                    EnergyAnalysisDetailModel energyAnalysisDetailModel = null;

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

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

                        Parameter parameter = null;

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

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

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

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

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


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

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

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

                    energyAnalysisDetailModel = EnergyAnalysisDetailModel.Create(document, energyAnalysisDetailModelOptions);

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

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

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

            return(result);
        }
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                Document doc = commandData.Application.ActiveUIDocument.Document;

                string fileName = null;
                using (System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog())
                {
                    dlg.Title            = "Select an Excel File";
                    dlg.RestoreDirectory = true;
                    dlg.Filter           = "Excel (*.xlsx; *.xls)|*.xlsx;*.xls|All Files (*.*)|*.*";

                    System.Windows.Forms.DialogResult result = dlg.ShowDialog();
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        fileName = dlg.FileName;
                    }
                }

                if (fileName != null)
                {
                    if (fileName.Split(new char[] { '.' }).Last().ToLower() == "xls" || fileName.Split(new char[] { '.' }).Last().ToLower() == "xlsx")
                    {
                        string fileOnly = new System.IO.FileInfo(fileName).Name;
                        // Launch the workset selector
                        System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();
                        IntPtr handle = proc.MainWindowHandle;
                        WorksheetSelectWindow selectWindow = new WorksheetSelectWindow(RevitCommon.Excel.GetWorksheetNames(fileName));

                        System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(selectWindow);
                        helper.Owner = handle;
                        selectWindow.ShowDialog();

                        if (selectWindow.WorksheetName != null)
                        {
                            Schema schema = Schema.Lookup(Properties.Settings.Default.SchemaIdElement);

                            // Get the masses from the project that mach the file name and worksheet.
                            IList <Element> massElements = new FilteredElementCollector(doc)
                                                           .OfCategory(BuiltInCategory.OST_Mass)
                                                           .WhereElementIsNotElementType()
                                                           .Where(x => x.GetEntity(schema) != null && x.GetEntity(schema).Schema != null)
                                                           .ToList();

                            List <Element> filteredMasses = new List <Element>();
                            List <string>  parameterNames = new List <string>();
                            List <string>  groupingParams = new List <string>();
                            ElementId      symbolId       = null;
                            ElementId      levelId        = null;
                            Level          selectedLevel  = null;
                            FamilySymbol   selectedSymbol = null;
                            string         creationTime   = null;

                            foreach (Element elem in massElements)
                            {
                                Entity entity = elem.GetEntity(schema);
                                if (entity != null && entity.IsValid())
                                {
                                    string elemFile  = entity.Get <string>(schema.GetField("FileName"));
                                    string worksheet = entity.Get <string>(schema.GetField("Worksheet"));
                                    if (fileOnly.ToLower() == elemFile.ToLower() && worksheet.ToLower() == selectWindow.WorksheetName.ToLower())
                                    {
                                        filteredMasses.Add(elem);
                                        if (parameterNames.Count == 0)
                                        {
                                            parameterNames = entity.Get <IList <string> >(schema.GetField("ParameterNames")).ToList();
                                        }
                                        if (groupingParams.Count == 0)
                                        {
                                            groupingParams = entity.Get <IList <string> >(schema.GetField("GroupingParameters")).ToList();
                                        }
                                        if (symbolId == null)
                                        {
                                            selectedSymbol = doc.GetElement(entity.Get <ElementId>(schema.GetField("SymbolId"))) as FamilySymbol;
                                        }
                                        if (levelId == null)
                                        {
                                            selectedLevel = doc.GetElement(entity.Get <ElementId>(schema.GetField("LevelId"))) as Level;
                                        }
                                        if (creationTime == null)
                                        {
                                            creationTime = entity.Get <string>(schema.GetField("CreationTime"));
                                        }
                                    }
                                }
                            }

                            if (filteredMasses.Count > 0)
                            {
                                string headerStream = string.Empty;
                                // Excel data
                                List <List <string> > data   = RevitCommon.Excel.Read(fileName, selectWindow.WorksheetName);
                                List <MassObject>     masses = ExcelToMassData(data);

                                List <string> headers = data[0];
                                List <int>    indices = new List <int>();
                                foreach (string gn in groupingParams)
                                {
                                    for (int i = 0; i < headers.Count; i++)
                                    {
                                        if (headers[i] == gn)
                                        {
                                            indices.Add(i);
                                            break;
                                        }
                                    }
                                }

                                // find all of the unique groupings
                                List <string> uniqueGroups = new List <string>();
                                for (int i = 1; i < masses.Count; i++)
                                {
                                    MassObject mo        = masses[i];
                                    string     groupName = GetGroupID(mo, indices);
                                    if (!uniqueGroups.Contains(groupName))
                                    {
                                        uniqueGroups.Add(groupName);
                                    }
                                }

                                // Organize the masses into groups
                                List <List <MassObject> > organizedMasses = OrganizeMasses(masses, uniqueGroups, indices);

                                // Get the DisplayUnitTypes for length and area.
                                Units           units     = doc.GetUnits();
                                FormatOptions   areaFO    = units.GetFormatOptions(UnitType.UT_Area);
                                FormatOptions   lengthFO  = units.GetFormatOptions(UnitType.UT_Length);
                                DisplayUnitType lengthDUT = lengthFO.DisplayUnits;
                                DisplayUnitType areaDUT   = areaFO.DisplayUnits;

                                double defaultHeight = 10;
                                if (lengthDUT == DisplayUnitType.DUT_CENTIMETERS || lengthDUT == DisplayUnitType.DUT_DECIMETERS || lengthDUT == DisplayUnitType.DUT_METERS ||
                                    lengthDUT == DisplayUnitType.DUT_METERS_CENTIMETERS || lengthDUT == DisplayUnitType.DUT_MILLIMETERS)
                                {
                                    defaultHeight = 9.84252;
                                }

                                Transaction trans = new Transaction(doc, "Update Space Planning Masses");
                                trans.Start();

                                // Iterate through the organized masses and either update an existing one or create a new one.
                                double currentX = 0;
                                foreach (List <MassObject> massGroup in organizedMasses)
                                {
                                    double maxX     = 0;
                                    double currentY = 0;
                                    foreach (MassObject mass in massGroup)
                                    {
                                        string rName     = mass.RoomName;
                                        string rNumber   = mass.RoomNumber;
                                        string groupName = mass.GroupId;

                                        ElementId      matId          = null;
                                        List <Element> massesToupdate = new List <Element>();
                                        foreach (Element elem in massElements)
                                        {
                                            Entity entity = null;
                                            try
                                            {
                                                entity = elem.GetEntity(schema);
                                            }
                                            catch { }
                                            if (entity != null)
                                            {
                                                string        groupId    = entity.Get <string>(schema.GetField("GroupId"));
                                                List <string> paramNames = entity.Get <IList <string> >(schema.GetField("ParameterNames")).ToList();
                                                string        roomname   = elem.LookupParameter(paramNames[2]).AsString();
                                                string        roomnumber = elem.LookupParameter(paramNames[3]).AsString();
                                                if (roomname == rName && roomnumber == rNumber && groupId == groupName)
                                                {
                                                    massesToupdate.Add(elem);
                                                }


                                                if (matId == null && groupName == groupId && paramNames[5] != null)
                                                {
                                                    matId = elem.LookupParameter(paramNames[5]).AsElementId();
                                                }
                                            }
                                        }

                                        // Calculate width and depth
                                        double sideLength = 10;
                                        if (mass.ProgramArea > 0)
                                        {
                                            sideLength = Math.Sqrt(mass.ProgramArea);
                                        }
                                        if (sideLength > maxX)
                                        {
                                            maxX = sideLength;
                                        }
                                        if (massesToupdate.Count > 0)
                                        {
                                            // Update mass element
                                            foreach (Element updateElem in massesToupdate)
                                            {
                                                try
                                                {
                                                    // update the program area and extra parameters only
                                                    FamilyInstance fi = updateElem as FamilyInstance;

                                                    Parameter areaParam = null;
                                                    if (parameterNames[4] != null)
                                                    {
                                                        areaParam = fi.LookupParameter(parameterNames[4]);
                                                    }
                                                    if (areaParam != null)
                                                    {
                                                        areaParam.Set(UnitUtils.ConvertToInternalUnits(mass.ProgramArea, areaDUT));
                                                    }

                                                    for (int k = 9; k < parameterNames.Count; k++)
                                                    {
                                                        ParameterObj po        = mass.Parameters[k - 9];
                                                        Parameter    miscParam = null;
                                                        miscParam = updateElem.LookupParameter(parameterNames[k]);
                                                        if (miscParam != null)
                                                        {
                                                            switch (miscParam.StorageType)
                                                            {
                                                            case StorageType.Double:
                                                                double dbl = 0;
                                                                if (double.TryParse(po.Value, out dbl))
                                                                {
                                                                    if (miscParam.Definition.ParameterType == ParameterType.Area)
                                                                    {
                                                                        miscParam.Set(UnitUtils.ConvertToInternalUnits(dbl, areaDUT));
                                                                    }
                                                                    else if (miscParam.Definition.ParameterType == ParameterType.Length)
                                                                    {
                                                                        miscParam.Set(UnitUtils.ConvertToInternalUnits(dbl, lengthDUT));
                                                                    }
                                                                    else
                                                                    {
                                                                        miscParam.Set(dbl);
                                                                    }
                                                                }
                                                                break;

                                                            case StorageType.Integer:
                                                                int integer = 0;
                                                                if (int.TryParse(po.Value, out integer))
                                                                {
                                                                    miscParam.Set(integer);
                                                                }
                                                                break;

                                                            case StorageType.ElementId:
                                                                int elemIdInt = 0;
                                                                if (int.TryParse(po.Value, out integer))
                                                                {
                                                                    miscParam.Set(new ElementId(elemIdInt));
                                                                }
                                                                break;

                                                            default:
                                                                miscParam.Set(po.Value);
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    TaskDialog.Show("error", ex.Message);
                                                }
                                            }
                                        }
                                        if (mass.Quantity - massesToupdate.Count > 0)
                                        {
                                            // Create a new mass element
                                            // need to track X and Y position for creating masses

                                            for (int j = 0; j < mass.Quantity - massesToupdate.Count; j++)
                                            {
                                                // Location
                                                XYZ loc = new XYZ(currentX, currentY, selectedLevel.ProjectElevation);

                                                //FamilyInstance
                                                FamilyInstance fi = doc.Create.NewFamilyInstance(loc, selectedSymbol, Autodesk.Revit.DB.Structure.StructuralType.NonStructural);

                                                // Set the parameters as necessary
                                                if (parameterNames[0] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[0]).Set(mass.Department);
                                                }

                                                if (parameterNames[1] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[1]).Set(mass.RoomType);
                                                }

                                                if (parameterNames[2] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[2]).Set(mass.RoomName);
                                                }

                                                if (parameterNames[3] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[3]).Set(mass.RoomNumber);
                                                }

                                                if (parameterNames[4] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[4]).Set(UnitUtils.ConvertToInternalUnits(mass.ProgramArea, areaDUT));
                                                }

                                                if (parameterNames[5] != null && matId != null)
                                                {
                                                    fi.LookupParameter(parameterNames[5]).Set(matId);
                                                }

                                                if (parameterNames[6] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[6]).Set(UnitUtils.ConvertToInternalUnits(sideLength, lengthDUT));
                                                }

                                                if (parameterNames[7] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[7]).Set(UnitUtils.ConvertToInternalUnits(sideLength, lengthDUT));
                                                }

                                                if (parameterNames[8] != null)
                                                {
                                                    fi.LookupParameter(parameterNames[8]).Set(UnitUtils.ConvertToInternalUnits(defaultHeight, lengthDUT));
                                                }

                                                for (int k = 9; k < parameterNames.Count; k++)
                                                {
                                                    ParameterObj po = mass.Parameters[k - 9];

                                                    if (parameterNames[k] != null)
                                                    {
                                                        try
                                                        {
                                                            Parameter p = fi.LookupParameter(parameterNames[k]);
                                                            switch (p.StorageType)
                                                            {
                                                            case StorageType.Double:
                                                                double dbl = 0;
                                                                if (double.TryParse(po.Value, out dbl))
                                                                {
                                                                    if (p.Definition.ParameterType == ParameterType.Area)
                                                                    {
                                                                        p.Set(UnitUtils.ConvertToInternalUnits(dbl, areaDUT));
                                                                    }
                                                                    else if (p.Definition.ParameterType == ParameterType.Length)
                                                                    {
                                                                        p.Set(UnitUtils.ConvertToInternalUnits(dbl, lengthDUT));
                                                                    }
                                                                    else
                                                                    {
                                                                        p.Set(dbl);
                                                                    }
                                                                }
                                                                break;

                                                            case StorageType.Integer:
                                                                int integer = 0;
                                                                if (int.TryParse(po.Value, out integer))
                                                                {
                                                                    p.Set(integer);
                                                                }
                                                                break;

                                                            case StorageType.ElementId:
                                                                int elemIdInt = 0;
                                                                if (int.TryParse(po.Value, out integer))
                                                                {
                                                                    p.Set(new ElementId(elemIdInt));
                                                                }
                                                                break;

                                                            default:
                                                                p.Set(po.Value);
                                                                break;
                                                            }
                                                        }
                                                        catch { }
                                                    }
                                                }

                                                // Store the local Schema data, ie the creation datetime.
                                                try
                                                {
                                                    StoreElemDateTime(fi, fileOnly, selectWindow.WorksheetName, parameterNames, groupingParams, selectedSymbol, selectedLevel, creationTime, groupName);
                                                }
                                                catch (Exception ex)
                                                {
                                                    TaskDialog.Show("Schema Error", ex.Message);
                                                }
                                                currentY = currentY + sideLength + 5;
                                            }
                                        }
                                    }
                                    // Adjust the X position
                                    currentX = currentX + maxX + 5;
                                }
                                trans.Commit();
                            }
                        }
                    }
                }

                return(Result.Succeeded);
            }
            catch (Exception ex)
            {
                message = ex.Message;
                return(Result.Failed);
            }
        }
        public static void Update(UIApplication uiApp)
        {
            Document   doc   = uiApp.ActiveUIDocument.Document;
            UIDocument uidoc = uiApp.ActiveUIDocument;

            try
            {
                using (TransactionGroup txGp = new TransactionGroup(doc))
                {
                    txGp.Start("Update support loads.");

                    string fileName = "";

                    //Select file to update with
                    CommonOpenFileDialog dialog = new CommonOpenFileDialog();
                    if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
                    {
                        fileName = dialog.FileName;
                    }
                    if (fileName.IsNullOrEmpty() || !File.Exists(fileName))
                    {
                        return;
                    }

                    //Process the file
                    //Skip is to remove the first line
                    string   allLines          = string.Join(Environment.NewLine, File.ReadAllLines(fileName).Skip(1).ToArray());
                    string[] splitByEmptyLines = allLines.Split(new string[]
                                                                { Environment.NewLine + " " + Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                    //Whole block as string
                    for (int i = 0; i < splitByEmptyLines.Length; i++)
                    {
                        string[] splitByLinebreak = splitByEmptyLines[i].Split(
                            new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                        string[][] atomised = new string[splitByLinebreak.Length][];

                        //Block as lines
                        for (int j = 0; j < splitByLinebreak.Length; j++)
                        {
                            string temp = Regex.Replace(splitByLinebreak[j], @"\s\s+", "");
                            temp        = Regex.Replace(temp, @"\s;", ";");
                            temp        = Regex.Replace(temp, @";\s", ";");
                            temp        = Regex.Replace(temp, "\"", "");
                            atomised[j] = temp.Split(';');
                        }

                        Console.WriteLine("-------------------------------------------------------------------");
                        Console.WriteLine("Type: " + atomised[3][2]);
                        Console.WriteLine("Tag: " + atomised[1][2]);
                        Console.WriteLine("Load Case: " + atomised[7][3]);
                        Console.WriteLine("Value: " + atomised[0][12] + " " + atomised[7][12]);

                        if (atomised[1][2].IsNullOrEmpty())
                        {
                            continue;                                 //Skipe record if the tag is empty
                        }
                        string[] tagParts = atomised[1][2].Split('_');

                        FilteredElementCollector col = new FilteredElementCollector(doc);
                        col = col.OfCategory(BuiltInCategory.OST_PipeAccessory).OfClass(typeof(FamilyInstance));

                        //Tag 1
                        ElementParameterFilter epf = fi.ParameterValueGenericFilter(
                            doc, tagParts[0], new Guid("a93679f7-ca9e-4a1e-bb44-0d890a5b4ba1"));
                        col = col.WherePasses(epf);
                        //Tag 2
                        epf = fi.ParameterValueGenericFilter(
                            doc, tagParts[1], new Guid("3b2afba4-447f-422a-8280-fd394718ad4e"));
                        col = col.WherePasses(epf);

                        var ids = col.ToElementIds();
                        if (ids.Count < 1)
                        {
                            throw new Exception($"No element found for tag: {atomised[1][2]}");
                        }
                        if (ids.Count > 1)
                        {
                            throw new Exception($"Multiple elements found for tag: {atomised[1][2]}");
                        }

                        using (Transaction tx = new Transaction(doc))
                        {
                            tx.Start("Update element's load");
                            foreach (ElementId id in ids)
                            {
                                Element   e   = doc.GetElement(id);
                                Parameter par = e.LookupParameter("Belastning");
                                if (par == null)
                                {
                                    throw new Exception($"Element id {e.Id} does not have 'Belastning' parameter!");
                                }
                                double rawValue       = Math.Abs(double.Parse(atomised[7][12]));
                                double convertedValue = UnitUtils.ConvertToInternalUnits(
                                    rawValue, UnitTypeId.Kilonewtons);
                                par.Set(convertedValue);
                            }
                            tx.Commit();
                        }

                        //Console.WriteLine(PrettyPrintArrayOfArrays(atomised));
                    }
                    txGp.Assimilate();
                }
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                //return Result.Failed;
            }
        }
Example #28
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 vm     = new DiggingHoleViewModel();
            var window = new DiggingHole(vm);

            window.ShowDialog();


            if (window.DialogResult == true)
            {
                var topoffset   = UnitUtils.ConvertToInternalUnits(double.Parse(vm.TopOffset), DisplayUnitType.DUT_MILLIMETERS);
                var botoffset   = UnitUtils.ConvertToInternalUnits(double.Parse(vm.BotOffset), DisplayUnitType.DUT_MILLIMETERS);
                var filter      = new FoundationFilter();
                var foundations = uidoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, filter)
                                  .Select(r => doc.GetElement(r.ElementId))
                                  .ToList();

                var results = new List <Element>();

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

                    var solids        = foundation.GetSolids();
                    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 topFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == 1);
                    var offsettopFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), topoffset, topFace.FaceNormal);

                    var offsetbotFace = CurveLoop.CreateViaOffset(botFace.GetEdgesAsCurveLoops().FirstOrDefault(), botoffset, botFace.FaceNormal);
                    offsetbotFace.Transform(Transform.CreateTranslation(new XYZ(0, 0, UnitUtils.ConvertToInternalUnits(-100, DisplayUnitType.DUT_MILLIMETERS))));
                    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(offsetbotFace);
                        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();
                        var ele = doc.Create.NewFamilyInstance(XYZ.Zero, symbol, Autodesk.Revit.DB.Structure.StructuralType.Footing);
                        results.Add(ele);
                        tran.Commit();
                    }
                }
                foreach (var ele in results)
                {
                    var boundingBox = ele.get_BoundingBox(null);

                    var solids = ele.GetSolids();

                    var outline  = new Outline(boundingBox.Min, boundingBox.Max);
                    var bbfilter = new BoundingBoxIntersectsFilter(outline);

                    var collectors = new FilteredElementCollector(doc, results.Select(e => e.Id).ToList())
                                     .WhereElementIsNotElementType()
                                     .WherePasses(bbfilter)
                                     .ToElements();

                    var solid  = ele.GetSolids().FirstOrDefault();
                    var firstZ = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1).Origin.Z;

                    foreach (var item in collectors)
                    {
                        var secondSolid = item.GetSolids().FirstOrDefault();
                        var secondZ     = secondSolid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1).Origin.Z;
                        if (Math.Round(firstZ, 2) == Math.Round(secondZ, 2))
                        {
                            solid = BooleanOperationsUtils.ExecuteBooleanOperation(solid, item.GetSolids().FirstOrDefault(), BooleanOperationsType.Union);
                        }
                    }
                    var botFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == -1);
                    var topFace       = solid.Faces.Cast <Face>().OfType <PlanarFace>().FirstOrDefault(f => Math.Round(f.FaceNormal.Z, 2) == 1);
                    var offsettopFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), 0, topFace.FaceNormal);
                    var offsetbotFace = CurveLoop.CreateViaOffset(topFace.GetEdgesAsCurveLoops().FirstOrDefault(), -topoffset + botoffset, topFace.FaceNormal);
                    offsetbotFace.Transform(Transform.CreateTranslation(new XYZ(0, 0, -topFace.Origin.Z + botFace.Origin.Z)));
                    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(offsetbotFace);
                        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()}{ele.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);
        }
Example #29
0
        public TextLineObject ConvertInsertpointsToInternal()
        {
            var PointInsert = new XYZ(UnitUtils.ConvertToInternalUnits(this.PointInsert.X, DisplayUnitType.DUT_METERS), UnitUtils.ConvertToInternalUnits(this.PointInsert.Y, DisplayUnitType.DUT_METERS), UnitUtils.ConvertToInternalUnits(this.PointInsert.Z, DisplayUnitType.DUT_METERS));
            var PointEnd    = new XYZ(UnitUtils.ConvertToInternalUnits(this.PointEnd.X, DisplayUnitType.DUT_METERS), UnitUtils.ConvertToInternalUnits(this.PointEnd.Y, DisplayUnitType.DUT_METERS), UnitUtils.ConvertToInternalUnits(this.PointEnd.Z, DisplayUnitType.DUT_METERS));

            //var LineLength = UnitUtils.ConvertToInternalUnits(this.LineLength, DisplayUnitType.DUT_METERS);
            return(new TextLineObject(this.StationStart, this.StationEnd, this.StationText, PointInsert, PointEnd, LineLength));
        }
        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);
        }